text
stringlengths
27
775k
namespace ComplementDrugSearch.Models { /// <summary> /// Represents a protein. /// </summary> public class Protein { /// <summary> /// Represents the protein index within the network. /// </summary> public int Index { get; set; } /// <summary> /// Represents the protein name. /// </summary> public string Name { get; set; } /// <summary> /// Represents the disease essential status of the protein.. /// </summary> public bool IsDiseaseEssential { get; set; } /// <summary> /// Represents the healthy essential status of the protein.. /// </summary> public bool IsHealthyEssential { get; set; } /// <summary> /// Initializes a new default instance of the class. /// </summary> public Protein() { // Assign the default value for each property. Index = 0; Name = null; IsDiseaseEssential = false; IsHealthyEssential = false; } /// <summary> /// Initializes a new instance of the class. /// </summary> /// <param name="index">The protein index within the network.</param> /// <param name="name">The name of the protein.</param> /// <param name="isDiseaseEssential">The disease essential status of the protein.</param> /// <param name="isHealthyEssential">The healthy essential status of the protein.</param> public Protein(int index, string name, bool isDiseaseEssential, bool isHealthyEssential) { // Assign the value for each property. Index = index; Name = name; IsDiseaseEssential = isDiseaseEssential; IsHealthyEssential = isHealthyEssential; } } }
package com.arkivanov.mvikotlin.timetravel.proto.internal.data.timetravelexport import com.arkivanov.mvikotlin.timetravel.proto.internal.data.ProtoObject class TimeTravelExport(val data: ByteArray) : ProtoObject
package typingsSlinky.qlikEngineapi.EngineAPI import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** * NxLinkedObjectInfo... */ @js.native trait INxLinkedObjectInfo extends StObject { /** * Information about the linked object. */ var qInfo: INxInfo = js.native /** * Identifier of the root object. * If the linked object is a child, the root identifier is the identifier of the parent. * If the linked object is an app object, the root identifier is the same than the * identifier of the linked object since the linked object is a root object. */ var qRootId: String = js.native } object INxLinkedObjectInfo { @scala.inline def apply(qInfo: INxInfo, qRootId: String): INxLinkedObjectInfo = { val __obj = js.Dynamic.literal(qInfo = qInfo.asInstanceOf[js.Any], qRootId = qRootId.asInstanceOf[js.Any]) __obj.asInstanceOf[INxLinkedObjectInfo] } @scala.inline implicit class INxLinkedObjectInfoMutableBuilder[Self <: INxLinkedObjectInfo] (val x: Self) extends AnyVal { @scala.inline def setQInfo(value: INxInfo): Self = StObject.set(x, "qInfo", value.asInstanceOf[js.Any]) @scala.inline def setQRootId(value: String): Self = StObject.set(x, "qRootId", value.asInstanceOf[js.Any]) } }
package ru.itmo.sd.tasks.events.model; import java.time.Duration; public class SubscriptionReport { private final int totalVisits; private final Duration totalDuration; public SubscriptionReport() { this(0, Duration.ZERO); } public SubscriptionReport(int totalVisits, Duration totalDuration) { this.totalVisits = totalVisits; this.totalDuration = totalDuration; } public int getTotalVisits() { return totalVisits; } public Duration getTotalDuration() { return totalDuration; } public SubscriptionReport addVisit(Duration duration) { return new SubscriptionReport(totalVisits + 1, totalDuration.plus(duration)); } public SubscriptionReport mergeReports(SubscriptionReport report) { return new SubscriptionReport(totalVisits + report.totalVisits, totalDuration.plus(report.totalDuration)); } @Override public String toString() { return "SubscriptionReport {\n" + " Total visits : " + totalVisits + ",\n" + " Total duration : " + totalDuration + ",\n" + " Average visit time : " + totalDuration.dividedBy(totalVisits) + "\n" + "}\n"; } }
# MicrochipNeoPixel Neo Pixel Control with PIC18F47K42 Used Board: https://www.microchip.com/Developmenttools/ProductDetails/DM182028
#!/bin/bash $HOME/workspace/git.rootknecht.net/scripts/fzf-nova/_keyboard.sh sync-mail.sh sync-pim.sh keepassxc & xbindkeys clipmenud xbanish &
# This file is auto-generated by AWSMetadata.jl using AWS using AWS.AWSServices: service_catalog_appregistry using AWS.Compat using AWS.UUIDs """ associate_attribute_group(application, attribute_group) associate_attribute_group(application, attribute_group, params::Dict{String,<:Any}) Associates an attribute group with an application to augment the application's metadata with the group's attributes. This feature enables applications to be described with user-defined details that are machine-readable, such as third-party integrations. # Arguments - `application`: The name or ID of the application. - `attribute_group`: The name or ID of the attribute group that holds the attributes to describe the application. """ function associate_attribute_group( application, attributeGroup; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "PUT", "/applications/$(application)/attribute-groups/$(attributeGroup)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_attribute_group( application, attributeGroup, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "PUT", "/applications/$(application)/attribute-groups/$(attributeGroup)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ associate_resource(application, resource, resource_type) associate_resource(application, resource, resource_type, params::Dict{String,<:Any}) Associates a resource with an application. Both the resource and the application can be specified either by ID or name. # Arguments - `application`: The name or ID of the application. - `resource`: The name or ID of the resource of which the application will be associated. - `resource_type`: The type of resource of which the application will be associated. """ function associate_resource( application, resource, resourceType; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "PUT", "/applications/$(application)/resources/$(resourceType)/$(resource)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function associate_resource( application, resource, resourceType, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "PUT", "/applications/$(application)/resources/$(resourceType)/$(resource)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_application(client_token, name) create_application(client_token, name, params::Dict{String,<:Any}) Creates a new application that is the top-level node in a hierarchy of related cloud resource abstractions. # Arguments - `client_token`: A unique identifier that you provide to ensure idempotency. If you retry a request that completed successfully using the same client token and the same parameters, the retry succeeds without performing any further actions. If you retry a successful request using the same client token, but one or more of the parameters are different, the retry fails. - `name`: The name of the application. The name must be unique in the region in which you are creating the application. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"description"`: The description of the application. - `"tags"`: Key-value pairs you can use to associate with the application. """ function create_application( clientToken, name; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "POST", "/applications", Dict{String,Any}("clientToken" => clientToken, "name" => name); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_application( clientToken, name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "POST", "/applications", Dict{String,Any}( mergewith( _merge, Dict{String,Any}("clientToken" => clientToken, "name" => name), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ create_attribute_group(attributes, client_token, name) create_attribute_group(attributes, client_token, name, params::Dict{String,<:Any}) Creates a new attribute group as a container for user-defined attributes. This feature enables users to have full control over their cloud application's metadata in a rich machine-readable format to facilitate integration with automated workflows and third-party tools. # Arguments - `attributes`: A JSON string in the form of nested key-value pairs that represent the attributes in the group and describes an application and its components. - `client_token`: A unique identifier that you provide to ensure idempotency. If you retry a request that completed successfully using the same client token and the same parameters, the retry succeeds without performing any further actions. If you retry a successful request using the same client token, but one or more of the parameters are different, the retry fails. - `name`: The name of the attribute group. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"description"`: The description of the attribute group that the user provides. - `"tags"`: Key-value pairs you can use to associate with the attribute group. """ function create_attribute_group( attributes, clientToken, name; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "POST", "/attribute-groups", Dict{String,Any}( "attributes" => attributes, "clientToken" => clientToken, "name" => name ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function create_attribute_group( attributes, clientToken, name, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "POST", "/attribute-groups", Dict{String,Any}( mergewith( _merge, Dict{String,Any}( "attributes" => attributes, "clientToken" => clientToken, "name" => name ), params, ), ); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_application(application) delete_application(application, params::Dict{String,<:Any}) Deletes an application that is specified either by its application ID or name. All associated attribute groups and resources must be disassociated from it before deleting an application. # Arguments - `application`: The name or ID of the application. """ function delete_application(application; aws_config::AbstractAWSConfig=global_aws_config()) return service_catalog_appregistry( "DELETE", "/applications/$(application)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_application( application, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "DELETE", "/applications/$(application)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ delete_attribute_group(attribute_group) delete_attribute_group(attribute_group, params::Dict{String,<:Any}) Deletes an attribute group, specified either by its attribute group ID or name. # Arguments - `attribute_group`: The name or ID of the attribute group that holds the attributes to describe the application. """ function delete_attribute_group( attributeGroup; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "DELETE", "/attribute-groups/$(attributeGroup)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function delete_attribute_group( attributeGroup, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "DELETE", "/attribute-groups/$(attributeGroup)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_attribute_group(application, attribute_group) disassociate_attribute_group(application, attribute_group, params::Dict{String,<:Any}) Disassociates an attribute group from an application to remove the extra attributes contained in the attribute group from the application's metadata. This operation reverts AssociateAttributeGroup. # Arguments - `application`: The name or ID of the application. - `attribute_group`: The name or ID of the attribute group that holds the attributes to describe the application. """ function disassociate_attribute_group( application, attributeGroup; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "DELETE", "/applications/$(application)/attribute-groups/$(attributeGroup)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_attribute_group( application, attributeGroup, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "DELETE", "/applications/$(application)/attribute-groups/$(attributeGroup)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ disassociate_resource(application, resource, resource_type) disassociate_resource(application, resource, resource_type, params::Dict{String,<:Any}) Disassociates a resource from application. Both the resource and the application can be specified either by ID or name. # Arguments - `application`: The name or ID of the application. - `resource`: The name or ID of the resource. - `resource_type`: The type of the resource that is being disassociated. """ function disassociate_resource( application, resource, resourceType; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "DELETE", "/applications/$(application)/resources/$(resourceType)/$(resource)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function disassociate_resource( application, resource, resourceType, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "DELETE", "/applications/$(application)/resources/$(resourceType)/$(resource)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_application(application) get_application(application, params::Dict{String,<:Any}) Retrieves metadata information about one of your applications. The application can be specified either by its unique ID or by its name (which is unique within one account in one region at a given point in time). Specify by ID in automated workflows if you want to make sure that the exact same application is returned or a ResourceNotFoundException is thrown, avoiding the ABA addressing problem. # Arguments - `application`: The name or ID of the application. """ function get_application(application; aws_config::AbstractAWSConfig=global_aws_config()) return service_catalog_appregistry( "GET", "/applications/$(application)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_application( application, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "GET", "/applications/$(application)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_associated_resource(application, resource, resource_type) get_associated_resource(application, resource, resource_type, params::Dict{String,<:Any}) Gets the resource associated with the application. # Arguments - `application`: The name or ID of the application. - `resource`: The name or ID of the resource associated with the application. - `resource_type`: The type of resource associated with the application. """ function get_associated_resource( application, resource, resourceType; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "GET", "/applications/$(application)/resources/$(resourceType)/$(resource)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_associated_resource( application, resource, resourceType, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "GET", "/applications/$(application)/resources/$(resourceType)/$(resource)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ get_attribute_group(attribute_group) get_attribute_group(attribute_group, params::Dict{String,<:Any}) Retrieves an attribute group, either by its name or its ID. The attribute group can be specified either by its unique ID or by its name. # Arguments - `attribute_group`: The name or ID of the attribute group that holds the attributes to describe the application. """ function get_attribute_group( attributeGroup; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "GET", "/attribute-groups/$(attributeGroup)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function get_attribute_group( attributeGroup, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "GET", "/attribute-groups/$(attributeGroup)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_applications() list_applications(params::Dict{String,<:Any}) Retrieves a list of all of your applications. Results are paginated. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The upper bound of the number of results to return (cannot exceed 25). If this parameter is omitted, it defaults to 25. This value is optional. - `"nextToken"`: The token to use to get the next page of results after a previous API call. """ function list_applications(; aws_config::AbstractAWSConfig=global_aws_config()) return service_catalog_appregistry( "GET", "/applications"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_applications( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "GET", "/applications", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_associated_attribute_groups(application) list_associated_attribute_groups(application, params::Dict{String,<:Any}) Lists all attribute groups that are associated with specified application. Results are paginated. # Arguments - `application`: The name or ID of the application. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The upper bound of the number of results to return (cannot exceed 25). If this parameter is omitted, it defaults to 25. This value is optional. - `"nextToken"`: The token to use to get the next page of results after a previous API call. """ function list_associated_attribute_groups( application; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "GET", "/applications/$(application)/attribute-groups"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_associated_attribute_groups( application, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "GET", "/applications/$(application)/attribute-groups", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_associated_resources(application) list_associated_resources(application, params::Dict{String,<:Any}) Lists all resources that are associated with specified application. Results are paginated. # Arguments - `application`: The name or ID of the application. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The upper bound of the number of results to return (cannot exceed 25). If this parameter is omitted, it defaults to 25. This value is optional. - `"nextToken"`: The token to use to get the next page of results after a previous API call. """ function list_associated_resources( application; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "GET", "/applications/$(application)/resources"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_associated_resources( application, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "GET", "/applications/$(application)/resources", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_attribute_groups() list_attribute_groups(params::Dict{String,<:Any}) Lists all attribute groups which you have access to. Results are paginated. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"maxResults"`: The upper bound of the number of results to return (cannot exceed 25). If this parameter is omitted, it defaults to 25. This value is optional. - `"nextToken"`: The token to use to get the next page of results after a previous API call. """ function list_attribute_groups(; aws_config::AbstractAWSConfig=global_aws_config()) return service_catalog_appregistry( "GET", "/attribute-groups"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET ) end function list_attribute_groups( params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "GET", "/attribute-groups", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ list_tags_for_resource(resource_arn) list_tags_for_resource(resource_arn, params::Dict{String,<:Any}) Lists all of the tags on the resource. # Arguments - `resource_arn`: The Amazon resource name (ARN) that specifies the resource. """ function list_tags_for_resource( resourceArn; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "GET", "/tags/$(resourceArn)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function list_tags_for_resource( resourceArn, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "GET", "/tags/$(resourceArn)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ sync_resource(resource, resource_type) sync_resource(resource, resource_type, params::Dict{String,<:Any}) Syncs the resource with current AppRegistry records. Specifically, the resource’s AppRegistry system tags sync with its associated application. We remove the resource's AppRegistry system tags if it does not associate with the application. The caller must have permissions to read and update the resource. # Arguments - `resource`: An entity you can work with and specify with a name or ID. Examples include an Amazon EC2 instance, an Amazon Web Services CloudFormation stack, or an Amazon S3 bucket. - `resource_type`: The type of resource of which the application will be associated. """ function sync_resource( resource, resourceType; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "POST", "/sync/$(resourceType)/$(resource)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function sync_resource( resource, resourceType, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "POST", "/sync/$(resourceType)/$(resource)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ tag_resource(resource_arn, tags) tag_resource(resource_arn, tags, params::Dict{String,<:Any}) Assigns one or more tags (key-value pairs) to the specified resource. Each tag consists of a key and an optional value. If a tag with the same key is already associated with the resource, this action updates its value. This operation returns an empty response if the call was successful. # Arguments - `resource_arn`: The Amazon resource name (ARN) that specifies the resource. - `tags`: The new or modified tags for the resource. """ function tag_resource(resourceArn, tags; aws_config::AbstractAWSConfig=global_aws_config()) return service_catalog_appregistry( "POST", "/tags/$(resourceArn)", Dict{String,Any}("tags" => tags); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function tag_resource( resourceArn, tags, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "POST", "/tags/$(resourceArn)", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tags" => tags), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ untag_resource(resource_arn, tag_keys) untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any}) Removes tags from a resource. This operation returns an empty response if the call was successful. # Arguments - `resource_arn`: The Amazon resource name (ARN) that specifies the resource. - `tag_keys`: A list of the tag keys to remove from the specified resource. """ function untag_resource( resourceArn, tagKeys; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "DELETE", "/tags/$(resourceArn)", Dict{String,Any}("tagKeys" => tagKeys); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function untag_resource( resourceArn, tagKeys, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "DELETE", "/tags/$(resourceArn)", Dict{String,Any}(mergewith(_merge, Dict{String,Any}("tagKeys" => tagKeys), params)); aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_application(application) update_application(application, params::Dict{String,<:Any}) Updates an existing application with new attributes. # Arguments - `application`: The name or ID of the application that will be updated. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"description"`: The new description of the application. - `"name"`: The new name of the application. The name must be unique in the region in which you are updating the application. """ function update_application(application; aws_config::AbstractAWSConfig=global_aws_config()) return service_catalog_appregistry( "PATCH", "/applications/$(application)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_application( application, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "PATCH", "/applications/$(application)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end """ update_attribute_group(attribute_group) update_attribute_group(attribute_group, params::Dict{String,<:Any}) Updates an existing attribute group with new details. # Arguments - `attribute_group`: The name or ID of the attribute group that holds the attributes to describe the application. # Optional Parameters Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are: - `"attributes"`: A JSON string in the form of nested key-value pairs that represent the attributes in the group and describes an application and its components. - `"description"`: The description of the attribute group that the user provides. - `"name"`: The new name of the attribute group. The name must be unique in the region in which you are updating the attribute group. """ function update_attribute_group( attributeGroup; aws_config::AbstractAWSConfig=global_aws_config() ) return service_catalog_appregistry( "PATCH", "/attribute-groups/$(attributeGroup)"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end function update_attribute_group( attributeGroup, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config(), ) return service_catalog_appregistry( "PATCH", "/attribute-groups/$(attributeGroup)", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET, ) end
use serde::{Deserialize, Serialize}; use crate::{error::RpelError, RpelPool}; #[derive(Debug, Deserialize, Serialize)] pub struct SelectItem { pub id: i64, pub name: Option<String>, } async fn select_name(pool: &RpelPool, name: &str) -> Result<Vec<SelectItem>, RpelError> { let client = pool.get().await?; let stmt = client .prepare( format!( " SELECT id, name FROM {} ORDER BY name ASC ", name ) .as_str(), ) .await?; let mut select_list = Vec::new(); for row in client.query(&stmt, &[]).await? { select_list.push(SelectItem { id: row.try_get(0)?, name: row.try_get(1)?, }) } Ok(select_list) } impl SelectItem { pub async fn company_all(pool: &RpelPool) -> Result<Vec<SelectItem>, RpelError> { Ok(select_name(pool, "companies").await?) } pub async fn contact_all(pool: &RpelPool) -> Result<Vec<SelectItem>, RpelError> { Ok(select_name(pool, "contacts").await?) } pub async fn department_all(pool: &RpelPool) -> Result<Vec<SelectItem>, RpelError> { Ok(select_name(pool, "departments").await?) } pub async fn kind_all(pool: &RpelPool) -> Result<Vec<SelectItem>, RpelError> { Ok(select_name(pool, "kinds").await?) } pub async fn post_all(pool: &RpelPool, go: bool) -> Result<Vec<SelectItem>, RpelError> { let client = pool.get().await?; let stmt = client .prepare( " SELECT id, name FROM posts WHERE go = $1 ORDER BY name ASC ", ) .await?; let mut posts = Vec::new(); for row in client.query(&stmt, &[&go]).await? { posts.push(SelectItem { id: row.try_get(0)?, name: row.try_get(1)?, }); } Ok(posts) } pub async fn rank_all(pool: &RpelPool) -> Result<Vec<SelectItem>, RpelError> { Ok(select_name(pool, "ranks").await?) } pub async fn scope_all(pool: &RpelPool) -> Result<Vec<SelectItem>, RpelError> { Ok(select_name(pool, "scopes").await?) } pub async fn siren_type_all(pool: &RpelPool) -> Result<Vec<SelectItem>, RpelError> { Ok(select_name(pool, "siren_types").await?) } }
// //Created by xuzhuoxi //on 2019-03-16. //@author xuzhuoxi // package lang import ( "fmt" "image" "image/draw" "testing" ) func TestTypeEqual(t *testing.T) { a := 1 b := uint16(1) c := 2 fmt.Println(TypeEqual(a, b)) fmt.Println(TypeEqual(a, c)) } func TestEqual(t *testing.T) { a := []uint16{1, 2, 3} b := []int16{1, 2, 3} c := []interface{}{1, 2, 3} d := []uint16{1, 2, 2} fmt.Println(Equal(a, b)) fmt.Println(Equal(a, c)) fmt.Println(Equal(b, c)) fmt.Println(Equal(a, d)) } func TestNil(t *testing.T) { var a []uint16 var b []uint16 fmt.Println(TypeEqual(a, b)) } func TestPointer(t *testing.T) { src := image.NewGray(image.Rect(0, 0, 2, 2)) dst := src fmt.Println(src == dst) } func TestPointer2(t *testing.T) { src := image.NewGray(image.Rect(0, 0, 2, 2)) var src1 image.Image = src var src2 draw.Image = src fmt.Println(src1 == src2) }
import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:cake_wallet/palette.dart'; import 'package:flutter/foundation.dart'; import 'package:provider/provider.dart'; import 'package:cake_wallet/theme_changer.dart'; import 'package:cake_wallet/themes.dart'; import 'package:cake_wallet/generated/i18n.dart'; class EnterPinCode extends StatefulWidget { const EnterPinCode(this.currentPinLength, this.currentPin); final int currentPinLength; final List<int> currentPin; @override EnterPinCodeState createState() => EnterPinCodeState(currentPinLength, currentPin); } class EnterPinCodeState extends State<EnterPinCode> { EnterPinCodeState(this.pinLength, this.currentPin); final _gridViewKey = GlobalKey(); final _closeButtonImage = Image.asset('assets/images/close_button.png'); final _closeButtonImageDarkTheme = Image.asset('assets/images/close_button_dark_theme.png'); static final deleteIconImage = Image.asset('assets/images/delete_icon.png'); final int pinLength; final List<int> currentPin; List<int> pin; double _aspectRatio = 0; void _calcualteCurrentAspectRatio() { final renderBox = _gridViewKey.currentContext.findRenderObject() as RenderBox; final cellWidth = renderBox.size.width / 3; final cellHeight = renderBox.size.height / 4; if (cellWidth > 0 && cellHeight > 0) { _aspectRatio = cellWidth / cellHeight; } setState(() {}); } @override void initState() { super.initState(); pin = List<int>.filled(pinLength, null); WidgetsBinding.instance.addPostFrameCallback(_afterLayout); } void _afterLayout(dynamic _) => _calcualteCurrentAspectRatio(); @override Widget build(BuildContext context) { final _themeChanger = Provider.of<ThemeChanger>(context); final _isDarkTheme = _themeChanger.getTheme() == Themes.darkTheme; return Scaffold( backgroundColor: Theme.of(context).backgroundColor, appBar: CupertinoNavigationBar( leading: ButtonTheme( minWidth: double.minPositive, child: FlatButton( onPressed: () { Navigator.pop(context, false); }, child: _isDarkTheme ? _closeButtonImageDarkTheme : _closeButtonImage), ), backgroundColor: Theme.of(context).backgroundColor, border: null), body: SafeArea( child: Container( padding: EdgeInsets.only(left: 40.0, right: 40.0, bottom: 40.0), child: Column( children: <Widget>[ Spacer(flex: 2), Text(S.of(context).enter_your_pin, style: TextStyle(fontSize: 24, color: Palette.wildDarkBlue)), Spacer(flex: 3), Container( width: 180, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: List.generate(pinLength, (index) { const size = 10.0; final isFilled = pin[index] != null; return Container( width: size, height: size, decoration: BoxDecoration( shape: BoxShape.circle, color: isFilled ? Palette.deepPurple : Colors.transparent, border: Border.all(color: Palette.wildDarkBlue), )); }), ), ), Spacer(flex: 3), Flexible( flex: 24, child: Container( key: _gridViewKey, child: _aspectRatio > 0 ? GridView.count( crossAxisCount: 3, childAspectRatio: _aspectRatio, physics: const NeverScrollableScrollPhysics(), children: List.generate(12, (index) { if (index == 9) { return Container( margin: EdgeInsets.all(5.0), decoration: BoxDecoration( shape: BoxShape.circle, color: _isDarkTheme ? PaletteDark.darkThemePinButton : Palette.darkGrey, ), ); } else if (index == 10) { index = 0; } else if (index == 11) { return Container( margin: EdgeInsets.all(5.0), child: FlatButton( onPressed: () { _pop(); }, color: _isDarkTheme ? PaletteDark.darkThemePinButton : Palette.darkGrey, shape: CircleBorder(), child: deleteIconImage, ), ); } else { index++; } return Container( margin: EdgeInsets.all(5.0), child: FlatButton( onPressed: () { _push(index); }, color: _isDarkTheme ? PaletteDark.darkThemePinDigitButton : Palette.creamyGrey, shape: CircleBorder(), child: Text('$index', style: TextStyle( fontSize: 23.0, color: Palette.blueGrey)), ), ); }), ) : null)) ], ), )), ); } void _showIncorrectPinDialog(BuildContext context) async { await showDialog<void>( context: context, builder: (BuildContext context) { return AlertDialog( content: Text(S.of(context).pin_is_incorrect), actions: <Widget>[ FlatButton( child: Text(S.of(context).ok), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }); } void _push(int num) { if (_pinLength() >= pinLength) { return; } for (var i = 0; i < pin.length; i++) { if (pin[i] == null) { setState(() => pin[i] = num); break; } } final currentPinLength = _pinLength(); if (currentPinLength == pinLength) { if (listEquals<int>(pin, currentPin)) { Navigator.pop(context, true); } else { Navigator.pop(context, false); _showIncorrectPinDialog(context); } } } void _pop() { if (_pinLength() == 0) { return; } for (var i = pin.length - 1; i >= 0; i--) { if (pin[i] != null) { setState(() => pin[i] = null); break; } } } int _pinLength() { return pin.fold(0, (v, e) { if (e != null) { return v + 1; } return v; }); } }
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #define MAX 10 typedef struct TipoCelula *TipoApontador; typedef int TipoChave; typedef struct TipoItem { TipoChave Chave; /* outros componentes */ } TipoItem; typedef struct TipoCelula { TipoItem Item; TipoApontador Prox; } TipoCelula; typedef struct TipoFila { TipoApontador Frente, Tras; } TipoFila; void FFVazia(TipoFila *Fila) { Fila->Frente = (TipoApontador) malloc(sizeof(TipoCelula)); Fila->Tras = Fila->Frente; Fila->Frente->Prox = NULL; } int Vazia(TipoFila Fila) { return (Fila.Frente == Fila.Tras); } void Enfileira(TipoItem x, TipoFila *Fila) { Fila->Tras->Prox = (TipoApontador) malloc(sizeof(TipoCelula)); Fila->Tras = Fila->Tras->Prox; Fila->Tras->Item = x; Fila->Tras->Prox = NULL; } void Desenfileira(TipoFila *Fila, TipoItem *Item) { TipoApontador q; if (Vazia(*Fila)) { printf("Erro fila esta vazia\n"); return; } q = Fila->Frente; Fila->Frente = Fila->Frente->Prox; *Item = Fila->Frente->Item; free(q); } void Imprime(TipoFila Fila) { TipoApontador Aux; Aux = Fila.Frente->Prox; while (Aux != NULL) { printf("%d\n", Aux->Item.Chave); Aux = Aux->Prox; } } int main(int argc, char *argv[]) { struct timeval t; TipoFila fila; TipoItem item; int vetor[MAX]; int i, j, k, n; gettimeofday(&t,NULL); srand((unsigned int)t.tv_usec); FFVazia(&fila); /*Gera uma permutacao aleatoria de chaves entre 1 e MAX*/ for(i = 0; i < MAX; i++) vetor[i] = i + 1; for(i = 0; i < MAX; i++) { k = (int) (10.0 * rand()/(RAND_MAX + 1.0)); j = (int) (10.0 * rand()/(RAND_MAX + 1.0)); n = vetor[k]; vetor[k] = vetor[j]; vetor[j] = n; } /*Insere cada chave na lista */ for (i = 0;i < MAX; i++) { item.Chave = vetor[i]; Enfileira(item, &fila); printf("Enfileirou: %d \n", item.Chave); } /*Desenfieleira cada chave */ for (i = 0;i < MAX; i++) { Desenfileira(&fila, &item); printf("Desenfileirou: %d \n", item.Chave); } return 0; }
import token from '../utils/token/color' const brandMono = ({ text, color }) => { const colorTextObject = { gray: token('gray3'), white: token('white'), red: token('primary1'), } color.text = colorTextObject[text] || colorTextObject.gray color.brand = color.text } const brandColor = ({ text, color }) => { const colorTextObject = { black: token('gray1'), white: token('white'), } color.text = colorTextObject[text] || colorTextObject.black color.brand = token('primary1') } export default ({ mono, text, color }) => { if (mono) { brandMono({ text: mono, color }) } else { brandColor({ text, color }) } }
(ns claro.data.tree.utils (:require [claro.data.protocols :as p])) (defn- can-resolve? [tree resolvable->resolved] (and (not (p/resolved? tree)) ;; it seems the following check is slower than just trying to apply the ;; resolution ... #_(some resolvable->resolved (p/resolvables tree)))) (defn apply-resolution [tree resolvable->resolved] (if (can-resolve? tree resolvable->resolved) (p/apply-resolved-values tree resolvable->resolved) tree)) (def all-resolvables-xf "Transducer to collect all resolvables in a seq of `ResolvableTree`values." (mapcat #(p/resolvables* %)))
package io.smooth.redux.harmony import io.smooth.redux.SmoothState import io.smooth.redux.StateSection import io.smooth.redux.activate import io.smooth.redux.deActivate object HarmonyUtils { fun SmoothState.reactOnUpdate(updatedSection: StateSection): SmoothState { var updatedState = this this.rules?.forEach { if (it.canApplyModification.invoke(updatedSection)) { it.getModifications(this, updatedSection)?.also { it.activateSections?.forEach { it.getSectionsToModify(this).forEach { updatedState = updatedState.activate(it::class) } } it.deactivateSections?.forEach { it.getSectionsToModify(this).forEach { updatedState = updatedState.deActivate(it::class) } } } } } return updatedState } }
import 'jest-extended' import axios from '../src/client' import fieldsMethods from '../src/api/fields' import { testApiKey } from '../config' describe('fields', () => { const client = fieldsMethods(axios(testApiKey)) it('gets account fields', async () => { await expect(client .getFields()) .resolves .toBeArray() }) })
package io.github.kevinmhankes.jokeapi.ui import android.os.Bundle import androidx.arch.core.executor.testing.CountingTaskExecutorRule import androidx.fragment.app.testing.FragmentScenario import androidx.fragment.app.testing.launchFragmentInContainer import androidx.lifecycle.MutableLiveData import androidx.test.espresso.Espresso import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import io.github.kevinmhankes.jokeapi.R import io.github.kevinmhankes.jokeapi.ui.fragment.JokeDetailFragment import io.github.kevinmhankes.jokeapi.ui.viewmodel.JokeDetailView import io.github.kevinmhankes.jokeapi.ui.viewmodel.JokeDetailViewModel import io.github.kevinmhankes.jokeapi.util.InjectKoinModuleRule import io.github.kevinmhankes.jokeapi.util.JOKE_ID import org.junit.Before import org.junit.ClassRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module /** * @author Kevin. * Created/Modified on February 17, 2021 */ @RunWith(AndroidJUnit4::class) class JokeDetailFragmentTest { private lateinit var scenario: FragmentScenario<JokeDetailFragment> private val mockJokeDetail = MutableLiveData<JokeDetailView>() private val bundle = Bundle() @Rule @JvmField val countingTaskExecutorRule = CountingTaskExecutorRule() companion object { lateinit var mockViewModel: JokeDetailViewModel @ClassRule @JvmField val koinRule = InjectKoinModuleRule( module { viewModel { mockViewModel } } ) } @Before fun setUp() { bundle.putInt(JOKE_ID, 1) mockViewModel = mock { on { jokeDetail } doReturn mockJokeDetail } mockJokeDetail.postValue(JokeDetailView(1, "Spooky","Why did the ghost go inside the bar?", "For the Boos.")) scenario = launchFragmentInContainer(fragmentArgs = bundle) } @Test fun testJokeDetail() { Espresso.onView(ViewMatchers.withId(R.id.joke_category)) .check(matches(withText("Spooky"))) Espresso.onView(ViewMatchers.withId(R.id.joke_setup)) .check(matches(withText("Why did the ghost go inside the bar?"))) Espresso.onView(ViewMatchers.withId(R.id.joke_delivery)) .check(matches(withText("For the Boos."))) } }
-- database: trino; tables: sample_jdbc_table; groups: trino_convention -- delimiter: |; ignoreOrder: false; types: BIGINT|VARCHAR --! SELECT * FROM sample_jdbc_table ORDER BY id; --! 1|C| 2|null| 3|A|
package io.webapp.module.system.role.basic.domain.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * [ ] * * @author yandanyang * @version 1.0 * @date 2019/3/27 0027 下午 15:27 * @since JDK1.8 */ @Data public class RoleSelectedVO extends RoleVO { @ApiModelProperty("角色名称") private Boolean selected; }
; edit date in 2010/05/04 20:37 list P=PIC16F84A INCLUDE "P16F84A.INC" __CONFIG _HS_OSC & _WDT_ON & _PWRTE_ON & _CP_OFF ARG0 EQU 0x0C ;引数用変数1 ARG1 EQU 0x0D ;引数用変数2 ARG2 EQU 0x0E ;引数用変数3 SELC EQU 0x0F ;アクション選択カウント変数 FLGS EQU 0x10 ;PICリセット用フラグ WREGTMP EQU 0x11 ;汎用Wレジスタ退避変数 ACMEM1 EQU 0x12 ;ACTION関数用変数1 ACMEM2 EQU 0x13 ;ACTION関数用変数2 ACMEM3 EQU 0x14 ;ACTION関数用変数3 WTMEM1 EQU 0x15 ;WAIT関数用変数1 WTMEM2 EQU 0x16 ;WAIT関数用変数2 WTMEM3 EQU 0x17 ;WAIT関数用変数3 WTMEM4 EQU 0x18 ;WAIT関数用変数4 WTARG0 EQU 0x19 ;WAIT関数用ARG0退避変数 BPMEM1 EQU 0x1A ;BEEP関数用変数1 BPMEM2 EQU 0x1B ;BEEP関数用変数2 BPMEM3 EQU 0x1C ;BEEP関数用変数3 BPMEM4 EQU 0x1D ;BEEP関数用変数4 BPARG0 EQU 0x1E ;BEEP関数用ARG0退避変数 BPARG1 EQU 0x1F ;BEEP関数用ARG1退避変数 PSMEM1 EQU 0x20 ;PLAYSCALE関数用変数1 PSMEM2 EQU 0x21 ;PLAYSCALE関数用変数2 PSMEM3 EQU 0x22 ;PLAYSCALE関数用変数3 PSMEM4 EQU 0x23 ;PLAYSCALE関数用変数4 PSWREG EQU 0x24 ;PLAYSCALE関数用Wレジスタ退避変数 PSARG0 EQU 0x25 ;PLAYSCALE関数用ARG0退避変数 DLWREG EQU 0x26 ;DRAWLED関数用Wレジスタ退避変数 DSMEM1 EQU 0x27 ;DRAWSEG関数用変数1 DSARG0 EQU 0x28 ;DRAWSEG関数用ARG0退避変数 DSWREG EQU 0x29 ;DRAWSEG関数用Wレジスタ退避変数 INTRMEM1 EQU 0x2A ;割込み用変数1 INTRMEM2 EQU 0x2B ;割込み用変数2 INTRWREG EQU 0x2C ;割込み用Wレジスタ退避変数 INTRARG0 EQU 0x2D ;割込み用ARG0退避変数 SEGNUM EQU 0x2E ;8セグ表示用変数 BLEDNUM EQU 0x2F ;8ビットLED表示用変数 RLEDNUM EQU 0x30 ;ルーレットLED表示用変数 DRAWFLG EQU 0x31 ;描画用フラグ変数 ;------------------フラグ分布------------------ ;0-3 :描画フラグ1,2,3,4 ;4-5 :描画選択カウント ;6 :SEGNUM変数の上位4ビットが0でも左側の8セグに表示するか ;7 :描画使用フラグ ;------------------------------------------- SWFLG EQU 0x32 ;スイッチ用フラグ変数 ;------------------フラグ分布------------------ ;0-2 :スイッチフラグ1,2,3 ;7 :スイッチ使用フラグ ;------------------------------------------- ORG 0 GOTO MAIN ORG 0x04 GOTO INTR INTR BTFSC FLGS, 1 ;リセットフラグが1ならば RETFIE ;割込み許可で終了 CLRWDT ;ウォッチドックタイマクリア BTFSS FLGS, 0 ;リセット許可フラグが0なら GOTO C_ESC_SKIP ;リセットボタンのチャックを飛ばす BTFSS PORTA, 4 ;3番目のスイッチが押されていたら BSF FLGS, 1 ;リセットフラグを1に C_ESC_SKIP BTFSS SWFLG, 7 ;スイッチ使用フラグが0ならば GOTO C_SW_SKIP ;スイッチチェックを飛ばす BTFSS PORTA, 2 BSF SWFLG, 0 BTFSS PORTA, 3 BSF SWFLG, 1 BTFSS PORTA, 4 BSF SWFLG, 2 C_SW_SKIP MOVWF INTRWREG ;Wレジスタ退避 BTFSS DRAWFLG, 7 ;描画使用フラグが0ならば GOTO D_RET_END ;描画処理をせずに終了処理へ MOVLW B'1111' ANDWF DRAWFLG, W ;DRAWFLGの下位4ビットと論理和をとって BTFSC STATUS, Z ;ゼロならば GOTO D_RET_END ;描画処理をせずに終了処理へ GOTO D_RET_SKIP ;描画処理へ D_RET_END BCF INTCON, T0IF ;割込みフラグをリセット MOVLW 0xFF MOVWF PORTB ;PORTBの全出力をHIに MOVF INTRWREG, W ;退避していたWレジスタを復元 RETFIE ;割込み許可で終了 D_RET_SKIP MOVF ARG0, W MOVWF INTRARG0 ;ARG0変数退避 SWAPF DRAWFLG, W ;DRAWFLGを入れ替えて、Wレジスタに代入し ADDLW B'1' ;1を加算して ANDLW B'11' ;下位2ビットのみ取り出して MOVWF INTRMEM1 ;INTRMEM1とINTMEM2変数に代入 MOVWF INTRMEM2 SWAPF INTRMEM1, F ;加算された描画選択カウントを上下入れ替えて MOVF DRAWFLG, W ; ANDLW B'11001111' ; IORWF INTRMEM1, W ; MOVWF DRAWFLG ;DRAWFLG変数に戻す CLRF PCLATH ;上位プログラムカウンタを0に MOVF INTRMEM2, W ADDWF PCL, F ;下位プログラムカウンタに描画選択カウントを加算 GOTO INTR_DRAW_1 ;描画処理1へ GOTO INTR_DRAW_2 ;描画処理2へ GOTO INTR_DRAW_3 ;描画処理3へ GOTO INTR_DRAW_4 ;描画処理4へ INTR_DRAW_1 BTFSS DRAWFLG, 0 GOTO INTR_DRAW_END ;描画フラグ1が0ならば描画処理終了へ MOVLW B'0' MOVWF ARG0 MOVF SEGNUM, W ;引数1に0を、WレジスタにSEGNUM変数の値を代入し CALL DRAWSEG ;DRAWSEG関数呼び出し BCF INTCON, T0IF ;割込みフラグをリセット GOTO INTR_DRAW_END ;描画処理終了へ INTR_DRAW_2 BTFSS DRAWFLG, 1 GOTO INTR_DRAW_END ;描画フラグ2が0ならば描画処理終了へ BTFSC DRAWFLG, 6 ;SEGNUM変数の上位ビットアンチェックフラグが1ならば GOTO INTR_DRAW_2SKIP ;常に上位ビットも8セグに表示するようにする MOVF SEGNUM, W ANDLW B'11110000' BTFSC STATUS, Z GOTO INTR_DRAW_END ;SEGNUM変数の上位ビットが0ならば何もせずに描画処理終了へ INTR_DRAW_2SKIP MOVLW B'1' MOVWF ARG0 MOVF SEGNUM, W CALL DRAWSEG ;引数1に1を、WレジスタにSEGNUM変数の値を代入し、DRAWSEG関数呼び出し BCF INTCON, T0IF ;割込みフラグをリセット GOTO INTR_DRAW_END ;描画処理終了へ INTR_DRAW_3 BTFSS DRAWFLG, 2 GOTO INTR_DRAW_END ;描画フラグ3が0ならば描画処理終了へ MOVLW B'11' MOVWF ARG0 ;引数1に、B'11'を代入して COMF BLEDNUM, W ;BLEDNUM変数を反転してWレジスタに代入し CALL DRAWLED ;DRAWLED関数呼び出し BCF INTCON, T0IF ;割込みフラグをリセット GOTO INTR_DRAW_END ;描画処理終了へ INTR_DRAW_4 BTFSS DRAWFLG, 3 GOTO INTR_DRAW_END ;描画フラグ4が0ならば描画処理終了へ MOVLW B'10' MOVWF ARG0 ;引数1に、B'10'を代入して COMF RLEDNUM, W ;RLEDNUM変数を反転してWレジスタに代入し CALL DRAWLED ;DRAWLED関数呼び出し BCF INTCON, T0IF ;割込みフラグをリセット INTR_DRAW_END MOVF INTRARG0, W MOVWF ARG0 ;退避していたARG0変数を復元 MOVF INTRWREG, W ;退避していたWレジスタを復元 RETFIE ;割込み許可で終了 MAIN BSF STATUS, RP0 ;バンク1を選択 CLRF TRISB ;PORTBの入出力設定を、全出力に MOVLW B'10000110' ;プリスケーラをTMR0に使用し MOVWF OPTION_REG ;スケールを1:128に BCF STATUS, RP0 ;バンク0を選択 MOVLW B'10100000' MOVWF INTCON ;TMR0割込み、グローバル割り込みを許可 MOVLW B'11111111' IORWF PORTB, F ;PORTBの出力をすべてHIに CLRF TMR0 CLRF SELC CLRF FLGS CLRF DRAWFLG CLRF SEGNUM CLRF BLEDNUM CLRF RLEDNUM CALL WAIT400MS CALL INITSWITCH ;スイッチ使用設定 CALL INITLED ;LED使用設定 BSF DRAWFLG, 0 ; BSF DRAWFLG, 1 ;描画フラグ1,2を1に MAIN_LOOP CALL CLRSW ;スイッチフラグリセット関数呼び出し CALL WAIT400MS ;スイッチ用ウェイト MOVF SELC, W MOVWF SEGNUM ;SEGNUM変数に、SELC変数を代入 MOVF SELC, W ;SELC変数の内容をWレジスタに代入 BTFSC SWFLG, 2 ;スイッチフラグ2が1ならば CALL ACTION ;ACTION関数呼び出し BCF FLGS, 0 ;リセット許可フラグを0に BTFSC SWFLG, 0 ;スイッチフラグ1が1ならば GOTO SEL_DEC ;SELC変数を減算する BTFSC SWFLG, 1 ;スイッチフラグ2が1ならば GOTO SEL_INC ;SELC変数を加算する GOTO MAIN_LOOP SEL_INC INCF SELC, F MOVF SELC, W SUBLW D'8' BTFSS STATUS, C ;SELC変数が、8を超えたら GOTO INC_OVER GOTO MAIN_LOOP INC_OVER CLRF SELC ;SELC変数を0に GOTO MAIN_LOOP SEL_DEC DECF SELC, F MOVF SELC, W XORLW 0xFF BTFSC STATUS, Z ;SELC変数が0のときに、減算したら GOTO DEC_ZERO GOTO MAIN_LOOP DEC_ZERO MOVLW D'8' MOVWF SELC ;SELC変数を8に GOTO MAIN_LOOP ;MAIN ACTION FUNCTION ACTION MOVWF ACMEM1 ;Wレジスタの内容を、ACMEM1変数へ CALL WAIT400MS MOVF ACMEM1, W SUBLW D'8' BTFSS STATUS, C ;ACMEM1変数の値が8を超えていたら RETURN ;終了 MOVF ACMEM1, W CLRF PCLATH ;上位プログラムカウンタを0に ADDWF PCL, F ;下位プログラムカウンタの内容に、ACMEM1変数の値を代入 GOTO ACT0 GOTO ACT1 GOTO ACT2 GOTO ACT3 GOTO ACT4 GOTO ACT5 GOTO ACT6 GOTO ACT7 GOTO ACT8 ;実験1 図1のLED 駆動回路1を用いて8ビットの2進数の値を1秒間隔で00000000 から00001111 までの値を順次発光させるプログラムを作れ。 ACT0 BSF FLGS, 0 ;リセット許可フラグを1に CLRF DRAWFLG ;描画フラグ用変数をリセット CALL INITLED ;LED使用設定 BSF DRAWFLG, 2 ;描画フラグ3を1に CLRF BLEDNUM ACTION_LOOP0 CALL WAIT1SEC INCF BLEDNUM, F MOVF BLEDNUM, W XORLW B'00001111' BTFSS STATUS, Z GOTO ACTION_LOOP0 ;BLEDNUM変数の値がB'00001111'になったらGOTOをスキップ CALL WAIT1SEC ;1秒待って終わる GOTO ACTION_END ;実験2 2つの8ゼグメントLED を制御して異なる2つの16進数値をあたかも同時に表示されているようするプログラムを作り実行させよ。 ACT1 BSF FLGS, 0 ;リセット許可フラグを1に BSF DRAWFLG, 6 ;SEGHI表示フラグを1に CLRF SEGNUM CLRF DRAWFLG CALL INITLED ;LED使用設定 BSF DRAWFLG, 0 BSF DRAWFLG, 1 ;描画フラグ1,2を1に ACTION_LOOP1 CALL WAIT100MS INCF SEGNUM, F ;100msごとに、SEGNUM変数の値を加算 GOTO ACTION_LOOP1 GOTO ACTION_END ;実験3 圧電スピーカ回路を利用して1 KH zの信号を鳴らすプログラムを作り実行させよ。 ←1秒間再生します ACT2 BSF FLGS, 0 ;リセット許可フラグを1に BCF DRAWFLG, 7 ;描画使用フラグを0に CALL INITBEEP ;ブザー使用設定 MOVLW D'250' MOVWF ARG2 MOVLW D'4' MOVWF ARG1 MOVLW D'100' MOVWF ARG0 MOVLW D'1' CALL BEEP ;1KHzの音を1秒間鳴らすように設定し、BEEP関数呼び出し GOTO ACTION_END ;実験4 圧電スピーカ回路を使って1 KH zの信号を2秒間発振し4秒間発振を止める無限ループプログラムを作り実行させよ。 ACT3 BSF FLGS, 0 ;リセット許可フラグを1に BCF DRAWFLG, 7 ;描画使用フラグを0に CALL INITBEEP ;ブザー使用設定 ACTION_LOOP3 MOVLW D'250' MOVWF ARG2 MOVLW D'8' MOVWF ARG1 MOVLW D'100' MOVWF ARG0 MOVLW D'1' CALL BEEP ;1KHzの音を2秒間鳴らすように設定し、BEEP関数呼び出し MOVLW D'250' MOVWF ARG1 MOVLW D'228' MOVWF ARG0 MOVLW D'7' CALL WAIT ;4秒間待つように設定し、WAIT関数呼び出し GOTO ACTION_LOOP3 GOTO ACTION_END ;実験5 タッチセンサーにタッチすると図3のLED 駆動回路1の出力が点滅を繰り返すプログラムを作り実行させよ。繰り返す周期は1秒にすること。 ACT4 BSF FLGS, 0 ;リセット許可フラグを1に CALL INITTOUCHSENSOR ;タッチセンサー使用設定 ACTION_LOOP4 BTFSC PORTA, 0 GOTO ACTION_LOOP4 ;タッチセンサーが触られるまで待つ CLRF BLEDNUM CLRF DRAWFLG CALL INITLED ;LED使用設定 BSF DRAWFLG, 2 ;描画フラグ3を1に ACTION_LOOP4_2 COMF BLEDNUM, F ;BLEDNUM変数を反転 CALL WAIT1SEC ;1秒待つ GOTO ACTION_LOOP4_2 GOTO ACTION_END ;実験6 3つのうちの1つのみを用いてスイッチを押した回数を表示回路1に表示するプログラムを作り実行させよ。 ACT5 BSF FLGS, 0 ;リセット許可フラグを1に CLRF SEGNUM CLRF BLEDNUM CLRF DRAWFLG CALL INITSWITCH ;スイッチ使用設定 CALL INITLED ;LED使用設定 BSF DRAWFLG, 0 ; BSF DRAWFLG, 1 ; BSF DRAWFLG, 2 ;描画フラグ1,2,3を1に CLRF ACMEM1 ACTION_LOOP5 CALL CLRSW ;スイッチフラグ1,2,3クリア CALL WAIT400MS ;スイッチ用ウェイト BTFSC SWFLG, 0 ;スイッチフラグ1が1ならば INCF BLEDNUM, F ;BLEDNUM変数を加算する BTFSC SWFLG, 1 ;スイッチフラグ2が1ならば CLRF BLEDNUM ;BLEDNUM変数をクリア MOVF BLEDNUM, W MOVWF SEGNUM ;SEGNUM変数にBLEDNUM変数の値を代入 GOTO ACTION_LOOP5 GOTO ACTION_END ;実験7 LED 駆動回路3を用いて数字の1からF までの数字を1秒間隔で順次表示していくプログラムをつくり実行させよ。 ←少し改造しました ACT6 BSF FLGS, 0 ;リセット許可フラグを1に CALL INITSWITCH ;スイッチ使用設定 CLRF DRAWFLG CALL INITLED ;描画使用設定 BSF DRAWFLG, 0 BSF DRAWFLG, 1 BSF DRAWFLG, 2 ;描画フラグ1,2,3を1に CLRF SEGNUM CLRF BLEDNUM ACTION_LOOP6 MOVLW D'10' ;100msを10回繰り返して1秒を作り出す MOVWF ACMEM1 ACTION_LOOP6_2 CALL CLRSW ;スイッチフラグ1,2,3をクリア CALL WAIT100MS BTFSC SWFLG, 0 ;スイッチフラグ1が1ならば CLRF SEGNUM ;SEGNUM変数をクリア BTFSC SWFLG, 0 ;スイッチフラグ1が1ならば CLRF BLEDNUM ;BLEDNUM変数をクリア DECFSZ ACMEM1, F ;ACMEM1変数を減算して GOTO ACTION_LOOP6_2 ;0になったらGOTOをスキップ INCF SEGNUM, F ;SEGNUM変数を加算して BTFSC STATUS, Z ;一周したら INCF BLEDNUM, F ;BLEDNUM変数を加算 GOTO ACTION_LOOP6 GOTO ACTION_END ;実験8 LED 表示回路2を用いて高速で00000000 B から11111111 B まで変化させながら表示させスイッチキーを押したときに表示している値を ;LED 表示回路1に表示するプログラムを作り実行させよ。 ACT7 BSF FLGS, 0 ;リセット許可フラグを1に CALL INITSWITCH ;スイッチ使用設定 CLRF DRAWFLG CALL INITLED ;LED使用設定 BSF DRAWFLG, 0 BSF DRAWFLG, 1 BSF DRAWFLG, 2 ;描画フラグ1,2,3を1に CLRF SEGNUM CLRF BLEDNUM CLRF ACMEM1 ACTION_LOOP7 CALL CLRSW ;スイッチフラグ1,2,3をクリア CALL WAIT400MS ;スイッチ用ウェイト INCF BLEDNUM, F ;BLEDNUMを加算 BTFSS SWFLG, 0 ;スイッチフラグ1が1ならば GOTO ACTION_LOOP7 ;ループを抜ける MOVF BLEDNUM, W MOVWF SEGNUM ;SEGNUM変数に、BLEDNUM変数をコピー CALL WAIT1SEC GOTO ACTION_END ;オリジナル(3オクターブの音階再生プログラム) ACT8 BSF FLGS, 0 ;リセット許可フラグを1に CLRF DRAWFLG CALL INITSWITCH ;スイッチ使用設定 CALL INITLED ;LED使用設定 BSF DRAWFLG, 0 BSF DRAWFLG, 1 ;描画フラグ1,2を1に BSF DRAWFLG, 6 CLRF ACMEM1 CLRF ACMEM2 ACTION_LOOP8 CALL CLRSW ;スイッチ使用設定 CALL WAIT400MS ;スイッチ用ウェイト CLRF SEGNUM ;SEGNUM変数をクリアして MOVF ACMEM2, W ; IORWF SEGNUM, F ; SWAPF ACMEM1, W ; ANDLW B'11110000' ;上位4ビットにACMEM1変数の下位4ビットの内容を IORWF SEGNUM, F ;下位4ビットにACMEM2変数の下位4ビットの内容を代入する BTFSC SWFLG, 0 ;スイッチフラグ1が1ならば INCF ACMEM1, F ;ACMEM1変数を加算する MOVF ACMEM1, W SUBLW D'10' BTFSC STATUS, C ;ACMEM1変数の内容が、10以内ならば GOTO ACTION_SKIP8 ;通常処理へジャンプ CLRF ACMEM1 ;10を超えていたら、ACMEM1の内容をクリアして INCF ACMEM2, F ;ACMEM2の内容を加算 MOVF ACMEM2, W SUBLW D'3' ;ACMEM2が3を超えていなければ BTFSC STATUS, C GOTO ACTION_SKIP8 ;通常処理へ戻る CLRF ACMEM2 ;超えていれば、ACMEM2をクリア ACTION_SKIP8 BTFSS SWFLG, 1 ;スイッチフラグ2が1ならば GOTO ACTION_SKIP8_2 ;GOTO文を飛ばして、音階を再生する BCF DRAWFLG, 7 ;描画使用フラグを0に CALL INITBEEP ;ビープ使用設定 MOVLW D'20' MOVWF ARG0 MOVF SEGNUM, W ;SEGNUM変数の上位4ビットを半音に、下位4ビットをオクターブに設定して CALL PLAYSCALE ;PLAYSCALE関数呼び出し BSF DRAWFLG, 7 ;描画使用フラグを1に CALL INITSWITCH ;スイッチ使用設定 ACTION_SKIP8_2 GOTO ACTION_LOOP8 GOTO ACTION_END ACTION_END CALL INITLED ;LED使用設定 CALL INITSWITCH ;スイッチ使用設定 CALL CLRSW ;スイッチフラグ1,2,3をクリア MOVF DRAWFLG, W ANDLW B'11110000' ;DRAWFLG変数の下位4ビットを0にして ADDLW B'11' ;B'11'を加算する MOVWF DRAWFLG BCF DRAWFLG, 6 ;SEGHI表示フラグを0に RETURN ;1秒待つ関数 ;250*200*2 *10 = 1,000,000 us WAIT1SEC MOVLW D'250' MOVWF ARG1 MOVLW D'200' MOVWF ARG0 MOVLW D'2' CALL WAIT RETURN ;400ミリ秒待つ関数 ;250*160*1 *10 = 400,000 us WAIT400MS MOVLW D'250' MOVWF ARG1 MOVLW D'160' MOVWF ARG0 MOVLW D'1' CALL WAIT RETURN ;100ミリ秒待つ関数 ;250*40*1 *10 = 100,000 us WAIT100MS MOVLW D'250' MOVWF ARG1 MOVLW D'40' MOVWF ARG0 MOVLW D'1' CALL WAIT RETURN ;音階再生関数 ; 使用引数 : Wレジスタ = 音階(上位4ビット:半音、下位4ビット:オクターブ) ; 半音は0~10まで、オクターブは0~3まで可能 ; : ARG0 = 再生時間 (* 50ms) ; 例: Wレジスタ=0 && ARG0=20 (130Hzの音階を1秒間再生する) PLAYSCALE MOVWF PSWREG ;Wレジスタ退避 MOVWF PSMEM1 ;Wレジスタの下位4ビットを MOVWF PSMEM2 ; MOVLW B'1111' ; ANDWF PSMEM1, F ;PSMEM1に SWAPF PSMEM2, F ; ANDWF PSMEM2, W ;上位4ビットを MOVWF PSMEM2 ;PSMEM2とPSMEM3に代入する MOVWF PSMEM3 ; MOVF PSMEM1, W ;PSMEM1が SUBLW D'3' ;3を超えていたら BTFSS STATUS, C ; RETURN ;終了する MOVF PSMEM2, W ;PSMEM2が SUBLW D'10' ;10を超えていたら BTFSS STATUS, C ; RETURN ;終了する MOVF PSMEM2, W ;PSMEM2の半音を引数に CALL GETTONETIME ;半音の定数を取得し MOVWF PSMEM2 ;PSMEM2に代入 MOVF PSMEM3, W ;PSMEM3の半音を引数に CALL GETTONECOUNT ;半音の定数を取得し MOVWF PSMEM3 ;PSMEM3に代入 MOVF PSMEM1, F ;PSMEM1のオクターブが BTFSC STATUS, Z ;0ならば GOTO SKIP_2MUL ;オクターブ上げ処理を飛ばす LOOP_2MUL RRF PSMEM2, F ;オクターブの数の分だけ BCF PSMEM2, 7 ;PSMEM2を2割する RLF PSMEM3, F ;オクターブの数の分だけ BCF PSMEM3, 0 ;PSMEM3を2倍する DECFSZ PSMEM1, F ;オクターブの数だけ繰り返したら GOTO LOOP_2MUL ;ループを抜ける SKIP_2MUL MOVF ARG0, W ;ARG0を MOVWF PSARG0 ;退避する MOVWF PSMEM4 ;ARG0にある再生時間をPSMEM4へ PLAY_LOOP MOVF PSMEM3, W ;50msになるように回数計算した MOVWF ARG2 ;PSMEM3をARG2へ MOVLW D'1' MOVWF ARG1 MOVF PSMEM2, W ;周波数を求めた MOVWF ARG0 ;PSMEM2をARG0へ MOVLW D'3' CALL BEEP ;ビープを鳴らす DECFSZ PSMEM4, F ;再生時間の数だけ50msを繰り返す GOTO PLAY_LOOP MOVF PSARG0, W MOVWF ARG0 ;ARG0復元 MOVF PSWREG, W ;Wレジスタ復元 RETURN ;ビープ再生関数 ; 使用引数 : Wレジスタ,ARG0 = 特殊周波数指定(求め方: X = ((1/Hz)*1000*100)/Y ;(X <= 255):: ARG0 = X, Wレジスタ = Y) ; : ARG1,ARG2 = 内部のループを何回するか(時間の求め方: ARG2*ARG1*ARG0*Wレジスタ*10us) ; : 推奨設定: ARG2 > ARG1 BEEP BCF PORTA, 3 ;ブザーを使用するためにRA3をLOWに MOVWF BPMEM1 ;Wレジスタの内容をBPMEM1に MOVF ARG0, W ; MOVWF BPARG0 ;ARG0の内容を退避 RRF ARG0, W ;ARG0の内容を2割して ANDLW B'1111111' ; MOVWF BPMEM2 ;BPMEM2に代入する MOVF ARG1, W ;ARG1の内容を退避 MOVWF BPARG1 ; MOVWF BPMEM3 ;ARG1の内容をBPMEM3に代入する BEEP_LOOP2 MOVF ARG2, W ; MOVWF BPMEM4 ;ARG2の内容をBPMEM4に代入する MOVF BPMEM2, W ;2割したARG0の内容を MOVWF ARG1 ;ARG1に代入 MOVF BPMEM1, W MOVWF ARG0 MOVLW D'1' BEEP_LOOP1 BCF PORTA, 2 ;ブザー系統の出力をLOWに CALL WAIT ;上で指定した時間だけウェイト BSF PORTA, 2 ;ブザー系統の出力をHIに CALL WAIT ;上で指定した時間だけウェイト DECFSZ BPMEM4, F ;BPMEM4が0になったら GOTO BEEP_LOOP1 ;ループを抜ける DECFSZ BPMEM3, F ;BPMEM3が0になったら GOTO BEEP_LOOP2 ;ブザーのループ終了 MOVF BPARG1, W MOVWF ARG1 ;退避したARG1を復元 MOVF BPARG0, W MOVWF ARG0 ;退避したARG0を復元 MOVF BPMEM1, W ;退避したWレジスタを復元 RETURN ;8セグ表示用関数 ; 使用引数 : Wレジスタ = 表示データ ; : ARG0   = セグメント選択(1:HighSeg, 0:LowSeg) DRAWSEG MOVWF DSWREG ;Wレジスタ退避 MOVWF DSMEM1 ;Wレジスタの内容をDSMEM1に MOVF ARG0, W MOVWF DSARG0 ;ARG0の内容を退避 BTFSC ARG0, 0 ;ARG0が1ならば GOTO DRAW_HIGHSEG ;HISEG描画処理へ MOVLW 0x0F ;下位4ビットを取り出し ANDWF DSMEM1, W ;Wレジスタに代入し CALL CONVSEG ;CONVSEG関数呼び出し MOVWF DSMEM1 ;結果をDSMEM1に代入 MOVLW B'01' ;LEDセレクト番号を指定 MOVWF ARG0 MOVF DSMEM1, W ;描画データをWレジスタに CALL DRAWLED ;DRAWLED関数呼び出し GOTO DRAWSEG_END ;終了処理へ DRAW_HIGHSEG SWAPF DSMEM1, F ;DSMEM1の上下入れ替え MOVLW 0x0F ;下位4ビット取り出し ANDWF DSMEM1, W ;Wレジスタへ代入し CALL CONVSEG ;CONVSEG関数呼び出し MOVWF DSMEM1 ;結果をDSMEM1に MOVLW B'00' ;LEDセレクト番号指定 MOVWF ARG0 MOVF DSMEM1, W ;描画データをWレジスタに代入し CALL DRAWLED ;DRAWLED関数呼び出し DRAWSEG_END MOVF DSARG0, W MOVWF ARG0 ;退避していたARG0の内容を復元 MOVF DSWREG, W ;退避していたWレジスタの内容を復元 RETURN ;LED表示関数 ; 使用引数 : Wレジスタ = 表示データ ; : ARG0 = LEDセレクト番号 DRAWLED MOVWF DLWREG ;Wレジスタの内容を退避 MOVF PORTA, W ;PORTAの状態を取り出し ANDLW B'11111100' ;下位2ビットを0にして IORWF ARG0, W ;ARG0のセレクト番号を書き込み MOVWF PORTA ;PORTAに代入 MOVF DLWREG, W ;表示データを MOVWF PORTB ;PORTBに出力 MOVF DLWREG, W ;退避していたWレジスタの内容を復元 RETURN ;ウェイト関数 ; 使用引数 : WREG, ARG0, ARG1 = 待ち時間( WREG*ARG0*ARG1*10(us) ) ; 推奨設定 : WREG < ARG0 < ARG1 WAIT MOVWF WREGTMP ;Wレジスタの内容を退避 MOVWF WTMEM1 ;Wレジスタの内容をWTMEM1に代入 MOVF ARG1, W ;ARG1の内容を MOVWF WTARG0 ;退避する MOVWF WTMEM2 ;さらにWTMEM2に代入する RRF WTMEM2, F ;ここでWTMEM2の内容を RRF WTMEM2, F ; RRF WTMEM2, F ;8割する MOVF WTMEM2, W ;WTMEM2の内容をWレジスタに書き込み RRF WTMEM2, F ;さらにWTMEM2の内容を2割して RRF WTMEM2, F ;擬似的に10割を作り出す ANDLW B'11111' ;Wレジスタに保存していた8割を MOVWF WTMEM3 ;余分なものを除いてWTMEM3へ代入 MOVF WTMEM2, W ;10割したWTMEM2をWレジスタに代入し ANDLW B'111' ;余分なものを取り除いて SUBWF WTMEM3, W ;WTMEM3からその数を引きWレジスタに代入 SUBWF ARG1, F ;さらにARG1からその数を引く ;以上の処理で長時間の待ち時間で誤差が ;大きくなりすぎないように調整している MOVF ARG1, W ;計算結果が SUBLW D'100' ;100を超えていたら BTFSS STATUS, C INCF ARG1, F ;補正として1引く WAIT_LOOP4 MOVF ARG0, W MOVWF WTMEM2 ;ARG0の内容をWTMEM2に代入 WAIT_LOOP3 MOVF ARG1, W MOVWF WTMEM3 ;ARG1の内容をWTMEM3に代入 WAIT_LOOP2 MOVLW D'10' MOVWF WTMEM4 ;WTMEM4に10を代入 WAIT_LOOP1 NOP NOP DECFSZ WTMEM4, F ;WTMEM4が0になったら GOTO WAIT_LOOP1 ;ループを抜ける DECFSZ WTMEM3, F ;WTMEM3が0になったら GOTO WAIT_LOOP2 ;ループを抜ける DECFSZ WTMEM2, F ;WTMEM2が0になったら GOTO WAIT_LOOP3 ;ループを抜ける DECFSZ WTMEM1, F ;WTMEM1が0になったら GOTO WAIT_LOOP4 ;ウェイトループ終了 MOVF WTARG0, W ;退避していたARG1の内容を MOVWF ARG1 ;復元する MOVF WREGTMP, W ;退避していたWレジスタの内容を復元 RETURN ; スイッチフラグクリア用関数 CLRSW MOVLW B'10000000' ANDWF SWFLG, F RETURN ; 初期化関数群 INITTOUCHSENSOR BSF STATUS, RP0 BSF TRISA, 0 BCF STATUS, RP0 BCF DRAWFLG, 7 RETURN INITCDS BSF STATUS, RP0 BSF TRISA, 1 BCF STATUS, RP0 BSF PORTA, 1 BCF DRAWFLG, 7 RETURN INITSWITCH BSF STATUS, RP0 BSF TRISA, 2 BSF TRISA, 3 BCF STATUS, RP0 CLRF SWFLG BSF SWFLG, 7 RETURN INITBEEP BSF STATUS, RP0 BCF TRISA, 2 BCF TRISA, 3 BCF STATUS, RP0 BCF SWFLG, 7 RETURN INITLED BSF STATUS, RP0 BCF TRISA, 0 BCF TRISA, 1 CLRF TRISB BCF STATUS, RP0 BSF DRAWFLG, 7 RETURN ;----------------定数用テーブル---------------- ORG 0x3C8 ;セグメント用表示定数テーブル CONVSEG MOVWF WREGTMP MOVLW 0x3 MOVWF PCLATH MOVF WREGTMP, W ADDWF PCL, F RETLW B'1000000' RETLW B'1111001' RETLW B'0100100' RETLW B'0110000' RETLW B'0011001' RETLW B'0010010' RETLW B'0000010' RETLW B'1011000' RETLW B'0000000' RETLW B'0010000' RETLW B'0001000' RETLW B'0000011' RETLW B'1000110' RETLW B'0100001' RETLW B'0000110' RETLW B'0001110' ;音階表示プログラム用定数テーブル GETTONETIME MOVWF WREGTMP MOVLW 0x3 MOVWF PCLATH MOVF WREGTMP, W ADDWF PCL, F RETLW D'255' RETLW D'241' RETLW D'227' RETLW D'214' RETLW D'202' RETLW D'191' RETLW D'180' RETLW D'170' RETLW D'161' RETLW D'152' RETLW D'143' RETLW D'135' ;音階表示プログラム用定数テーブル GETTONECOUNT MOVWF WREGTMP MOVLW 0x3 MOVWF PCLATH MOVF WREGTMP, W ADDWF PCL, F RETLW D'7' RETLW D'7' RETLW D'7' RETLW D'8' RETLW D'8' RETLW D'9' RETLW D'9' RETLW D'10' RETLW D'10' RETLW D'11' RETLW D'12' RETLW D'12' END
@file:JvmName("Utils") @file:JvmMultifileClass package test fun commonFun1() {} // TODO uncomment when generated value will also be private in bytecode //private val deletedVal1: Int = 20 private fun deletedFun1(): Int = 10 private fun changedFun1(arg: Int) {}
// Copyright by Barry G. Becker, 2017. Licensed under MIT License: http://www.opensource.org/licenses/MIT package com.barrybecker4.ui.dialogs import com.barrybecker4.ui.components.ScrollingTextArea import javax.swing._ import java.awt._ object OutputWindow { private val TEXT_FONT = new Font("Times-Roman", Font.PLAIN, 10) //NON-NLS } /** * Use this dialog to show the user a body of text * @author Barry Becker */ @SerialVersionUID(1L) class OutputWindow(title: String, parent: JFrame) extends AbstractDialog(parent) { protected var textArea: ScrollingTextArea = _ this.setTitle(title) this.setModal(false) showContent() override protected def createDialogContent: JComponent = { textArea = new ScrollingTextArea(40, 30) // if its editable then we can copy from it textArea.setEditable(true) textArea.setFont(OutputWindow.TEXT_FONT) textArea } /** Add this text to what is already there */ def appendText(text: String): Unit = { if (text != null) textArea.append(text) } /** Replace current text with this text */ def setText(text: String): Unit = { textArea.setText(text) } }
#include "modules/sway/mode.hpp" namespace waybar::modules::sway { Mode::Mode(const std::string& id, const Json::Value& config) : ALabel(config, "{}") { label_.set_name("mode"); if (!id.empty()) { label_.get_style_context()->add_class(id); } ipc_.subscribe(R"(["mode"])"); ipc_.signal_event.connect(sigc::mem_fun(*this, &Mode::onEvent)); // Launch worker worker(); dp.emit(); } void Mode::onEvent(const struct Ipc::ipc_response& res) { try { auto payload = parser_.parse(res.payload); if (payload["change"] != "default") { mode_ = payload["change"].asString(); } else { mode_.clear(); } dp.emit(); } catch (const std::exception& e) { std::cerr << "Mode: " << e.what() << std::endl; } } void Mode::worker() { thread_ = [this] { try { ipc_.handleEvent(); } catch (const std::exception& e) { std::cerr << "Mode: " << e.what() << std::endl; } }; } auto Mode::update() -> void { if (mode_.empty()) { event_box_.hide(); } else { label_.set_markup(fmt::format(format_, mode_)); if (tooltipEnabled()) { label_.set_tooltip_text(mode_); } event_box_.show(); } } } // namespace waybar::modules::sway
# rp This is a mono-repo. - [docs](/docs) is the frontend handlebars/bootstrap app deployed from Github pages - [lambda-app](/lambda-app) is the backend cloudformation/lambda backend ## Deploy Backend `npm run deploy-backend`
using System.Threading.Tasks; using Changey.Models; namespace Changey.Services { internal interface IChangeLogSerializer { Task<ChangeLog> Deserialize(string path); Task Serialize(ChangeLog changeLog, string path); Task Serialize(Version version, string path, bool header); } }
#include "module.hh" #include <cassert> #include <set> #include <iostream> #include "ptr_list.hh" #include "isa.hh" #include <utils/cli/err.hh> void Instruction::erase_from_parent() { parent().erase_ins(ins_iterator_t(this)); } void Instruction::dump(std::ostream &os) const { isa::dump(*this, os); } void BasicBlock::check() const { for (auto it = ins_begin(); it != ins_end(); ++it) { const auto &ins = *it; bool is_last = it + 1 == ins_end(); PANIC_IF(&ins.parent() != this, "invalid instruction parent"); PANIC_IF(isa::is_branch(ins) && !is_last, "branch instruction forbidden in the middle of a basicblock"); PANIC_IF(!isa::is_branch(ins) && is_last, "last instruction must must be a branch"); if (isa::is_branch(ins)) { for (const auto &t : isa::branch_targets(ins)) PANIC_IF(!_fun.get_bb(t), "branch to invalid basick block"); } } } void BasicBlock::erase_from_parent() { parent().erase_bb(*this); } ins_iterator_t BasicBlock::ins_move(BasicBlock &in_bb, ins_iterator_t in_beg, ins_iterator_t in_end, BasicBlock &out_bb, ins_iterator_t out_beg) { if (in_beg == in_end) // empty range return out_beg; bool same_block = &in_bb == &out_bb; assert(!same_block); //@TODO handle same block auto res = in_bb._ins.move(in_beg, in_end, out_bb._ins, out_beg); if (!same_block) { for (auto it = in_beg; it != out_beg; ++it) it->_parent = &out_bb; } return res; } Function::Function(Module &mod, const std::string &name, const std::vector<std::string> &args) : _mod(mod), _name(name), _args(args), _bb_entry(nullptr), _bb_unique_count(0) {} void Function::check() const { PANIC_IF(_bb_entry == nullptr, "Entry BB not set"); PANIC_IF(_bbs.index_of(const_bb_iterator_t(_bb_entry)) != 0, "Entry BB must be the first"); for (const auto &bb : _bbs) bb.check(); } BasicBlock *Function::get_bb(const std::string &label) { auto it = _bbs_labelsm.find(label); return it == _bbs_labelsm.end() ? nullptr : it->second; } const BasicBlock *Function::get_bb(const std::string &label) const { auto it = _bbs_labelsm.find(label); return it == _bbs_labelsm.end() ? nullptr : it->second; } bb_iterator_t Function::insert_bb(bb_iterator_t it, const std::string &label) { ++_bb_unique_count; std::string cpy_label = label.empty() ? ".L" + std::to_string(_bb_unique_count) : label; auto res = _bbs.emplace(it, *this, cpy_label); _bbs_labelsm.emplace(cpy_label, &*res); return res; } BasicBlock &Function::add_bb(const std::string &label) { return *insert_bb(bb_end(), label); } void Function::erase_bb(BasicBlock &bb) { _bbs_labelsm.erase(bb.label()); if (&bb == _bb_entry) _bb_entry = nullptr; _bbs.erase(bb_iterator_t(&bb)); } Function *Module::get_fun(const std::string &name) { auto it = _funs_map.find(name); return it == _funs_map.end() ? nullptr : it->second; } const Function *Module::get_fun(const std::string &name) const { auto it = _funs_map.find(name); return it == _funs_map.end() ? nullptr : it->second; } Function &Module::add_fun(const std::string &name, const std::vector<std::string> &args) { PANIC_IF(get_fun(name) != nullptr, "Function name taken"); auto &fun = *_funs.emplace(_funs.end(), *this, name, args); _funs_map.emplace(name, &fun); return fun; } void Module::check() const { for (const auto &f : _funs) f.check(); } std::unique_ptr<Module> Module::create() { return std::unique_ptr<Module>(new Module{}); } Module::Module() {}
export NEWS_API_KEY='5ce38f880c884e2488e2cd2e3419c108' export SECRET_KEY='<Flask WTF Secret Key>' python3.9 manage.py server
package api // EqChannel defines a channel receiving an array of Entry instance representing // equivalent file system entries type EqChannel chan<- []*Entry // Traversing is a function traversing a hierarchy of file system entries type Traversing func(conf *Config, src *Source, root *Entry, out chan *Entry) error // Traverse retrieves traversal results and returns them as a tree type Traverse func(conf *Config, src *Source, tr *Tree) error // Match takes Tree instances and determines equivalent file system entries type Match func(conf *Config, trees []*Tree, eqChan EqChannel) error
require 'net/http' module Spectre module Http class Request attr_accessor :uri, :headers, :body, :method, :options DEFAULT_OPEN_TIMEOUT = 3.freeze DEFAULT_READ_TIMEOUT = 3.freeze VALID_REQUEST_METHODS = %i[get post put patch delete].freeze GET = :get POST = :post DELETE = :delete PUT = :put PATCH = :patch RESPONSE = Struct.new(:body, :code) def initialize(url, request_method, request_headers, request_body, request_options) self.uri = URI(url) self.method = request_method self.headers = request_headers || {} self.body = request_body self.options = request_options || {} end def perform validate_request_method construct_request_options construct_headers request_class = Kernel.const_get("Net::HTTP::#{self.method.to_s.capitalize}") request = request_class.new(self.uri.path, self.headers) request.body = self.body.to_json unless self.body.nil? begin http_response = Net::HTTP.start(self.uri.host, self.uri.port, self.options) do |http| http.request(request) end response = RESPONSE.new response.body = JSON.parse(http_response.body, symbolize_names: true) response.code = http_response.code.to_i rescue => e response = error_response(e) end response end def error_response(error) res = RESPONSE.new(:body, :code) res.body = { message: "Something went wrong! #{error.message}" } res.code = 500 res end def construct_request_options self.options[:read_timeout] ||= DEFAULT_OPEN_TIMEOUT self.options[:open_timeout] ||= DEFAULT_OPEN_TIMEOUT if self.uri.scheme == "https" self.options[:use_ssl] = true self.options[:verify_mode] = OpenSSL::SSL::VERIFY_NONE end end def construct_headers self.headers end def validate_request_method unless VALID_REQUEST_METHODS.include?(self.method.to_sym) raise InvalidRequestMethodError.new("The request method #{self.method} is invalid!") end end end end end
"use strict"; const path = require("path"); const readdirRecursive = require("fs-readdir-recursive"); const testsPath = path.resolve(__dirname, "to-upstream"); const runWebPlatformTest = require("./run-to-upstream-web-platform-test")(exports, testsPath); readdirRecursive(testsPath).forEach(runWebPlatformTest);
--- name: "APPFORUM Europe" website: https://www.zebra.com/appforum location: Prague, Czech Republic date_start: 2017-06-14 date_end: 2017-06-16 ---
var precision = 1e-6; function approxEql(matrixA, matrixB) { var i = matrixA.length; while(i--) { var j = matrixA[0].length; while(j--) { if((Math.abs(matrixA[i][j] - matrixB[i][j]) > precision)) { return false; } } } return true; } module.exports = approxEql;
name "pummelzacken" description "Master role applied to pummelzacken" default_attributes( :networking => { :interfaces => { :internal_ipv4 => { :interface => "em1", :role => :internal, :family => :inet, :address => "10.0.0.20" }, :external_ipv4 => { :interface => "em2", :role => :external, :family => :inet, :address => "128.40.45.204" } } }, :postgresql => { :settings => { :defaults => { :listen_addresses => "10.0.0.20", :work_mem => "160MB", :maintenance_work_mem => "10GB", :random_page_cost => "1.5", :effective_cache_size => "60GB" } } }, :nominatim => { :flatnode_file => "/ssd/nominatim/nodes.store", :database => { :cluster => "9.3/main", :dbname => "nominatim", :postgis => "2.1" }, :fpm_pools => { :www => { :port => "8000", :pm => "dynamic", :max_children => "60" }, :bulk => { :port => "8001", :pm => "static", :max_children => "10" } }, :redirects => { :reverse => "poldi.openstreetmap.org" } }, :hardware => { :grub => { # lock kernel to 3.16.0-46 due to some issue with igb driver # see https://github.com/openstreetmap/operations/issues/45 # for more information. :kernel => "3.16.0-46" } } ) run_list( "role[ucl-wolfson]", "role[nominatim-master]" )
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './Shared/navbar/login/login.component'; import { FlexLayoutModule } from '@angular/flex-layout'; import { MatCardModule } from '@angular/material/card'; import { MatInputModule } from '@angular/material/input'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { ForgotPasswordComponent } from './Shared/navbar/forgot-password/forgot-password.component'; import { NavbarComponent } from './Shared/navbar/navbar.component'; import { SignupComponent } from './Shared/navbar/signup/signup.component'; import { AuthGuardGuard } from './Guards/auth-guard.guard'; import { AlertComponent } from './_components/alert.component'; import { ProductsComponent } from './Shared/Products/products/products.component'; import { HomeComponent } from './Admin/Home/home/home.component'; import { UserHomeComponent } from './User/user-home/user-home.component'; import { ProductComponent } from './Products/product/product.component'; import { DashboardComponent } from './Admin/Dashboard/dashboard/dashboard.component'; import { UserService } from './services/user.service'; import { OrderListComponent } from './Admin/OrderList/order-list/order-list.component'; import { StocksComponent } from './Admin/Stocks/stocks/stocks.component'; import { TotalOrderComponent } from './Admin/TotalOrder/total-order/total-order.component'; import { SettingsComponent } from './Admin/Settings/settings/settings.component'; import { fakeBackendProvider } from './_helpers/fake-backend'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { JwtInterceptor } from './_helpers/jwt.interceptor'; import { ErrorInterceptor } from './_helpers/error.interceptor'; import { CommonModule } from '@angular/common'; @NgModule({ declarations: [ AppComponent, LoginComponent, ForgotPasswordComponent, AppComponent, NavbarComponent, SignupComponent, ProductsComponent, HomeComponent, UserHomeComponent, ProductComponent, DashboardComponent, AlertComponent, OrderListComponent, StocksComponent, TotalOrderComponent, SettingsComponent, //AdminComponent, ], imports: [ BrowserModule, AppRoutingModule, FlexLayoutModule, MatCardModule, MatInputModule, ReactiveFormsModule, FormsModule, MatFormFieldModule, MatIconModule, HttpClientModule, CommonModule ], providers: [{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, AuthGuardGuard , UserService, // provider used to create fake backend fakeBackendProvider,AuthGuardGuard], // providers: [AuthGuardGuard], bootstrap: [AppComponent], }) export class AppModule { MaterialModule; }
use crate::graph::NodeContents; use crate::{Channel, Result, UrbitAPIError}; /// A struct that provides an interface for interacting with Urbit chats pub struct Chat<'a> { pub channel: &'a mut Channel, } /// A struct that represents a message that is to be sent to an Urbit chat. /// `Message` provides methods to build a message in chunks, thereby allowing you /// to add content which needs to be parsed, for example links @p mentions. /// It is technically an alias for the `NodeContents` struct. // #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] pub type Message = NodeContents; /// A `Message` with the author @p also included #[derive(Clone, Debug)] pub struct AuthoredMessage { pub author: String, pub message: Message, } impl AuthoredMessage { /// Create a new `AuthoredMessage` pub fn new(author: String, message: Message) -> Self { AuthoredMessage { author: author, message: message, } } } /// Methods for interacting with a Chat impl<'a> Chat<'a> { /// Send a message to an Urbit chat. /// Returns the index of the node that was added /// to Graph Store. pub fn send_message( &mut self, chat_ship: &str, chat_name: &str, message: &Message, ) -> Result<String> { let node = self.channel.graph_store().new_node(message); if let Ok(_) = self .channel .graph_store() .add_node(chat_ship, chat_name, &node) { Ok(node.index) } else { Err(UrbitAPIError::FailedToSendChatMessage( message.to_json().dump(), )) } } /// Extracts a Chat's messages automatically into a list of `String`s pub fn export_chat_log(&mut self, chat_ship: &str, chat_name: &str) -> Result<Vec<String>> { let chat_graph = &self.channel.graph_store().get_graph(chat_ship, chat_name)?; let mut export_log = vec![]; let mut nodes = chat_graph.clone().nodes; nodes.sort_by(|a, b| a.time_sent.cmp(&b.time_sent)); for node in nodes { if !node.contents.is_empty() { export_log.push(node.to_formatted_string()); } } Ok(export_log) } }
<?php /** * Molajito Position Class * * @package Molajo * @license http://www.opensource.org/licenses/mit-license.html MIT License * @copyright 2014-2015 Amy Stephen. All rights reserved. */ namespace Molajito\Render; use CommonApi\Render\RenderInterface; use stdClass; /** * Molajito Position Class * * @package Molajo * @license http://www.opensource.org/licenses/mit-license.html MIT License * @copyright 2014-2015 Amy Stephen. All rights reserved. * @since 1.0.0 */ final class Position extends AbstractRenderer implements RenderInterface { /** * Render output * * @param array $data * * @return array * @since 1.0.0 * @throws \CommonApi\Exception\RuntimeException */ public function renderOutput(array $data = array()) { $data['on_before_event'] = 'onBeforeRenderPosition'; $data['on_after_event'] = 'onAfterRenderPosition'; $this->initialise($data); $this->scheduleEvent($this->on_before_event, array()); $this->renderView(''); $this->scheduleEvent($this->on_after_event, array()); return $this->rendered_view; } /** * Render View * * @param string $suffix * * @return $this * @since 1.0.0 */ protected function renderView($suffix) { if (trim($this->parameters->token->name) === '') { return $this; } if (is_array($this->parameters->token->name)) { $templates = $this->parameters->token->name; } else { $templates = array($this->parameters->token->name); } if (count($templates) > 0) { $this->setTemplates($templates); } return $this; } /** * Set Templates * * @param array $templates * * @return $this * @since 1.0.0 */ protected function setTemplates(array $templates = array()) { $attributes = $this->setAttributes(); foreach ($templates as $template) { $template_name = $this->escapeTemplateName($template); if ($this->rendered_view === '') { } else { $this->rendered_view .= PHP_EOL; } $this->rendered_view .= '{I template=' . ucfirst(strtolower(trim($template_name))); if (trim($attributes) === '') { } else { $this->rendered_view .= ' ' . $attributes; } $this->rendered_view .= ' I} '; } return $this; } /** * Create Include Statements for Position Templates * * @param string $template_name * * @return string * @throws \CommonApi\Exception\RuntimeException */ protected function escapeTemplateName($template_name) { $row = new stdClass(); $row->name = $template_name; $data = array(); $data[] = $row; $escaped = $this->escape_instance->escapeOutput($data); return $escaped[0]->name; } /** * Set Attributes as String * * @return string */ protected function setAttributes() { $attributes = ''; if (count($this->parameters->token->attributes) === 0) { return $attributes; } foreach ($this->parameters->token->attributes as $key => $value) { $attributes .= ' ' . $key . '=' . $value; } return trim($attributes); } }
namespace Hexalith.Roles.Application.ModelViews { public record RoleSummaryInformations(string Id, string Name) { } }
package handler import ( feedbackfee "fgame/fgame/game/feedbackfee/feedbackfee" "fgame/fgame/game/player/dao" "fgame/fgame/game/remote/cmd" cmdpb "fgame/fgame/game/remote/cmd/pb" log "github.com/Sirupsen/logrus" "github.com/golang/protobuf/proto" ) func init() { cmd.RegisterCmdHandler(cmd.CmdType(cmdpb.CmdType_CMD_EXCHANGE_TYPE), cmd.CmdHandlerFunc(handleExchange)) } func handleExchange(msg proto.Message) (err error) { log.Info("cmd:请求兑换") cmdExchange := msg.(*cmdpb.CmdExchange) exchangeId := cmdExchange.GetExchangeId() playerId := cmdExchange.GetPlayerId() code := cmdExchange.GetCode() money := cmdExchange.GetMoney() err = exchange(exchangeId, playerId, code, money) if err != nil { log.WithFields( log.Fields{ "exchangeId": exchangeId, "playerId": playerId, "code": code, "money": money, "err": err, }).Error("cmd:请求兑换,错误") return } log.WithFields( log.Fields{ "exchangeId": exchangeId, "playerId": playerId, "code": code, "money": money, }).Info("cmd:请求兑换,成功") return } func exchange(exchangeId int64, playerId int64, code string, money int32) (err error) { pe, err := dao.GetPlayerDao().QueryById(playerId) if err != nil { return } if pe == nil { return cmd.ErrorCodeCommonPlayerNoExist } feedbackfee.GetFeedbackFeeService().CodeExchange(exchangeId, playerId, code, money) return }
import { testUrl } from "../testUrls"; describe("Order Placed", () => { it("does not allow direct access by url", () => { cy.visit(`${testUrl}/orderplaced`); cy.url().should("not", "include", "/orderplaced"); }); it("allows access through confirming order", () => { cy.visit(testUrl); cy.get("[data-cy=1add]").click(); cy.get("[data-cy=3add]").click(); cy.get("[data-cy=5add]").click(); cy.get("[data-cy=cartIcon]").click(); cy.get("[data-cy=checkout]").click(); cy.get("[data-cy=nameInput]").type("TestName"); cy.get("[data-cy=contactInput]").type("12-1234-1234"); cy.get("[data-cy=addressInput]").type("123 Street"); cy.get("[data-cy=continueButton]").click(); cy.get("[data-cy=placeOrder]").click(); cy.get("[data-cy=processPopup]"); cy.wait(2000); cy.url().should("include", "/orderplaced"); }); });
package com.esafirm.androidplayground.dagger.example /** * This class is scoped in [com.esafirm.androidplayground.dagger.modules.AppModule] */ class ScopedClass
#!/usr/bin/env bash if [ -z "${RAFT_HOME}" ]; then export RAFT_HOME="$(cd "`dirname "$0"`"/..; pwd)" fi . $RAFT_HOME/sbin/raft-config.sh class="me.invkrh.raft.deploy.remote.ServerLauncherSystem" curr_ins=`ls $RAFT_PID_DIR | grep $class | wc -l` for ((i=0; i<$curr_ins; i++)); do "${RAFT_HOME}/sbin"/raft-daemon.sh stop $class $(( 1 + $i )) "$@" done
package com.oneliang.ktx.frame.forecaster import com.oneliang.ktx.util.common.getZeroTime import com.oneliang.ktx.util.json.toJson import java.math.BigDecimal import java.util.* class ResourceInputItem( var amount: BigDecimal = BigDecimal(0), var direction: Int = Direction.IN.value, var type: Int = Type.PLAN_SHOULD.value, var time: Date = Date()//数据输入时间,用于totalXxxShould等数据计算 ) { var amountTime = Date()//对应amount时发生的时间 enum class Direction(val value: Int) { IN(0), OUT(1) } enum class Type(val value: Int) { PLAN_SHOULD(0),//计划应该,用于计划应收/应付 ACTUAL_SHOULD(1), //实际应该,用于实际应收/应付 ACTUAL(2)//实际,实际收付 } fun calculateMinAndMaxTime(modulusTime: Long): Pair<Date, Date> { val timeLong = this.time.getZeroTime(modulusTime) val amountTimeLong = this.amountTime.getZeroTime(modulusTime) return if (timeLong > amountTimeLong) { this.amountTime to this.time } else { this.time to this.amountTime } } override fun toString(): String { return this.toJson() } }
import 'package:flutter/cupertino.dart'; class Player { String name; int runs = 0; int balls = 0; Player(this.name); }
if CONFIG.use_basic_auth == "true" Rails.application.config.middleware.use Rack::Auth::Basic , "Antiqua v0.1" do | username , password | valid_username = username == CONFIG.basic_auth_username valid_password = password == CONFIG.basic_auth_password valid_username && valid_password end end
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Paramore.Brighter.Outbox.MySql; using Xunit; namespace Paramore.Brighter.MySQL.Tests.Outbox { [Trait("Category", "MySql")] public class MySqlOutboxBulkAsyncTests : IDisposable { private readonly MySqlTestHelper _mySqlTestHelper; private readonly string _Topic1 = "test_topic"; private readonly string _Topic2 = "test_topic3"; private IEnumerable<Message> _messages; private readonly Message _message1; private readonly Message _message2; private readonly Message _message3; private readonly Message _message; private readonly MySqlOutboxSync _sqlOutbox; public MySqlOutboxBulkAsyncTests() { _mySqlTestHelper = new MySqlTestHelper(); _mySqlTestHelper.SetupMessageDb(); _sqlOutbox = new MySqlOutboxSync(_mySqlTestHelper.OutboxConfiguration); _message = new Message(new MessageHeader(Guid.NewGuid(), _Topic1, MessageType.MT_COMMAND), new MessageBody("message body")); _message1 = new Message(new MessageHeader(Guid.NewGuid(), _Topic2, MessageType.MT_EVENT), new MessageBody("message body2")); _message2 = new Message(new MessageHeader(Guid.NewGuid(), _Topic1, MessageType.MT_COMMAND), new MessageBody("message body3")); _message3 = new Message(new MessageHeader(Guid.NewGuid(), _Topic2, MessageType.MT_EVENT), new MessageBody("message body4")); } [Fact] public async Task When_there_are_multiple_messages_and_some_are_recievied_and_Dispatched_bulk_Async() { await _sqlOutbox.AddAsync(_message); await Task.Delay(100); await _sqlOutbox.AddAsync(_message1); await Task.Delay(100); await _sqlOutbox.AddAsync(_message2); await Task.Delay(100); await _sqlOutbox.AddAsync(_message3); await Task.Delay(100); _messages = await _sqlOutbox.GetAsync(new[] { _message1.Id, _message2.Id }); //should fetch 1 message _messages.Should().HaveCount(2); //should fetch expected message _messages.Should().Contain(m => m.Id == _message1.Id); _messages.Should().Contain(m => m.Id == _message2.Id); await _sqlOutbox.MarkDispatchedAsync(_messages.Select(m => m.Id), DateTime.UtcNow); await Task.Delay(TimeSpan.FromSeconds(5)); var undispatchedMessages = await _sqlOutbox.OutstandingMessagesAsync(0); undispatchedMessages.Count().Should().Be(2); } public void Dispose() { _mySqlTestHelper.CleanUpDb(); } } }
include array.validator.ArrayValidator @class AppServerValidator(){ @private _getAppServers(){ local appServers=( glassfish jboss jetty jonas resin tcat tcserver tomcat weblogic websphere wildfly ) echo ${appServers[@]} } @private _validateAppServer(){ local args=(${@}) for appServer in $(_getAppServers); do if [[ $(ArrayValidator hasEntry args ${appServer}) ]]; then echo ${appServer} break fi done } isGlassfish(){ if [[ $(ArrayValidator hasEntry ${1} glassfish) ]]; then echo true fi } isJboss(){ if [[ $(ArrayValidator hasEntry ${1} jboss) ]]; then echo true fi } isJetty(){ if [[ $(ArrayValidator hasEntry ${1} jetty) ]]; then echo true fi } isJonas(){ if [[ $(ArrayValidator hasEntry ${1} jonas) ]]; then echo true fi } isResin(){ if [[ $(ArrayValidator hasEntry ${1} resin) ]]; then echo true fi } isTcat(){ if [[ $(ArrayValidator hasEntry ${1} tcat) ]]; then echo true fi } @deprecated isTCServer(){ if [[ $(ArrayValidator hasEntry ${1} tc*server) ]]; then echo true fi } isTomcat(){ if [[ $(ArrayValidator hasEntry ${1} tomcat) ]]; then echo true fi } isWeblogic(){ if [[ $(ArrayValidator hasEntry ${1} weblogic) ]]; then echo true fi } isWebsphere(){ if [[ $(ArrayValidator hasEntry ${1} websphere) ]]; then echo true fi } isWildfly(){ if [[ $(ArrayValidator hasEntry ${1} wildfly) ]]; then echo true fi } returnAppServer(){ if [[ ! $@ ]]; then echo tomcat else local appServer=$(_validateAppServer $@) if [[ ${appServer} ]]; then echo ${appServer} else echo tomcat fi fi } $@ }
require 'rexml/document' require File.expand_path('../../../../spec_helper', __FILE__) describe "REXML::Document#stand_alone?" do it "returns the XMLDecl standalone value" do d = REXML::Document.new decl = REXML::XMLDecl.new("1.0", "UTF-8", "yes") d.add decl d.stand_alone?.should == "yes" end # According to the docs this should return the default XMLDecl but that # will carry some more problems when printing the document. Currently, it # returns nil. See http://www.ruby-forum.com/topic/146812#650061 it "returns the default value when no XML declaration present" do REXML::Document.new.stand_alone?.should == nil end end
import { createCategory } from './create-category'; import { authenticatedMiddleware } from '../../../utils/middlewares/authenticatedMiddleware'; export default { Mutation: { createCategory: authenticatedMiddleware(createCategory), }, };
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "presto_cpp/presto_protocol/Duration.h" #include <gtest/gtest.h> using namespace facebook::presto::protocol; void assertDuration( Duration duration, double value, TimeUnit unit, const std::string& serialized) { EXPECT_EQ(duration.getValue(), value); EXPECT_EQ(duration.getTimeUnit(), unit); EXPECT_EQ(duration.toString(), serialized); } void assertDuration( const std::string& durationString, double value, TimeUnit unit) { { Duration duration(durationString); assertDuration(duration, value, unit, durationString); } { Duration duration(value, unit); assertDuration(duration, value, unit, durationString); } } class DurationTest : public ::testing::Test {}; TEST_F(DurationTest, basic) { assertDuration(Duration(), 0, TimeUnit::SECONDS, "0.00s"); assertDuration("1.00d", 1, TimeUnit::DAYS); assertDuration("1.00m", 1, TimeUnit::MINUTES); assertDuration("1800000.00ns", 1'800'000, TimeUnit::NANOSECONDS); Duration d("4 ms"); assertDuration(d, 4, TimeUnit::MILLISECONDS, "4.00ms"); ASSERT_NEAR(d.getValue(TimeUnit::NANOSECONDS), 4000000, 0.0000000001); ASSERT_NEAR(d.getValue(TimeUnit::MICROSECONDS), 4000, 0.0000000001); ASSERT_NEAR(d.getValue(TimeUnit::MILLISECONDS), 4, 0.0000000001); ASSERT_NEAR(d.getValue(TimeUnit::SECONDS), 0.004, 0.0000000001); ASSERT_NEAR(d.getValue(TimeUnit::MINUTES), 0.000066666666667, 0.0000000001); ASSERT_NEAR(d.getValue(TimeUnit::HOURS), 1.11111e-06, 0.0000000001); ASSERT_NEAR(d.getValue(TimeUnit::DAYS), 4.6296296296296295e-08, 0.0000000001); } TEST_F(DurationTest, chronoConversion) { Duration d("4 ms"); assertDuration(d, 4, TimeUnit::MILLISECONDS, "4.00ms"); EXPECT_EQ(d.asChronoDuration<std::chrono::nanoseconds>().count(), 4000000); EXPECT_EQ(d.asChronoDuration<std::chrono::microseconds>().count(), 4000); EXPECT_EQ(d.asChronoDuration<std::chrono::milliseconds>().count(), 4); d = Duration("120m"); EXPECT_EQ(d.asChronoDuration<std::chrono::seconds>().count(), 7200); EXPECT_EQ(d.asChronoDuration<std::chrono::minutes>().count(), 120); EXPECT_EQ(d.asChronoDuration<std::chrono::hours>().count(), 2); }
# ho_operwall.pl # # $Id: ho_operwall.pl,v 1.15 2004/10/02 10:10:21 jvunder REL_0_3 $ # # Part of the Hybrid Oper Script Collection (I hope) # # This script grabs all wallops starting OPERWALL and # reformats them with the "operwall" format, and sends them to # the 'operwall' window. # # --------------------------------------------------------------------- use strict; use Irssi; use Irssi::Irc; use HOSC::again; use HOSC::again 'HOSC::Base'; use HOSC::again 'HOSC::Tools'; import HOSC::Tools qw{get_named_token}; use vars qw[$VERSION %IRSSI $SCRIPT_NAME]; $SCRIPT_NAME = 'Operwall'; ($VERSION) = '$Revision: 1.15 $' =~ / (\d+\.\d+) /; %IRSSI = ( authors => 'James Seward', contact => 'james@jamesoff.net', name => 'ho_operwall', description => 'Sends operwall and locops messages named windows.', license => 'Public Domain', url => 'http://www.jamesoff.net/irc', changed => '06/04/2004 08:15', changes => 'v1.2 - fixed typo', ); # --------------------------------------------------------------------- # # Thanks to: # Garion - for creating the hosc project :) # # --------------------------------------------------------------------- # catch a line typed in any operwall window, and operwall it to the # server # Keeps track of the most recent operwall messages per tag. Used to # prevent duplication of operwalls. my %operwall_history; # --------------------------------------------------------------------- sub cmd_operwall { my ($args, $server, $item) = @_; if ($args =~ m/^(status)|(help)|(example)/i ) { Irssi::command_runsub ('operwall', $args, $server, $item); return; } print_usage(); } # --------------------------------------------------------------------- sub cmd_operwall_help { print_help(); } # --------------------------------------------------------------------- sub cmd_operwall_status { print_status(); } # --------------------------------------------------------------------- sub cmd_operwall_example { print_example(); } # --------------------------------------------------------------------- sub event_operwall_text { my ( $text, $server, $witem ) = @_; my $active_window = Irssi::active_win(); # Only process typed text in named windows. return unless length $active_window->{name} > 0; my $sdata = get_send_data_for_windowname(lc $active_window->{name}); return unless defined $sdata->{type}; for my $tag (@{ $sdata->{servers} }) { if ($tag eq 'active server') { # special tag! my $server = Irssi::active_server(); if (!defined $server) { ho_print_error("No active server in this window."); return; } if ($sdata->{type} eq 'operwall') { $server->send_raw_now("OPERWALL :$text"); } else { $server->send_raw_now("LOCOPS :$text"); } return; } my $server = Irssi::server_find_tag($tag); next unless defined $server; next unless $server->{server_operator} or $server->{usermode} =~ /o/i; if ($sdata->{type} eq 'operwall') { $server->send_raw_now("OPERWALL :$text"); } else { $server->send_raw_now("LOCOPS :$text"); } return; } ho_print_warning("Not connected to a server in (" . (join ',', @{ $sdata->{servers} }) . ") for this window."); } # --------------------------------------------------------------------- # catch an incoming wallop and reformat if it's an operwall sub event_wallop { my ($server, $args, $sender, $addr) = @_; clear_operwall_history(); my @ignorenicks = split(/ +/, Irssi::settings_get_str("ho_operwall_ignore")); if (grep /^$sender$/, @ignorenicks) { Irssi::signal_stop(); return; } if ($args =~ s/^:OPERWALL - //) { process_incoming_operwall($server, $sender, $args); } if ($args =~ s/^:LOCOPS - //) { process_incoming_locops($server, $sender, $args); } } # --------------------------------------------------------------------- sub process_incoming_operwall { my ($server, $sender, $text) = @_; my $tag = $server->{tag}; my $lc_tag = lc $tag; my $window_name = get_named_token( lc Irssi::settings_get_str('ho_operwall_operwall_windows'), $lc_tag); # Fergot about it if no window has been found. return if length $window_name == 0; if ($window_name eq 'devnull') { Irssi::signal_stop(); return; } my $win = Irssi::window_find_name(lc $window_name); if (!defined $win) { ho_print_error("Operwall: window named $window_name for tag " . "$tag not found."); return; } Irssi::signal_stop(); return if already_displayed($server, $sender, $text); add_to_history($server, $sender, $text); my @prepend_tags = split / +/, lc Irssi::settings_get_str('ho_operwall_ow_prepend_tag'); if (grep /^$lc_tag$/, @prepend_tags) { $win->printformat(MSGLEVEL_WALLOPS | MSGLEVEL_CLIENTCRAP, 'ho_operwall_tag', $tag, $sender, $text); } else { $win->printformat(MSGLEVEL_WALLOPS | MSGLEVEL_CLIENTCRAP, 'ho_operwall', $sender, $text); } } # --------------------------------------------------------------------- sub process_incoming_locops { my ($server, $sender, $args) = @_; my $tag = $server->{'tag'}; my $lc_tag = lc $tag; my $window_name = get_named_token( lc Irssi::settings_get_str('ho_operwall_locops_windows'), $lc_tag); # Fergot about it if no window has been found. return if length $window_name == 0; if ($window_name eq 'devnull') { Irssi::signal_stop(); return; } my $win = Irssi::window_find_name(lc $window_name); if (!defined $win) { ho_print_error("Locops: window named $window_name for tag " . "$tag not found."); return; } Irssi::signal_stop(); my @prepend_tags = split / +/, lc Irssi::settings_get_str('ho_operwall_lo_prepend_tag'); if (grep /^$lc_tag$/, @prepend_tags) { $win->printformat(MSGLEVEL_WALLOPS | MSGLEVEL_CLIENTCRAP, 'ho_locops_tag', $tag, $sender, $args); } else { $win->printformat(MSGLEVEL_WALLOPS | MSGLEVEL_CLIENTCRAP, 'ho_locops', $sender, $args); } } # --------------------------------------------------------------------- sub get_send_data_for_windowname { my ($windowname) = @_; my %data = ( type => undef, servers => [], ); for my $type (qw[operwall locops]) { my $windows = Irssi::settings_get_str("ho_operwall_".$type."_windows"); for my $dest (split /\s+/, $windows) { if ($dest =~ /^([^:]+):$windowname$/) { push @{ $data{servers} }, $1; } elsif ($dest eq $windowname) { $data{type} = $type; push @{ $data{servers} }, 'active server'; return \%data; } } if (@{ $data{servers} } > 0) { $data{type} = $type; return \%data; } } return \%data; } # --------------------------------------------------------------------- sub add_to_history { my ($server, $sender, $text) = @_; my $group = get_group(lc $server->{tag}); return unless $group; my $item = { ts => time(), sender => $sender, text => $text, }; push @{ $operwall_history{$group} }, $item; } # --------------------------------------------------------------------- sub clear_operwall_history { my $history_time = Irssi::settings_get_int('ho_operwall_history_time'); my %new_history; my $now = time(); for my $group (keys %operwall_history) { my @history_items = @{ $operwall_history{$group} }; for my $msg (@history_items) { if ($msg->{ts} >= $now - $history_time) { push @{ $new_history{$group} }, $msg; } } } undef %operwall_history; %operwall_history = %new_history; } # --------------------------------------------------------------------- sub already_displayed { my ($server, $sender, $text) = @_; my $group = get_group(lc $server->{tag}); return 0 unless $group; my $now = time(); my $history_time = Irssi::settings_get_int('ho_operwall_history_time'); return 0 unless defined $operwall_history{$group}; my @history_items = @{ $operwall_history{$group} }; for my $msg (@history_items) { if ($msg->{ts} >= $now - $history_time && $msg->{sender} eq $sender && $msg->{text} eq $text ) { return 1; } } return 0; } # --------------------------------------------------------------------- sub get_group { my ($tag) = @_; my @groups = split /\s+/, lc Irssi::settings_get_str('ho_operwall_groups'); for my $group (@groups) { my @servers = split /,/, $group; next unless grep /^$tag$/, @servers; return $group; } return undef; } # --------------------------------------------------------------------- # Still ugly, but will be improved. sub print_status { ho_print("Operwall/Locops status."); my %target_windows; ho_print("Recv. OW. Network Target window"); my $windows = Irssi::settings_get_str("ho_operwall_operwall_windows"); for my $dest (split /\s+/, $windows) { if ($dest =~ /^([^:]+):(.+)$/) { $target_windows{$2} = 1; ho_print((' ' x 11) . $1 . (' ' x (12 - length $1)) . $2); } else { $target_windows{$dest} = 1; ho_print((' ' x 11) . "[rest] $dest"); } } ho_print("Recv. LO. Network Target window"); my $windows = Irssi::settings_get_str("ho_operwall_locops_windows"); for my $dest (split /\s+/, $windows) { if ($dest =~ /^([^:]+):(.+)$/) { $target_windows{$2} = 1; ho_print((' ' x 11) . $1 . (' ' x (12 - length $1)) . $2); } else { $target_windows{$dest} = 1; ho_print((' ' x 11) . "[rest] $dest"); } } ho_print("Sent OW/LO Window name Type Target server"); for my $window_name (sort keys %target_windows) { my $data = get_send_data_for_windowname($window_name); if (defined $data->{type}) { ho_print((' ' x 11) . $window_name . (' ' x (11 - length $window_name)) . " " . $data->{type}. (' ' x (10 - length $data->{type})) . join ', ', @{ $data->{servers} }); } else { ho_print("$window_name: ERROR"); } } } # --------------------------------------------------------------------- ho_print_init_begin(); Irssi::theme_register([ # i like my nicks right-aligned to 9 chars, with overspill 'ho_operwall', '[{nick $[!-9]0}] $1-', 'ho_locops', '[{nick $[!-9]0}] $1-', 'ho_operwall_tag', '[$0] [{nick $[!-9]1}] $2-', 'ho_locops_tag', '[$0] [{nick $[!-9]1}] $2-', ]); Irssi::signal_add('send text', 'event_operwall_text'); Irssi::signal_add('event wallops', 'event_wallop'); Irssi::settings_add_str("ho", "ho_operwall_ignore", ''); Irssi::settings_add_str('ho', 'ho_operwall_operwall_windows', 'operwall'); Irssi::settings_add_str('ho', 'ho_operwall_locops_windows', 'locops'); Irssi::settings_add_str('ho', 'ho_operwall_groups', ''); Irssi::settings_add_int('ho', 'ho_operwall_history_time', 15); Irssi::settings_add_str('ho', 'ho_operwall_ow_prepend_tag', ''); Irssi::settings_add_str('ho', 'ho_operwall_lo_prepend_tag', ''); Irssi::command_bind('operwall', 'cmd_operwall'); Irssi::command_bind('operwall help', 'cmd_operwall_help'); Irssi::command_bind('operwall example', 'cmd_operwall_example'); Irssi::command_bind('operwall status', 'cmd_operwall_status'); ho_print("If you have an alias '/OPERWALL', remove that for optimal ". "functionality of this script."); ho_print("Use /OPERWALL HELP for help."); ho_print_init_end(); # --------------------------------------------------------------------- sub print_usage { ho_print_help('section', 'Syntax'); ho_print_help('syntax', 'OPERWALL help'); ho_print_help('syntax', 'OPERWALL example'); ho_print_help('syntax', 'OPERWALL status'); } sub print_help { ho_print_help('head', $SCRIPT_NAME); print_usage(); ho_print_help('section', 'Description'); ho_print_help('This script reformats all OPERWALL and LOCOPS '. "messages and sends them to the right windows. Also, it allows ". "text to be typed in those windows, which will then be sent as ". "OPERWALL or LOCOPS message to the right server.\n"); ho_print_help("If you only oper on one server, forget about the ". "complex settings and just create a window named 'operwall' and ". "one named 'locops'.\n"); ho_print_help("If you want to use the script to manipulate ". "OPERWALL and LOCOPS for multiple servers on multiple networks, ". "read the explanation of the settings carefully. The meaning of " . "the settings is best shown by example: /OPERWALL EXAMPLE.\n"); ho_print_help('section', 'Settings'); ho_print_help('setting', 'ho_operwall_operwall_windows', 'Destination windows of OPERWALL messages. '. 'This is a multitoken. See /HO HELP MULTITOKEN'); ho_print_help('setting', 'ho_operwall_locops_windows', 'Destination windows of LOCOPS messages. '. 'This is a multitoken. See /HO HELP MULTITOKEN'); ho_print_help('setting', 'ho_operwall_groups', 'Space separated list of comma separated network tags. Each comma '. 'separated list defines one group of tags which are considered to '. 'be on the same network.'); ho_print_help('setting', 'ho_operwall_ow_prepend_tag', 'Space separated list of network tags for which each operwall '. 'message must have [tag] in front of it.'); ho_print_help('setting', 'ho_operwall_lo_prepend_tag', 'Space separated list of network tags for which each locops '. 'message must have [tag] in front of it.'); } sub print_example { ho_print_help('section', 'Example'); ho_print_help("Consider the following settings:\n"); ho_print_help('setting', "ho_operwall_operwall_windows", "operwall cnqnet:ow_cnq vuurwerk:ow_efnet ". "dkom:ow_efnet blackened:ow_efnet test1:blah test2:blah"); ho_print_help('setting', "ho_operwall_locops_windows", "locops vuurwerk:lo_vuurwerk test1:bleh test2:devnull"); ho_print_help('setting', "ho_operwall_groups", "vuurwerk,dkom,blackened test1,test2\n"); ho_print_help("Operwalls for network tag 'cnqnet' will be sent to the ". "window named 'ow_cnq'. Operwalls for tags 'vuurwerk', 'dkom', and ". "'blackened' all go to the window 'ow_efnet'. The operwalls for ". "'test1' and 'test2' both go to window 'blah', and all other ". "operwalls go to window 'operwall'.\n"); ho_print_help("When typing in window 'ow_cnq', the script can see ". "that this should be an Operwall message for tag 'cnqnet', so ". "it will search for the server with that tag and send the operwall ". "to there."); ho_print_help("For a message in window 'ow_efnet', the script will " . "first see if a connection to tag 'vuurwerk' exists. If so, that " . "is used to send the operwall. If not, the script will try tags ". "'dkom' and 'blackened', i.e. the same order as in the setting.\n"); ho_print_help("If the client is receiving operwall messages for all ". "three tags that send to ow_efnet, the script will still only ". "display each message once. That is because the ho_operwall_groups ". "setting indicates that these three servers are on the same ". "network.\n"); ho_print_help("For Locops message, the same rules are followed, except ". "that they can't be grouped."); }
import React from 'react'; import Timer from './Timer'; const DisplayTimers = ({ timers }) => { let key = 0; return ( <> { timers.map(timer => <Timer key={timer._id} timer={timer} />) } </> ); }; export default DisplayTimers;
# frozen_string_literal: true RSpec.describe "bundle licenses" do before :each do install_gemfile <<-G source "#{file_uri_for(gem_repo1)}" gem "rails" gem "with_license" G end it "prints license information for all gems in the bundle" do bundle "licenses" expect(out).to include("bundler: MIT") expect(out).to include("with_license: MIT") end it "performs an automatic bundle install" do gemfile <<-G source "#{file_uri_for(gem_repo1)}" gem "rails" gem "with_license" gem "foo" G bundle "config set auto_install 1" bundle :licenses expect(out).to include("Installing foo 1.0") end end
import 'package:flutter/material.dart'; import 'package:shortube/api/errorpage.dart'; import 'package:shortube/pages/categorypage.dart'; import 'package:shortube/pages/channelpage.dart'; import 'package:shortube/pages/countrypage.dart'; import 'package:shortube/pages/home.dart'; import 'package:shortube/pages/sortbypage.dart'; import 'package:shortube/pages/splashscreen.dart'; import 'package:shortube/pages/webpage.dart'; import 'package:shortube/pages/worldmeter.dart'; import 'package:shortube/util/widgets.dart'; void main(){ runApp(MaterialApp( debugShowCheckedModeBanner: false, home: splash(), routes: routes, )); } var routes = <String,WidgetBuilder>{ "/splash": (BuildContext context) => splash(), "/home": (BuildContext context) => Home(data), "/Country": (BuildContext context) => CountryPage(home_data), "/Category": (BuildContext context) => CategoryPage(home_data), "/Sortby": (BuildContext context) => SortByPage(home_data), "/webpage": (BuildContext context) => WebPage(urldata), "/worldmeter": (BuildContext context) => worldometer(), "/channels": (BuildContext context) => ChannelPage(home_data), "/error": (BuildContext context) => ErrorPage(home_data), }; class splash extends StatefulWidget { @override _splashState createState() => _splashState(); } class _splashState extends State<splash> { @override Widget build(BuildContext context) { return Splashscreen(); } }
# yamlsh - YAML Parsed in `#!` for shell (I'm sure there is already a util out there that does this (I couldn't find one, though admittedly I didn't search very hard), but I'm learning the Go language and needed the practice, so...) Parse a yaml file and pass as environment variables to a script from `#!`. You can download a prebuilt binary from the project's releases page [here](https://github.com/gbevan/yamlsh/releases/latest). ## Build and install Requires GOPATH setup and this project cloned out to `src/` ``` go get github.com/golang/dep/cmd/dep dep ensure -v --vendor-only go build && sudo cp yamlsh /usr/local/bin ``` ## Usage To use within a shell script replace the #! line with: ``` #!/usr/local/bin/yamlsh --yaml=${MYFILE} # ...rest of your script goes here... ``` `${MYFILE}` will be substituted with the environment variable `MYFILE`, e.g.: ``` MYFILE=test.yml ./test.sh ``` The `test.sh` script and `test.yml` file produces this output: ``` IN SCRIPT YAMLSH_DICT1_NEST1_FloatNum=3.14 YAMLSH_VAR1=my var 1 YAMLSH_DICT1_NEST1_MultiLinePp=aaaaaaaaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbbbbbbbb\ncccccccccccccccccccccc\n YAMLSH_DICT1_NEST1_MultiLineGt=aaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbb cccccccccccccccccccccc\n YAMLSH_DICT1_NEST1_ARRAY2_1=array YAMLSH_DICT1_NEST1_ARRAY2_0=an YAMLSH_DICT1_NEST1_Number=100 YAMLSH_PREFIX=YAMLSH YAMLSH_DICT1_NEST1_NEST2=value of NEST2 YAMLSH_ARRAY1_0=val1 YAMLSH_ARRAY1_1=val2 ``` As can be seen, complex yaml structures are flattened for easy use in shell scripts. By default variables passed are prefixed with `YAMLSH_`. To change this use the `YAMLSH_PREFIX` environment variable, e.g.: ``` MYFILE=test.yml YAMLSH_PREFIX=FOO ./test.sh ``` The shell used defaults to `/bin/bash`, but you can override to use your preferred shell via environment variable `YAMLSH_SHELL` Likewise you can also set the YAML file to preload using environment variable `YAMLSH_YAMLFILE`. However, the `--yaml=file.yml` will take precedence.
/* ************************************************************************** */ /* * For conditions of distribution and use, * */ /* * see copyright notice in libmng.h * */ /* ************************************************************************** */ /* * * */ /* * project : libmng * */ /* * file : libmng_display.h copyright (c) 2000-2007 G.Juyn * */ /* * version : 1.0.10 * */ /* * * */ /* * purpose : Display management (definition) * */ /* * * */ /* * author : G.Juyn * */ /* * * */ /* * comment : Definition of the display managament routines * */ /* * * */ /* * changes : 0.5.1 - 05/08/2000 - G.Juyn * */ /* * - changed strict-ANSI stuff * */ /* * * */ /* * 0.5.2 - 05/20/2000 - G.Juyn * */ /* * - added JNG support stuff * */ /* * * */ /* * 0.5.3 - 06/16/2000 - G.Juyn * */ /* * - changed progressive-display processing * */ /* * 0.5.3 - 06/22/2000 - G.Juyn * */ /* * - added support for delta-image processing * */ /* * - added support for PPLT chunk processing * */ /* * * */ /* * 0.9.2 - 08/05/2000 - G.Juyn * */ /* * - changed file-prefixes * */ /* * 0.9.3 - 08/07/2000 - G.Juyn * */ /* * - B111300 - fixup for improved portability * */ /* * 0.9.3 - 08/26/2000 - G.Juyn * */ /* * - added MAGN chunk * */ /* * 0.9.3 - 10/16/2000 - G.Juyn * */ /* * - added JDAA chunk * */ /* * * */ /* * 0.9.4 - 11/24/2000 - G.Juyn * */ /* * - moved restore of object 0 to libmng_display * */ /* * * */ /* * 1.0.5 - 08/19/2002 - G.Juyn * */ /* * - B597134 - libmng pollutes the linker namespace * */ /* * 1.0.5 - 09/13/2002 - G.Juyn * */ /* * - fixed read/write of MAGN chunk * */ /* * 1.0.5 - 09/20/2002 - G.Juyn * */ /* * - added support for PAST * */ /* * 1.0.5 - 10/07/2002 - G.Juyn * */ /* * - added proposed change in handling of TERM- & if-delay * */ /* * 1.0.5 - 10/20/2002 - G.Juyn * */ /* * - fixed display of visible target of PAST operation * */ /* * * */ /* * 1.0.7 - 03/24/2004 - G.R-P. * */ /* * - added some SKIPCHUNK conditionals * */ /* * * */ /* * 1.0.9 - 12/11/2004 - G.Juyn * */ /* * - added conditional MNG_OPTIMIZE_DISPLAYCALLS * */ /* * * */ /* * 1.0.10 - 04/08/2007 - G.Juyn * */ /* * - added support for mPNG proposal * */ /* * 1.0.10 - 04/12/2007 - G.Juyn * */ /* * - added support for ANG proposal * */ /* * * */ /* ************************************************************************** */ #if defined(__BORLANDC__) && defined(MNG_STRICT_ANSI) #pragma option -A /* force ANSI-C */ #endif #ifndef _libmng_display_h_ #define _libmng_display_h_ /* ************************************************************************** */ #ifdef MNG_INCLUDE_DISPLAY_PROCS /* ************************************************************************** */ mng_retcode mng_display_progressive_refresh (mng_datap pData, mng_uint32 iInterval); /* ************************************************************************** */ mng_retcode mng_reset_objzero (mng_datap pData); mng_retcode mng_display_image (mng_datap pData, mng_imagep pImage, mng_bool bLayeradvanced); mng_retcode mng_execute_delta_image (mng_datap pData, mng_imagep pTarget, mng_imagep pDelta); /* ************************************************************************** */ mng_retcode mng_process_display (mng_datap pData); /* ************************************************************************** */ #ifdef MNG_OPTIMIZE_FOOTPRINT_INIT png_imgtype mng_png_imgtype (mng_uint8 colortype, mng_uint8 bitdepth); #endif /* ************************************************************************** */ #ifndef MNG_OPTIMIZE_DISPLAYCALLS mng_retcode mng_process_display_ihdr (mng_datap pData); #ifdef MNG_INCLUDE_MPNG_PROPOSAL mng_retcode mng_process_display_mpng (mng_datap pData); #endif #ifdef MNG_INCLUDE_ANG_PROPOSAL mng_retcode mng_process_display_ang (mng_datap pData); #endif mng_retcode mng_process_display_idat (mng_datap pData, mng_uint32 iRawlen, mng_uint8p pRawdata); mng_retcode mng_process_display_iend (mng_datap pData); mng_retcode mng_process_display_mend (mng_datap pData); mng_retcode mng_process_display_mend2 (mng_datap pData); mng_retcode mng_process_display_defi (mng_datap pData); #ifndef MNG_SKIPCHUNK_BASI mng_retcode mng_process_display_basi (mng_datap pData, mng_uint16 iRed, mng_uint16 iGreen, mng_uint16 iBlue, mng_bool bHasalpha, mng_uint16 iAlpha, mng_uint8 iViewable); #endif #ifndef MNG_SKIPCHUNK_CLON mng_retcode mng_process_display_clon (mng_datap pData, mng_uint16 iSourceid, mng_uint16 iCloneid, mng_uint8 iClonetype, mng_bool bHasdonotshow, mng_uint8 iDonotshow, mng_uint8 iConcrete, mng_bool bHasloca, mng_uint8 iLocationtype, mng_int32 iLocationx, mng_int32 iLocationy); mng_retcode mng_process_display_clon2 (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_DISC mng_retcode mng_process_display_disc (mng_datap pData, mng_uint32 iCount, mng_uint16p pIds); #endif #ifndef MNG_SKIPCHUNK_FRAM mng_retcode mng_process_display_fram (mng_datap pData, mng_uint8 iFramemode, mng_uint8 iChangedelay, mng_uint32 iDelay, mng_uint8 iChangetimeout, mng_uint32 iTimeout, mng_uint8 iChangeclipping, mng_uint8 iCliptype, mng_int32 iClipl, mng_int32 iClipr, mng_int32 iClipt, mng_int32 iClipb); mng_retcode mng_process_display_fram2 (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_MOVE mng_retcode mng_process_display_move (mng_datap pData, mng_uint16 iFromid, mng_uint16 iToid, mng_uint8 iMovetype, mng_int32 iMovex, mng_int32 iMovey); #endif #ifndef MNG_SKIPCHUNK_CLIP mng_retcode mng_process_display_clip (mng_datap pData, mng_uint16 iFromid, mng_uint16 iToid, mng_uint8 iCliptype, mng_int32 iClipl, mng_int32 iClipr, mng_int32 iClipt, mng_int32 iClipb); #endif #ifndef MNG_SKIPCHUNK_SHOW mng_retcode mng_process_display_show (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_SAVE mng_retcode mng_process_display_save (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_SEEK mng_retcode mng_process_display_seek (mng_datap pData); #endif #ifdef MNG_INCLUDE_JNG mng_retcode mng_process_display_jhdr (mng_datap pData); mng_retcode mng_process_display_jdaa (mng_datap pData, mng_uint32 iRawlen, mng_uint8p pRawdata); mng_retcode mng_process_display_jdat (mng_datap pData, mng_uint32 iRawlen, mng_uint8p pRawdata); #endif #ifndef MNG_NO_DELTA_PNG mng_retcode mng_process_display_dhdr (mng_datap pData, mng_uint16 iObjectid, mng_uint8 iImagetype, mng_uint8 iDeltatype, mng_uint32 iBlockwidth, mng_uint32 iBlockheight, mng_uint32 iBlockx, mng_uint32 iBlocky); mng_retcode mng_process_display_prom (mng_datap pData, mng_uint8 iBitdepth, mng_uint8 iColortype, mng_uint8 iFilltype); mng_retcode mng_process_display_ipng (mng_datap pData); #ifdef MNG_INCLUDE_JNG mng_retcode mng_process_display_ijng (mng_datap pData); #endif mng_retcode mng_process_display_pplt (mng_datap pData, mng_uint8 iType, mng_uint32 iCount, mng_palette8ep paIndexentries, mng_uint8p paAlphaentries, mng_uint8p paUsedentries); #endif #ifndef MNG_SKIPCHUNK_MAGN mng_retcode mng_process_display_magn (mng_datap pData, mng_uint16 iFirstid, mng_uint16 iLastid, mng_uint8 iMethodX, mng_uint16 iMX, mng_uint16 iMY, mng_uint16 iML, mng_uint16 iMR, mng_uint16 iMT, mng_uint16 iMB, mng_uint8 iMethodY); mng_retcode mng_process_display_magn2 (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_PAST mng_retcode mng_process_display_past (mng_datap pData, mng_uint16 iTargetid, mng_uint8 iTargettype, mng_int32 iTargetx, mng_int32 iTargety, mng_uint32 iCount, mng_ptr pSources); mng_retcode mng_process_display_past2 (mng_datap pData); #endif #else /* MNG_OPTIMIZE_DISPLAYCALLS */ mng_retcode mng_process_display_ihdr (mng_datap pData); #ifdef MNG_INCLUDE_MPNG_PROPOSAL mng_retcode mng_process_display_mpng (mng_datap pData); #endif mng_retcode mng_process_display_idat (mng_datap pData); mng_retcode mng_process_display_iend (mng_datap pData); mng_retcode mng_process_display_mend (mng_datap pData); mng_retcode mng_process_display_mend2 (mng_datap pData); mng_retcode mng_process_display_defi (mng_datap pData); #ifndef MNG_SKIPCHUNK_BASI mng_retcode mng_process_display_basi (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_CLON mng_retcode mng_process_display_clon (mng_datap pData); mng_retcode mng_process_display_clon2 (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_DISC mng_retcode mng_process_display_disc (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_FRAM mng_retcode mng_process_display_fram (mng_datap pData); mng_retcode mng_process_display_fram2 (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_MOVE mng_retcode mng_process_display_move (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_CLIP mng_retcode mng_process_display_clip (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_SHOW mng_retcode mng_process_display_show (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_SAVE mng_retcode mng_process_display_save (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_SEEK mng_retcode mng_process_display_seek (mng_datap pData); #endif #ifdef MNG_INCLUDE_JNG mng_retcode mng_process_display_jhdr (mng_datap pData); mng_retcode mng_process_display_jdaa (mng_datap pData); mng_retcode mng_process_display_jdat (mng_datap pData); #endif #ifndef MNG_NO_DELTA_PNG mng_retcode mng_process_display_dhdr (mng_datap pData); mng_retcode mng_process_display_prom (mng_datap pData); mng_retcode mng_process_display_ipng (mng_datap pData); #ifdef MNG_INCLUDE_JNG mng_retcode mng_process_display_ijng (mng_datap pData); #endif mng_retcode mng_process_display_pplt (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_MAGN mng_retcode mng_process_display_magn (mng_datap pData); mng_retcode mng_process_display_magn2 (mng_datap pData); #endif #ifndef MNG_SKIPCHUNK_PAST mng_retcode mng_process_display_past (mng_datap pData); mng_retcode mng_process_display_past2 (mng_datap pData); #endif #endif /* MNG_OPTIMIZE_DISPLAYCALLS */ /* ************************************************************************** */ #endif /* MNG_INCLUDE_DISPLAY_PROCS */ /* ************************************************************************** */ #endif /* _libmng_display_h_ */ /* ************************************************************************** */ /* * end of file * */ /* ************************************************************************** */
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { updateItem } from '../../redux/items'; import { fetchUnits } from '../../redux/units'; import { fetchItemTypes } from '../../redux/itemTypes'; import { fetchItemGroups } from '../../redux/itemGroups'; import ItemForm from '../../components/Items/Form'; const initialState = { status: false, }; class EditForm extends Component { constructor (props) { super(props); this.state = initialState; this.handleSubmit = this.handleSubmit.bind(this); } static propTypes = { errors: PropTypes.any, item: PropTypes.object, units: PropTypes.array.isRequired, itemTypes: PropTypes.array.isRequired, itemGroups: PropTypes.array.isRequired, updateItem: PropTypes.func.isRequired, fetchUnits: PropTypes.func.isRequired, fetchItemTypes: PropTypes.func.isRequired, fetchItemGroups: PropTypes.func.isRequired }; componentDidMount() { this.props.fetchUnits(); this.props.fetchItemTypes(); this.props.fetchItemGroups(); } handleSubmit = item => { this.props.updateItem(item); } render() { let { item, units, itemTypes, itemGroups, errors } = this.props; return ( <div className="animated fadeIn"> <ItemForm item={item} units={units} itemTypes={itemTypes} itemGroups={itemGroups} handleSubmit={this.handleSubmit} formMode={false} validateErrors={errors} /> </div> ); } } const mapStateToProps = (state, props) => { const { id } = props.match.params; return { item: state.item.items.find(item => parseInt(item.id) === parseInt(id)), units: state.unit.units, itemTypes: state.itemType.itemTypes, itemGroups: state.itemGroup.itemGroups, errors: state.item.errors } }; export default connect( mapStateToProps, { fetchUnits, fetchItemTypes, fetchItemGroups, updateItem } )(EditForm);
create table users ( id bigint(20) not null primary key auto_increment, username varchar(50) not null, password varchar(60) not null, enabled tinyint(4) not null default '1' comment '用户是否可用', roles text character set utf8 comment '用户角色,多个角色之间用逗号隔开' ); insert into users (username, password, roles) values ('admin', '123', 'ROLE_ADMIN,ROLE_USER'); insert into users (username, password, roles) values ('user', '123', 'ROLE_USER');
class ExprNode { constructor(name, args = [], language) { this.name = name; this.args = args; this.language = language; } } class StrNode { constructor(value) { this.value = value; } } class NumNode { constructor(value) { this.value = value; } } class BoolNode { constructor(value) { this.value = value; } } class ArrNode { constructor(items) { this.items = items; } } class ObjNode { constructor(pairs = []) { this.pairs = pairs; } } class NullNode { } class UndefNode { } class FuncNode { constructor(func) { this.func = func; } } module.exports = { ExprNode, StrNode, NumNode, BoolNode, NullNode, UndefNode, ArrNode, ObjNode, FuncNode, }
using Amazon.Runtime; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; using Amazon.SQS; using Amazon.SQS.Model; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using SNSMessageAttributeValue = Amazon.SimpleNotificationService.Model.MessageAttributeValue; using AWSSDK.Tests.Framework; namespace AWSSDK.IntegrationTests.SNS { [TestFixture(TestOf = typeof(SNSTests))] [Category("Integration")] public class SNSTests : TestBase<AmazonSimpleNotificationServiceClient> { [Test] [Category("WWW")] public void CRUDTopics() { // list all topics var allTopics = GetAllTopics(); var currentTopicCount = allTopics.Count; // create new topic var name = "unitysdk" + DateTime.Now.Ticks; AutoResetEvent ars = new AutoResetEvent(false); Exception responseException = new Exception(); string topicArn = null; Client.CreateTopicAsync(new CreateTopicRequest { Name = name }, (response) => { responseException = response.Exception; if (responseException == null) { topicArn = response.Response.TopicArn; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); Assert.IsNotNull(topicArn); try { // verify there is a new topic allTopics = GetAllTopics(); Assert.AreNotEqual(currentTopicCount, allTopics.Count); // set topic attribute var attributeName = "DisplayName"; var attributeValue = "Test topic"; Client.SetTopicAttributesAsync(new SetTopicAttributesRequest { TopicArn = topicArn, AttributeName = attributeName, AttributeValue = attributeValue }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); // verify topic attributes Dictionary<string, string> attributes = null; Client.GetTopicAttributesAsync(new GetTopicAttributesRequest { TopicArn = topicArn }, (response) => { responseException = response.Exception; if (responseException == null) { attributes = response.Response.Attributes; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); Assert.AreEqual(attributeValue, attributes[attributeName]); } finally { // delete new topic Client.DeleteTopicAsync(new DeleteTopicRequest { TopicArn = topicArn }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); // verify the topic was deleted allTopics = GetAllTopics(); Assert.AreEqual(currentTopicCount, allTopics.Count); } } [Test] [Category("WWW")] public void TestPublishAsJson() { AutoResetEvent ars = new AutoResetEvent(false); Exception responseException = new Exception(); // create new topic string topicArn = null; var name = "unitysdk" + DateTime.Now.Ticks; Client.CreateTopicAsync(new CreateTopicRequest { Name = name }, (response) => { responseException = response.Exception; if (responseException == null) { topicArn = response.Response.TopicArn; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); try { Client.PublishAsync(new PublishRequest() { TopicArn = topicArn, MessageStructure = "json", Message = "{\"default\" : \"Data\"}" }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); var x = new PublishRequest() { TopicArn = topicArn, MessageStructure = "json", Message = "stuff" }; Client.PublishAsync(x, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNotNull(responseException); var invalidParameterResponse = responseException as InvalidParameterException; Assert.AreEqual("InvalidParameter", invalidParameterResponse.ErrorCode); Utils.AssertTrue(invalidParameterResponse.Message.Contains("parse")); } finally { Client.DeleteTopicAsync(new DeleteTopicRequest { TopicArn = topicArn }, (response) => { responseException = response.Exception; ars.Set(); }); ars.WaitOne(); Assert.IsNull(responseException); } } // Constraints: // to run this test, a valid email address must be supplied and // the subscription confirmed within two minutes by default //[Test] // [Category("WWW")] public void SubscribeTopicTest() { const string emailAddress = "replaceme@example.com"; var subscriptionWaitDelay = TimeSpan.FromMinutes(2); // create new topic var name = "unitysdk" + DateTime.Now.Ticks; AutoResetEvent ars = new AutoResetEvent(false); Exception responseException = new Exception(); string topicArn = null; Client.CreateTopicAsync(new CreateTopicRequest { Name = name }, (response) => { responseException = response.Exception; if (responseException == null) { topicArn = response.Response.TopicArn; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); try { // subscribe an email address to the topic Client.SubscribeAsync(new SubscribeRequest { Protocol = "email", Endpoint = emailAddress, TopicArn = topicArn }, (response) => { responseException = response.Exception; ars.Set(); }); ars.WaitOne(); Assert.IsNull(responseException); // wait until subscription has been confirmed, maximum wait time of two minutes // by default string subArn = null; var latest = DateTime.Now + subscriptionWaitDelay; while (DateTime.Now < latest) { List<Subscription> subscriptions = null; // get subscriptions for topic Client.ListSubscriptionsByTopicAsync(new ListSubscriptionsByTopicRequest { TopicArn = topicArn }, (response) => { responseException = response.Exception; if (responseException == null) { subscriptions = response.Response.Subscriptions; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); Assert.AreEqual(1, subscriptions.Count); // test whether the subscription has been confirmed var subscription = subscriptions[0]; if (!string.Equals(subscription.SubscriptionArn, "PendingConfirmation", StringComparison.Ordinal)) { subArn = subscription.SubscriptionArn; break; } // wait Thread.Sleep(TimeSpan.FromSeconds(15)); } // verify that the subscription was confirmed and the arn has been set Assert.IsNotNull(subArn); // publish a message to the topic Client.PublishAsync(new PublishRequest { TopicArn = topicArn, Subject = "Test subject", Message = "Test message" }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); // delete the subscription Client.UnsubscribeAsync(new UnsubscribeRequest { SubscriptionArn = subArn }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); } finally { // delete the topic Client.DeleteTopicAsync(new DeleteTopicRequest { TopicArn = topicArn }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); } } private List<Topic> GetAllTopics() { var allTopics = new List<Topic>(); AutoResetEvent ars = new AutoResetEvent(false); Exception responseException = new Exception(); var listRequest = new ListTopicsRequest(); do { Client.ListTopicsAsync(listRequest, (response) => { responseException = response.Exception; if (responseException == null) { allTopics.AddRange(response.Response.Topics); listRequest.NextToken = response.Response.NextToken; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Assert.IsNull(responseException); } while (!string.IsNullOrEmpty(listRequest.NextToken)); return allTopics; } } }
(defsystem #:trivial-gamekit-tiled :version "0.0.0" :description "Tiled/trivial-gamekit integration." :author "Wilfredo Velázquez-Rodríguez <zulu.inuoe@gmail.com>" :license "CC0 1.0 Universal" :serial t :components ((:file "trivial-gamekit-tiled")) :depends-on (#:alexandria #:trivial-gamekit #:cl-tiled)) (defsystem #:trivial-gamekit-tiled/example :version "0.0.0" :description "Example of tiled/trivial-gamekit integration." :author "Wilfredo Velázquez-Rodríguez <zulu.inuoe@gmail.com>" :license "CC0 1.0 Universal" :serial t :components ((:file "example")) :depends-on (#:alexandria #:trivial-gamekit-tiled #:cl-tiled))
# Clean Code Quick and dirty, throw-away-on-time-use methods to clean migrated Firefly code. --- This console program reads .cs files and removes any `if (false)` code
/* * @description: 抽离开源版本 * @Author: chuyinlong * @Date: 2021-08-20 17:29:09 * @LastEditors: chuyinlong * @LastEditTime: 2021-08-27 09:54:06 */ import MContent from "@/components/MContent.vue"; import MMain from "@/components/MMain.vue"; interface RouteMeta { icon: string; title: string; islink: number; mode: string; } const routes = [ { path: "/overview", // 临时比对本地版本用 version: +new Date(), component: MMain, meta: { icon: "iconjiankonggaikuang_huaban", title: "经营概况", islink: 1, }, children: [ { path: "", name: "OverView", meta: { title: "经营概况", isShow: 1, }, show: true, component: () => import("@/views/manage/Index.vue"), }, ], }, { path: "", component: MMain, meta: { icon: "iconshangpinguanli", title: "商品管理", }, children: [ { path: "goods", component: MContent, meta: { title: "商品列表", }, show: true, children: [ { path: "", name: "Goods", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/Goods.vue" ), }, { path: "addGood", name: "AddGood", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/AddGood.vue" ), meta: { title: "发布商品", noPadding: true, }, show: true, }, ], }, { path: "goodRegion", // name: "goodRegion", component: MContent, meta: { title: "设置专区", }, show: true, children: [ { path: "", name: "goodRegion", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/goodManage/GoodRegion.vue" ), }, { path: "class", name: "class", show: true, component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/goodManage/GoodClass.vue" ), meta: { title: "商品分类", }, }, ], }, { path: "attributeTemple", name: "Attribute", show: true, component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/goodManage/AttributeTemple.vue" ), meta: { title: "属性模板", }, }, { path: "supplier", name: "sup", show: true, component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/goodManage/SupplierManage.vue" ), meta: { title: "供货商", }, }, { path: "csvImport", name: "csvImport", show: true, component: MContent, meta: { title: "素材导入", }, children: [ { path: "", name: "csvList", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/csvImport/CsvIndex.vue" ), }, { path: "editGood", name: "editGood", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/csvImport/EditGood.vue" ), meta: { title: "编辑商品", noPadding: true, }, show: true, }, ], }, ], }, { path: "/order", component: MMain, meta: { title: "订单管理", icon: "icondingdan", }, children: [ { path: "delivery", meta: { title: "快递订单", }, show: true, component: MContent, children: [ { meta: { title: "", }, path: "", component: () => import( /* webpackChunkName: "order" */ "@/views/order/DeliveryOrder.vue" ), }, { path: "send", meta: { title: "批量发货", noPadding: true, }, component: () => import( /* webpackChunkName: "order" */ "@/views/order/DeliverySend.vue" ), }, ], }, { path: "evaluation", component: () => import( /* webpackChunkName: "order" */ "@/views/order/Evaluation.vue" ), meta: { title: "评价管理", }, show: true, }, { path: "afterSale", component: () => import( /* webpackChunkName: "order" */ "@/views/order/AfterSaleOrder.vue" ), meta: { title: "售后工单", }, show: true, }, ], }, { path: "/customer", component: MMain, meta: { title: "客户管理", icon: "iconkehu", }, children: [ { path: "list", component: MContent, children: [ { path: "", name: "list", component: () => import( /* webpackChunkName: "goods" */ "@/views/customer/list/Index.vue" ), }, ], meta: { title: "客户列表", }, show: true, }, { path: "blacklist", name: "blacklist", component: () => import( /* webpackChunkName: "blacklist" */ "@/views/customer/blacklist/Index.vue" ), meta: { title: "黑名单", }, show: true, }, ], }, { path: "/distribution", component: MMain, meta: { title: "配送方式", icon: "icondaifahuo", }, children: [ { path: "logistics", component: () => import( /* webpackChunkName: "finance" */ "@/views/logistics/logistics/Index.vue" ), meta: { title: "快递配送", }, show: true, }, ], }, { path: "/setting", component: MMain, meta: { title: "商城设置", icon: "iconshangpinxiangqing-dianpu", }, children: [ { path: "channel", component: () => import(/* webpackChunkName: "setting" */ "@/views/channel/Index.vue"), meta: { title: "销售渠道", }, show: true, }, { path: "editorPage", redirect: "/editorPage", component: () => import( /* webpackChunkName: "setting" */ "@/views/decoration/components/EditorPage/src/Editor.vue" ), meta: { title: "装修", // isShow: 1, }, show: true, }, { path: "", name: "setting", component: () => import(/* webpackChunkName: "setting" */ "@/views/setting/Index.vue"), meta: { title: "通用设置", }, show: true, }, ], }, { path: "/logistics", component: MMain, meta: { title: "物流管理", isShow: 1, }, children: [ { path: "logistics", name: "logistics", component: () => import( /* webpackChunkName: "logistics" */ "@/views/logistics/logistics/Index.vue" ), meta: { title: "快递配送", }, show: true, }, ], }, { path: "/market", component: MMain, meta: { title: "商超系统", isShow: 1, }, children: [ { path: "goods", component: MContent, meta: { title: "商品列表", }, show: true, children: [ { path: "", name: "Goods", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/Goods.vue" ), }, { path: "addGood", name: "AddGood", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/AddGood.vue" ), meta: { title: "发布商品", }, }, ], }, ], }, { path: "/CategoryTem", component: MMain, meta: { title: "商品属性", isShow: 1, }, children: [ { path: "/", name: "CategoryTem", component: () => import( /* webpackChunkName: "CategoryTem" */ "@/views/goods/goodManage/components/CategoryTem.vue" ), meta: { title: "商品属性", }, show: true, }, ], }, { path: "/business", component: MMain, meta: { title: "商家中心", isShow: 1, }, children: [ { path: "/", name: "businessCenter", component: () => import( /* webpackChunkName: "businessCenter" */ "@/views/businessCenter/Index.vue" ), meta: { title: "", }, show: true, }, ], }, { path: "/editorPage", name: "editorPage", component: () => import( /* webpackChunkName: "CategoryTem" */ "@/views/decoration/components/EditorPage/src/Editor.vue" ), meta: { title: "装修", isShow: 1, }, }, { path: "/changepass", name: "changepass", component: () => import( /* webpackChunkName: "changepass" */ "@/views/businessCenter/Account/ChangePassword.vue" ), meta: { title: "修改密码", isShow: 1, }, }, { path: "/redirect/:type", name: "redirect", component: () => import(/* webpackChunkName: "CategoryTem" */ "@/views/sign/Redirect.vue"), meta: { title: "重定向页面", isShow: 1, }, }, { path: "/static", component: MContent, meta: { title: "", isShow: 1, }, children: [ { path: "protocol", name: "protocol", component: () => import( /* webpackChunkName: "meal" */ "@/views/businessCenter/Static/Protocol.vue" ), meta: { title: "注册协议", }, }, { path: "privacy", name: "privacy", component: () => import( /* webpackChunkName: "meal" */ "@/views/businessCenter/Static/Privacy.vue" ), meta: { title: "隐私政策", }, }, { path: "order", name: "order", component: () => import( /* webpackChunkName: "meal" */ "@/views/businessCenter/Static/Order.vue" ), meta: { title: "订购及服务协议", }, }, { path: "register", name: "register", component: () => import( /* webpackChunkName: "meal" */ "@/views/businessCenter/Static/Register.vue" ), meta: { title: "开户及服务协议", }, }, ], }, { path: "/", component: MMain, meta: { title: "商品管理", isShow: 1, }, children: [ { path: "", component: MContent, meta: { title: "商超商品", }, show: true, children: [ { path: "", name: "index", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/Goods.vue" ), }, ], }, ], }, { path: "*", name: "404", component: () => import(/* webpackChunkName: "404" */ "@/views/sign/404.vue"), meta: { title: "404", isShow: 1, }, }, ]; export default routes;
namespace Ceres.Spatial.Geometries.UnitTests { using System; using System.Linq; using NUnit.Framework; [TestFixture] public class MultiPointTest { [Test] public void t1() { var mp = new MultiPoint(0, new[] { new Point(0, 1, 2) }); var gc = (GeometryCollection)mp; var p1 = mp[0] switch { Point p => p, _ => throw new InvalidOperationException() }; var g1 = gc.First(); } } }
require 'leveldb-native/leveldb_native' module LevelDBNative class DB include Enumerable class << self # Loads or creates a database as necessary, stored on disk at # +pathname+. # # See #make for possible options. def new pathname, options={} make path_string(pathname), options.merge(:create_if_missing => true, :error_if_exists => false) end # Creates a new database stored on disk at +pathname+. Raises # LevelDBNative::Error if the database already exists. # # See #make for possible options. def create pathname, options={} make path_string(pathname), options.merge(:create_if_missing => true, :error_if_exists => true) end # Loads a database stored on disk at +pathname+. Raises # LevelDBNative::Error unless the database already exists. def load pathname make path_string(pathname), :create_if_missing => false, :error_if_exists => false end private # Coerces the argument into a String for use as a filename/-path def path_string pathname File.respond_to?(:path) ? File.path(pathname) : pathname.to_str end end attr_reader :pathname attr_reader :options alias :includes? :exists? alias :contains? :exists? alias :member? :exists? alias :[] :get alias :[]= :put alias :close! :close def each(*args, &block) i = iterator(*args) i.each(&block) if block i end def iterator(*args); Iterator.new self, *args; end def keys; map {|k, v| k} end def values; map {|k, v| v} end # If called with a block, yields a snapshot to the caller, and the # snapshot is released after the block finishes. Otherwise, returns a # snapshot and caller must call #release on the snapshot. def snapshot(*args) sn = Snapshot.new self, *args if block_given? begin yield sn ensure sn.release end else sn end end def inspect "<#{self.class} #{@pathname.inspect}>" end end class Iterator include Enumerable attr_reader :db, :from, :to def self.new(db, opts={}) make db, opts end def keys; map {|k, v| k} end def values; map {|k, v| v} end def reversed?; @reversed end def inspect "<#{self.class} #{db.inspect} " + "@from=#{@from.inspect} @to=#{@to.inspect}#{' (reversed)' if @reversed}>" end end class WriteBatch class << self private :new end alias :[]= :put end # Snapshot has the same API as DB, restricted to read access. class Snapshot include Enumerable def self.new(db) make db end def each(*args, &block) i = iterator(*args) i.each(&block) if block i end def get(*args) db.get(*args, snapshot: self) end alias :[] :get alias :includes? :exists? alias :contains? :exists? alias :member? :exists? def iterator(*args); db.iterator *args, snapshot: self; end def keys; map {|k, v| k} end def values; map {|k, v| v} end def inspect "<#{self.class} #{db.inspect} #{' (released)' if released?}>" end end class Options DEFAULT_MAX_OPEN_FILES = 1000 DEFAULT_WRITE_BUFFER_SIZE = 4 * 1024 * 1024 DEFAULT_BLOCK_SIZE = 4 * 1024 DEFAULT_BLOCK_RESTART_INTERVAL = 16 DEFAULT_COMPRESSION = LevelDBNative::CompressionType::SnappyCompression attr_reader :create_if_missing, :error_if_exists, :block_cache_size, :paranoid_checks, :write_buffer_size, :max_open_files, :block_size, :block_restart_interval, :compression end end
# frozen_string_literal: true require "mongoid/timestamps/updated/short" module Mongoid module Timestamps # This module handles the behavior for setting up document updated at # timestamp. module Updated extend ActiveSupport::Concern included do include Mongoid::Timestamps::Timeless field :updated_at, type: Time set_callback :create, :before, :set_updated_at set_callback :update, :before, :set_updated_at end # Update the updated_at field on the Document to the current time. # This is only called on create and on save. # # @example Set the updated at time. # person.set_updated_at def set_updated_at if able_to_set_updated_at? self.updated_at = Time.now.utc unless updated_at_changed? end clear_timeless_option end # Is the updated timestamp able to be set? # # @example Can the timestamp be set? # document.able_to_set_updated_at? # # @return [ true, false ] If the timestamp can be set. def able_to_set_updated_at? !frozen? && !timeless? && (new_record? || changed?) end end end end
--- title: Back up Opensea NFTs and earn KOII permalink: https://blog.koii.network/OpenSea-Tutorial/ number: 8 layout: koii101 ---
#pragma once #include <string> #include <tuple> namespace open_protocol::api { std::tuple<uint32_t, uint32_t, uint32_t> parse_message_prefix_revision(const std::string &s); }
#!/bin/bash # See http://stackoverflow.com/questions/5119946/find-exec-with-multiple-commands # for more information about find # Display recursively all the lines containing 'function' in the project folder # {} corresponds to the file name find . -not -path "*/node_modules/*" -name '*.js' \ -exec echo {} \;\ -exec grep function {} \; # Convert CRLF to LF in all files find . -not -path "*/node_modules/*" -name '*.js' \ -exec perl -pi -e 's/\r\n/\n/g' {} \; # Remove all ; at the end of lines find . -not -path "*/node_modules/*" -name '*.js' \ -exec perl -pi -e 's/;$//g' {} \;
import { useMutation, UseMutationOptions, useQuery, UseQueryOptions } from "react-query"; import { amplifyFetcher } from "../lib/fetcher"; export type Maybe<T> = T | null | undefined; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K]; }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; AWSDate: any; AWSDateTime: any; AWSEmail: any; AWSIPAddress: any; AWSJSON: any; AWSPhone: any; AWSTime: any; AWSTimestamp: any; AWSURL: any; BigInt: any; Double: any; }; export type CreateEc2ConfigInput = { id?: Maybe<Scalars["ID"]>; terminateTimestamp: Scalars["AWSTimestamp"]; userId: Scalars["String"]; vmType: Scalars["Int"]; }; export type CreateHistoryEntryInput = { id?: Maybe<Scalars["ID"]>; ec2ConfigId: Scalars["ID"]; comment: Scalars["String"]; time: Scalars["AWSDateTime"]; }; export type CreateMessageInput = { id?: Maybe<Scalars["ID"]>; authorId: Scalars["String"]; content: Scalars["String"]; createdAt?: Maybe<Scalars["AWSDateTime"]>; updatedAt?: Maybe<Scalars["AWSDateTime"]>; }; export type CreatePostInput = { id?: Maybe<Scalars["ID"]>; title: Scalars["String"]; content: Scalars["String"]; username: Scalars["String"]; }; export type DeleteEc2ConfigInput = { id?: Maybe<Scalars["ID"]>; }; export type DeleteHistoryEntryInput = { id?: Maybe<Scalars["ID"]>; }; export type DeleteMessageInput = { id?: Maybe<Scalars["ID"]>; }; export type DeletePostInput = { id?: Maybe<Scalars["ID"]>; }; export type Ec2 = { __typename?: "Ec2"; id: Scalars["ID"]; userId: Scalars["String"]; vmType: Scalars["Int"]; name: Scalars["String"]; state: State; publicDnsName?: Maybe<Scalars["String"]>; privateKey?: Maybe<Scalars["String"]>; }; export type Ec2Config = { __typename?: "Ec2Config"; id: Scalars["ID"]; terminateTimestamp: Scalars["AWSTimestamp"]; userId: Scalars["String"]; vmType: Scalars["Int"]; history?: Maybe<ModelHistoryEntryConnection>; createdAt: Scalars["AWSDateTime"]; updatedAt: Scalars["AWSDateTime"]; owner?: Maybe<Scalars["String"]>; }; export type Ec2ConfigHistoryArgs = { comment?: Maybe<ModelStringKeyConditionInput>; filter?: Maybe<ModelHistoryEntryFilterInput>; sortDirection?: Maybe<ModelSortDirection>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }; export type HistoryEntry = { __typename?: "HistoryEntry"; id: Scalars["ID"]; ec2ConfigId: Scalars["ID"]; comment: Scalars["String"]; time: Scalars["AWSDateTime"]; createdAt: Scalars["AWSDateTime"]; updatedAt: Scalars["AWSDateTime"]; }; export type Message = { __typename?: "Message"; id: Scalars["ID"]; authorId: Scalars["String"]; content: Scalars["String"]; createdAt: Scalars["AWSDateTime"]; updatedAt: Scalars["AWSDateTime"]; owner?: Maybe<Scalars["String"]>; }; export type ModelBooleanFilterInput = { ne?: Maybe<Scalars["Boolean"]>; eq?: Maybe<Scalars["Boolean"]>; }; export type ModelEc2ConfigConnection = { __typename?: "ModelEc2ConfigConnection"; items?: Maybe<Array<Maybe<Ec2Config>>>; nextToken?: Maybe<Scalars["String"]>; }; export type ModelEc2ConfigFilterInput = { id?: Maybe<ModelIdFilterInput>; terminateTimestamp?: Maybe<ModelIntFilterInput>; userId?: Maybe<ModelStringFilterInput>; vmType?: Maybe<ModelIntFilterInput>; and?: Maybe<Array<Maybe<ModelEc2ConfigFilterInput>>>; or?: Maybe<Array<Maybe<ModelEc2ConfigFilterInput>>>; not?: Maybe<ModelEc2ConfigFilterInput>; }; export type ModelFloatFilterInput = { ne?: Maybe<Scalars["Float"]>; eq?: Maybe<Scalars["Float"]>; le?: Maybe<Scalars["Float"]>; lt?: Maybe<Scalars["Float"]>; ge?: Maybe<Scalars["Float"]>; gt?: Maybe<Scalars["Float"]>; between?: Maybe<Array<Maybe<Scalars["Float"]>>>; }; export type ModelHistoryEntryConnection = { __typename?: "ModelHistoryEntryConnection"; items?: Maybe<Array<Maybe<HistoryEntry>>>; nextToken?: Maybe<Scalars["String"]>; }; export type ModelHistoryEntryFilterInput = { id?: Maybe<ModelIdFilterInput>; ec2ConfigId?: Maybe<ModelIdFilterInput>; comment?: Maybe<ModelStringFilterInput>; time?: Maybe<ModelStringFilterInput>; and?: Maybe<Array<Maybe<ModelHistoryEntryFilterInput>>>; or?: Maybe<Array<Maybe<ModelHistoryEntryFilterInput>>>; not?: Maybe<ModelHistoryEntryFilterInput>; }; export type ModelIdFilterInput = { ne?: Maybe<Scalars["ID"]>; eq?: Maybe<Scalars["ID"]>; le?: Maybe<Scalars["ID"]>; lt?: Maybe<Scalars["ID"]>; ge?: Maybe<Scalars["ID"]>; gt?: Maybe<Scalars["ID"]>; contains?: Maybe<Scalars["ID"]>; notContains?: Maybe<Scalars["ID"]>; between?: Maybe<Array<Maybe<Scalars["ID"]>>>; beginsWith?: Maybe<Scalars["ID"]>; }; export type ModelIntFilterInput = { ne?: Maybe<Scalars["Int"]>; eq?: Maybe<Scalars["Int"]>; le?: Maybe<Scalars["Int"]>; lt?: Maybe<Scalars["Int"]>; ge?: Maybe<Scalars["Int"]>; gt?: Maybe<Scalars["Int"]>; between?: Maybe<Array<Maybe<Scalars["Int"]>>>; }; export type ModelMessageConnection = { __typename?: "ModelMessageConnection"; items?: Maybe<Array<Maybe<Message>>>; nextToken?: Maybe<Scalars["String"]>; }; export type ModelMessageFilterInput = { id?: Maybe<ModelIdFilterInput>; authorId?: Maybe<ModelStringFilterInput>; content?: Maybe<ModelStringFilterInput>; createdAt?: Maybe<ModelStringFilterInput>; updatedAt?: Maybe<ModelStringFilterInput>; and?: Maybe<Array<Maybe<ModelMessageFilterInput>>>; or?: Maybe<Array<Maybe<ModelMessageFilterInput>>>; not?: Maybe<ModelMessageFilterInput>; }; export type ModelPostConnection = { __typename?: "ModelPostConnection"; items?: Maybe<Array<Maybe<Post>>>; nextToken?: Maybe<Scalars["String"]>; }; export type ModelPostFilterInput = { id?: Maybe<ModelIdFilterInput>; title?: Maybe<ModelStringFilterInput>; content?: Maybe<ModelStringFilterInput>; username?: Maybe<ModelStringFilterInput>; and?: Maybe<Array<Maybe<ModelPostFilterInput>>>; or?: Maybe<Array<Maybe<ModelPostFilterInput>>>; not?: Maybe<ModelPostFilterInput>; }; export enum ModelSortDirection { Asc = "ASC", Desc = "DESC" } export type ModelStringFilterInput = { ne?: Maybe<Scalars["String"]>; eq?: Maybe<Scalars["String"]>; le?: Maybe<Scalars["String"]>; lt?: Maybe<Scalars["String"]>; ge?: Maybe<Scalars["String"]>; gt?: Maybe<Scalars["String"]>; contains?: Maybe<Scalars["String"]>; notContains?: Maybe<Scalars["String"]>; between?: Maybe<Array<Maybe<Scalars["String"]>>>; beginsWith?: Maybe<Scalars["String"]>; }; export type ModelStringKeyConditionInput = { eq?: Maybe<Scalars["String"]>; le?: Maybe<Scalars["String"]>; lt?: Maybe<Scalars["String"]>; ge?: Maybe<Scalars["String"]>; gt?: Maybe<Scalars["String"]>; between?: Maybe<Array<Maybe<Scalars["String"]>>>; beginsWith?: Maybe<Scalars["String"]>; }; export type Mutation = { __typename?: "Mutation"; createHistoryEntry?: Maybe<HistoryEntry>; updateHistoryEntry?: Maybe<HistoryEntry>; deleteHistoryEntry?: Maybe<HistoryEntry>; createEc2Config?: Maybe<Ec2Config>; updateEc2Config?: Maybe<Ec2Config>; deleteEc2Config?: Maybe<Ec2Config>; createPost?: Maybe<Post>; updatePost?: Maybe<Post>; deletePost?: Maybe<Post>; createMessage?: Maybe<Message>; updateMessage?: Maybe<Message>; deleteMessage?: Maybe<Message>; }; export type MutationCreateHistoryEntryArgs = { input: CreateHistoryEntryInput; }; export type MutationUpdateHistoryEntryArgs = { input: UpdateHistoryEntryInput; }; export type MutationDeleteHistoryEntryArgs = { input: DeleteHistoryEntryInput; }; export type MutationCreateEc2ConfigArgs = { input: CreateEc2ConfigInput; }; export type MutationUpdateEc2ConfigArgs = { input: UpdateEc2ConfigInput; }; export type MutationDeleteEc2ConfigArgs = { input: DeleteEc2ConfigInput; }; export type MutationCreatePostArgs = { input: CreatePostInput; }; export type MutationUpdatePostArgs = { input: UpdatePostInput; }; export type MutationDeletePostArgs = { input: DeletePostInput; }; export type MutationCreateMessageArgs = { input: CreateMessageInput; }; export type MutationUpdateMessageArgs = { input: UpdateMessageInput; }; export type MutationDeleteMessageArgs = { input: DeleteMessageInput; }; export type Post = { __typename?: "Post"; id: Scalars["ID"]; title: Scalars["String"]; content: Scalars["String"]; username: Scalars["String"]; createdAt: Scalars["AWSDateTime"]; updatedAt: Scalars["AWSDateTime"]; owner?: Maybe<Scalars["String"]>; }; export type Query = { __typename?: "Query"; listTodos?: Maybe<Array<Maybe<Todo>>>; listEc2?: Maybe<Array<Maybe<Ec2>>>; getHistoryEntry?: Maybe<HistoryEntry>; listHistoryEntrys?: Maybe<ModelHistoryEntryConnection>; getEc2Config?: Maybe<Ec2Config>; listEc2Configs?: Maybe<ModelEc2ConfigConnection>; getPost?: Maybe<Post>; listPosts?: Maybe<ModelPostConnection>; getMessage?: Maybe<Message>; listMessages?: Maybe<ModelMessageConnection>; getTodo?: Maybe<Todo>; }; export type QueryGetHistoryEntryArgs = { id: Scalars["ID"]; }; export type QueryListHistoryEntrysArgs = { filter?: Maybe<ModelHistoryEntryFilterInput>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }; export type QueryGetEc2ConfigArgs = { id: Scalars["ID"]; }; export type QueryListEc2ConfigsArgs = { filter?: Maybe<ModelEc2ConfigFilterInput>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }; export type QueryGetPostArgs = { id: Scalars["ID"]; }; export type QueryListPostsArgs = { filter?: Maybe<ModelPostFilterInput>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }; export type QueryGetMessageArgs = { id: Scalars["ID"]; }; export type QueryListMessagesArgs = { filter?: Maybe<ModelMessageFilterInput>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }; export type QueryGetTodoArgs = { params: QueryGetTodoParamsInput; }; export type QueryGetTodoParamsInput = { id: Scalars["String"]; }; export enum State { Pending = "PENDING", Running = "RUNNING", Terminated = "TERMINATED", Stopping = "STOPPING", Stopped = "STOPPED", ShuttingDown = "SHUTTING_DOWN", Unkown = "UNKOWN" } export type Subscription = { __typename?: "Subscription"; onCreateHistoryEntry?: Maybe<HistoryEntry>; onUpdateHistoryEntry?: Maybe<HistoryEntry>; onDeleteHistoryEntry?: Maybe<HistoryEntry>; onCreateEc2Config?: Maybe<Ec2Config>; onUpdateEc2Config?: Maybe<Ec2Config>; onDeleteEc2Config?: Maybe<Ec2Config>; onCreatePost?: Maybe<Post>; onUpdatePost?: Maybe<Post>; onDeletePost?: Maybe<Post>; onCreateMessage?: Maybe<Message>; onUpdateMessage?: Maybe<Message>; onDeleteMessage?: Maybe<Message>; }; export type SubscriptionOnCreatePostArgs = { owner?: Maybe<Scalars["String"]>; }; export type SubscriptionOnUpdatePostArgs = { owner?: Maybe<Scalars["String"]>; }; export type SubscriptionOnDeletePostArgs = { owner?: Maybe<Scalars["String"]>; }; export type Todo = { __typename?: "Todo"; id: Scalars["Int"]; userId: Scalars["Int"]; title: Scalars["String"]; completed: Scalars["Boolean"]; }; export type UpdateEc2ConfigInput = { id: Scalars["ID"]; terminateTimestamp?: Maybe<Scalars["AWSTimestamp"]>; userId?: Maybe<Scalars["String"]>; vmType?: Maybe<Scalars["Int"]>; }; export type UpdateHistoryEntryInput = { id: Scalars["ID"]; ec2ConfigId?: Maybe<Scalars["ID"]>; comment?: Maybe<Scalars["String"]>; time?: Maybe<Scalars["AWSDateTime"]>; }; export type UpdateMessageInput = { id: Scalars["ID"]; authorId?: Maybe<Scalars["String"]>; content?: Maybe<Scalars["String"]>; createdAt?: Maybe<Scalars["AWSDateTime"]>; updatedAt?: Maybe<Scalars["AWSDateTime"]>; }; export type UpdatePostInput = { id: Scalars["ID"]; title?: Maybe<Scalars["String"]>; content?: Maybe<Scalars["String"]>; username?: Maybe<Scalars["String"]>; }; export type CreateHistoryEntryMutationVariables = Exact<{ input: CreateHistoryEntryInput; }>; export type CreateHistoryEntryMutation = { __typename?: "Mutation" } & { createHistoryEntry?: Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > >; }; export type UpdateHistoryEntryMutationVariables = Exact<{ input: UpdateHistoryEntryInput; }>; export type UpdateHistoryEntryMutation = { __typename?: "Mutation" } & { updateHistoryEntry?: Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > >; }; export type DeleteHistoryEntryMutationVariables = Exact<{ input: DeleteHistoryEntryInput; }>; export type DeleteHistoryEntryMutation = { __typename?: "Mutation" } & { deleteHistoryEntry?: Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > >; }; export type CreateEc2ConfigMutationVariables = Exact<{ input: CreateEc2ConfigInput; }>; export type CreateEc2ConfigMutation = { __typename?: "Mutation" } & { createEc2Config?: Maybe< { __typename?: "Ec2Config" } & Pick< Ec2Config, | "id" | "terminateTimestamp" | "userId" | "vmType" | "createdAt" | "updatedAt" | "owner" > & { history?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; } >; }; export type UpdateEc2ConfigMutationVariables = Exact<{ input: UpdateEc2ConfigInput; }>; export type UpdateEc2ConfigMutation = { __typename?: "Mutation" } & { updateEc2Config?: Maybe< { __typename?: "Ec2Config" } & Pick< Ec2Config, | "id" | "terminateTimestamp" | "userId" | "vmType" | "createdAt" | "updatedAt" | "owner" > & { history?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; } >; }; export type DeleteEc2ConfigMutationVariables = Exact<{ input: DeleteEc2ConfigInput; }>; export type DeleteEc2ConfigMutation = { __typename?: "Mutation" } & { deleteEc2Config?: Maybe< { __typename?: "Ec2Config" } & Pick< Ec2Config, | "id" | "terminateTimestamp" | "userId" | "vmType" | "createdAt" | "updatedAt" | "owner" > & { history?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; } >; }; export type CreatePostMutationVariables = Exact<{ input: CreatePostInput; }>; export type CreatePostMutation = { __typename?: "Mutation" } & { createPost?: Maybe< { __typename?: "Post" } & Pick< Post, | "id" | "title" | "content" | "username" | "createdAt" | "updatedAt" | "owner" > >; }; export type UpdatePostMutationVariables = Exact<{ input: UpdatePostInput; }>; export type UpdatePostMutation = { __typename?: "Mutation" } & { updatePost?: Maybe< { __typename?: "Post" } & Pick< Post, | "id" | "title" | "content" | "username" | "createdAt" | "updatedAt" | "owner" > >; }; export type DeletePostMutationVariables = Exact<{ input: DeletePostInput; }>; export type DeletePostMutation = { __typename?: "Mutation" } & { deletePost?: Maybe< { __typename?: "Post" } & Pick< Post, | "id" | "title" | "content" | "username" | "createdAt" | "updatedAt" | "owner" > >; }; export type CreateMessageMutationVariables = Exact<{ input: CreateMessageInput; }>; export type CreateMessageMutation = { __typename?: "Mutation" } & { createMessage?: Maybe< { __typename?: "Message" } & Pick< Message, "id" | "authorId" | "content" | "createdAt" | "updatedAt" | "owner" > >; }; export type UpdateMessageMutationVariables = Exact<{ input: UpdateMessageInput; }>; export type UpdateMessageMutation = { __typename?: "Mutation" } & { updateMessage?: Maybe< { __typename?: "Message" } & Pick< Message, "id" | "authorId" | "content" | "createdAt" | "updatedAt" | "owner" > >; }; export type DeleteMessageMutationVariables = Exact<{ input: DeleteMessageInput; }>; export type DeleteMessageMutation = { __typename?: "Mutation" } & { deleteMessage?: Maybe< { __typename?: "Message" } & Pick< Message, "id" | "authorId" | "content" | "createdAt" | "updatedAt" | "owner" > >; }; export type ListTodosQueryVariables = Exact<{ [key: string]: never }>; export type ListTodosQuery = { __typename?: "Query" } & { listTodos?: Maybe< Array< Maybe< { __typename?: "Todo" } & Pick< Todo, "id" | "userId" | "title" | "completed" > > > >; }; export type ListEc2QueryVariables = Exact<{ [key: string]: never }>; export type ListEc2Query = { __typename?: "Query" } & { listEc2?: Maybe< Array< Maybe< { __typename?: "Ec2" } & Pick< Ec2, | "id" | "userId" | "vmType" | "name" | "state" | "publicDnsName" | "privateKey" > > > >; }; export type GetHistoryEntryQueryVariables = Exact<{ id: Scalars["ID"]; }>; export type GetHistoryEntryQuery = { __typename?: "Query" } & { getHistoryEntry?: Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > >; }; export type ListHistoryEntrysQueryVariables = Exact<{ filter?: Maybe<ModelHistoryEntryFilterInput>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }>; export type ListHistoryEntrysQuery = { __typename?: "Query" } & { listHistoryEntrys?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; }; export type GetEc2ConfigQueryVariables = Exact<{ id: Scalars["ID"]; }>; export type GetEc2ConfigQuery = { __typename?: "Query" } & { getEc2Config?: Maybe< { __typename?: "Ec2Config" } & Pick< Ec2Config, | "id" | "terminateTimestamp" | "userId" | "vmType" | "createdAt" | "updatedAt" | "owner" > & { history?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; } >; }; export type ListEc2ConfigsQueryVariables = Exact<{ filter?: Maybe<ModelEc2ConfigFilterInput>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }>; export type ListEc2ConfigsQuery = { __typename?: "Query" } & { listEc2Configs?: Maybe< { __typename?: "ModelEc2ConfigConnection" } & Pick< ModelEc2ConfigConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "Ec2Config" } & Pick< Ec2Config, | "id" | "terminateTimestamp" | "userId" | "vmType" | "createdAt" | "updatedAt" | "owner" > & { history?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; } > > >; } >; }; export type GetPostQueryVariables = Exact<{ id: Scalars["ID"]; }>; export type GetPostQuery = { __typename?: "Query" } & { getPost?: Maybe< { __typename?: "Post" } & Pick< Post, | "id" | "title" | "content" | "username" | "createdAt" | "updatedAt" | "owner" > >; }; export type ListPostsQueryVariables = Exact<{ filter?: Maybe<ModelPostFilterInput>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }>; export type ListPostsQuery = { __typename?: "Query" } & { listPosts?: Maybe< { __typename?: "ModelPostConnection" } & Pick< ModelPostConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "Post" } & Pick< Post, | "id" | "title" | "content" | "username" | "createdAt" | "updatedAt" | "owner" > > > >; } >; }; export type GetMessageQueryVariables = Exact<{ id: Scalars["ID"]; }>; export type GetMessageQuery = { __typename?: "Query" } & { getMessage?: Maybe< { __typename?: "Message" } & Pick< Message, "id" | "authorId" | "content" | "createdAt" | "updatedAt" | "owner" > >; }; export type ListMessagesQueryVariables = Exact<{ filter?: Maybe<ModelMessageFilterInput>; limit?: Maybe<Scalars["Int"]>; nextToken?: Maybe<Scalars["String"]>; }>; export type ListMessagesQuery = { __typename?: "Query" } & { listMessages?: Maybe< { __typename?: "ModelMessageConnection" } & Pick< ModelMessageConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "Message" } & Pick< Message, | "id" | "authorId" | "content" | "createdAt" | "updatedAt" | "owner" > > > >; } >; }; export type GetTodoQueryVariables = Exact<{ params: QueryGetTodoParamsInput; }>; export type GetTodoQuery = { __typename?: "Query" } & { getTodo?: Maybe< { __typename?: "Todo" } & Pick< Todo, "id" | "userId" | "title" | "completed" > >; }; export type OnCreateHistoryEntrySubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnCreateHistoryEntrySubscription = { __typename?: "Subscription"; } & { onCreateHistoryEntry?: Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > >; }; export type OnUpdateHistoryEntrySubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnUpdateHistoryEntrySubscription = { __typename?: "Subscription"; } & { onUpdateHistoryEntry?: Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > >; }; export type OnDeleteHistoryEntrySubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnDeleteHistoryEntrySubscription = { __typename?: "Subscription"; } & { onDeleteHistoryEntry?: Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > >; }; export type OnCreateEc2ConfigSubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnCreateEc2ConfigSubscription = { __typename?: "Subscription" } & { onCreateEc2Config?: Maybe< { __typename?: "Ec2Config" } & Pick< Ec2Config, | "id" | "terminateTimestamp" | "userId" | "vmType" | "createdAt" | "updatedAt" | "owner" > & { history?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; } >; }; export type OnUpdateEc2ConfigSubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnUpdateEc2ConfigSubscription = { __typename?: "Subscription" } & { onUpdateEc2Config?: Maybe< { __typename?: "Ec2Config" } & Pick< Ec2Config, | "id" | "terminateTimestamp" | "userId" | "vmType" | "createdAt" | "updatedAt" | "owner" > & { history?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; } >; }; export type OnDeleteEc2ConfigSubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnDeleteEc2ConfigSubscription = { __typename?: "Subscription" } & { onDeleteEc2Config?: Maybe< { __typename?: "Ec2Config" } & Pick< Ec2Config, | "id" | "terminateTimestamp" | "userId" | "vmType" | "createdAt" | "updatedAt" | "owner" > & { history?: Maybe< { __typename?: "ModelHistoryEntryConnection" } & Pick< ModelHistoryEntryConnection, "nextToken" > & { items?: Maybe< Array< Maybe< { __typename?: "HistoryEntry" } & Pick< HistoryEntry, | "id" | "ec2ConfigId" | "comment" | "time" | "createdAt" | "updatedAt" > > > >; } >; } >; }; export type OnCreatePostSubscriptionVariables = Exact<{ owner?: Maybe<Scalars["String"]>; }>; export type OnCreatePostSubscription = { __typename?: "Subscription" } & { onCreatePost?: Maybe< { __typename?: "Post" } & Pick< Post, | "id" | "title" | "content" | "username" | "createdAt" | "updatedAt" | "owner" > >; }; export type OnUpdatePostSubscriptionVariables = Exact<{ owner?: Maybe<Scalars["String"]>; }>; export type OnUpdatePostSubscription = { __typename?: "Subscription" } & { onUpdatePost?: Maybe< { __typename?: "Post" } & Pick< Post, | "id" | "title" | "content" | "username" | "createdAt" | "updatedAt" | "owner" > >; }; export type OnDeletePostSubscriptionVariables = Exact<{ owner?: Maybe<Scalars["String"]>; }>; export type OnDeletePostSubscription = { __typename?: "Subscription" } & { onDeletePost?: Maybe< { __typename?: "Post" } & Pick< Post, | "id" | "title" | "content" | "username" | "createdAt" | "updatedAt" | "owner" > >; }; export type OnCreateMessageSubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnCreateMessageSubscription = { __typename?: "Subscription" } & { onCreateMessage?: Maybe< { __typename?: "Message" } & Pick< Message, "id" | "authorId" | "content" | "createdAt" | "updatedAt" | "owner" > >; }; export type OnUpdateMessageSubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnUpdateMessageSubscription = { __typename?: "Subscription" } & { onUpdateMessage?: Maybe< { __typename?: "Message" } & Pick< Message, "id" | "authorId" | "content" | "createdAt" | "updatedAt" | "owner" > >; }; export type OnDeleteMessageSubscriptionVariables = Exact<{ [key: string]: never; }>; export type OnDeleteMessageSubscription = { __typename?: "Subscription" } & { onDeleteMessage?: Maybe< { __typename?: "Message" } & Pick< Message, "id" | "authorId" | "content" | "createdAt" | "updatedAt" | "owner" > >; }; export const CreateHistoryEntryDocument = ` mutation CreateHistoryEntry($input: CreateHistoryEntryInput!) { createHistoryEntry(input: $input) { id ec2ConfigId comment time createdAt updatedAt } } `; export const useCreateHistoryEntryMutation = < TError = unknown, TContext = unknown >( options?: UseMutationOptions< CreateHistoryEntryMutation, TError, CreateHistoryEntryMutationVariables, TContext > ) => useMutation< CreateHistoryEntryMutation, TError, CreateHistoryEntryMutationVariables, TContext >( (variables?: CreateHistoryEntryMutationVariables) => amplifyFetcher< CreateHistoryEntryMutation, CreateHistoryEntryMutationVariables >(CreateHistoryEntryDocument, variables)(), options ); export const UpdateHistoryEntryDocument = ` mutation UpdateHistoryEntry($input: UpdateHistoryEntryInput!) { updateHistoryEntry(input: $input) { id ec2ConfigId comment time createdAt updatedAt } } `; export const useUpdateHistoryEntryMutation = < TError = unknown, TContext = unknown >( options?: UseMutationOptions< UpdateHistoryEntryMutation, TError, UpdateHistoryEntryMutationVariables, TContext > ) => useMutation< UpdateHistoryEntryMutation, TError, UpdateHistoryEntryMutationVariables, TContext >( (variables?: UpdateHistoryEntryMutationVariables) => amplifyFetcher< UpdateHistoryEntryMutation, UpdateHistoryEntryMutationVariables >(UpdateHistoryEntryDocument, variables)(), options ); export const DeleteHistoryEntryDocument = ` mutation DeleteHistoryEntry($input: DeleteHistoryEntryInput!) { deleteHistoryEntry(input: $input) { id ec2ConfigId comment time createdAt updatedAt } } `; export const useDeleteHistoryEntryMutation = < TError = unknown, TContext = unknown >( options?: UseMutationOptions< DeleteHistoryEntryMutation, TError, DeleteHistoryEntryMutationVariables, TContext > ) => useMutation< DeleteHistoryEntryMutation, TError, DeleteHistoryEntryMutationVariables, TContext >( (variables?: DeleteHistoryEntryMutationVariables) => amplifyFetcher< DeleteHistoryEntryMutation, DeleteHistoryEntryMutationVariables >(DeleteHistoryEntryDocument, variables)(), options ); export const CreateEc2ConfigDocument = ` mutation CreateEc2Config($input: CreateEc2ConfigInput!) { createEc2Config(input: $input) { id terminateTimestamp userId vmType history { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } createdAt updatedAt owner } } `; export const useCreateEc2ConfigMutation = < TError = unknown, TContext = unknown >( options?: UseMutationOptions< CreateEc2ConfigMutation, TError, CreateEc2ConfigMutationVariables, TContext > ) => useMutation< CreateEc2ConfigMutation, TError, CreateEc2ConfigMutationVariables, TContext >( (variables?: CreateEc2ConfigMutationVariables) => amplifyFetcher<CreateEc2ConfigMutation, CreateEc2ConfigMutationVariables>( CreateEc2ConfigDocument, variables )(), options ); export const UpdateEc2ConfigDocument = ` mutation UpdateEc2Config($input: UpdateEc2ConfigInput!) { updateEc2Config(input: $input) { id terminateTimestamp userId vmType history { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } createdAt updatedAt owner } } `; export const useUpdateEc2ConfigMutation = < TError = unknown, TContext = unknown >( options?: UseMutationOptions< UpdateEc2ConfigMutation, TError, UpdateEc2ConfigMutationVariables, TContext > ) => useMutation< UpdateEc2ConfigMutation, TError, UpdateEc2ConfigMutationVariables, TContext >( (variables?: UpdateEc2ConfigMutationVariables) => amplifyFetcher<UpdateEc2ConfigMutation, UpdateEc2ConfigMutationVariables>( UpdateEc2ConfigDocument, variables )(), options ); export const DeleteEc2ConfigDocument = ` mutation DeleteEc2Config($input: DeleteEc2ConfigInput!) { deleteEc2Config(input: $input) { id terminateTimestamp userId vmType history { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } createdAt updatedAt owner } } `; export const useDeleteEc2ConfigMutation = < TError = unknown, TContext = unknown >( options?: UseMutationOptions< DeleteEc2ConfigMutation, TError, DeleteEc2ConfigMutationVariables, TContext > ) => useMutation< DeleteEc2ConfigMutation, TError, DeleteEc2ConfigMutationVariables, TContext >( (variables?: DeleteEc2ConfigMutationVariables) => amplifyFetcher<DeleteEc2ConfigMutation, DeleteEc2ConfigMutationVariables>( DeleteEc2ConfigDocument, variables )(), options ); export const CreatePostDocument = ` mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id title content username createdAt updatedAt owner } } `; export const useCreatePostMutation = <TError = unknown, TContext = unknown>( options?: UseMutationOptions< CreatePostMutation, TError, CreatePostMutationVariables, TContext > ) => useMutation< CreatePostMutation, TError, CreatePostMutationVariables, TContext >( (variables?: CreatePostMutationVariables) => amplifyFetcher<CreatePostMutation, CreatePostMutationVariables>( CreatePostDocument, variables )(), options ); export const UpdatePostDocument = ` mutation UpdatePost($input: UpdatePostInput!) { updatePost(input: $input) { id title content username createdAt updatedAt owner } } `; export const useUpdatePostMutation = <TError = unknown, TContext = unknown>( options?: UseMutationOptions< UpdatePostMutation, TError, UpdatePostMutationVariables, TContext > ) => useMutation< UpdatePostMutation, TError, UpdatePostMutationVariables, TContext >( (variables?: UpdatePostMutationVariables) => amplifyFetcher<UpdatePostMutation, UpdatePostMutationVariables>( UpdatePostDocument, variables )(), options ); export const DeletePostDocument = ` mutation DeletePost($input: DeletePostInput!) { deletePost(input: $input) { id title content username createdAt updatedAt owner } } `; export const useDeletePostMutation = <TError = unknown, TContext = unknown>( options?: UseMutationOptions< DeletePostMutation, TError, DeletePostMutationVariables, TContext > ) => useMutation< DeletePostMutation, TError, DeletePostMutationVariables, TContext >( (variables?: DeletePostMutationVariables) => amplifyFetcher<DeletePostMutation, DeletePostMutationVariables>( DeletePostDocument, variables )(), options ); export const CreateMessageDocument = ` mutation CreateMessage($input: CreateMessageInput!) { createMessage(input: $input) { id authorId content createdAt updatedAt owner } } `; export const useCreateMessageMutation = <TError = unknown, TContext = unknown>( options?: UseMutationOptions< CreateMessageMutation, TError, CreateMessageMutationVariables, TContext > ) => useMutation< CreateMessageMutation, TError, CreateMessageMutationVariables, TContext >( (variables?: CreateMessageMutationVariables) => amplifyFetcher<CreateMessageMutation, CreateMessageMutationVariables>( CreateMessageDocument, variables )(), options ); export const UpdateMessageDocument = ` mutation UpdateMessage($input: UpdateMessageInput!) { updateMessage(input: $input) { id authorId content createdAt updatedAt owner } } `; export const useUpdateMessageMutation = <TError = unknown, TContext = unknown>( options?: UseMutationOptions< UpdateMessageMutation, TError, UpdateMessageMutationVariables, TContext > ) => useMutation< UpdateMessageMutation, TError, UpdateMessageMutationVariables, TContext >( (variables?: UpdateMessageMutationVariables) => amplifyFetcher<UpdateMessageMutation, UpdateMessageMutationVariables>( UpdateMessageDocument, variables )(), options ); export const DeleteMessageDocument = ` mutation DeleteMessage($input: DeleteMessageInput!) { deleteMessage(input: $input) { id authorId content createdAt updatedAt owner } } `; export const useDeleteMessageMutation = <TError = unknown, TContext = unknown>( options?: UseMutationOptions< DeleteMessageMutation, TError, DeleteMessageMutationVariables, TContext > ) => useMutation< DeleteMessageMutation, TError, DeleteMessageMutationVariables, TContext >( (variables?: DeleteMessageMutationVariables) => amplifyFetcher<DeleteMessageMutation, DeleteMessageMutationVariables>( DeleteMessageDocument, variables )(), options ); export const ListTodosDocument = ` query ListTodos { listTodos { id userId title completed } } `; export const useListTodosQuery = <TData = ListTodosQuery, TError = unknown>( variables?: ListTodosQueryVariables, options?: UseQueryOptions<ListTodosQuery, TError, TData> ) => useQuery<ListTodosQuery, TError, TData>( ["ListTodos", variables], amplifyFetcher<ListTodosQuery, ListTodosQueryVariables>( ListTodosDocument, variables ), options ); export const ListEc2Document = ` query ListEc2 { listEc2 { id userId vmType name state publicDnsName privateKey } } `; export const useListEc2Query = <TData = ListEc2Query, TError = unknown>( variables?: ListEc2QueryVariables, options?: UseQueryOptions<ListEc2Query, TError, TData> ) => useQuery<ListEc2Query, TError, TData>( ["ListEc2", variables], amplifyFetcher<ListEc2Query, ListEc2QueryVariables>( ListEc2Document, variables ), options ); export const GetHistoryEntryDocument = ` query GetHistoryEntry($id: ID!) { getHistoryEntry(id: $id) { id ec2ConfigId comment time createdAt updatedAt } } `; export const useGetHistoryEntryQuery = < TData = GetHistoryEntryQuery, TError = unknown >( variables: GetHistoryEntryQueryVariables, options?: UseQueryOptions<GetHistoryEntryQuery, TError, TData> ) => useQuery<GetHistoryEntryQuery, TError, TData>( ["GetHistoryEntry", variables], amplifyFetcher<GetHistoryEntryQuery, GetHistoryEntryQueryVariables>( GetHistoryEntryDocument, variables ), options ); export const ListHistoryEntrysDocument = ` query ListHistoryEntrys($filter: ModelHistoryEntryFilterInput, $limit: Int, $nextToken: String) { listHistoryEntrys(filter: $filter, limit: $limit, nextToken: $nextToken) { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } } `; export const useListHistoryEntrysQuery = < TData = ListHistoryEntrysQuery, TError = unknown >( variables?: ListHistoryEntrysQueryVariables, options?: UseQueryOptions<ListHistoryEntrysQuery, TError, TData> ) => useQuery<ListHistoryEntrysQuery, TError, TData>( ["ListHistoryEntrys", variables], amplifyFetcher<ListHistoryEntrysQuery, ListHistoryEntrysQueryVariables>( ListHistoryEntrysDocument, variables ), options ); export const GetEc2ConfigDocument = ` query GetEc2Config($id: ID!) { getEc2Config(id: $id) { id terminateTimestamp userId vmType history { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } createdAt updatedAt owner } } `; export const useGetEc2ConfigQuery = < TData = GetEc2ConfigQuery, TError = unknown >( variables: GetEc2ConfigQueryVariables, options?: UseQueryOptions<GetEc2ConfigQuery, TError, TData> ) => useQuery<GetEc2ConfigQuery, TError, TData>( ["GetEc2Config", variables], amplifyFetcher<GetEc2ConfigQuery, GetEc2ConfigQueryVariables>( GetEc2ConfigDocument, variables ), options ); export const ListEc2ConfigsDocument = ` query ListEc2Configs($filter: ModelEc2ConfigFilterInput, $limit: Int, $nextToken: String) { listEc2Configs(filter: $filter, limit: $limit, nextToken: $nextToken) { items { id terminateTimestamp userId vmType history { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } createdAt updatedAt owner } nextToken } } `; export const useListEc2ConfigsQuery = < TData = ListEc2ConfigsQuery, TError = unknown >( variables?: ListEc2ConfigsQueryVariables, options?: UseQueryOptions<ListEc2ConfigsQuery, TError, TData> ) => useQuery<ListEc2ConfigsQuery, TError, TData>( ["ListEc2Configs", variables], amplifyFetcher<ListEc2ConfigsQuery, ListEc2ConfigsQueryVariables>( ListEc2ConfigsDocument, variables ), options ); export const GetPostDocument = ` query GetPost($id: ID!) { getPost(id: $id) { id title content username createdAt updatedAt owner } } `; export const useGetPostQuery = <TData = GetPostQuery, TError = unknown>( variables: GetPostQueryVariables, options?: UseQueryOptions<GetPostQuery, TError, TData> ) => useQuery<GetPostQuery, TError, TData>( ["GetPost", variables], amplifyFetcher<GetPostQuery, GetPostQueryVariables>( GetPostDocument, variables ), options ); export const ListPostsDocument = ` query ListPosts($filter: ModelPostFilterInput, $limit: Int, $nextToken: String) { listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) { items { id title content username createdAt updatedAt owner } nextToken } } `; export const useListPostsQuery = <TData = ListPostsQuery, TError = unknown>( variables?: ListPostsQueryVariables, options?: UseQueryOptions<ListPostsQuery, TError, TData> ) => useQuery<ListPostsQuery, TError, TData>( ["ListPosts", variables], amplifyFetcher<ListPostsQuery, ListPostsQueryVariables>( ListPostsDocument, variables ), options ); export const GetMessageDocument = ` query GetMessage($id: ID!) { getMessage(id: $id) { id authorId content createdAt updatedAt owner } } `; export const useGetMessageQuery = <TData = GetMessageQuery, TError = unknown>( variables: GetMessageQueryVariables, options?: UseQueryOptions<GetMessageQuery, TError, TData> ) => useQuery<GetMessageQuery, TError, TData>( ["GetMessage", variables], amplifyFetcher<GetMessageQuery, GetMessageQueryVariables>( GetMessageDocument, variables ), options ); export const ListMessagesDocument = ` query ListMessages($filter: ModelMessageFilterInput, $limit: Int, $nextToken: String) { listMessages(filter: $filter, limit: $limit, nextToken: $nextToken) { items { id authorId content createdAt updatedAt owner } nextToken } } `; export const useListMessagesQuery = < TData = ListMessagesQuery, TError = unknown >( variables?: ListMessagesQueryVariables, options?: UseQueryOptions<ListMessagesQuery, TError, TData> ) => useQuery<ListMessagesQuery, TError, TData>( ["ListMessages", variables], amplifyFetcher<ListMessagesQuery, ListMessagesQueryVariables>( ListMessagesDocument, variables ), options ); export const GetTodoDocument = ` query GetTodo($params: QueryGetTodoParamsInput!) { getTodo(params: $params) { id userId title completed } } `; export const useGetTodoQuery = <TData = GetTodoQuery, TError = unknown>( variables: GetTodoQueryVariables, options?: UseQueryOptions<GetTodoQuery, TError, TData> ) => useQuery<GetTodoQuery, TError, TData>( ["GetTodo", variables], amplifyFetcher<GetTodoQuery, GetTodoQueryVariables>( GetTodoDocument, variables ), options ); export const OnCreateHistoryEntryDocument = ` subscription OnCreateHistoryEntry { onCreateHistoryEntry { id ec2ConfigId comment time createdAt updatedAt } } `; export const OnUpdateHistoryEntryDocument = ` subscription OnUpdateHistoryEntry { onUpdateHistoryEntry { id ec2ConfigId comment time createdAt updatedAt } } `; export const OnDeleteHistoryEntryDocument = ` subscription OnDeleteHistoryEntry { onDeleteHistoryEntry { id ec2ConfigId comment time createdAt updatedAt } } `; export const OnCreateEc2ConfigDocument = ` subscription OnCreateEc2Config { onCreateEc2Config { id terminateTimestamp userId vmType history { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } createdAt updatedAt owner } } `; export const OnUpdateEc2ConfigDocument = ` subscription OnUpdateEc2Config { onUpdateEc2Config { id terminateTimestamp userId vmType history { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } createdAt updatedAt owner } } `; export const OnDeleteEc2ConfigDocument = ` subscription OnDeleteEc2Config { onDeleteEc2Config { id terminateTimestamp userId vmType history { items { id ec2ConfigId comment time createdAt updatedAt } nextToken } createdAt updatedAt owner } } `; export const OnCreatePostDocument = ` subscription OnCreatePost($owner: String) { onCreatePost(owner: $owner) { id title content username createdAt updatedAt owner } } `; export const OnUpdatePostDocument = ` subscription OnUpdatePost($owner: String) { onUpdatePost(owner: $owner) { id title content username createdAt updatedAt owner } } `; export const OnDeletePostDocument = ` subscription OnDeletePost($owner: String) { onDeletePost(owner: $owner) { id title content username createdAt updatedAt owner } } `; export const OnCreateMessageDocument = ` subscription OnCreateMessage { onCreateMessage { id authorId content createdAt updatedAt owner } } `; export const OnUpdateMessageDocument = ` subscription OnUpdateMessage { onUpdateMessage { id authorId content createdAt updatedAt owner } } `; export const OnDeleteMessageDocument = ` subscription OnDeleteMessage { onDeleteMessage { id authorId content createdAt updatedAt owner } } `;
import 'package:hetu_script/hetu_script.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; class TableRowAutoBinding extends HTExternalClass { TableRowAutoBinding() : super('TableRow'); @override dynamic memberGet(String varName, {String from = HTLexicon.global}) { switch (varName) { case 'TableRow': return ({positionalArgs, namedArgs, typeArgs}) => TableRow( key: namedArgs.containsKey('key') ? namedArgs['key'] : null, decoration: namedArgs.containsKey('decoration') ? namedArgs['decoration'] : null, children: namedArgs.containsKey('children') ? List<Widget>.from(namedArgs['children']) : null); default: throw HTError.undefined(varName); } } @override dynamic instanceMemberGet(dynamic instance, String id) { return (instance as TableRow).htFetch(id); } } extension TableRowBinding on TableRow { dynamic htFetch(String varName) { switch (varName) { case 'runtimeType': return const HTType('TableRow'); case 'key': return key; case 'decoration': return decoration; case 'children': return children; case 'toString': return ({positionalArgs, namedArgs, typeArgs}) => toString(); default: throw HTError.undefined(varName); } } } class TableAutoBinding extends HTExternalClass { TableAutoBinding() : super('Table'); @override dynamic memberGet(String varName, {String from = HTLexicon.global}) { switch (varName) { case 'Table': return ({positionalArgs, namedArgs, typeArgs}) => Table( key: namedArgs.containsKey('key') ? namedArgs['key'] : null, children: namedArgs.containsKey('children') ? List<TableRow>.from(namedArgs['children']) : const <TableRow>[], columnWidths: namedArgs.containsKey('columnWidths') ? namedArgs['columnWidths'] : null, defaultColumnWidth: namedArgs.containsKey('defaultColumnWidth') ? namedArgs['defaultColumnWidth'] : const FlexColumnWidth(1.0), textDirection: namedArgs.containsKey('textDirection') ? namedArgs['textDirection'] : null, border: namedArgs.containsKey('border') ? namedArgs['border'] : null, defaultVerticalAlignment: namedArgs.containsKey('defaultVerticalAlignment') ? namedArgs['defaultVerticalAlignment'] : TableCellVerticalAlignment.top, textBaseline: namedArgs.containsKey('textBaseline') ? namedArgs['textBaseline'] : null); default: throw HTError.undefined(varName); } } @override dynamic instanceMemberGet(dynamic instance, String id) { return (instance as Table).htFetch(id); } } extension TableBinding on Table { dynamic htFetch(String varName) { switch (varName) { case 'runtimeType': return const HTType('Table'); case 'children': return children; case 'columnWidths': return columnWidths; case 'defaultColumnWidth': return defaultColumnWidth; case 'textDirection': return textDirection; case 'border': return border; case 'defaultVerticalAlignment': return defaultVerticalAlignment; case 'textBaseline': return textBaseline; case 'key': return key; case 'hashCode': return hashCode; case 'createElement': return ({positionalArgs, namedArgs, typeArgs}) => createElement(); case 'createRenderObject': return ({positionalArgs, namedArgs, typeArgs}) => createRenderObject(positionalArgs[0]); case 'updateRenderObject': return ({positionalArgs, namedArgs, typeArgs}) => updateRenderObject(positionalArgs[0], positionalArgs[1]); case 'toStringShort': return ({positionalArgs, namedArgs, typeArgs}) => toStringShort(); case 'debugFillProperties': return ({positionalArgs, namedArgs, typeArgs}) => debugFillProperties(positionalArgs[0]); case 'toStringShallow': return ({positionalArgs, namedArgs, typeArgs}) => toStringShallow( joiner: namedArgs.containsKey('joiner') ? namedArgs['joiner'] : ', ', minLevel: namedArgs.containsKey('minLevel') ? namedArgs['minLevel'] : DiagnosticLevel.debug); case 'toStringDeep': return ({positionalArgs, namedArgs, typeArgs}) => toStringDeep( prefixLineOne: namedArgs.containsKey('prefixLineOne') ? namedArgs['prefixLineOne'] : '', prefixOtherLines: namedArgs.containsKey('prefixOtherLines') ? namedArgs['prefixOtherLines'] : null, minLevel: namedArgs.containsKey('minLevel') ? namedArgs['minLevel'] : DiagnosticLevel.debug); case 'toDiagnosticsNode': return ({positionalArgs, namedArgs, typeArgs}) => toDiagnosticsNode( name: namedArgs.containsKey('name') ? namedArgs['name'] : null, style: namedArgs.containsKey('style') ? namedArgs['style'] : null); case 'toString': return ({positionalArgs, namedArgs, typeArgs}) => toString( minLevel: namedArgs.containsKey('minLevel') ? namedArgs['minLevel'] : DiagnosticLevel.info); default: throw HTError.undefined(varName); } } } class TableCellAutoBinding extends HTExternalClass { TableCellAutoBinding() : super('TableCell'); @override dynamic memberGet(String varName, {String from = HTLexicon.global}) { switch (varName) { case 'TableCell': return ({positionalArgs, namedArgs, typeArgs}) => TableCell( key: namedArgs.containsKey('key') ? namedArgs['key'] : null, verticalAlignment: namedArgs.containsKey('verticalAlignment') ? namedArgs['verticalAlignment'] : null, child: namedArgs['child']); default: throw HTError.undefined(varName); } } @override dynamic instanceMemberGet(dynamic instance, String id) { return (instance as TableCell).htFetch(id); } } extension TableCellBinding on TableCell { dynamic htFetch(String varName) { switch (varName) { case 'runtimeType': return const HTType('TableCell'); case 'verticalAlignment': return verticalAlignment; case 'child': return child; case 'key': return key; case 'debugTypicalAncestorWidgetClass': return debugTypicalAncestorWidgetClass; case 'hashCode': return hashCode; case 'applyParentData': return ({positionalArgs, namedArgs, typeArgs}) => applyParentData(positionalArgs[0]); case 'debugFillProperties': return ({positionalArgs, namedArgs, typeArgs}) => debugFillProperties(positionalArgs[0]); case 'createElement': return ({positionalArgs, namedArgs, typeArgs}) => createElement(); case 'debugIsValidRenderObject': return ({positionalArgs, namedArgs, typeArgs}) => debugIsValidRenderObject(positionalArgs[0]); case 'toStringShort': return ({positionalArgs, namedArgs, typeArgs}) => toStringShort(); case 'toStringShallow': return ({positionalArgs, namedArgs, typeArgs}) => toStringShallow( joiner: namedArgs.containsKey('joiner') ? namedArgs['joiner'] : ', ', minLevel: namedArgs.containsKey('minLevel') ? namedArgs['minLevel'] : DiagnosticLevel.debug); case 'toStringDeep': return ({positionalArgs, namedArgs, typeArgs}) => toStringDeep( prefixLineOne: namedArgs.containsKey('prefixLineOne') ? namedArgs['prefixLineOne'] : '', prefixOtherLines: namedArgs.containsKey('prefixOtherLines') ? namedArgs['prefixOtherLines'] : null, minLevel: namedArgs.containsKey('minLevel') ? namedArgs['minLevel'] : DiagnosticLevel.debug); case 'toDiagnosticsNode': return ({positionalArgs, namedArgs, typeArgs}) => toDiagnosticsNode( name: namedArgs.containsKey('name') ? namedArgs['name'] : null, style: namedArgs.containsKey('style') ? namedArgs['style'] : null); case 'toString': return ({positionalArgs, namedArgs, typeArgs}) => toString( minLevel: namedArgs.containsKey('minLevel') ? namedArgs['minLevel'] : DiagnosticLevel.info); default: throw HTError.undefined(varName); } } }
#!/usr/bin/env bash # Copyright 2017-2020 Maximilian Huber <oss@maximilian-huber.de> # SPDX-License-Identifier: MIT set -euo pipefail borgCmd="borg" borgMountDir="/mnt/borgMountDir" show_help() { >&2 cat <<EOF run as: $0 b[ackup] -n ALIAS $0 i[nit] -n ALIAS -- alias for the backup -s SOURCE -- what to backup, e.g. $HOME -t TARGET -- e.g. - /dev/disk/by-uuid/... - /mnt/backup - backup@nas:/mnt/backup/ [-e] -- enable encryption $0 [-h] EOF } handleTarget() { local target="$1" if [[ $target != *":"* ]]; then if [[ $target == "/dev/"* ]]; then echo "0 0 0" | sudo tee /sys/class/scsi_host/host*/scan || true sudo mkdir -p "$borgMountDir" sudo umount $target || true sudo mount $target "$borgMountDir" fi if [[ "$(df --output=source / | tail -1)" == "$(df --output=source "$target" | tail -1)" ]]; then >&2 echo "backup should be made to another filesystem or to ssh, \$target=$target does not satisfy that" exit 1 fi fi echo "$target" } writeExcludes() { local excludes="$1" cat <<EOF >"$excludes" *.ARW *.img *.iso *.ova *.pyc */.Trash*/ */.cache/ */.compose-cache/ */.config/GIMP/*/backups */.gem/ */.gradle/ */.local/share/ */.m2/ */.nox/ */.npm/ */.ort/ */.thumbnails/ */.wine/ */Bilder/workspace/ */Downloads/ */PIP/_* */TNG/ */VirtualBox VMs/ */tmp/ EOF } doInitPreperations() { >&2 echo "## doInitPreperations..." local home="$1" shift if [[ -d "$home" ]]; then >&2 echo "the folder \$home=$home already exists, probably already initialized" exit 1 fi local target="" local source="" local encryption=none while [[ $# -gt 0 && "${1:-}" != "--" ]]; do opt="$1" case $opt in -t) target="$2" shift shift ;; -s) source="$2" shift shift ;; -e) encryption="repokey" shift ;; *) POSITIONAL+=("$1") shift ;; esac done local prefix="$(hostname)-" local repository="" if [[ $target == "/dev/"* ]]; then repository="${borgMountDir}/${prefix}${name}.borg" else repository="${target}/${prefix}${name}.borg" fi local excludes="$home/excludes" mkdir -p "$home" cat <<EOF | tee "$home/init" export name="$name" export target="$target" export prefix="$prefix" export repository="$repository" export source="$source" export encryption="$encryption" export excludes="$excludes" EOF writeExcludes "$excludes" if [[ "$encryption" != "none" ]]; then local passphraseFile="$home/passphrase" if [[ ! -f "$passphraseFile" ]]; then head -c 32 /dev/urandom | base64 -w 0 > "$passphraseFile" chmod 400 "$passphraseFile" fi echo "export BORG_PASSCOMMAND=\"cat '$passphraseFile'\"" | tee -a "$home/init" fi } doInitActually() { >&2 echo "## doInitActually..." set -x $borgCmd \ init \ --encryption "$encryption" \ "$repository" if [[ "$encryption" != "none" ]]; then $borgCmd key export "$repository" "$home/keyExport.txt" $borgCmd key export --paper "$repository" "$home/keyExport.paper" $borgCmd key export --qr-html "$repository" "$home/keyExport.html" fi set +x } getBackupName() { echo "$(hostname)-$(date +%Y-%m-%d_%H:%M:%S)" } doBackup() { >&2 echo "## doBackup..." local home="$1" shift source "$home/init" set -x $borgCmd \ create \ --stats \ --verbose \ --progress \ --filter AME \ --show-rc \ --one-file-system \ --exclude-caches \ --compression lz4 \ --exclude-from "$excludes" \ "${repository}::$(getBackupName)" \ "${source}" set +x } doPrune() { >&2 echo "## doPrune..." local home="$1" shift source "$home/init" set -x $borgCmd \ prune \ --stats \ --verbose \ --list \ --show-rc \ --keep-within=2d --keep-daily=7 --keep-weekly=4 --keep-monthly=6 \ --prefix "$prefix" \ "$repository" set +x } doMount() { >&2 echo "## doMount..." local home="$1" shift set -x $borgCmd \ mount \ --foreground \ $repository \ $(mktemp -d) set +x } main() { >&2 echo "# main..." local name="" local doInit=false local doBackup=false local doPrune=false local doMount=false while [[ $# -gt 0 && "${1:-}" != "--" ]]; do opt="$1" case $opt in -h) show_help exit 0 ;; -n) name="$2" shift shift ;; init|i) doInit=true shift ;; backup|b) doBackup=true shift ;; prune) doPrune=true shift ;; mount) doMount=true shift ;; *) POSITIONAL+=("$1") shift ;; esac done if [[ -z "$name" ]]; then >&2 echo "a name is required" exit 1 fi local base="$HOME/.myborgbackup" mkdir -p "$base" local home="$base/$name" local logfile="$home/logfile" ############################################################################ # Run if $doInit; then doInitPreperations "$home" "${POSITIONAL[@]}" fi if [[ ! -d "$home" ]]; then >&2 echo "\$home=$home not yet initialized" exit 1 fi echo -e "\n\n\n\n\n\n\n" >> $logfile exec &> >(tee -a $logfile) source "$home/init" export target="$(handleTarget "$target")" if $doInit; then doInitActually "$home" "${POSITIONAL[@]}" fi borg info "$repository" --last 1 if $doBackup; then doBackup "$home" "${POSITIONAL[@]}" echo "date" >> "$home/dates" fi if $doPrune; then doPrune "$home" "${POSITIONAL[@]}" fi if $doMount; then doMount "$home" "${POSITIONAL[@]}" fi if [[ -d "$target" ]]; then if [[ "$(df --output=source / | tail -1)" == "$(df --output=source "$target" | tail -1)" ]]; then sudo umount "$target" || echo "umount failed... continue" fi fi } time main "$@"
/** * * Copyright (c) 2018 - present, byteAgenten GmbH, Germany. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { color: function (colorString) { return Snap.getRGB(colorString); }, rgb2hex: function (color) { // Edge-case: If a color is "undefined" (e.g. "none") then Snap.getRGB parses rgb values to -1 // However Snap.rgb doesn't handle that case when converting back to hex so we do it here if (color.r < 0 || color.g < 0 || color.b < 0) { return 'none'; } var opacity = color.opacity; opacity = opacity != null && opacity < 1 ? opacity : undefined; // Only provide opacity if it exists and has a value less than one, // without providing an opacity we force Snap to return a hex value return Snap.rgb(color.r, color.g, color.b, opacity); }, interpolateRgb: function (color1, color2, factor) { if (factor == 0) return color1; if (factor == 1) return color2; // Edge-case: If a color is "undefined" (e.g. "none") then Snap.getRGB parses rgb values to -1 // We can't interpolate from "none", // so we replace "none" with the color value from the second color and use an opacity of 0 if (color1.r < 0 || color1.g < 0 || color1.b < 0) { color1 = { r: color2.r, g: color2.g, b: color2.b, opacity: 0 }; } if (color2.r < 0 || color2.g < 0 || color2.b < 0) { color2 = { r: color1.r, g: color1.g, b: color1.b, opacity: 0 }; } if (arguments.length < 3) { factor = 0.5; } var opacity1 = color1.opacity != null ? color1.opacity : 1; var opacity2 = color2.opacity != null ? color2.opacity : 1; return { r: Math.round(color1.r + (factor * (color2.r - color1.r))), g: Math.round(color1.g + (factor * (color2.g - color1.g))), b: Math.round(color1.b + (factor * (color2.b - color1.b))), opacity: opacity1 + (factor * (opacity2 - opacity1)) }; } };
-- +migrate Up ALTER TABLE campaign ADD COLUMN folder_id integer references folder(id); -- +migrate Down
require 'vault-tools/log' module Vault # Base class for HTTP API services. class Web < Sinatra::Base # List of paths that are not protected thus overriding protected! set :unprotected_paths, [] # Work with request id out of the box def call(env) Thread.current[:request_id] = env['HTTP_X_REQUEST_ID'] || SecureRandom.uuid if defined? Excon decorate_excon! Excon.defaults[:headers]['X-Request-ID'] = Thread.current[:request_id] end env['HTTP_X_REQUEST_ID'] = Thread.current[:request_id] status, headers, response = super(env) headers['Request-ID'] = Thread.current[:request_id] [status, headers, response] end def decorate_excon! return unless defined? Excon begin return if Excon.request_id_decorated? rescue Excon.module_eval do def self.request_id_decorated? true end end Excon::Connection.class_eval do alias :stock_initialize :initialize def initialize(params={}) stock_initialize(params) if Excon.defaults[:headers].key? 'X-Request-ID' @data[:headers]['X-Request-ID'] ||= Excon.defaults[:headers]['X-Request-ID'] end end end end end class << self # Store the action for logging purposes. def route(verb, action, *) condition { @action = action } super end # Create :method:_unprotected methods for instances where default # protect! is used %w{get put post delete head options path link unlink}.each do |meth| define_method "#{meth}_unprotected".to_sym do |path, opts = {}, &block| pattern = compile!(meth.upcase, path, block, **opts).first set :unprotected_paths, settings.unprotected_paths + [pattern] if meth.downcase == 'get' conditions = @conditions.dup route 'GET', path, opts, &block @conditions = conditions route 'HEAD', path, opts, &block else route meth.upcase, path, opts, &block end end end end # HTTP Basic Auth Support helpers do # Protects an http method. Returns 401 Not Authorized response # when authorized? returns false def protected!(*passwords) unless unprotected? || authorized?(passwords) response['WWW-Authenticate'] = %(Basic realm="Restricted Area") throw(:halt, [401, "Not authorized\n"]) end end # Check the list of unprotected_paths and see if any of them match def unprotected? settings.unprotected_paths.any? { |path| path.match(request.path) } end # Check request for HTTP Basic creds and # password matches settings.basic_password def authorized?(passwords) if passwords.empty? passwords = passwords + Array(settings.basic_password) end passwords << settings.basic_password if passwords.empty? @auth ||= Rack::Auth::Basic::Request.new(request.env) @auth.provided? && @auth.basic? && @auth.credentials && passwords.include?(@auth.credentials[1]) end end # Start timing the request. before do @start_request = Time.now # if client sends content_type: application/json which no longer works # https://github.com/puma/puma/compare/4.3.1...4.3.5#commitcomment-39478516 # # fixing this here so that we do not break all client users at once if request.env["CONTENT_TYPE"].nil? && request.env["HTTP_CONTENT_TYPE"] request.env["CONTENT_TYPE"] = request.env["HTTP_CONTENT_TYPE"] end end # Log details about the request including how long it took. after do @action ||= 'unknown' Log.count_status(response.status, request_path: request.path_info) Log.time("http.#{@action}", (Time.now - @start_request) * 1000) end # Make sure error handler blocks are invoked in tests. set :show_exceptions, false set :raise_errors, false # Require HTTPS connections when production mode is enabled. use Rack::SslEnforcer if (Config.enable_ssl? && Config.production?) # Return an *HTTP 500 Internal Server Error* with a traceback in the # body for easy debugging of errors. error do e = env['sinatra.error'] Rollbar.notify(e, rack_env: env) content = "#{e.class}: #{e.message}\n\n" content << e.backtrace.join("\n") [500, content] end # Determine if the service is running and responding to requests. # # @method status-check # @return The following responses may be returned by this method: # # - *HTTP 200 OK*: Returned if the request was successful. head_unprotected '/' do status(200) end # Determine if the service is running and responding to requests. # # @method health-check # @return The following responses may be returned by this method: # # - *HTTP 200 OK*: Returned if the request was successful with `OK` in # the body. get_unprotected '/health' do [200, 'OK'] end # Trigger an internal server error (to test monitoring and paging tools). # # @method boom # @return The following responses may be returned by this method: # # - *HTTP 500 Internal Server Error*: Returned with a traceback in the # body. get_unprotected '/boom' do raise "An expected error occurred." end end end
import 'package:flutter/material.dart'; import './cq-bubble/bubble_widget.dart'; class GuideOverlayEntryFactory1 { void addGuideOverlayEntrys(BuildContext context) { List<OverlayEntry> overlayEntryList = List<OverlayEntry>(); var width = MediaQuery.of(context).size.width; // var height = MediaQuery.of(context).size.height; OverlayEntry overlayBackgroundEntry; OverlayEntry overlayEntry1, overlayEntry2, overlayEntry3; var overIndex = 4; overlayBackgroundEntry = OverlayEntry(builder: (context) { return Stack(children: <Widget>[ GestureDetector( onTap: () { --overIndex; if (overIndex == 3) { overlayEntry1.remove(); overlayEntryList.removeLast(); Overlay.of(context).insert(overlayEntry2); } else if (overIndex == 2) { overlayEntry2.remove(); Overlay.of(context).insert(overlayEntry3); } else if (overIndex == 1) { overlayEntry3.remove(); overlayBackgroundEntry.remove(); overlayEntryList.removeLast(); } }, child: Container(color: Colors.black.withOpacity(0.4))) ]); }); overlayEntry1 = OverlayEntry(builder: (context) { return Stack(children: <Widget>[ Positioned( top: 75, left: width - 185.0, child: GestureDetector( onTap: () { --overIndex; overlayEntry1.remove(); overlayEntryList.removeLast(); Overlay.of(context).insert(overlayEntry2); }, child: _itemGuideTop())) ]); }); overlayEntryList.add(overlayBackgroundEntry); overlayEntryList.add(overlayEntry1); overlayEntry2 = OverlayEntry(builder: (context) { return Stack(children: <Widget>[ Positioned( bottom: 105, right: 80, child: GestureDetector( onTap: () { --overIndex; overlayEntry2.remove(); Overlay.of(context).insert(overlayEntry3); }, child: _itemGuideRight())) ]); }); overlayEntry3 = OverlayEntry(builder: (context) { return Stack(children: <Widget>[ Positioned( bottom: 85, left: (width - 260) * 0.5, child: GestureDetector( onTap: () { --overIndex; overlayEntry3.remove(); overlayBackgroundEntry.remove(); overlayEntryList.removeLast(); }, child: _itemGuideBottom())) ]); }); Overlay.of(context).insertAll(overlayEntryList); } _itemGuideTop() { return Material( color: Color.fromARGB(0, 0, 0, 0), child: Padding( padding: EdgeInsets.only(right: 4.0), child: Container( child: BubbleWidget( 180.0, 60.0, Colors.deepOrange.withOpacity(0.7), BubbleArrowDirection.top, length: 140.0, child: Text('This is Setting Button!', textAlign: TextAlign.left, style: TextStyle(color: Colors.white, fontSize: 16.0)))))); } _itemGuideRight() { return Material( color: Color.fromARGB(0, 0, 0, 0), child: Padding( padding: EdgeInsets.only(right: 4.0), child: Container( child: BubbleWidget(240.0, 50.0, Colors.green.withOpacity(0.7), BubbleArrowDirection.right, child: Text('This is FloatingActionButton!', textAlign: TextAlign.left, style: TextStyle(color: Colors.white, fontSize: 16.0)))))); } _itemGuideBottom() { return Material( color: Color.fromARGB(0, 0, 0, 0), child: Padding( padding: EdgeInsets.only(right: 4.0), child: Container( child: BubbleWidget( 260.0, 80.0, Colors.pinkAccent.withOpacity(0.7), BubbleArrowDirection.bottom, child: Text('This is ACEBottomNavigationBar! \nindex = 3', textAlign: TextAlign.left, style: TextStyle(color: Colors.white, fontSize: 16.0)))))); } }
--- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.Count --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.HookUpControlEvents(System.Object) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.BaseGetItem(System.Int16) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.#ctor --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.Dispose --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.Load(System.Int16) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.LBound --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.components --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.#ctor(System.ComponentModel.IContainer) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.BaseShouldSerializeIndex(System.Object) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.GetControlInstanceType --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.Dispose(System.Boolean) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.GetEnumerator --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.System#ComponentModel#ISupportInitialize#EndInit --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.BaseGetIndex(System.Object) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.fIsEndInitCalled --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.controls --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.BaseResetIndex(System.Object) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.UBound --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.indices --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.Unload(System.Int16) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.BaseSetIndex(System.Object,System.Int16,System.Boolean) --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.System#ComponentModel#ISupportInitialize#BeginInit --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.controlAddedAtDesignTime --- --- uid: Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray.BaseCanExtend(System.Object) ---
# ReplaceIt ReplaceIt it's a new gem that can replace strings from a file. ## Installation Add this line to your application's Gemfile: ```ruby gem 'replace_it' ``` And then execute: $ bundle Or install it yourself as: $ gem install replace_it ## Usage ### Replace txt files To replace one string from a `.txt`: ```ruby #Create a new file with the same content replace = ReplaceDocument.new('temp_file.txt', 'myfile.txt') replace.document_replace('mystring', 'mynewstring') ``` ## Contributing To make a contribuition with the gem. `git pull origin master` `git checkout -b feature_yourbranchname` `git push` `Create a Pull Request` ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
package com.aspose.slides.examples.Presentation.Properties; import com.aspose.slides.IDocumentProperties; import com.aspose.slides.Presentation; import com.aspose.slides.examples.Utils; public class AccessingBuiltInProperties { public static void main(String[] args) { //ExStart:AccessingBuiltInProperties // The path to the documents directory. String dataDir = Utils.getDataDir(AccessingBuiltInProperties.class); // Instantiate the Presentation class that represents the presentation Presentation pres = new Presentation(dataDir + "Presentation.pptx"); // Create a reference to IDocumentProperties object associated with Presentation IDocumentProperties dp = pres.getDocumentProperties(); // Display the built-in properties System.out.println("Category : " + dp.getCategory()); System.out.println("Current Status : " + dp.getContentStatus()); System.out.println("Creation Date : " + dp.getCreatedTime()); System.out.println("Author : " + dp.getAuthor()); System.out.println("Description : " + dp.getComments()); System.out.println("KeyWords : " + dp.getKeywords()); System.out.println("Last Modified By : " + dp.getLastSavedBy()); System.out.println("Supervisor : " + dp.getManager()); System.out.println("Modified Date : " + dp.getLastSavedTime()); System.out.println("Presentation Format : " + dp.getPresentationFormat()); System.out.println("Last Print Date : " + dp.getLastPrinted()); System.out.println("Is Shared between producers : " + dp.getSharedDoc()); System.out.println("Subject : " + dp.getSubject()); System.out.println("Title : " + dp.getTitle()); //ExEnd:AccessingBuiltInProperties } }
package temple.generate.database.ast /** AST representation for boolean comparisons */ sealed trait ComparisonOperator object ComparisonOperator { case object GreaterEqual extends ComparisonOperator case object Greater extends ComparisonOperator case object Equal extends ComparisonOperator case object NotEqual extends ComparisonOperator case object Less extends ComparisonOperator case object LessEqual extends ComparisonOperator }
import 'package:mockito/mockito.dart'; import 'package:redux/redux.dart'; import 'package:test_api/test_api.dart'; import 'package:berightthere_client/providers/trip_provider.dart'; import 'package:berightthere_client/redux/actions/trip_actions.dart'; import 'package:berightthere_client/redux/actions/location_actions.dart'; import 'package:berightthere_client/redux/app_state.dart'; import 'package:berightthere_client/redux/location.dart'; import 'package:berightthere_client/redux/middleware/trip_middleware.dart'; import 'package:berightthere_client/redux/trip_identifier.dart'; class MockTripProvider extends Mock implements TripProvider {} class MockStore extends Mock implements Store<AppState> {} main() { TripMiddleware tripMiddleware; MockTripProvider mockTripProvider; MockStore mockStore; setUp(() { mockTripProvider = MockTripProvider(); tripMiddleware = TripMiddleware(mockTripProvider); mockStore = MockStore(); }); test('should dispatch CheckInLoadingAction while checking in', () { final tripIdentifier = TripIdentifier('identifier'); when(mockTripProvider.checkIn()) .thenAnswer((_) => Future.value(tripIdentifier)); tripMiddleware.call(mockStore, CheckInAction(), (action) => {}); verify(mockStore.dispatch(TypeMatcher<CheckInLoadingAction>())); }); test('should dispatch CheckInSucceededAction when check-in succeeds', () async { final tripIdentifier = TripIdentifier('identifier'); when(mockTripProvider.checkIn()) .thenAnswer((_) => Future.value(tripIdentifier)); tripMiddleware.call(mockStore, CheckInAction(), (action) => {}); await untilCalled( mockStore.dispatch(const TypeMatcher<CheckInSucceededAction>())); var checkInSucceededAction = verify(mockStore .dispatch(captureThat(const TypeMatcher<CheckInSucceededAction>()))) .captured .single; expect(checkInSucceededAction.tripIdentifier, equals(tripIdentifier)); }); test('should dispatch CheckInFailedAction when check-in fails', () async { final error = 'Expected error'; when(mockTripProvider.checkIn()).thenAnswer((_) => Future.error(error)); tripMiddleware.call(mockStore, CheckInAction(), (action) => {}); await untilCalled( mockStore.dispatch(const TypeMatcher<CheckInFailedAction>())); var action = verify(mockStore .dispatch(captureThat(const TypeMatcher<CheckInFailedAction>()))) .captured .single; expect(action.error, equals(error)); }); test( 'should dispatch ReportLocationAction when location changed and incoming locations is empty', () async { final location = Location(55.6739062, 12.5556993); var appState = AppState(); when(mockStore.state).thenReturn(appState); tripMiddleware.call( mockStore, LocationChangedAction(location), (action) => {}); var action = verify(mockStore .dispatch(captureThat(const TypeMatcher<ReportLocationAction>()))) .captured .single; expect(action.location, equals(location)); }); test( 'should not dispatch ReportLocationAction when location changed and incoming locations is not empty', () async { final location = Location(55.6739062, 12.5556993); var appState = AppState(incomingLocations: [Location(0, 0)]); when(mockStore.state).thenReturn(appState); tripMiddleware.call( mockStore, LocationChangedAction(location), (action) => {}); verifyNever(mockStore.dispatch(any)); }); test( 'should dispatch ReportLocationAction for next location when reporting ' 'location succeeded and incoming locations not empty', () async { final location1 = Location(55.6739062, 12.5556993); final location2 = Location(55.6746322, 12.5585318); var appState = AppState(incomingLocations: [location1, location2]); when(mockStore.state).thenReturn(appState); tripMiddleware.call(mockStore, ReportLocationSucceededAction(Location(0, 0)), (action) => {}); var action = verify(mockStore .dispatch(captureThat(const TypeMatcher<ReportLocationAction>()))) .captured .single; expect(action.location, equals(location2)); }); test( 'should dispatch ReportLocationAction for next location when reporting ' 'location failed and incoming locations not empty', () async { final location1 = Location(55.6739062, 12.5556993); final location2 = Location(55.6746322, 12.5585318); var appState = AppState(incomingLocations: [location1, location2]); when(mockStore.state).thenReturn(appState); tripMiddleware.call(mockStore, ReportLocationSucceededAction(Location(0, 0)), (action) => {}); var action = verify(mockStore .dispatch(captureThat(const TypeMatcher<ReportLocationAction>()))) .captured .single; expect(action.location, equals(location2)); }); test('should dispatch ReportLocationSucceededAction when reporting succeeds', () async { final tripIdentifier = TripIdentifier('identifier'); final location = Location(55.6739062, 12.5556993); var appState = AppState(tripIdentifier: tripIdentifier); when(mockStore.state).thenReturn(appState); when(mockTripProvider.addLocation(tripIdentifier, location)) .thenAnswer((_) => Future.value()); tripMiddleware.call( mockStore, ReportLocationAction(location), (action) => {}); await untilCalled( mockStore.dispatch(const TypeMatcher<ReportLocationSucceededAction>())); var action = verify(mockStore.dispatch( captureThat(const TypeMatcher<ReportLocationSucceededAction>()))) .captured .single; expect(action.location, equals(location)); }); test('should dispatch ReportLocationFailedAction when reporting succeeds', () async { final tripIdentifier = TripIdentifier('identifier'); final location = Location(55.6739062, 12.5556993); var appState = AppState(tripIdentifier: tripIdentifier); when(mockStore.state).thenReturn(appState); when(mockTripProvider.addLocation(tripIdentifier, location)) .thenAnswer((_) => Future.error('Error')); tripMiddleware.call( mockStore, ReportLocationAction(location), (action) => {}); await untilCalled( mockStore.dispatch(const TypeMatcher<ReportLocationFailedAction>())); var action = verify(mockStore.dispatch( captureThat(const TypeMatcher<ReportLocationFailedAction>()))) .captured .single; expect(action.location, equals(location)); }); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using Steeltoe.Common.Util; using System; using System.Text; namespace Steeltoe.Messaging.Converter { public class StringMessageConverter : AbstractMessageConverter { public const string DEFAULT_SERVICE_NAME = nameof(StringMessageConverter); private readonly Encoding _defaultCharset; public StringMessageConverter() : this(Encoding.UTF8) { } public StringMessageConverter(Encoding defaultCharset) : base(new MimeType("text", "plain", defaultCharset)) { if (defaultCharset == null) { throw new ArgumentNullException(nameof(defaultCharset)); } _defaultCharset = defaultCharset; } public override string ServiceName { get; set; } = DEFAULT_SERVICE_NAME; protected override bool Supports(Type clazz) => typeof(string) == clazz; protected override object ConvertFromInternal(IMessage message, Type targetClass, object conversionHint) { var charset = GetContentTypeCharset(GetMimeType(message.Headers)); var payload = message.Payload; return payload is string ? payload : new string(charset.GetChars((byte[])payload)); } protected override object ConvertToInternal(object payload, IMessageHeaders headers, object conversionHint) { if (typeof(byte[]) == SerializedPayloadClass) { var charset = GetContentTypeCharset(GetMimeType(headers)); var payStr = (string)payload; payload = charset.GetBytes(payStr); } return payload; } private Encoding GetContentTypeCharset(MimeType mimeType) { if (mimeType != null && mimeType.Encoding != null) { return mimeType.Encoding; } else { return _defaultCharset; } } } }
package ssilvalucas.botservice.mapper import org.springframework.stereotype.Component import ssilvalucas.botservice.model.entity.Checklist import ssilvalucas.botservice.web.dto.request.ChecklistRequest @Component class ChecklistMapper { fun requestToEntity(driver: String, request: ChecklistRequest): Checklist { return Checklist( phoneNumber = driver, medidorOleo = request.medidorOleo, pneus = request.pneus, farois = request.farois, lanternas = request.lanternas, limpeza = request.limpeza ) } }
module EC class PublicKey def self.convert( *args, **kwargs ) if args.size==1 && args[0].is_a?( PublicKey ) args[0] ## pass through as is (already a public key) else new( *args, group: kwargs[:group] ) end end def self.decode_pem( str ) new( str ); end def self.decode_der( str ) new( str ); end ## todo/check: only use (allow) base64 for ## der (binary)-encoded? why? why not? def self.decode_base64( str ) new( Base64.decode64(str)); end class << self alias_method :from_pem, :decode_pem alias_method :from_der, :decode_der alias_method :from_base64, :decode_base64 end def initialize( *args, group: nil ) if args.size == 2 ## assume (x,y) raw integer points @pt = Point.new( *args, group: group ) point = @pt.to_ec_point ## convert point to openssl (native) class @pkey = OpenSSL::PKey::EC.new( point.group ) @pkey.public_key = point elsif args[0].is_a?( Point ) || args[0].is_a?( OpenSSL::PKey::EC::Point ) ## "restore" public key (only) from point for verify ## - OpenSSL::PKey::EC::Point ## assume public key only (restore pkey object for verify?) ## - Point point = if args[0].is_a?( Point ) @pt = args[0] @pt.to_ec_point else args[0] ## assume it is already OpenSSL::PKey::EC::Point end ## note: (auto)get group from point @pkey = OpenSSL::PKey::EC.new( point.group ) @pkey.public_key = point else ## assume string in pem/der/base64 @pkey = OpenSSL::PKey::EC.new( args[0] ) end end def point ## cache returned point - why? why not? @pt ||= Point.new( @pkey.public_key ) @pt end def to_pem() @pkey.to_pem; end def to_der() @pkey.to_der; end def to_base64() Base64.encode64( to_der ); end def verify?( message, signature ) signature_der = signature.to_der @pkey.dsa_verify_asn1( message, signature_der ) end alias_method :valid_signature?, :verify? ### ## more helpers for debugging / internals def group() @pkey.group; end def to_text() @pkey.to_text; end def private?() @pkey.private?; end ## todo/check: keep - needed? - why? why not? def public?() @pkey.public?; end ## todo/check: keep - needed? - why? why not? end # class PublicKey end ## module EC
--- Author: "lingTalfi" Description: "Simple bash theme with strong color contrasts for comments/finding/selection" FileName: "bashling.tmTheme" ID: "bashling" Title: "bashling" layout: theme ---
. .gitrc # 引入环境变量 # 设定工作目录 cd ${PROJ_GIT_DIR} # 【更新】指定版本 git fetch git checkout ${PROJ_GIT_BRANCH} git pull # 【更新】子模块 git submodule init git submodule update
package org.firstinspires.ftc.teamcode; /** * Created by Miranda on 10/20/2017. */ import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; /** * game pad 1: * move/turn - left stick * strafe - right stick * foundation up - button 1 * foundation down - button 2 * * game pad 2: * arm up/dn and in/out w/o changing end effector orientation - left stick * end effector manual level and open/close - right stick (probably not used) * Presets: * arm and end effector move to pick-up position - button 1 * close end effector, pick-up stone, collapse to fit under bridge - button 2 (or reuse button 1) * <<after picking up stone, should we roll the end effetor back so that gravity is not working against us?>> * end effector open - button 3 * end effector close - button 4 * retract arm to fit under bridge (only needed if button 1 does not fit under bridge) - button 5 */ @TeleOp(name = "Servo Test", group = "TeleOp") //@Disabled public class ServoTest extends LinearOpMode { /* Declare OpMode members. */ THardware1 robot = new THardware1(); // Use a hardware ElapsedTime runtime = new ElapsedTime(); BNO055IMU imu; Orientation angles; double target_x, current_x, now_seconds; ArtArm reach = new ArtArm(14.5, 15.75, 3, 1, 1, 2); //Double for more precision @Override public void runOpMode() throws InterruptedException { double MFR; double MFL; double MBR; double MBL; double SFB; double SRL; double T; double max; double x = 2; double y = 1; double[] pos; /* Initialize the hardware variables. * The init() method of the hardware class does all the work here */ robot.init(hardwareMap); //Initialize gyro stuff BNO055IMU.Parameters parameters = initIMUParams(); imu = hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); // Send telemetry message to signify robot waiting; telemetry.addData("Say", "Hello Driver"); telemetry.update(); // Wait for the game to start (driver presses PLAY) waitForStart(); //The "flat" robot angle angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.XYZ, AngleUnit.DEGREES); target_x = angles.firstAngle; // run until the end of the match (driver presses STOP) while (opModeIsActive()) { robot.EndJoint.setPosition((gamepad1.left_stick_y + 1)/2); robot.Gripper.setPosition((gamepad1.right_stick_y + 1)/2); telemetry.addData("joint", robot.EndJoint.getPosition()); telemetry.addData("grip", robot.Gripper.getPosition()); telemetry.update(); // Pause for metronome tick. 40 mS each cycle = update 25 times a second. robot.waitForTick(40); } } //Tipping-check variables and methods private final double ANGLE_THRESHOLD = 20; //Angle to decide tipping has occurred private final double TIME_THRESHOLD = 10; //Minimum seconds between tipping reports private boolean tipping = false; //Current state of robot private double last_tip_time = 0; private ElapsedTime tip_timer = new ElapsedTime(); /* This method returns true only once when the robot goes from non-tipped to tipped. If the robot remains tipped, it returns false. It returns true no more than once every TIME_THRESHOLD seconds. */ private boolean checkTip(double pitch) { boolean result; boolean exceed = Math.abs(pitch) > ANGLE_THRESHOLD; //Check if the robot is going from "not tipping" to "tipping" after TIME_THRESHOLD if ( tipping == false && exceed == true && tip_timer.seconds() > last_tip_time+TIME_THRESHOLD){ result = true; //Report that tipping has occurred last_tip_time = tip_timer.seconds(); } else{ result = false; } tipping = exceed; return result; } private BNO055IMU.Parameters initIMUParams(){ BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); return parameters; } }
#!/usr/bin/env bash PROJECT_ID=${1} CONFIG_CONTROLLER_NAME=${2} LOCATION=${3} SA_OUTPUT_FILE=${4} print_message(){ export MSG_TO_PRINT=${1} echo "############################################" echo $MSG_TO_PRINT echo "############################################" } main(){ print_message "Creating config connector can take upto 15 minutes" gcloud alpha anthos config controller create ${CONFIG_CONTROLLER_NAME} \ --project=${PROJECT_ID} \ --location=${LOCATION} \ --quiet print_message "Created following config connector" gcloud alpha anthos config controller describe ${CONFIG_CONTROLLER_NAME} \ --project=${PROJECT_ID} \ --location=${LOCATION} \ --quiet print_message "Configuring service account" gcloud alpha anthos config controller get-credentials ${CONFIG_CONTROLLER_NAME} \ --project=${PROJECT_ID} \ --location ${LOCATION} \ --quiet export SA_EMAIL="$(kubectl get ConfigConnectorContext -n config-control \ -o jsonpath='{.items[0].spec.googleServiceAccount}' 2> /dev/null)" echo -n ${SA_EMAIL} > ${SA_OUTPUT_FILE} print_message "SA used with config controller is: ${SA_EMAIL}" # gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ # --member "serviceAccount:${SA_EMAIL}" \ # --role "roles/owner" \ # --quiet } # Calling main with all the arguments main
* Resident clock programs  1985 T.Tebby QJUMP * section exten * xdef tm_susrc * include dev8_sbsext_ext_keys * * suspend and read clock (time in d3) * tm_susrc moveq #mt.susjb,d0 suspend moveq #myself,d1 myself suba.l a1,a1 no flag address trap #1 * moveq #mt.rclck,d0 now read the time into d1 trap #1 rts * end
#!/bin/bash -x g++ -fpermissive \ ../../metrics-discovery/instrumentation/metrics_discovery/common/md_calculation.cpp \ ../../metrics-discovery/instrumentation/utils/common/iu_debug.c \ ../../metrics-discovery/instrumentation/utils/linux/iu_os.cpp \ ../../metrics-discovery/instrumentation/utils/linux/iu_std.cpp \ ../../source/context.cpp \ ../../source/equations.cpp \ ../../source/values.cpp \ ../../source/periodic_metrics.cpp \ ../../source/report_memory.cpp periodic_sample.cpp \ -I. -I ../../source/ \ -I ../../metrics-discovery/inc/common/instrumentation/api \ -I ../../metrics-discovery/instrumentation/metrics_discovery/common/inc \ -I ../../metrics-discovery/instrumentation/utils/common/inc \ -I ../../metrics-discovery/instrumentation/utils/linux/inc \ -I /usr/local/include/mdapi/ -L /usr/local/lib/ -ldl #../../source/range_metrics_dx11.cpp \
using System; using System.Management.Automation; using Microsoft.SharePoint.Client; using SharePointPnP.PowerShell.CmdletHelpAttributes; using SharePointPnP.PowerShell.Commands.Base.PipeBinds; namespace SharePointPnP.PowerShell.Commands.Workflows { [Cmdlet(VerbsCommon.Remove, "PnPWorkflowDefinition")] [CmdletAlias("Remove-SPOWorkflowDefinition")] [CmdletHelp("Removes a workflow definition", Category = CmdletHelpCategory.Workflows)] public class RemoveWorkflowDefinition : SPOWebCmdlet { [Parameter(Mandatory = true, HelpMessage = "The definition to remove", Position = 0)] public WorkflowDefinitionPipeBind Identity; protected override void ExecuteCmdlet() { if (Identity.Definition != null) { Identity.Definition.Delete(); } else if (Identity.Id != Guid.Empty) { var definition = SelectedWeb.GetWorkflowDefinition(Identity.Id); if (definition != null) definition.Delete(); } else if (!string.IsNullOrEmpty(Identity.Name)) { var definition = SelectedWeb.GetWorkflowDefinition(Identity.Name); if (definition != null) definition.Delete(); } } } }
# This script computes the MFCC features for automatic speech recognition # # You need to complete the part indicated by #### so that the code can produce # sensible results. # # Ning Ma (n.ma@sheffield.ac.uk) # import matplotlib.pyplot as plt import scipy.io.wavfile as wav import numpy as np from scipy.fftpack import dct # from librosa.feature import delta class MFCC: def __init__(self, file, num_ceps=12, use_hamming=True, num_filters=26, use_preemph=True, normalize=False, deltas=False): self.fs_hz, self.signal = wav.read(file) self.signal_length = len(self.signal) # Define parameters self.use_preemph = use_preemph # where as to use pre-emphasis or not self.preemph = 0.97 # pre-emphasis coefficient self.frame_length_ms = 25 # frame length in ms self.frame_step_ms = 10 # frame shift in ms self.low_freq_hz = 0 # filterbank low frequency in Hz self.high_freq_hz = 8000 # filterbank high frequency in Hz self.nyquist = self.fs_hz / 2.0 # Check the Nyquist frequency if self.high_freq_hz > self.nyquist: self.high_freq_hz = self.nyquist self.num_filters = num_filters # number of mel-filters self.num_ceps = num_ceps # number of cepstral coefficients (excluding C0) self.cep_lifter = 22 # Cepstral liftering order self.eps = 0.001 # Floor to avoid log(0) self.use_hamming = use_hamming # Determines if hamming should be used or not self.normalize = normalize # Determines if mean normalization should be performed self.deltas = deltas def get_mffc(self, verbose=False): # Pre-emphasis if self.use_preemph: signal = self.pre_emphasize(self.signal) else: signal = self.signal # Split signal into frames frames = self.split_frames(signal) frame_length = frames.shape[1] # Find the smallest power of 2 greater than frame_length NFFT = 1 << (frame_length - 1).bit_length() # Apply the Hamming window if self.use_hamming: frames *= np.hamming(frame_length) # Compute magnitude spectrum magspec = np.absolute(np.fft.rfft(frames, NFFT)) # Compute power spectrum powspec = np.power(magspec, 2) / NFFT # Compute mel-filters mel_filters = self.compute_mel_filters(NFFT) # Compute log mel spectrum fbank = np.dot(powspec, mel_filters.T) fbank[fbank < self.eps] = self.eps fbank = np.log(fbank) # Apply DCT to get num_ceps MFCCs, omit C0 mfcc = dct(fbank, norm='ortho')[:, 1:self.num_ceps+1] # Liftering mfcc = self.liftering(mfcc) # Log-compress power spectrogram powspec = np.log(powspec + self.eps) if verbose: print("=== Before normalisation") print(f"mfcc mean = {np.round(np.mean(mfcc, axis=0), 2)}") print(f"mfcc std = {np.round(np.std(mfcc, axis=0), 2)}") if self.normalize: mfcc_out = (mfcc - np.mean(mfcc, axis=0))/np.std(mfcc, axis=0) if verbose: print("=== After normalisation") print(f"mfcc mean = {np.round(np.mean(mfcc_out, axis=0), 2)}") print(f"mfcc std = {np.round(np.std(mfcc_out, axis=0), 2)}") else: mfcc_out = mfcc if verbose: self.plot_results(powspec, fbank, mfcc, mfcc_out) """if self.deltas: # Compute MFCC deltas and delta deltas: mfcc_delta = delta(mfcc_out) mfcc_delta_2 = delta(mfcc_out, order=2) mfcc_out = np.hstack([mfcc_out, mfcc_delta, mfcc_delta_2])""" return mfcc_out def pre_emphasize(self, signal): """ Applies pre-emphasis filter on the signal to amplify the high frequencies. Using: H(t) = x(t) - preemph * x(t-1) ---------- Parameters ---------- signal : array (n) Raw audio signal Returns ------- signal : array (n-1) Pre-emphasized signal """ return np.append(signal[0], signal[1:] - self.preemph * signal[:-1]) def split_frames(self, signal): """ Splits a signal into equal size frames with a step. Uses frame length and step defined during initialization ---------- Parameters ---------- signal : array (n) Signal to be split Returns ------- frames : array (num_frames * frame_length) """ # Compute number of frames and padding frame_length = int(round(self.frame_length_ms / 1000.0 * self.fs_hz)) frame_step = int(round(self.frame_step_ms / 1000.0 * self.fs_hz)) num_frames = int(np.ceil(float(self.signal_length - frame_length) / frame_step)) print("number of frames is {}".format(num_frames)) pad_signal_length = num_frames * frame_step + frame_length pad_zeros = np.zeros((pad_signal_length - self.signal_length)) pad_signal = np.append(signal, pad_zeros) # Split signal into frames frames = np.empty((num_frames, frame_length)) for i in range(num_frames): start = i*frame_step frames[i] = pad_signal[start:start+frame_length] return frames def compute_mel_filters(self, NFFT): """ Computes mel filter banks ---------- Parameters ---------- NFFT : int Returns ------- mel_filter : array (NFFT//2 + 1 * num_filters) """ mel_filters = np.zeros((self.num_filters, NFFT // 2 + 1)) # Calculate filter centers low_freq_mel = self.freq2mel(self.low_freq_hz) high_freq_mel = self.freq2mel(self.high_freq_hz) mel_centers = np.linspace(low_freq_mel, high_freq_mel, self.num_filters+2) hz_centers = self.mel2freq(mel_centers) idx = ((hz_centers * NFFT+1) // self.fs_hz).astype(np.int) for i in range(0, self.num_filters): # For each filter perform linear interpolation between edges and center: for j in range(idx[i], idx[i + 1]): mel_filters[i, j] = (j - idx[i]) / (idx[i + 1] - idx[i]) for j in range(idx[i + 1], idx[i + 2]): mel_filters[i, j] = (idx[i + 2] - j) / (idx[i + 2] - idx[i + 1]) return mel_filters def liftering(self, mfcc): """ Applies sinusoidal liftering to de-emphasize higher MFCCs ---------- Parameters ---------- mfcc : np.array Returns ------- mfcc : np.array with lift applied """ lift = 1 + (self.cep_lifter / 2.0) * np.sin(np.pi * np.arange(self.num_ceps) / self.cep_lifter) mfcc *= lift return mfcc @staticmethod def freq2mel(freq): """Convert Frequency in Hertz to Mels Args: freq: A value in Hertz. This can also be a numpy array. Returns A value in Mels. """ return 2595 * np.log10(1 + freq / 700.0) @staticmethod def mel2freq(mel): """Convert a value in Mels to Hertz Args: mel: A value in Mels. This can also be a numpy array. Returns A value in Hertz. """ return 700 * (10 ** (mel / 2595.0) - 1) @staticmethod def write_to_txt(mfcc): with open("mfcc.txt", "w") as txt_file: for vec in mfcc.T: txt_file.write(" ".join(np.round(vec, 3).astype('str')) + "\n") def plot_results(self, powspec, fbank, mfcc, mfcc_z): # Plotting power spectrogram vs mel-spectrogram plt.figure(1) siglen = len(self.signal) / np.float(self.fs_hz); plt.subplot(211) plt.imshow(powspec.T, origin='lower', aspect='auto', extent=(0, siglen, 0, self.fs_hz / 2000), cmap='jet') plt.title('Power Spectrogram') plt.gca().get_xaxis().set_ticks([]) plt.gca().set_yticklabels(['', 1, 2, 3, 4, 5, 6, 7, 8]) plt.ylabel('Frequency (kHz)') plt.subplot(212) # freq_bins = freq_bins.astype(int) plt.imshow(fbank.T, origin='lower', aspect='auto', extent=(0, siglen, 0, self.num_filters), cmap='jet') plt.yticks(np.arange(0, fbank.shape[1]+1, int(fbank.shape[1]/5))) # plt.gca().set_yticklabels(['', freq_bins[5], freq_bins[10], freq_bins[16], freq_bins[21], freq_bins[27]]) plt.title('Mel-filter Spectrogram') plt.xlabel('Time (s)') plt.ylabel('Frequency (Hz)') plt.show() # Plotting MFCCs with CMN plt.figure(2) plt.subplot(211) plt.imshow(mfcc.T, origin='lower', aspect='auto', extent=(0, siglen, 1, self.num_ceps), cmap='jet') plt.title('MFCC without mean and variance normalisation') plt.subplot(212) plt.imshow(mfcc_z.T, origin='lower', aspect='auto', extent=(0, siglen, 1, self.num_ceps), cmap='jet') plt.title('MFCC with mean and variance normalisation') plt.show()
using Aurora.Models.Primitives; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aurora.Models.Derived { /// <summary> /// Describes a Student Object and its associated properties /// A Student contains all the necessary parameters defined in its base class and also defines /// the additional parameters that qualify him to be a student for placement. /// </summary> public class Student : User { /// <summary> /// Company Details if Student is placed /// </summary> public Company Company { get; set; } /// <summary> /// Registered Hiring Profies for this Student /// </summary> public ICollection<StudentProgression> HiringProfiles { get; set; } /// <summary> /// Tenth Percentage of the Student /// </summary> public float TenthPercentage { get; set; } /// <summary> /// Twelvth Percentage of the Student /// </summary> public float TwelvthPercentage { get; set; } /// <summary> /// CGPA of the Student /// </summary> public float CGPA { get; set; } /// <summary> /// UnderGraduate Percentage of the Student [Optional] /// </summary> public float UnderGraduatePercentage { get; set; } /// <summary> /// Standing Arrears of the Student /// </summary> public int StandingArrears { get; set; } /// <summary> /// Historical Arrears of the Student /// </summary> public int HistoricalArrears { get; set; } } /// <summary> /// Configures the Student Object and maps respective properties to their Columns. /// Also describes relationships to the other tables and constraints on the properties. /// </summary> public class StudentConfiguration : EntityTypeConfiguration<Student> { public StudentConfiguration() { #region Table Definition this.ToTable("Students"); #endregion #region Property Constraints this.Property(t => t.TenthPercentage) .IsRequired(); this.Property(t => t.TwelvthPercentage) .IsRequired(); this.Property(t => t.CGPA) .IsRequired(); #endregion #region Foreign Keys this.HasOptional(t => t.Company) .WithOptionalDependent() .Map(t => t.MapKey("CompanyId")); this.HasMany(t => t.HiringProfiles) .WithRequired(t => t.Student) .HasForeignKey(t => t.StudentId) .WillCascadeOnDelete(); #endregion } } }
<?php namespace Medicaments\Controller; use CmsIr\System\Util\Inflector; use Medicaments\Form\MedicamentsForm; use Medicaments\Form\MedicamentsFormFilter; use Medicaments\Model\Medicaments; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; use Zend\Authentication\Adapter\DbTable as AuthAdapter; use Zend\Json\Json; class MedicamentsController extends AbstractActionController { public function listAction() { $request = $this->getRequest(); if ($request->isPost()) { $data = $this->getRequest()->getPost(); $columns = array('id', 'name', 'id'); $listData = $this->getMedicamentsTable()->getDatatables($columns, $data); $output = array( "sEcho" => $this->getRequest()->getPost('sEcho'), "iTotalRecords" => $listData['iTotalRecords'], "iTotalDisplayRecords" => $listData['iTotalDisplayRecords'], "aaData" => $listData['aaData'] ); $jsonObject = Json::encode($output, true); echo $jsonObject; return $this->response; } $viewParams = array(); $viewModel = new ViewModel(); $viewModel->setVariables($viewParams); return $viewModel; } public function createAction() { $form = new MedicamentsForm(); $request = $this->getRequest(); if ($request->isPost()) { $form->setInputFilter(new MedicamentsFormFilter($this->getServiceLocator())); $form->setData($request->getPost()); if ($form->isValid()) { $medicaments = new Medicaments(); $medicaments->exchangeArray($form->getData()); $id = $this->getMedicamentsTable()->save($medicaments); $this->flashMessenger()->addMessage('Informacja o lekach została dodana poprawnie.'); return $this->redirect()->toRoute('medicaments'); } } $viewParams = array(); $viewParams['form'] = $form; $viewModel = new ViewModel(); $viewModel->setVariables($viewParams); return $viewModel; } public function editAction() { $id = $this->params()->fromRoute('medicaments_id'); /* @var $medicaments Medicaments */ $medicaments = $this->getMedicamentsTable()->getOneBy(array('id' => $id)); if(!$medicaments) { return $this->redirect()->toRoute('medicaments'); } $form = new MedicamentsForm(); $form->bind($medicaments); $request = $this->getRequest(); if ($request->isPost()) { $form->setInputFilter(new MedicamentsFormFilter($this->getServiceLocator())); $form->setData($request->getPost()); if ($form->isValid()) { $id = $this->getMedicamentsTable()->save($medicaments); $this->flashMessenger()->addMessage('Informacja o lekach została edytowana poprawnie.'); return $this->redirect()->toRoute('medicaments'); } } $viewParams = array(); $viewParams['form'] = $form; $viewModel = new ViewModel(); $viewModel->setVariables($viewParams); return $viewModel; } public function deleteAction() { $request = $this->getRequest(); $id = (int) $this->params()->fromRoute('medicaments_id', 0); if (!$id) { return $this->redirect()->toRoute('medicaments'); } if ($request->isPost()) { $del = $request->getPost('del', 'Anuluj'); if ($del == 'Tak') { $id = $request->getPost('id'); if(!is_array($id)) { $id = array($id); } $this->getMedicamentsTable()->deleteMedicaments($id); $this->flashMessenger()->addMessage('Element został usunięty poprawnie.'); $modal = $request->getPost('modal', false); if($modal == true) { $jsonObject = Json::encode($params['status'] = $id, true); echo $jsonObject; return $this->response; } } return $this->redirect()->toRoute('file'); } return array( 'id' => $id, 'page' => $this->getMedicamentsTable()->getOneBy(array('id' => $id)) ); } /** * @return \Medicaments\Model\MedicamentsTable */ public function getMedicamentsTable() { return $this->getServiceLocator()->get('Medicaments\Model\MedicamentsTable'); } }
import { Recording } from "./recording.model"; export interface UserRecording{ from: string, to: string, page_count: number, page_size: number, total_records: number, next_page_token: string, meetings: Recording[] }
using System; using System.Linq; using FubuMVC.Core.Registration; namespace FubuMVC.Diagnostics.Features.Html.Preview { public class PreviewModelTypeResolver : IPreviewModelTypeResolver { private readonly BehaviorGraph _graph; public PreviewModelTypeResolver(BehaviorGraph graph) { _graph = graph; } public Type TypeFor(string typeName) { var type = Type.GetType(typeName); if (type != null) return type; // this is really only going to work for internals return _graph.Behaviors .Select(x => x.ActionOutputType()) .FirstOrDefault(x => x != null && x.FullName == typeName); } } }
package coop.rchain.models.either import coop.rchain.either.EitherAny import coop.rchain.models.StacksafeMessage import scalapb._ object EitherAnyHelper { def pack[A <: StacksafeMessage[A]](generatedMessage: A): EitherAny = pack(generatedMessage, "type.rchain.coop/") def pack[A <: StacksafeMessage[A]]( generatedMessage: A, urlPrefix: String ): EitherAny = EitherAny( typeUrl = if (urlPrefix.endsWith("/")) urlPrefix + generatedMessage.companion.scalaDescriptor.fullName else urlPrefix + "/" + generatedMessage.companion.scalaDescriptor.fullName, value = generatedMessage.toByteString ) private def typeNameFromTypeUrl(typeUrl: String): String = typeUrl.split("/").lastOption.getOrElse(typeUrl) def is[A <: StacksafeMessage[A]]( eitherAny: EitherAny )(implicit cmp: GeneratedMessageCompanion[A]): Boolean = typeNameFromTypeUrl(eitherAny.typeUrl) == cmp.scalaDescriptor.fullName def unpack[A <: StacksafeMessage[A]]( eitherAny: EitherAny )(implicit cmp: GeneratedMessageCompanion[A]): A = { require(is[A](eitherAny), s"Type of the EitherAny message does not match the given class.") cmp.parseFrom(eitherAny.value.newCodedInput()) } }
import { foo } from "./foo"; export const bar = foo;
use nom::{ bytes::complete::take_until, character::complete::{anychar, multispace0, one_of}, combinator::recognize, error::ErrorKind, multi::many1, sequence::tuple, IResult, }; use std::{ fmt, io, iter::{self, FromIterator}, path::Path, }; use horrorshow::html; use horrorshow::prelude::*; use horrorshow::helper::doctype; use crate::string_utils; #[cfg(test)] mod tests; pub struct SymbolTable(Vec<SymbolTableEntry>); impl SymbolTable { /// Creates a new SymbolTable object /// /// # Examples /// ```ignore /// use arm_binary_utils::symbol_table::SymbolTable; /// let symbol_table = SymbolTable::new(); /// ``` fn new() -> Self { SymbolTable(Vec::new()) } /// Creates a symbol table from a file /// /// # Arguments /// * 'filename' - Path/filename to read /// /// # Examples /// ```ignore /// let symbol_table = symbol_table::SymbolTable::from_file("binary.txt")?; /// ``` pub fn from_file(filename: impl AsRef<Path>) -> io::Result<Self> { let input = string_utils::read_lines_from_file(filename)?; let result = input .iter() .map(|x| parse_symbol_table_entry(x)) .filter(|x| x.is_ok()) .map(|x| x.unwrap()) .map(|(_, result)| result) .collect::<SymbolTable>(); Ok(result) } /// Creates a symbol table from a vector of lines read /// /// # Arguments /// * 'lines' - Vector of lines containing the data /// /// # Examples /// ```ignore /// let lines: Vec<String> = vec!["some symbol table stuff here", "more here"]; /// let symbol_table = symbol_table::SymbolTable::from_lines(&lines); /// ``` pub fn from_lines(lines: &Vec<String>) -> Self { lines.iter() .map(|x| parse_symbol_table_entry(x)) .filter(|x| x.is_ok()) .map(|x| x.unwrap()) .map(|(_, result)| result) .collect::<SymbolTable>() } /// Helper function to sort the symbol table by symbol size in an ascending manner pub fn sort_by_size_ascending(&mut self) -> () { self.0.sort_by(|x, y| { x.alignment_or_size .partial_cmp(&y.alignment_or_size) .unwrap() }); } /// Helper function to sort the symbol table by symbol size in a descending manner pub fn sort_by_size_descending(&mut self) -> () { self.0.sort_by(|x, y| { y.alignment_or_size .partial_cmp(&x.alignment_or_size) .unwrap() }); } /// Converts a symbol table into an HTML formatted string pub fn to_html(&self) -> String { format!("{}", html! { : doctype::HTML; html { head { title : "Symbol Table"; style : "table { font-family: arial, sans-serif; border-collapse: collapse; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; }"; } body { // attributes h1(id="heading", class="title") : "Symbol Table Sizes"; table(class="tg") { thead { tr { th: "Name"; th: "Section"; th: "Address"; th: "Size"; } } tbody { @ for i in 0..self.len() { tr { td: Raw(format!("{}", self[i].name)); td: Raw(format!("{}", self[i].section)); td: Raw(format!("{:08x}", self[i].address)); td: Raw(format!("{}", self[i].alignment_or_size)); } } } } } } }) } /// Gets the maximum length of all names contained in the symbol table fn get_max_name_length(&self) -> usize { self.iter().map(|x| x.name.len()).max().unwrap() } /// Gets the maximum length of all symbol location names fn get_max_section_name_length(&self) -> usize { let min = self.iter().map(|x| x.section.len()).max().unwrap(); if min < "Section".len() { "Section".len() } else { min } } } impl std::ops::Deref for SymbolTable { type Target = Vec<SymbolTableEntry>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for SymbolTable { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl FromIterator<SymbolTableEntry> for SymbolTable { fn from_iter<T: IntoIterator<Item = SymbolTableEntry>>(iter: T) -> Self { let mut collection = SymbolTable::new(); for i in iter { collection.push(i); } collection } } impl IntoIterator for SymbolTable { type Item = SymbolTableEntry; type IntoIter = std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } impl fmt::Debug for SymbolTable { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let max_name_width = self.get_max_name_length(); let max_section_width = self.get_max_section_name_length(); let max_width = max_name_width + max_section_width + 19; // Hack for now for formatting, fix later let banner_break: String = iter::repeat("-").take(max_width).collect(); f.write_fmt(format_args!("{}\r\n", banner_break)).unwrap(); f.write_fmt(format_args!( "{:0n_width$} {:0s_width$} {:8} {:8}\r\n", "Name", "Section", "Address", "Size", n_width = max_name_width, s_width = max_section_width )) .unwrap(); f.write_fmt(format_args!("{}\r\n", banner_break)).unwrap(); for i in &self.0 { let result = f.write_str(&i.to_string(max_name_width, max_section_width)); if result.is_err() { return Err(std::fmt::Error); } } Ok(()) } } #[derive(Debug, PartialEq)] pub struct SymbolTableEntry { pub address: u32, pub flags: SymbolTableFlags, pub section: String, pub alignment_or_size: u32, pub name: String, } impl SymbolTableEntry { fn to_string(&self, name_width: usize, section_width: usize) -> String { format!( "{:0n_width$} {:0s_width$} {:08x} {:08x}\r\n", self.name, self.section, self.address, self.alignment_or_size, n_width = name_width, s_width = section_width ) } } #[derive(Debug, PartialEq)] pub struct SymbolTableFlags { pub scope: SymbolScope, pub weakness: SymbolWeakness, pub constructor: SymbolConstructor, pub warning: SymbolWarning, pub reference: SymbolReference, pub debugging: SymbolDebugging, pub symbol_type: SymbolType, } #[derive(Debug, PartialEq)] pub enum SymbolScope { Local, Global, Neither, Both, } #[derive(Debug, PartialEq)] pub enum SymbolWeakness { Weak, Strong, } #[derive(Debug, PartialEq)] pub enum SymbolConstructor { Constructor, Regular, } #[derive(Debug, PartialEq)] pub enum SymbolWarning { Warning, Regular, } #[derive(Debug, PartialEq)] pub enum SymbolReference { Reference, Regular, } #[derive(Debug, PartialEq)] pub enum SymbolDebugging { Debug, Dynamic, Regular, } #[derive(Debug, PartialEq)] pub enum SymbolType { Function, File, Object, Regular, } /// Parses an unsigned decimal value from a string fn parse_u32(input: &str) -> IResult<&str, u32> { recognize(many1(one_of("0123456789abcdefABCDEF")))(input) .map(|(i, o)| (i, u32::from_str_radix(o, 16).unwrap())) } /// Parses the symbol table scope bit out of the bit flags sequence fn parse_flag_bit_scope(input: &str) -> IResult<&str, SymbolScope> { let result = one_of("lg !")(input)?; match result.1 { 'l' => Ok((result.0, SymbolScope::Local)), 'g' => Ok((result.0, SymbolScope::Global)), ' ' => Ok((result.0, SymbolScope::Neither)), '!' => Ok((result.0, SymbolScope::Both)), _ => Err(nom::Err::Error(nom::error::Error { input, code: ErrorKind::Char, })), } } /// Parses the symbol table weak/strong symbol bit out of the bit flags sequence fn parse_flag_bit_weakness(input: &str) -> IResult<&str, SymbolWeakness> { let result = one_of("w ")(input)?; match result.1 { 'w' => Ok((result.0, SymbolWeakness::Weak)), ' ' => Ok((result.0, SymbolWeakness::Strong)), _ => Err(nom::Err::Error(nom::error::Error { input, code: ErrorKind::Char, })), } } /// Parses the symbol table constructor flag bit fn parse_flag_bit_constructor(input: &str) -> IResult<&str, SymbolConstructor> { let result = one_of("C ")(input)?; match result.1 { 'C' => Ok((result.0, SymbolConstructor::Constructor)), ' ' => Ok((result.0, SymbolConstructor::Regular)), _ => Err(nom::Err::Error(nom::error::Error { input, code: ErrorKind::Char, })), } } /// Parses if the symbol is a warning symbol or not fn parse_flag_bit_warning(input: &str) -> IResult<&str, SymbolWarning> { let result = one_of("W ")(input)?; match result.1 { 'W' => Ok((result.0, SymbolWarning::Warning)), ' ' => Ok((result.0, SymbolWarning::Regular)), _ => Err(nom::Err::Error(nom::error::Error { input, code: ErrorKind::Char, })), } } /// Parses the symbol flags reference bit fn parse_flag_bit_reference(input: &str) -> IResult<&str, SymbolReference> { let result = one_of("l ")(input)?; match result.1 { 'l' => Ok((result.0, SymbolReference::Reference)), ' ' => Ok((result.0, SymbolReference::Regular)), _ => Err(nom::Err::Error(nom::error::Error { input, code: ErrorKind::Char, })), } } /// Parses debug symbols from the flag bits fn parse_flag_bit_debugging(input: &str) -> IResult<&str, SymbolDebugging> { let result = one_of("dD ")(input)?; match result.1 { 'd' => Ok((result.0, SymbolDebugging::Debug)), 'D' => Ok((result.0, SymbolDebugging::Dynamic)), ' ' => Ok((result.0, SymbolDebugging::Regular)), _ => Err(nom::Err::Error(nom::error::Error { input, code: ErrorKind::Char, })), } } /// Parses the symbol type from the flag bits fn parse_flag_bit_type(input: &str) -> IResult<&str, SymbolType> { let result = one_of("FfO ")(input)?; match result.1 { 'F' => Ok((result.0, SymbolType::Function)), 'f' => Ok((result.0, SymbolType::File)), 'O' => Ok((result.0, SymbolType::Object)), ' ' => Ok((result.0, SymbolType::Regular)), _ => Err(nom::Err::Error(nom::error::Error { input, code: ErrorKind::Char, })), } } /// Parses a string into symbol table flags fn parse_symbol_flags(input: &str) -> IResult<&str, SymbolTableFlags> { let result = tuple(( parse_flag_bit_scope, parse_flag_bit_weakness, parse_flag_bit_constructor, parse_flag_bit_warning, parse_flag_bit_reference, parse_flag_bit_debugging, parse_flag_bit_type, ))(input)?; let symbol_flags = result.1; Ok(( result.0, SymbolTableFlags { scope: symbol_flags.0, weakness: symbol_flags.1, constructor: symbol_flags.2, warning: symbol_flags.3, reference: symbol_flags.4, debugging: symbol_flags.5, symbol_type: symbol_flags.6, }, )) } /// Parses a symbol table entry from a string. Returns a results type containing the parsed result if successful /// /// # Arguments /// * 'input' - The input string to parse the symbol table entry from pub fn parse_symbol_table_entry(input: &str) -> IResult<&str, SymbolTableEntry> { let mut parser = tuple(( parse_u32, one_of(" "), parse_symbol_flags, multispace0, take_until("\t"), multispace0, parse_u32, multispace0, many1(anychar), )); let result = parser(input)?; let (address, _, flags, _, section, _, alignment_or_size, _, name) = result.1; Ok(( "", SymbolTableEntry { address, flags, section: section.to_string(), alignment_or_size, name: name.iter().collect::<String>(), }, )) }
<?php return[ 'careers'=>'التوظيف', 'notice'=>'في حالة رغبتك في الانضمام إلى فريق عمل ريق النحل, يرجى ملئ البيانات التالية', 'email'=>'البريد الألكترونى', 'job_title'=>'المسمى الوظيفي', 'years'=>'سنوات الخبره', 'date_of_birth'=>'تاريخ الميلاد', 'cv'=>'رفع السيرة الذاتية الملفات المسموح بها PDF, DOC بحد أقصى ٢ ميجابايت.', 'thank_message'=>'شكراً لكم, لقد تم استلام الطلب الخاص بكم بنجاح', ];
%% %% %CopyrightBegin% %% %% Copyright Ericsson AB 2006-2021. All Rights Reserved. %% %% Licensed under the Apache License, Version 2.0 (the "License"); %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% http://www.apache.org/licenses/LICENSE-2.0 %% %% Unless required by applicable law or agreed to in writing, software %% distributed under the License is distributed on an "AS IS" BASIS, %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% -module(snmpa_conf). %% Avoid warning for local function error/1 clashing with autoimported BIF. -compile({no_auto_import,[error/1]}). -export([ %% agent.conf agent_entry/2, write_agent_config/2, write_agent_config/3, append_agent_config/2, read_agent_config/1, %% context.conf context_entry/1, write_context_config/2, write_context_config/3, append_context_config/2, read_context_config/1, %% community.conf community_entry/1, community_entry/5, write_community_config/2, write_community_config/3, append_community_config/2, read_community_config/1, %% standard.conf standard_entry/2, write_standard_config/2, write_standard_config/3, append_standard_config/2, read_standard_config/1, %% target_addr.conf target_addr_entry/5, target_addr_entry/6, target_addr_entry/7, target_addr_entry/8, target_addr_entry/10, target_addr_entry/11, write_target_addr_config/2, write_target_addr_config/3, append_target_addr_config/2, read_target_addr_config/1, %% target_params.conf target_params_entry/2, target_params_entry/4, target_params_entry/5, write_target_params_config/2, write_target_params_config/3, append_target_params_config/2, read_target_params_config/1, %% xyz.conf notify_entry/3, write_notify_config/2, write_notify_config/3, append_notify_config/2, read_notify_config/1, %% xyz.conf usm_entry/1, usm_entry/13, write_usm_config/2, write_usm_config/3, append_usm_config/2, read_usm_config/1, %% xyz.conf vacm_s2g_entry/3, vacm_acc_entry/8, vacm_vtf_entry/2, vacm_vtf_entry/4, write_vacm_config/2, write_vacm_config/3, append_vacm_config/2, read_vacm_config/1 ]). -export_type([ usm_entry/0 ]). -type usm_entry() :: { EngineID :: string(), UserName :: string(), SecName :: string(), Clone :: zeroDotZero | [non_neg_integer()], AuthP :: usmNoAuthProtocol | usmHMACMD5AuthProtocol | usmHMACSHAAuthProtocol | usmHMAC128SHA224AuthProtocol | usmHMAC192SHA256AuthProtocol | usmHMAC256SHA384AuthProtocol | usmHMAC384SHA512AuthProtocol, AuthKeyC :: string(), OwnAuthKeyC :: string(), PrivP :: usmNoPrivProtocol | usmDESPrivProtocol | usmAesCfb128Protocol, PrivKeyC :: string(), OwnPrivKeyC :: string(), Public :: string(), %% Size 16 for usmHMACMD5AuthProtocol %% Size 20 for usmHMACSHAAuthProtocol %% Size 28 for usmHMAC128SHA224AuthProtocol %% Size 32 for usmHMAC192SHA256AuthProtocol %% Size 48 for usmHMAC256SHA384AuthProtocol %% Size 64 for usmHMAC384SHA512AuthProtocol AuthKey :: [non_neg_integer()], %% Size 16 for usmDESPrivProtocol | usmAesCfb128Protocol PrivKey :: [non_neg_integer()] }. %% %% ------ agent.conf ------ %% agent_entry(Tag, Val) -> {Tag, Val}. write_agent_config(Dir, Conf) -> Comment = "%% This file defines the Agent local configuration info\n" "%% The data is inserted into the snmpEngine* variables defined\n" "%% in SNMP-FRAMEWORK-MIB, and the intAgent* variables defined\n" "%% in OTP-SNMPEA-MIB.\n" "%% Each row is a 2-tuple:\n" "%% {AgentVariable, Value}.\n" "%% For example\n" "%% {intAgentUDPPort, 4000}.\n" "%% The ip address for the agent is sent as id in traps.\n" "%% {intAgentIpAddress, [127,42,17,5]}.\n" "%% {snmpEngineID, \"agentEngine\"}.\n" "%% {snmpEngineMaxMessageSize, 484}.\n" "%%\n\n", Hdr = header() ++ Comment, write_agent_config(Dir, Hdr, Conf). write_agent_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_framework_mib:order_agent/2, Check = fun snmp_framework_mib:check_agent/2, Write = fun (Fd, Entries) -> write_agent_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "agent.conf", Order, Check, Write, Conf). append_agent_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_framework_mib:order_agent/2, Check = fun snmp_framework_mib:check_agent/2, Write = fun write_agent_conf/2, append_config_file(Dir, "agent.conf", Order, Check, Write, Conf). read_agent_config(Dir) -> Order = fun snmp_framework_mib:order_agent/2, Check = fun snmp_framework_mib:check_agent/2, read_config_file(Dir, "agent.conf", Order, Check). write_agent_conf(Fd, "", Conf) -> write_agent_conf(Fd, Conf); write_agent_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_agent_conf(Fd, Conf). write_agent_conf(_Fd, []) -> ok; write_agent_conf(Fd, [H|T]) -> do_write_agent_conf(Fd, H), write_agent_conf(Fd, T). do_write_agent_conf(Fd, {intAgentTransports = Tag, Val}) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_agent_conf(Fd, {intAgentTransportDomain = Tag, Val}) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_agent_conf(Fd, {intAgentIpAddress = Tag, Val}) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_agent_conf(Fd, {intAgentUDPPort = Tag, Val} ) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_agent_conf(Fd, {intAgentMaxPacketSize = Tag, Val} ) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_agent_conf(Fd, {snmpEngineMaxMessageSize = Tag, Val} ) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_agent_conf(Fd, {snmpEngineID = Tag, Val} ) -> io:format(Fd, "{~w, ~p}.~n", [Tag, Val]); do_write_agent_conf(_Fd, Crap) -> error({bad_agent_config, Crap}). %% %% ------ context.conf ------ %% context_entry(Ctx) -> Ctx. write_context_config(Dir, Conf) -> Comment = "%% This file defines the contexts known to the agent.\n" "%% The data is inserted into the vacmContextTable defined\n" "%% in SNMP-VIEW-BASED-ACM-MIB.\n" "%% Each row is a string:\n" "%% ContextName.\n" "%%\n" "%% The empty string is the default context.\n" "%% For example\n" "%% \"bridge1\".\n" "%% \"bridge2\".\n" "%%\n\n", Hdr = header() ++ Comment, write_context_config(Dir, Hdr, Conf). write_context_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_context/2, Write = fun (Fd, Entries) -> write_context_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "context.conf", Order, Check, Write, Conf). append_context_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_context/2, Write = fun write_context_conf/2, append_config_file(Dir, "context.conf", Order, Check, Write, Conf). read_context_config(Dir) -> Order = fun snmp_conf:no_order/2, Check = fun check_context/2, read_config_file(Dir, "context.conf", Order, Check). check_context(Entry, State) -> {check_ok(snmp_framework_mib:check_context(Entry)), State}. write_context_conf(Fd, "", Conf) -> write_context_conf(Fd, Conf); write_context_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_context_conf(Fd, Conf). write_context_conf(_Fd, []) -> ok; write_context_conf(Fd, [H|T]) when is_list(H) -> io:format(Fd, "\"~s\".~n", [H]), write_context_conf(Fd, T); write_context_conf(_Fd, X) -> error({invalid_context_config, X}). %% %% ------ community.conf ------ %% community_entry(CommIndex) when CommIndex == "public" -> CommName = CommIndex, SecName = "initial", CtxName = "", TransportTag = "", community_entry(CommIndex, CommName, SecName, CtxName, TransportTag); community_entry(CommIndex) when CommIndex == "all-rights" -> CommName = CommIndex, SecName = CommIndex, CtxName = "", TransportTag = "", community_entry(CommIndex, CommName, SecName, CtxName, TransportTag). community_entry(CommIndex, CommName, SecName, CtxName, TransportTag) -> {CommIndex, CommName, SecName, CtxName, TransportTag}. write_community_config(Dir, Conf) -> Comment = "%% This file defines the community info which maps to VACM parameters.\n" "%% The data is inserted into the snmpCommunityTable defined\n" "%% in SNMP-COMMUNITY-MIB.\n" "%% Each row is a 5-tuple:\n" "%% {CommunityIndex, CommunityName, SecurityName, ContextName, TransportTag}.\n" "%% For example\n" "%% {\"1\", \"public\", \"initial\", \"\", \"\"}.\n" "%% {\"2\", \"secret\", \"secret_name\", \"\", \"tag\"}.\n" "%% {\"3\", \"bridge1\", \"initial\", \"bridge1\", \"\"}.\n" "%%\n\n", Hdr = header() ++ Comment, write_community_config(Dir, Hdr, Conf). write_community_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_community/2, Write = fun (Fd, Entries) -> write_community_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "community.conf", Order, Check, Write, Conf). append_community_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_community/2, Write = fun write_community_conf/2, append_config_file(Dir, "community.conf", Order, Check, Write, Conf). read_community_config(Dir) -> Order = fun snmp_conf:no_order/2, Check = fun check_community/2, read_config_file(Dir, "community.conf", Order, Check). check_community(Entry, State) -> {check_ok(snmp_community_mib:check_community(Entry)), State}. write_community_conf(Fd, "", Conf) -> write_community_conf(Fd, Conf); write_community_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_community_conf(Fd, Conf). write_community_conf(Fd, Conf) -> Fun = fun({Idx, Name, SecName, CtxName, TranspTag}) -> io:format( Fd, "{\"~s\", \"~s\", \"~s\", \"~s\", \"~s\"}.~n", [Idx, Name, SecName, CtxName, TranspTag]); (Crap) -> error({bad_community_config, Crap}) end, lists:foreach(Fun, Conf). %% %% ------ standard.conf ------ %% standard_entry(Tag, Val) -> {Tag, Val}. write_standard_config(Dir, Conf) -> Comment = "%% This file defines the STANDARD-MIB info.\n" "%% Each row is a 2-tuple:\n" "%% {StandardVariable, Value}.\n" "%% For example\n" "%% {sysDescr, \"Erlang SNMP agent\"}.\n" "%% {sysObjectID, [1,2,3]}.\n" "%% {sysContact, \"{mbj,eklas}@erlang.ericsson.se\"}.\n" "%% {sysName, \"test\"}.\n" "%% {sysLocation, \"erlang\"}.\n" "%% {sysServices, 72}.\n" "%% {snmpEnableAuthenTraps, enabled}.\n" "%%\n\n", Hdr = header() ++ Comment, write_standard_config(Dir, Hdr, Conf). write_standard_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_standard/2, Write = fun (Fd, Entries) -> write_standard_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "standard.conf", Order, Check, Write, Conf). append_standard_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_standard/2, Write = fun write_standard_conf/2, append_config_file(Dir, "standard.conf", Order, Check, Write, Conf). read_standard_config(Dir) -> Order = fun snmp_conf:no_order/2, Check = fun check_standard/2, read_config_file(Dir, "standard.conf", Order, Check). check_standard(Entry, State) -> {check_ok(snmp_standard_mib:check_standard(Entry)), State}. write_standard_conf(Fd, "", Conf) -> write_standard_conf(Fd, Conf); write_standard_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_standard_conf(Fd, Conf). write_standard_conf(Fd, Conf) -> Fun = fun({Tag, Val}) -> do_write_standard_conf(Fd, Tag, Val) end, lists:foreach(Fun, Conf). do_write_standard_conf(Fd, sysDescr = Tag, Val) -> io:format(Fd, "{~w, \"~s\"}.~n", [Tag, Val]); do_write_standard_conf(Fd, sysObjectID = Tag, Val) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_standard_conf(Fd, sysContact = Tag, Val) -> io:format(Fd, "{~w, \"~s\"}.~n", [Tag, Val]); do_write_standard_conf(Fd, sysName = Tag, Val) -> io:format(Fd, "{~w, \"~s\"}.~n", [Tag, Val]); do_write_standard_conf(Fd, sysLocation = Tag, Val) -> io:format(Fd, "{~w, \"~s\"}.~n", [Tag, Val]); do_write_standard_conf(Fd, sysServices = Tag, Val) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_standard_conf(Fd, snmpEnableAuthenTraps = Tag, Val) -> io:format(Fd, "{~w, ~w}.~n", [Tag, Val]); do_write_standard_conf(_Fd, Tag, Val) -> error({bad_standard_config, {Tag, Val}}). %% %% ------ target_addr.conf ------ %% target_addr_entry( Name, Ip, TagList, ParamsName, EngineId) -> target_addr_entry(Name, Ip, TagList, ParamsName, EngineId, []). target_addr_entry( Name, Domain, Addr, TagList, ParamsName, EngineId) when is_atom(Domain) -> target_addr_entry( Name, Domain, Addr, TagList, ParamsName, EngineId, []); target_addr_entry( Name, Ip, TagList, ParamsName, EngineId, TMask) -> target_addr_entry( Name, Ip, 162, TagList, ParamsName, EngineId, TMask, 2048). target_addr_entry( Name, Domain_or_Ip, Addr_or_Port, TagList, ParamsName, EngineId, TMask) -> target_addr_entry( Name, Domain_or_Ip, Addr_or_Port, TagList, ParamsName, EngineId, TMask, 2048). target_addr_entry( Name, Domain_or_Ip, Addr_or_Port, TagList, ParamsName, EngineId, TMask, MaxMessageSize) -> target_addr_entry( Name, Domain_or_Ip, Addr_or_Port, 1500, 3, TagList, ParamsName, EngineId, TMask, MaxMessageSize). target_addr_entry( Name, Domain_or_Ip, Addr_or_Port, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize) -> {Name, Domain_or_Ip, Addr_or_Port, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}. target_addr_entry( Name, Domain, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId,TMask, MaxMessageSize) -> {Name, Domain, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}. write_target_addr_config(Dir, Conf) -> Comment = "%% This file defines the target address parameters.\n" "%% The data is inserted into the snmpTargetAddrTable defined\n" "%% in SNMP-TARGET-MIB, and in the snmpTargetAddrExtTable defined\n" "%% in SNMP-COMMUNITY-MIB.\n" "%% Each row is a 10 or 11-tuple (Domain is optional):\n" "%% {Name, \n" "%% Domain, Ip, Port, \n" "%% Timeout, RetryCount, TagList, ParamsName, EngineId,\n" "%% TMask, MaxMessageSize}.\n" "%% The value of Domain decide the format of the Ip and TMask values. \n" "%% If not present, classic Ipv4 is assumed. \n" "%% The EngineId value is only used if Inform-Requests are sent to this\n" "%% target. If Informs are not sent, this value is ignored, and can be\n" "%% e.g. an empty string. However, if Informs are sent, it is essential\n" "%% that the value of EngineId matches the value of the target's\n" "%% actual snmpEngineID.\n" "%% For example\n" "%% {\"1.2.3.4 v1\", [1,2,3,4], 162, \n" "%% 1500, 3, \"std_inform\", \"otp_v2\", \"\",\n" "%% [127,0,0,0], 2048}.\n" "%%\n\n", Hdr = header() ++ Comment, write_target_addr_config(Dir, Hdr, Conf). write_target_addr_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_target_addr/2, Write = fun (Fd, Entries) -> write_target_addr_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "target_addr.conf", Order, Check, Write, Conf). append_target_addr_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_target_addr/2, Write = fun write_target_addr_conf/2, append_config_file(Dir, "target_addr.conf", Order, Check, Write, Conf). read_target_addr_config(Dir) -> Order = fun snmp_conf:no_order/2, Check = fun check_target_addr/2, read_config_file(Dir, "target_addr.conf", Order, Check). check_target_addr(Entry, State) -> {check_ok(snmp_target_mib:check_target_addr(Entry)), State}. write_target_addr_conf(Fd, "", Conf) -> write_target_addr_conf(Fd, Conf); write_target_addr_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_target_addr_conf(Fd, Conf). write_target_addr_conf(Fd, Conf) -> Fun = fun(Entry) -> do_write_target_addr_conf(Fd, Entry) end, lists:foreach(Fun, Conf), ok. do_write_target_addr_conf( Fd, {Name, Domain, Address, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}) when is_atom(Domain) -> io:format( Fd, "{\"~s\", ~w, ~w, ~w, ~w, \"~s\", \"~s\", \"~s\", ~w, ~w}.~n", [Name, Domain, Address, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize]); do_write_target_addr_conf( Fd, {Name, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}) when is_integer(Udp) -> Domain = snmp_target_mib:default_domain(), Address = {Ip, Udp}, do_write_target_addr_conf( Fd, {Name, Domain, Address, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}); do_write_target_addr_conf( _Fd, {_Name, Domain, Address, _Timeout, _RetryCount, _TagList, _ParamsName, _EngineId, _TMask, _MaxMessageSize}) -> error({bad_address, {Domain, Address}}); do_write_target_addr_conf( Fd, {Name, Domain, Ip, Udp, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}) -> Address = {Ip, Udp}, do_write_target_addr_conf( Fd, {Name, Domain, Address, Timeout, RetryCount, TagList, ParamsName, EngineId, TMask, MaxMessageSize}); do_write_target_addr_conf(_Fd, Crap) -> error({bad_target_addr_config, Crap}). %% %% ------ target_params.conf ------ %% target_params_entry(Name, Vsn) -> SecName = "initial", SecLevel = noAuthNoPriv, target_params_entry(Name, Vsn, SecName, SecLevel). target_params_entry(Name, Vsn, SecName, SecLevel) -> MPModel = if Vsn =:= v1 -> v1; Vsn =:= v2 -> v2c; Vsn =:= v3 -> v3 end, SecModel = if Vsn =:= v1 -> v1; Vsn =:= v2 -> v2c; Vsn =:= v3 -> usm end, target_params_entry(Name, MPModel, SecModel, SecName, SecLevel). target_params_entry(Name, MPModel, SecModel, SecName, SecLevel) -> {Name, MPModel, SecModel, SecName, SecLevel}. write_target_params_config(Dir, Conf) -> Comment = "%% This file defines the target parameters.\n" "%% The data is inserted into the snmpTargetParamsTable defined\n" "%% in SNMP-TARGET-MIB.\n" "%% Each row is a 5-tuple:\n" "%% {Name, MPModel, SecurityModel, SecurityName, SecurityLevel}.\n" "%% For example\n" "%% {\"target_v3\", v3, usm, \"\", noAuthNoPriv}.\n" "%%\n\n", Hdr = header() ++ Comment, write_target_params_config(Dir, Hdr, Conf). write_target_params_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_target_params/2, Write = fun (Fd, Entries) -> write_target_params_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "target_params.conf", Order, Check, Write, Conf). append_target_params_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_target_params/2, Write = fun write_target_params_conf/2, append_config_file(Dir, "target_params.conf", Order, Check, Write, Conf). read_target_params_config(Dir) -> Order = fun snmp_conf:no_order/2, Check = fun check_target_params/2, read_config_file(Dir, "target_params.conf", Order, Check). check_target_params(Entry, State) -> {check_ok(snmp_target_mib:check_target_params(Entry)), State}. write_target_params_conf(Fd, "", Conf) -> write_target_params_conf(Fd, Conf); write_target_params_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_target_params_conf(Fd, Conf). write_target_params_conf(Fd, Conf) -> Fun = fun(Entry) -> do_write_target_params_conf(Fd, Entry) end, lists:foreach(Fun, Conf). do_write_target_params_conf(Fd, {Name, MpModel, SecModel, SecName, SecLevel}) -> io:format(Fd, "{\"~s\", ~w, ~w, \"~s\", ~w}.~n", [Name, MpModel, SecModel, SecName, SecLevel]); do_write_target_params_conf(_Fd, Crap) -> error({bad_target_params_config, Crap}). %% %% ------ notify.conf ------ %% notify_entry(Name, Tag, Type) -> {Name, Tag, Type}. write_notify_config(Dir, Conf) -> Comment = "%% This file defines the notification parameters.\n" "%% The data is inserted into the snmpNotifyTable defined\n" "%% in SNMP-NOTIFICATION-MIB.\n" "%% The Name is used as CommunityString for v1 and v2c.\n" "%% Each row is a 3-tuple:\n" "%% {Name, Tag, Type}.\n" "%% For example\n" "%% {\"standard trap\", \"std_trap\", trap}.\n" "%% {\"standard inform\", \"std_inform\", inform}.\n" "%%\n\n", Hdr = header() ++ Comment, write_notify_config(Dir, Hdr, Conf). write_notify_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_notify/2, Write = fun (Fd, Entries) -> write_notify_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "notify.conf", Order, Check, Write, Conf). append_notify_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_notify/2, Write = fun write_notify_conf/2, append_config_file(Dir, "notify.conf", Order, Check, Write, Conf). read_notify_config(Dir) -> Order = fun snmp_conf:no_order/2, Check = fun check_notify/2, read_config_file(Dir, "notify.conf", Order, Check). check_notify(Entry, State) -> {check_ok(snmp_notification_mib:check_notify(Entry)), State}. write_notify_conf(Fd, "", Conf) -> write_notify_conf(Fd, Conf); write_notify_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_notify_conf(Fd, Conf). write_notify_conf(Fd, Conf) -> Fun = fun(Entry) -> do_write_notify_conf(Fd, Entry) end, lists:foreach(Fun, Conf). do_write_notify_conf(Fd, {Name, Tag, Type}) -> io:format(Fd, "{\"~s\", \"~s\", ~w}.~n", [Name, Tag, Type]); do_write_notify_conf(_Fd, Crap) -> error({bad_notify_config, Crap}). %% %% ------ usm.conf ------ %% usm_entry(EngineID) -> UserName = "initial", SecName = "initial", Clone = zeroDotZero, AuthP = usmNoAuthProtocol, AuthKeyC = "", OwnAuthKeyC = "", PrivP = usmNoPrivProtocol, PrivKeyC = "", OwnPrivKeyC = "", Public = "", AuthKey = "", PrivKey = "", usm_entry(EngineID, UserName, SecName, Clone, AuthP, AuthKeyC, OwnAuthKeyC, PrivP, PrivKeyC, OwnPrivKeyC, Public, AuthKey, PrivKey). usm_entry(EngineID, UserName, SecName, Clone, AuthP, AuthKeyC, OwnAuthKeyC, PrivP, PrivKeyC, OwnPrivKeyC, Public, AuthKey, PrivKey) -> {EngineID, UserName, SecName, Clone, AuthP, AuthKeyC, OwnAuthKeyC, PrivP, PrivKeyC, OwnPrivKeyC, Public, AuthKey, PrivKey}. write_usm_config(Dir, Conf) -> Comment = "%% This file defines the security parameters for the user-based\n" "%% security model.\n" "%% The data is inserted into the usmUserTable defined\n" "%% in SNMP-USER-BASED-SM-MIB.\n" "%% Each row is a 13-tuple:\n" "%% {EngineID, UserName, SecName, Clone, AuthP, AuthKeyC, OwnAuthKeyC,\n" "%% PrivP, PrivKeyC, OwnPrivKeyC, Public, AuthKey, PrivKey}.\n" "%% For example\n" "%% {\"agentEngine\", \"initial\", \"initial\", zeroDotZero,\n" "%% usmNoAuthProtocol, \"\", \"\", usmNoPrivProtocol, \"\", \"\", \"\",\n" "%% \"\", \"\"}.\n" "%%\n\n", Hdr = header() ++ Comment, write_usm_config(Dir, Hdr, Conf). write_usm_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_usm/2, Write = fun (Fd, Entries) -> write_usm_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "usm.conf", Order, Check, Write, Conf). append_usm_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_usm/2, Write = fun write_usm_conf/2, append_config_file(Dir, "usm.conf", Order, Check, Write, Conf). read_usm_config(Dir) -> Order = fun snmp_conf:no_order/2, Check = fun check_usm/2, read_config_file(Dir, "usm.conf", Order, Check). check_usm(Entry, State) -> {check_ok(snmp_user_based_sm_mib:check_usm(Entry)), State}. write_usm_conf(Fd, "", Conf) -> write_usm_conf(Fd, Conf); write_usm_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_usm_conf(Fd, Conf). write_usm_conf(Fd, Conf) -> Fun = fun(Entry) -> do_write_usm_conf(Fd, Entry) end, lists:foreach(Fun, Conf). do_write_usm_conf( Fd, {EngineID, UserName, SecName, Clone, AuthP, AuthKeyC, OwnAuthKeyC, PrivP, PrivKeyC, OwnPrivKeyC, Public, AuthKey, PrivKey}) -> io:format(Fd, "{", []), io:format(Fd, "~p, ", [EngineID]), io:format(Fd, "~p, ", [UserName]), io:format(Fd, "~p, ", [SecName]), io:format(Fd, "~w, ", [Clone]), io:format(Fd, "~w, ", [AuthP]), do_write_usm2(Fd, AuthKeyC, ", "), do_write_usm2(Fd, OwnAuthKeyC, ", "), io:format(Fd, "~w, ", [PrivP]), do_write_usm2(Fd, PrivKeyC, ", "), do_write_usm2(Fd, OwnPrivKeyC, ", "), do_write_usm2(Fd, Public, ", "), do_write_usm2(Fd, AuthKey, ", "), do_write_usm2(Fd, PrivKey, ""), io:format(Fd, "}.~n", []); do_write_usm_conf(_Fd, Crap) -> error({bad_usm_config, Crap}). do_write_usm2(Fd, "", P) -> io:format(Fd, "\"\"~s", [P]); do_write_usm2(Fd, X, P) -> io:format(Fd, "~w~s", [X, P]). %% %% ------ vacm.conf ------ %% vacm_s2g_entry(SecModel, SecName, GroupName) -> {vacmSecurityToGroup, SecModel, SecName, GroupName}. vacm_acc_entry(GroupName, Prefix, SecModel, SecLevel, Match, RV, WV, NV) -> {vacmAccess, GroupName, Prefix, SecModel, SecLevel, Match, RV, WV, NV}. vacm_vtf_entry(ViewIndex, ViewSubtree) -> vacm_vtf_entry(ViewIndex, ViewSubtree, included, null). vacm_vtf_entry(ViewIndex, ViewSubtree, ViewStatus, ViewMask) -> {vacmViewTreeFamily, ViewIndex, ViewSubtree, ViewStatus, ViewMask}. write_vacm_config(Dir, Conf) -> Comment = "%% This file defines the Mib Views.\n" "%% The data is inserted into the vacm* tables defined\n" "%% in SNMP-VIEW-BASED-ACM-MIB.\n" "%% Each row is one of 3 tuples; one for each table in the MIB:\n" "%% {vacmSecurityToGroup, SecModel, SecName, GroupName}.\n" "%% {vacmAccess, GroupName, Prefix, SecModel, SecLevel, Match, RV, WV, NV}.\n" "%% {vacmViewTreeFamily, ViewIndex, ViewSubtree, ViewStatus, ViewMask}.\n" "%% For example\n" "%% {vacmSecurityToGroup, v2c, \"initial\", \"initial\"}.\n" "%% {vacmSecurityToGroup, usm, \"initial\", \"initial\"}.\n" "%% read/notify access to system\n" "%% {vacmAccess, \"initial\", \"\", any, noAuthNoPriv, exact,\n" "%% \"system\", \"\", \"system\"}.\n" "%% {vacmViewTreeFamily, \"system\", [1,3,6,1,2,1,1], included, null}.\n" "%% {vacmViewTreeFamily, \"exmib\", [1,3,6,1,3], included, null}." " % for EX1-MIB\n" "%% {vacmViewTreeFamily, \"internet\", [1,3,6,1], included, null}.\n" "%%\n\n", Hdr = header() ++ Comment, write_vacm_config(Dir, Hdr, Conf). write_vacm_config(Dir, Hdr, Conf) when is_list(Dir) and is_list(Hdr) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_vacm/2, Write = fun (Fd, Entries) -> write_vacm_conf(Fd, Hdr, Entries) end, write_config_file(Dir, "vacm.conf", Order, Check, Write, Conf). append_vacm_config(Dir, Conf) when is_list(Dir) and is_list(Conf) -> Order = fun snmp_conf:no_order/2, Check = fun check_vacm/2, Write = fun write_vacm_conf/2, append_config_file(Dir, "vacm.conf", Order, Check, Write, Conf). read_vacm_config(Dir) -> Order = fun snmp_conf:no_order/2, Check = fun check_vacm/2, read_config_file(Dir, "vacm.conf", Order, Check). check_vacm(Entry, State) -> {check_ok(snmp_view_based_acm_mib:check_vacm(Entry)), State}. write_vacm_conf(Fd, "", Conf) -> write_vacm_conf(Fd, Conf); write_vacm_conf(Fd, Hdr, Conf) -> io:format(Fd, "~s~n", [Hdr]), write_vacm_conf(Fd, Conf). write_vacm_conf(Fd, Conf) -> Fun = fun(Entry) -> do_write_vacm_conf(Fd, Entry) end, lists:foreach(Fun, Conf). do_write_vacm_conf( Fd, {vacmSecurityToGroup, SecModel, SecName, GroupName}) -> io:format( Fd, "{vacmSecurityToGroup, ~w, ~p, ~p}.~n", [SecModel, SecName, GroupName]); do_write_vacm_conf( Fd, {vacmAccess, GroupName, Prefix, SecModel, SecLevel, Match, RV, WV, NV}) -> io:format( Fd, "{vacmAccess, ~p, ~p, ~w, ~w, ~w, " "~p, ~p, ~p}.~n", [GroupName, Prefix, SecModel, SecLevel, Match, RV, WV, NV]); do_write_vacm_conf( Fd, {vacmViewTreeFamily, ViewIndex, ViewSubtree, ViewStatus, ViewMask}) -> io:format( Fd, "{vacmViewTreeFamily, ~p, ~w, ~w, ~w}.~n", [ViewIndex, ViewSubtree, ViewStatus, ViewMask]); do_write_vacm_conf(_Fd, Crap) -> error({bad_vacm_config, Crap}). %% ---- config file wrapper functions ---- write_config_file(Dir, File, Order, Check, Write, Conf) -> snmp_config:write_config_file(Dir, File, Order, Check, Write, Conf). append_config_file(Dir, File, Order, Check, Write, Conf) -> snmp_config:append_config_file(Dir, File, Order, Check, Write, Conf). read_config_file(Dir, File, Order, Check) -> snmp_config:read_config_file(Dir, File, Order, Check). %% ---- config file utility functions ---- check_ok(ok) -> ok; check_ok({ok, _}) -> ok. header() -> {Y,Mo,D} = date(), {H,Mi,S} = time(), io_lib:format( "%% This file was generated by " "~w (version-~s) ~w-~2.2.0w-~2.2.0w " "~2.2.0w:~2.2.0w:~2.2.0w\n", [?MODULE, ?version, Y, Mo, D, H, Mi, S]). error(R) -> throw({error, R}).
# Changelog 0.9.10 (unreleased) ------------------- - Nothing changed yet. 0.9.9 (2020-05-06) ------------------ - Fix healthchecks after Django upgrade 0.9.8 (2020-05-05) ------------------ - Fix PyPI packaging 0.9.7 (2020-05-05) ------------------ - Upgrade dependencies - Remove yarn in favor of npm - Fix issue in result format with recent Salt version 0.9.6 (2019-04-17) ------------------ - Dependency updates 0.9.5 (2018-05-24) ------------------ - Adds `HIDE_OUTPUT` config to prevent showing secrets in web interface 0.9.4 (2018-05-15) ------------------ - Fixes operation with systemd socket activation 0.9.3 (2018-05-15) ------------------ - Adds proper SSL handling 0.9.2 (2018-05-15) ------------------ - Fixes healthcheck middleware to avoid `ALLOWED_HOSTS` checking - Update dependencies - Documentation updates 0.9.1 (2018-05-14) ------------------ - Packaging fixes 0.9 (2018-05-14) ---------------- - Initial PyPI release