file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
base.py
# Copyright 2014 Cisco Systems, 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. import os import random from neutron.agent.linux import ovs_lib from neutron.agent.linux import utils from neutron.common import constants as n_const from neutron.tests import base BR_PREFIX = 'test-br' class BaseLinuxTestCase(base.BaseTestCase): def setUp(self, root_helper='sudo'): super(BaseLinuxTestCase, self).setUp() self.root_helper = root_helper def check_command(self, cmd, error_text, skip_msg): try: utils.execute(cmd) except RuntimeError as e: if error_text in str(e): self.skipTest(skip_msg) raise def check_sudo_enabled(self): if os.environ.get('OS_SUDO_TESTING') not in base.TRUE_STRING: self.skipTest('testing with sudo is not enabled') def get_rand_name(self, max_length, prefix='test'): name = prefix + str(random.randint(1, 0x7fffffff)) return name[:max_length] def create_resource(self, name_prefix, creation_func, *args, **kwargs): """Create a new resource that does not already exist. :param name_prefix: The prefix for a randomly generated name :param creation_func: A function taking the name of the resource to be created as it's first argument. An error is assumed to indicate a name collision. :param *args *kwargs: These will be passed to the create function. """ while True: name = self.get_rand_name(n_const.DEV_NAME_MAX_LEN, name_prefix) try: return creation_func(name, *args, **kwargs) except RuntimeError: continue
class BaseOVSLinuxTestCase(BaseLinuxTestCase): def setUp(self, root_helper='sudo'): super(BaseOVSLinuxTestCase, self).setUp(root_helper) self.ovs = ovs_lib.BaseOVS(self.root_helper) def create_ovs_bridge(self, br_prefix=BR_PREFIX): br = self.create_resource(br_prefix, self.ovs.add_bridge) self.addCleanup(br.destroy) return br
random_line_split
base.py
# Copyright 2014 Cisco Systems, 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. import os import random from neutron.agent.linux import ovs_lib from neutron.agent.linux import utils from neutron.common import constants as n_const from neutron.tests import base BR_PREFIX = 'test-br' class BaseLinuxTestCase(base.BaseTestCase): def setUp(self, root_helper='sudo'): super(BaseLinuxTestCase, self).setUp() self.root_helper = root_helper def check_command(self, cmd, error_text, skip_msg): try: utils.execute(cmd) except RuntimeError as e: if error_text in str(e): self.skipTest(skip_msg) raise def check_sudo_enabled(self): if os.environ.get('OS_SUDO_TESTING') not in base.TRUE_STRING: self.skipTest('testing with sudo is not enabled') def get_rand_name(self, max_length, prefix='test'): name = prefix + str(random.randint(1, 0x7fffffff)) return name[:max_length] def create_resource(self, name_prefix, creation_func, *args, **kwargs):
class BaseOVSLinuxTestCase(BaseLinuxTestCase): def setUp(self, root_helper='sudo'): super(BaseOVSLinuxTestCase, self).setUp(root_helper) self.ovs = ovs_lib.BaseOVS(self.root_helper) def create_ovs_bridge(self, br_prefix=BR_PREFIX): br = self.create_resource(br_prefix, self.ovs.add_bridge) self.addCleanup(br.destroy) return br
"""Create a new resource that does not already exist. :param name_prefix: The prefix for a randomly generated name :param creation_func: A function taking the name of the resource to be created as it's first argument. An error is assumed to indicate a name collision. :param *args *kwargs: These will be passed to the create function. """ while True: name = self.get_rand_name(n_const.DEV_NAME_MAX_LEN, name_prefix) try: return creation_func(name, *args, **kwargs) except RuntimeError: continue
identifier_body
base.py
# Copyright 2014 Cisco Systems, 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. import os import random from neutron.agent.linux import ovs_lib from neutron.agent.linux import utils from neutron.common import constants as n_const from neutron.tests import base BR_PREFIX = 'test-br' class BaseLinuxTestCase(base.BaseTestCase): def setUp(self, root_helper='sudo'): super(BaseLinuxTestCase, self).setUp() self.root_helper = root_helper def check_command(self, cmd, error_text, skip_msg): try: utils.execute(cmd) except RuntimeError as e: if error_text in str(e): self.skipTest(skip_msg) raise def check_sudo_enabled(self): if os.environ.get('OS_SUDO_TESTING') not in base.TRUE_STRING: self.skipTest('testing with sudo is not enabled') def get_rand_name(self, max_length, prefix='test'): name = prefix + str(random.randint(1, 0x7fffffff)) return name[:max_length] def create_resource(self, name_prefix, creation_func, *args, **kwargs): """Create a new resource that does not already exist. :param name_prefix: The prefix for a randomly generated name :param creation_func: A function taking the name of the resource to be created as it's first argument. An error is assumed to indicate a name collision. :param *args *kwargs: These will be passed to the create function. """ while True:
class BaseOVSLinuxTestCase(BaseLinuxTestCase): def setUp(self, root_helper='sudo'): super(BaseOVSLinuxTestCase, self).setUp(root_helper) self.ovs = ovs_lib.BaseOVS(self.root_helper) def create_ovs_bridge(self, br_prefix=BR_PREFIX): br = self.create_resource(br_prefix, self.ovs.add_bridge) self.addCleanup(br.destroy) return br
name = self.get_rand_name(n_const.DEV_NAME_MAX_LEN, name_prefix) try: return creation_func(name, *args, **kwargs) except RuntimeError: continue
conditional_block
base.py
# Copyright 2014 Cisco Systems, 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. import os import random from neutron.agent.linux import ovs_lib from neutron.agent.linux import utils from neutron.common import constants as n_const from neutron.tests import base BR_PREFIX = 'test-br' class
(base.BaseTestCase): def setUp(self, root_helper='sudo'): super(BaseLinuxTestCase, self).setUp() self.root_helper = root_helper def check_command(self, cmd, error_text, skip_msg): try: utils.execute(cmd) except RuntimeError as e: if error_text in str(e): self.skipTest(skip_msg) raise def check_sudo_enabled(self): if os.environ.get('OS_SUDO_TESTING') not in base.TRUE_STRING: self.skipTest('testing with sudo is not enabled') def get_rand_name(self, max_length, prefix='test'): name = prefix + str(random.randint(1, 0x7fffffff)) return name[:max_length] def create_resource(self, name_prefix, creation_func, *args, **kwargs): """Create a new resource that does not already exist. :param name_prefix: The prefix for a randomly generated name :param creation_func: A function taking the name of the resource to be created as it's first argument. An error is assumed to indicate a name collision. :param *args *kwargs: These will be passed to the create function. """ while True: name = self.get_rand_name(n_const.DEV_NAME_MAX_LEN, name_prefix) try: return creation_func(name, *args, **kwargs) except RuntimeError: continue class BaseOVSLinuxTestCase(BaseLinuxTestCase): def setUp(self, root_helper='sudo'): super(BaseOVSLinuxTestCase, self).setUp(root_helper) self.ovs = ovs_lib.BaseOVS(self.root_helper) def create_ovs_bridge(self, br_prefix=BR_PREFIX): br = self.create_resource(br_prefix, self.ovs.add_bridge) self.addCleanup(br.destroy) return br
BaseLinuxTestCase
identifier_name
lazy-components.js
!(function() { 'use strict'; function ComponentLoader($window, $q) { var self = this; this.basePath = '.'; this.queue = [ /*{path: '.', name: 'svg-viewer', scripts:['lazy.js'], run: function(){}}*/ ]; this.loaded = { /*'svg-viewer':true'*/ }; this.loadAll = function() { var components = self.queue.map(function loadEach(component) { component.pending = true; return self.load(component); }) return $q.all(components); } this.load = function(component) { if (angular.isString(component)) { component = resolveComponent(component) } if (!component) throw new Error('The lazy component is not registered and cannot load') if (!component.name) throw new Error('The lazy component must register with name property and cannot load'); if (self.loaded[component.name]) { return $q.when(component); } var scripts = component.scripts.map(function scriptInComponent(path) { return loadItem(path, component); }); return $q.all(scripts).then(function(result) { component.pending = false; self.loaded[component.name] = true; if (angular.isFunction(component.run)) component.run.apply(component); return component; }); } function resolveComponent(name) { var match = self.queue.filter(function componentFilter(component) { return component.name === name; }); return match.length ? match[0] : null; } function
(path, component) { var d = $q.defer(); var startPath = component.path || self.basePath; var newScriptTag = document.createElement('script'); newScriptTag.type = 'text/javascript'; newScriptTag.src = startPath ? startPath + '/' + path : path; console.log(component.path) newScriptTag.setAttribute('data-name', component.name) newScriptTag.addEventListener('load', function(ev) { d.resolve(component); }); newScriptTag.addEventListener('error', function(ev) { d.reject(component); }); $window.setTimeout(function() { if (component.pending) { throw new Error('Component ' + component.name + ' did not load in time.'); } }, 10000); document.head.appendChild(newScriptTag); return d.promise; } } ComponentLoader.$inject = ['$window', '$q']; angular.module('lazy.components', ['ng']).service('componentLoader', ComponentLoader); })();
loadItem
identifier_name
lazy-components.js
!(function() { 'use strict'; function ComponentLoader($window, $q) { var self = this; this.basePath = '.'; this.queue = [ /*{path: '.', name: 'svg-viewer', scripts:['lazy.js'], run: function(){}}*/ ]; this.loaded = { /*'svg-viewer':true'*/ }; this.loadAll = function() { var components = self.queue.map(function loadEach(component) { component.pending = true; return self.load(component); }) return $q.all(components); } this.load = function(component) { if (angular.isString(component))
if (!component) throw new Error('The lazy component is not registered and cannot load') if (!component.name) throw new Error('The lazy component must register with name property and cannot load'); if (self.loaded[component.name]) { return $q.when(component); } var scripts = component.scripts.map(function scriptInComponent(path) { return loadItem(path, component); }); return $q.all(scripts).then(function(result) { component.pending = false; self.loaded[component.name] = true; if (angular.isFunction(component.run)) component.run.apply(component); return component; }); } function resolveComponent(name) { var match = self.queue.filter(function componentFilter(component) { return component.name === name; }); return match.length ? match[0] : null; } function loadItem(path, component) { var d = $q.defer(); var startPath = component.path || self.basePath; var newScriptTag = document.createElement('script'); newScriptTag.type = 'text/javascript'; newScriptTag.src = startPath ? startPath + '/' + path : path; console.log(component.path) newScriptTag.setAttribute('data-name', component.name) newScriptTag.addEventListener('load', function(ev) { d.resolve(component); }); newScriptTag.addEventListener('error', function(ev) { d.reject(component); }); $window.setTimeout(function() { if (component.pending) { throw new Error('Component ' + component.name + ' did not load in time.'); } }, 10000); document.head.appendChild(newScriptTag); return d.promise; } } ComponentLoader.$inject = ['$window', '$q']; angular.module('lazy.components', ['ng']).service('componentLoader', ComponentLoader); })();
{ component = resolveComponent(component) }
conditional_block
lazy-components.js
!(function() { 'use strict'; function ComponentLoader($window, $q) { var self = this; this.basePath = '.'; this.queue = [ /*{path: '.', name: 'svg-viewer', scripts:['lazy.js'], run: function(){}}*/ ]; this.loaded = { /*'svg-viewer':true'*/ }; this.loadAll = function() { var components = self.queue.map(function loadEach(component) { component.pending = true; return self.load(component); }) return $q.all(components); } this.load = function(component) { if (angular.isString(component)) { component = resolveComponent(component) } if (!component) throw new Error('The lazy component is not registered and cannot load') if (!component.name) throw new Error('The lazy component must register with name property and cannot load'); if (self.loaded[component.name]) { return $q.when(component); } var scripts = component.scripts.map(function scriptInComponent(path) { return loadItem(path, component); }); return $q.all(scripts).then(function(result) { component.pending = false; self.loaded[component.name] = true; if (angular.isFunction(component.run)) component.run.apply(component); return component; }); } function resolveComponent(name) { var match = self.queue.filter(function componentFilter(component) { return component.name === name; }); return match.length ? match[0] : null; } function loadItem(path, component) { var d = $q.defer(); var startPath = component.path || self.basePath; var newScriptTag = document.createElement('script'); newScriptTag.type = 'text/javascript'; newScriptTag.src = startPath ? startPath + '/' + path : path; console.log(component.path) newScriptTag.setAttribute('data-name', component.name) newScriptTag.addEventListener('load', function(ev) { d.resolve(component);
d.reject(component); }); $window.setTimeout(function() { if (component.pending) { throw new Error('Component ' + component.name + ' did not load in time.'); } }, 10000); document.head.appendChild(newScriptTag); return d.promise; } } ComponentLoader.$inject = ['$window', '$q']; angular.module('lazy.components', ['ng']).service('componentLoader', ComponentLoader); })();
}); newScriptTag.addEventListener('error', function(ev) {
random_line_split
lazy-components.js
!(function() { 'use strict'; function ComponentLoader($window, $q)
ComponentLoader.$inject = ['$window', '$q']; angular.module('lazy.components', ['ng']).service('componentLoader', ComponentLoader); })();
{ var self = this; this.basePath = '.'; this.queue = [ /*{path: '.', name: 'svg-viewer', scripts:['lazy.js'], run: function(){}}*/ ]; this.loaded = { /*'svg-viewer':true'*/ }; this.loadAll = function() { var components = self.queue.map(function loadEach(component) { component.pending = true; return self.load(component); }) return $q.all(components); } this.load = function(component) { if (angular.isString(component)) { component = resolveComponent(component) } if (!component) throw new Error('The lazy component is not registered and cannot load') if (!component.name) throw new Error('The lazy component must register with name property and cannot load'); if (self.loaded[component.name]) { return $q.when(component); } var scripts = component.scripts.map(function scriptInComponent(path) { return loadItem(path, component); }); return $q.all(scripts).then(function(result) { component.pending = false; self.loaded[component.name] = true; if (angular.isFunction(component.run)) component.run.apply(component); return component; }); } function resolveComponent(name) { var match = self.queue.filter(function componentFilter(component) { return component.name === name; }); return match.length ? match[0] : null; } function loadItem(path, component) { var d = $q.defer(); var startPath = component.path || self.basePath; var newScriptTag = document.createElement('script'); newScriptTag.type = 'text/javascript'; newScriptTag.src = startPath ? startPath + '/' + path : path; console.log(component.path) newScriptTag.setAttribute('data-name', component.name) newScriptTag.addEventListener('load', function(ev) { d.resolve(component); }); newScriptTag.addEventListener('error', function(ev) { d.reject(component); }); $window.setTimeout(function() { if (component.pending) { throw new Error('Component ' + component.name + ' did not load in time.'); } }, 10000); document.head.appendChild(newScriptTag); return d.promise; } }
identifier_body
paths.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import * as arrays from 'vs/base/common/arrays'; import * as strings from 'vs/base/common/strings'; import * as extpath from 'vs/base/common/extpath'; import * as platform from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { ParsedArgs } from 'vs/platform/environment/node/argv'; export function validatePaths(args: ParsedArgs): ParsedArgs { // Track URLs if they're going to be used if (args['open-url']) { args._urls = args._; args._ = []; } // Normalize paths and watch out for goto line mode if (!args['remote']) { const paths = doValidatePaths(args._, args.goto); args._ = paths; } return args; } function doValidatePaths(args: string[], gotoLineMode?: boolean): string[]
function preparePath(cwd: string, p: string): string { // Trim trailing quotes if (platform.isWindows) { p = strings.rtrim(p, '"'); // https://github.com/Microsoft/vscode/issues/1498 } // Trim whitespaces p = strings.trim(strings.trim(p, ' '), '\t'); if (platform.isWindows) { // Resolve the path against cwd if it is relative p = path.resolve(cwd, p); // Trim trailing '.' chars on Windows to prevent invalid file names p = strings.rtrim(p, '.'); } return p; } function toPath(p: extpath.IPathWithLineAndColumn): string { const segments = [p.path]; if (types.isNumber(p.line)) { segments.push(String(p.line)); } if (types.isNumber(p.column)) { segments.push(String(p.column)); } return segments.join(':'); }
{ const cwd = process.env['VSCODE_CWD'] || process.cwd(); const result = args.map(arg => { let pathCandidate = String(arg); let parsedPath: extpath.IPathWithLineAndColumn | undefined = undefined; if (gotoLineMode) { parsedPath = extpath.parseLineAndColumnAware(pathCandidate); pathCandidate = parsedPath.path; } if (pathCandidate) { pathCandidate = preparePath(cwd, pathCandidate); } const sanitizedFilePath = extpath.sanitizeFilePath(pathCandidate, cwd); const basename = path.basename(sanitizedFilePath); if (basename /* can be empty if code is opened on root */ && !extpath.isValidBasename(basename)) { return null; // do not allow invalid file names } if (gotoLineMode && parsedPath) { parsedPath.path = sanitizedFilePath; return toPath(parsedPath); } return sanitizedFilePath; }); const caseInsensitive = platform.isWindows || platform.isMacintosh; const distinct = arrays.distinct(result, e => e && caseInsensitive ? e.toLowerCase() : (e || '')); return arrays.coalesce(distinct); }
identifier_body
paths.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import * as arrays from 'vs/base/common/arrays'; import * as strings from 'vs/base/common/strings'; import * as extpath from 'vs/base/common/extpath'; import * as platform from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { ParsedArgs } from 'vs/platform/environment/node/argv'; export function validatePaths(args: ParsedArgs): ParsedArgs { // Track URLs if they're going to be used if (args['open-url']) { args._urls = args._;
// Normalize paths and watch out for goto line mode if (!args['remote']) { const paths = doValidatePaths(args._, args.goto); args._ = paths; } return args; } function doValidatePaths(args: string[], gotoLineMode?: boolean): string[] { const cwd = process.env['VSCODE_CWD'] || process.cwd(); const result = args.map(arg => { let pathCandidate = String(arg); let parsedPath: extpath.IPathWithLineAndColumn | undefined = undefined; if (gotoLineMode) { parsedPath = extpath.parseLineAndColumnAware(pathCandidate); pathCandidate = parsedPath.path; } if (pathCandidate) { pathCandidate = preparePath(cwd, pathCandidate); } const sanitizedFilePath = extpath.sanitizeFilePath(pathCandidate, cwd); const basename = path.basename(sanitizedFilePath); if (basename /* can be empty if code is opened on root */ && !extpath.isValidBasename(basename)) { return null; // do not allow invalid file names } if (gotoLineMode && parsedPath) { parsedPath.path = sanitizedFilePath; return toPath(parsedPath); } return sanitizedFilePath; }); const caseInsensitive = platform.isWindows || platform.isMacintosh; const distinct = arrays.distinct(result, e => e && caseInsensitive ? e.toLowerCase() : (e || '')); return arrays.coalesce(distinct); } function preparePath(cwd: string, p: string): string { // Trim trailing quotes if (platform.isWindows) { p = strings.rtrim(p, '"'); // https://github.com/Microsoft/vscode/issues/1498 } // Trim whitespaces p = strings.trim(strings.trim(p, ' '), '\t'); if (platform.isWindows) { // Resolve the path against cwd if it is relative p = path.resolve(cwd, p); // Trim trailing '.' chars on Windows to prevent invalid file names p = strings.rtrim(p, '.'); } return p; } function toPath(p: extpath.IPathWithLineAndColumn): string { const segments = [p.path]; if (types.isNumber(p.line)) { segments.push(String(p.line)); } if (types.isNumber(p.column)) { segments.push(String(p.column)); } return segments.join(':'); }
args._ = []; }
random_line_split
paths.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import * as arrays from 'vs/base/common/arrays'; import * as strings from 'vs/base/common/strings'; import * as extpath from 'vs/base/common/extpath'; import * as platform from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { ParsedArgs } from 'vs/platform/environment/node/argv'; export function validatePaths(args: ParsedArgs): ParsedArgs { // Track URLs if they're going to be used if (args['open-url']) { args._urls = args._; args._ = []; } // Normalize paths and watch out for goto line mode if (!args['remote']) { const paths = doValidatePaths(args._, args.goto); args._ = paths; } return args; } function doValidatePaths(args: string[], gotoLineMode?: boolean): string[] { const cwd = process.env['VSCODE_CWD'] || process.cwd(); const result = args.map(arg => { let pathCandidate = String(arg); let parsedPath: extpath.IPathWithLineAndColumn | undefined = undefined; if (gotoLineMode) { parsedPath = extpath.parseLineAndColumnAware(pathCandidate); pathCandidate = parsedPath.path; } if (pathCandidate) { pathCandidate = preparePath(cwd, pathCandidate); } const sanitizedFilePath = extpath.sanitizeFilePath(pathCandidate, cwd); const basename = path.basename(sanitizedFilePath); if (basename /* can be empty if code is opened on root */ && !extpath.isValidBasename(basename)) { return null; // do not allow invalid file names } if (gotoLineMode && parsedPath) { parsedPath.path = sanitizedFilePath; return toPath(parsedPath); } return sanitizedFilePath; }); const caseInsensitive = platform.isWindows || platform.isMacintosh; const distinct = arrays.distinct(result, e => e && caseInsensitive ? e.toLowerCase() : (e || '')); return arrays.coalesce(distinct); } function preparePath(cwd: string, p: string): string { // Trim trailing quotes if (platform.isWindows) { p = strings.rtrim(p, '"'); // https://github.com/Microsoft/vscode/issues/1498 } // Trim whitespaces p = strings.trim(strings.trim(p, ' '), '\t'); if (platform.isWindows)
return p; } function toPath(p: extpath.IPathWithLineAndColumn): string { const segments = [p.path]; if (types.isNumber(p.line)) { segments.push(String(p.line)); } if (types.isNumber(p.column)) { segments.push(String(p.column)); } return segments.join(':'); }
{ // Resolve the path against cwd if it is relative p = path.resolve(cwd, p); // Trim trailing '.' chars on Windows to prevent invalid file names p = strings.rtrim(p, '.'); }
conditional_block
paths.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import * as arrays from 'vs/base/common/arrays'; import * as strings from 'vs/base/common/strings'; import * as extpath from 'vs/base/common/extpath'; import * as platform from 'vs/base/common/platform'; import * as types from 'vs/base/common/types'; import { ParsedArgs } from 'vs/platform/environment/node/argv'; export function validatePaths(args: ParsedArgs): ParsedArgs { // Track URLs if they're going to be used if (args['open-url']) { args._urls = args._; args._ = []; } // Normalize paths and watch out for goto line mode if (!args['remote']) { const paths = doValidatePaths(args._, args.goto); args._ = paths; } return args; } function doValidatePaths(args: string[], gotoLineMode?: boolean): string[] { const cwd = process.env['VSCODE_CWD'] || process.cwd(); const result = args.map(arg => { let pathCandidate = String(arg); let parsedPath: extpath.IPathWithLineAndColumn | undefined = undefined; if (gotoLineMode) { parsedPath = extpath.parseLineAndColumnAware(pathCandidate); pathCandidate = parsedPath.path; } if (pathCandidate) { pathCandidate = preparePath(cwd, pathCandidate); } const sanitizedFilePath = extpath.sanitizeFilePath(pathCandidate, cwd); const basename = path.basename(sanitizedFilePath); if (basename /* can be empty if code is opened on root */ && !extpath.isValidBasename(basename)) { return null; // do not allow invalid file names } if (gotoLineMode && parsedPath) { parsedPath.path = sanitizedFilePath; return toPath(parsedPath); } return sanitizedFilePath; }); const caseInsensitive = platform.isWindows || platform.isMacintosh; const distinct = arrays.distinct(result, e => e && caseInsensitive ? e.toLowerCase() : (e || '')); return arrays.coalesce(distinct); } function preparePath(cwd: string, p: string): string { // Trim trailing quotes if (platform.isWindows) { p = strings.rtrim(p, '"'); // https://github.com/Microsoft/vscode/issues/1498 } // Trim whitespaces p = strings.trim(strings.trim(p, ' '), '\t'); if (platform.isWindows) { // Resolve the path against cwd if it is relative p = path.resolve(cwd, p); // Trim trailing '.' chars on Windows to prevent invalid file names p = strings.rtrim(p, '.'); } return p; } function
(p: extpath.IPathWithLineAndColumn): string { const segments = [p.path]; if (types.isNumber(p.line)) { segments.push(String(p.line)); } if (types.isNumber(p.column)) { segments.push(String(p.column)); } return segments.join(':'); }
toPath
identifier_name
demo_satpy_ndvi_decorate.py
#from satpy import Scene from satpy.utils import debug_on debug_on() #from glob import glob #base_dir="/data/COALITION2/database/meteosat/radiance_HRIT/case-studies/2015/07/07/" #import os #os.chdir(base_dir) #filenames = glob("*201507071200*__") #print base_dir #print filenames ##global_scene = Scene(reader="hrit_msg", filenames=filenames, base_dir=base_dir, ppp_config_dir="/opt/users/hau/PyTroll//cfg_offline/") #global_scene = Scene(reader="hrit_msg", filenames=filenames, base_dir=base_dir, ppp_config_dir="/opt/users/hau/PyTroll/packages/satpy/satpy/etc") #from satpy import available_readers #available_readers() # new version of satpy after 0.8 ################################# from satpy import find_files_and_readers, Scene from datetime import datetime import numpy as np show_details=False save_overview=True files_sat = find_files_and_readers(sensor='seviri', start_time=datetime(2015, 7, 7, 12, 0), end_time=datetime(2015, 7, 7, 12, 0), base_dir="/data/COALITION2/database/meteosat/radiance_HRIT/case-studies/2015/07/07/", reader="seviri_l1b_hrit") #print files_sat #files = dict(files_sat.items() + files_nwc.items()) files = dict(files_sat.items()) global_scene = Scene(filenames=files) # not allowed any more: reader="hrit_msg", print dir(global_scene) #global_scene.load([0.6, 0.8, 10.8]) #global_scene.load(['IR_120', 'IR_134']) if save_overview: global_scene.load(['overview',0.6, 0.8]) else: global_scene.load([0.6,0.8]) #print(global_scene[0.6]) # works only if you load also the 0.6 channel, but not an RGB that contains the 0.6 #!!# print(global_scene['overview']) ### this one does only work in the develop version global_scene.available_dataset_names() global_scene["ndvi"] = (global_scene[0.8] - global_scene[0.6]) / (global_scene[0.8] + global_scene[0.6]) # !!! BUG: will not be resampled in global_scene.resample(area) #from satpy import DatasetID #my_channel_id = DatasetID(name='IR_016', calibration='radiance') #global_scene.load([my_channel_id]) #print(scn['IR_016']) #area="eurol" #area="EuropeCanaryS95" area="ccs4" local_scene = global_scene.resample(area) if show_details: help(local_scene) print global_scene.available_composite_ids() print global_scene.available_composite_names() print global_scene.available_dataset_names() print global_scene.available_writers() if save_overview: #local_scene.show('overview') local_scene.save_dataset('overview', './overview_'+area+'.png', overlay={'coast_dir': '/data/OWARNA/hau/maps_pytroll/', 'color': (255, 255, 255), 'resolution': 'i'}) print 'display ./overview_'+area+'.png &' local_scene["ndvi"] = (local_scene[0.8] - local_scene[0.6]) / (local_scene[0.8] + local_scene[0.6]) #local_scene["ndvi"].area = local_scene[0.8].area print "local_scene[\"ndvi\"].min()", local_scene["ndvi"].compute().min() print "local_scene[\"ndvi\"].max()", local_scene["ndvi"].compute().max() lsmask_file="/data/COALITION2/database/LandSeaMask/SEVIRI/LandSeaMask_"+area+".nc" from netCDF4 import Dataset
#print 'type(local_scene["ndvi"].data)', type(local_scene["ndvi"].data), local_scene["ndvi"].data.compute().shape #print "type(lsmask)", type(lsmask), lsmask.shape, lsmask[:,:,0].shape, #local_scene["ndvi"].data.compute()[lsmask[:,:,0]==0]=np.nan ndvi_numpyarray=local_scene["ndvi"].data.compute() if area=="EuropeCanaryS95": ndvi_numpyarray[lsmask[::-1,:,0]==0]=np.nan else: ndvi_numpyarray[lsmask[:,:,0]==0]=np.nan local_scene["ndvi"].data = da.from_array(ndvi_numpyarray, chunks='auto') #local_scene["ndvi"].data = local_scene["ndvi"].data.where(lsmask!=0) colorized=True if not colorized: #local_scene.save_dataset('ndvi', './ndvi_'+area+'.png') local_scene.save_dataset('ndvi', './ndvi_'+area+'.png', overlay={'coast_dir': '/data/OWARNA/hau/maps_pytroll/', 'color': (255, 255, 255), 'resolution': 'i'}) #print dir(local_scene.save_dataset) else: # https://github.com/pytroll/satpy/issues/459 # from satpy.enhancements import colorize # colorize(img, **kwargs) # 'ylgn' # https://satpy.readthedocs.io/en/latest/writers.html # nice NDVI colourbar here: # https://www.researchgate.net/figure/NDVI-maps-Vegetation-maps-created-by-measuring-the-Normalized-Vegetation-Difference_fig7_323885082 from satpy.composites import BWCompositor from satpy.enhancements import colorize from satpy.writers import to_image compositor = BWCompositor("test", standard_name="ndvi") composite = compositor((local_scene["ndvi"], )) img = to_image(composite) #from trollimage import colormap #dir(colormap) # 'accent', 'blues', 'brbg', 'bugn', 'bupu', 'colorbar', 'colorize', 'dark2', 'diverging_colormaps', 'gnbu', 'greens', # 'greys', 'hcl2rgb', 'np', 'oranges', 'orrd', 'paired', 'palettebar', 'palettize', 'pastel1', 'pastel2', 'piyg', 'prgn', # 'pubu', 'pubugn', 'puor', 'purd', 'purples', 'qualitative_colormaps', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', # 'reds', 'rgb2hcl', 'sequential_colormaps', 'set1', 'set2', 'set3', 'spectral', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd' # kwargs = {"palettes": [{"colors": 'ylgn', # "min_value": -0.1, "max_value": 0.9}]} #arr = np.array([[230, 227, 227], [191, 184, 162], [118, 148, 61], [67, 105, 66], [5, 55, 8]]) arr = np.array([ [ 95, 75, 49], [210, 175, 131], [118, 148, 61], [67, 105, 66], [28, 29, 4]]) np.save("/tmp/binary_colormap.npy", arr) kwargs = {"palettes": [{"filename": "/tmp/binary_colormap.npy", "min_value": -0.1, "max_value": 0.8}]} colorize(img, **kwargs) from satpy.writers import add_decorate, add_overlay decorate = { 'decorate': [ {'logo': {'logo_path': '/opt/users/common/logos/meteoSwiss.png', 'height': 60, 'bg': 'white','bg_opacity': 255, 'align': {'top_bottom': 'top', 'left_right': 'right'}}}, {'text': {'txt': ' MSG, '+local_scene.start_time.strftime('%Y-%m-%d %H:%MUTC')+', '+ area+', NDVI', 'align': {'top_bottom': 'top', 'left_right': 'left'}, 'font': "/usr/openv/java/jre/lib/fonts/LucidaTypewriterBold.ttf", 'font_size': 19, 'height': 25, 'bg': 'white', 'bg_opacity': 0, 'line': 'white'}} ] } img = add_decorate(img, **decorate) #, fill_value='black' img = add_overlay(img, area, '/data/OWARNA/hau/maps_pytroll/', color='red', width=0.5, resolution='i', level_coast=1, level_borders=1, fill_value=None) #from satpy.writers import compute_writer_results #res1 = scn.save_datasets(filename="/tmp/{name}.png", # writer='simple_image', # compute=False) #res2 = scn.save_datasets(filename="/tmp/{name}.tif", # writer='geotiff', # compute=False) #results = [res1, res2] #compute_writer_results(results) #img.show() img.save('./ndvi_'+area+'.png') print 'display ./ndvi_'+area+'.png &'
ncfile = Dataset(lsmask_file,'r') # Read variable corresponding to channel name lsmask = ncfile.variables['lsmask'][:,:] # attention [:,:] or [:] is really necessary import dask.array as da
random_line_split
demo_satpy_ndvi_decorate.py
#from satpy import Scene from satpy.utils import debug_on debug_on() #from glob import glob #base_dir="/data/COALITION2/database/meteosat/radiance_HRIT/case-studies/2015/07/07/" #import os #os.chdir(base_dir) #filenames = glob("*201507071200*__") #print base_dir #print filenames ##global_scene = Scene(reader="hrit_msg", filenames=filenames, base_dir=base_dir, ppp_config_dir="/opt/users/hau/PyTroll//cfg_offline/") #global_scene = Scene(reader="hrit_msg", filenames=filenames, base_dir=base_dir, ppp_config_dir="/opt/users/hau/PyTroll/packages/satpy/satpy/etc") #from satpy import available_readers #available_readers() # new version of satpy after 0.8 ################################# from satpy import find_files_and_readers, Scene from datetime import datetime import numpy as np show_details=False save_overview=True files_sat = find_files_and_readers(sensor='seviri', start_time=datetime(2015, 7, 7, 12, 0), end_time=datetime(2015, 7, 7, 12, 0), base_dir="/data/COALITION2/database/meteosat/radiance_HRIT/case-studies/2015/07/07/", reader="seviri_l1b_hrit") #print files_sat #files = dict(files_sat.items() + files_nwc.items()) files = dict(files_sat.items()) global_scene = Scene(filenames=files) # not allowed any more: reader="hrit_msg", print dir(global_scene) #global_scene.load([0.6, 0.8, 10.8]) #global_scene.load(['IR_120', 'IR_134']) if save_overview: global_scene.load(['overview',0.6, 0.8]) else: global_scene.load([0.6,0.8]) #print(global_scene[0.6]) # works only if you load also the 0.6 channel, but not an RGB that contains the 0.6 #!!# print(global_scene['overview']) ### this one does only work in the develop version global_scene.available_dataset_names() global_scene["ndvi"] = (global_scene[0.8] - global_scene[0.6]) / (global_scene[0.8] + global_scene[0.6]) # !!! BUG: will not be resampled in global_scene.resample(area) #from satpy import DatasetID #my_channel_id = DatasetID(name='IR_016', calibration='radiance') #global_scene.load([my_channel_id]) #print(scn['IR_016']) #area="eurol" #area="EuropeCanaryS95" area="ccs4" local_scene = global_scene.resample(area) if show_details:
if save_overview: #local_scene.show('overview') local_scene.save_dataset('overview', './overview_'+area+'.png', overlay={'coast_dir': '/data/OWARNA/hau/maps_pytroll/', 'color': (255, 255, 255), 'resolution': 'i'}) print 'display ./overview_'+area+'.png &' local_scene["ndvi"] = (local_scene[0.8] - local_scene[0.6]) / (local_scene[0.8] + local_scene[0.6]) #local_scene["ndvi"].area = local_scene[0.8].area print "local_scene[\"ndvi\"].min()", local_scene["ndvi"].compute().min() print "local_scene[\"ndvi\"].max()", local_scene["ndvi"].compute().max() lsmask_file="/data/COALITION2/database/LandSeaMask/SEVIRI/LandSeaMask_"+area+".nc" from netCDF4 import Dataset ncfile = Dataset(lsmask_file,'r') # Read variable corresponding to channel name lsmask = ncfile.variables['lsmask'][:,:] # attention [:,:] or [:] is really necessary import dask.array as da #print 'type(local_scene["ndvi"].data)', type(local_scene["ndvi"].data), local_scene["ndvi"].data.compute().shape #print "type(lsmask)", type(lsmask), lsmask.shape, lsmask[:,:,0].shape, #local_scene["ndvi"].data.compute()[lsmask[:,:,0]==0]=np.nan ndvi_numpyarray=local_scene["ndvi"].data.compute() if area=="EuropeCanaryS95": ndvi_numpyarray[lsmask[::-1,:,0]==0]=np.nan else: ndvi_numpyarray[lsmask[:,:,0]==0]=np.nan local_scene["ndvi"].data = da.from_array(ndvi_numpyarray, chunks='auto') #local_scene["ndvi"].data = local_scene["ndvi"].data.where(lsmask!=0) colorized=True if not colorized: #local_scene.save_dataset('ndvi', './ndvi_'+area+'.png') local_scene.save_dataset('ndvi', './ndvi_'+area+'.png', overlay={'coast_dir': '/data/OWARNA/hau/maps_pytroll/', 'color': (255, 255, 255), 'resolution': 'i'}) #print dir(local_scene.save_dataset) else: # https://github.com/pytroll/satpy/issues/459 # from satpy.enhancements import colorize # colorize(img, **kwargs) # 'ylgn' # https://satpy.readthedocs.io/en/latest/writers.html # nice NDVI colourbar here: # https://www.researchgate.net/figure/NDVI-maps-Vegetation-maps-created-by-measuring-the-Normalized-Vegetation-Difference_fig7_323885082 from satpy.composites import BWCompositor from satpy.enhancements import colorize from satpy.writers import to_image compositor = BWCompositor("test", standard_name="ndvi") composite = compositor((local_scene["ndvi"], )) img = to_image(composite) #from trollimage import colormap #dir(colormap) # 'accent', 'blues', 'brbg', 'bugn', 'bupu', 'colorbar', 'colorize', 'dark2', 'diverging_colormaps', 'gnbu', 'greens', # 'greys', 'hcl2rgb', 'np', 'oranges', 'orrd', 'paired', 'palettebar', 'palettize', 'pastel1', 'pastel2', 'piyg', 'prgn', # 'pubu', 'pubugn', 'puor', 'purd', 'purples', 'qualitative_colormaps', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', # 'reds', 'rgb2hcl', 'sequential_colormaps', 'set1', 'set2', 'set3', 'spectral', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd' # kwargs = {"palettes": [{"colors": 'ylgn', # "min_value": -0.1, "max_value": 0.9}]} #arr = np.array([[230, 227, 227], [191, 184, 162], [118, 148, 61], [67, 105, 66], [5, 55, 8]]) arr = np.array([ [ 95, 75, 49], [210, 175, 131], [118, 148, 61], [67, 105, 66], [28, 29, 4]]) np.save("/tmp/binary_colormap.npy", arr) kwargs = {"palettes": [{"filename": "/tmp/binary_colormap.npy", "min_value": -0.1, "max_value": 0.8}]} colorize(img, **kwargs) from satpy.writers import add_decorate, add_overlay decorate = { 'decorate': [ {'logo': {'logo_path': '/opt/users/common/logos/meteoSwiss.png', 'height': 60, 'bg': 'white','bg_opacity': 255, 'align': {'top_bottom': 'top', 'left_right': 'right'}}}, {'text': {'txt': ' MSG, '+local_scene.start_time.strftime('%Y-%m-%d %H:%MUTC')+', '+ area+', NDVI', 'align': {'top_bottom': 'top', 'left_right': 'left'}, 'font': "/usr/openv/java/jre/lib/fonts/LucidaTypewriterBold.ttf", 'font_size': 19, 'height': 25, 'bg': 'white', 'bg_opacity': 0, 'line': 'white'}} ] } img = add_decorate(img, **decorate) #, fill_value='black' img = add_overlay(img, area, '/data/OWARNA/hau/maps_pytroll/', color='red', width=0.5, resolution='i', level_coast=1, level_borders=1, fill_value=None) #from satpy.writers import compute_writer_results #res1 = scn.save_datasets(filename="/tmp/{name}.png", # writer='simple_image', # compute=False) #res2 = scn.save_datasets(filename="/tmp/{name}.tif", # writer='geotiff', # compute=False) #results = [res1, res2] #compute_writer_results(results) #img.show() img.save('./ndvi_'+area+'.png') print 'display ./ndvi_'+area+'.png &'
help(local_scene) print global_scene.available_composite_ids() print global_scene.available_composite_names() print global_scene.available_dataset_names() print global_scene.available_writers()
conditional_block
key_templates.rs
// Copyright 2020 The Tink-Rust 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
// //////////////////////////////////////////////////////////////////////////////// //! This module contains pre-generated [`KeyTemplate`] instances for deterministic AEAD. use tink_proto::{prost::Message, KeyTemplate}; /// Return a [`KeyTemplate`](tink_proto::KeyTemplate) that generates a AES-SIV key. pub fn aes_siv_key_template() -> KeyTemplate { let format = tink_proto::AesSivKeyFormat { key_size: 64, version: crate::AES_SIV_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: crate::AES_SIV_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Tink as i32, value: serialized_format, } }
// limitations under the License.
random_line_split
key_templates.rs
// Copyright 2020 The Tink-Rust 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. // //////////////////////////////////////////////////////////////////////////////// //! This module contains pre-generated [`KeyTemplate`] instances for deterministic AEAD. use tink_proto::{prost::Message, KeyTemplate}; /// Return a [`KeyTemplate`](tink_proto::KeyTemplate) that generates a AES-SIV key. pub fn
() -> KeyTemplate { let format = tink_proto::AesSivKeyFormat { key_size: 64, version: crate::AES_SIV_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: crate::AES_SIV_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Tink as i32, value: serialized_format, } }
aes_siv_key_template
identifier_name
key_templates.rs
// Copyright 2020 The Tink-Rust 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. // //////////////////////////////////////////////////////////////////////////////// //! This module contains pre-generated [`KeyTemplate`] instances for deterministic AEAD. use tink_proto::{prost::Message, KeyTemplate}; /// Return a [`KeyTemplate`](tink_proto::KeyTemplate) that generates a AES-SIV key. pub fn aes_siv_key_template() -> KeyTemplate
{ let format = tink_proto::AesSivKeyFormat { key_size: 64, version: crate::AES_SIV_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: crate::AES_SIV_TYPE_URL.to_string(), output_prefix_type: tink_proto::OutputPrefixType::Tink as i32, value: serialized_format, } }
identifier_body
qurawl.py
# -*- coding: utf-8 -*- """Qurawl Main""" #### from __future__ import absolute_import from __future__ import unicode_literals import itertools as it import random as rand import difflib as diff #### import common.debugit as debugit import qurawl.regparse as rp from qurawl.level import * from qurawl.items import * import qurawl.zoo as zoo #### __all__ = ['Qurawl', 'Commenter'] ####
dbg = debugit.Debugit(__name__, NO_DBG) #MONSTERS) #### OBSTACLES = ('#',) #### Word Categories names = set(['yip', 'otto', 'xenia']) verbs = set(['move', 'attack', 'use', 'push']) obverbs = set(['drop']) objects = set(['health', 'armor', 'strength', 'mine', 'silver_key', 'gold_key']) directs = set(['up', 'left', 'right', 'down']) # Lookup table (word -> Category) LEXICON = rp.make_lexicon((names, verbs, obverbs, objects, directs), 'NVWOD') #### class Qurawl(object): """Main Game Class""" def __init__(self, conf, lexicon=LEXICON): seed = conf['seed'] if seed > 0: rand.seed(seed) self.conf = conf self.lexicon = lexicon self.commenter = Commenter() def init_all(self): level_map = LevelMap(zoo.make_level(20, 30)) actors = zoo.make_actors() self.act_level = Level(level_map, self.commenter, self.conf, actors=actors, monsters=zoo.make_monsters(), things=zoo.make_things(), obstacles=OBSTACLES) self.name_actors = dict(zip((actor.name for actor in actors), actors)) def start(self): self.init_all() @property def level(self): return self.act_level def input_action(self, tokens): scan_info = fuzzy_scan(tokens, self.lexicon) dbg(4, scan_info, 'scan info', self.input_action) if 'err' in scan_info: self.commenter(1, "Don't know {0}.".format(scan_info['err'])) return parse_info = rp.parse_nvod(scan_info['match'], self.lexicon) dbg(4, parse_info, 'parse info', self.input_action) if 'err' in parse_info: self.commenter(1, "Don't know what to do: {0}".\ format(show_parse_errors(parse_info['err']))) return cmd = make_command(parse_info) verb, args = cmd[0], cmd[1:] try: action_method = getattr(self.level, verb) except AttributeError: self.commenter(1, "Don't know how to '{0}'!".format(verb)) return for name in parse_info['name']: action_method(self.name_actors[name], *args) def action(self, meta_info): self.level.action() if 'quit' == meta_info: self.fin() def get_actor_stats(self): dbg(6, [m.stat for m in self.level.monsters]) return [actor.stat for actor in self.level.actors if not actor.is_dead] def get_comments(self): return self.commenter.show(100) def loop_reset(self): self.commenter.reset() def fin(self): self.commenter(1, "Bye") #### class Commenter(object): """Collect and return state and action comments""" def __init__(self): self.reset() def reset(self): self.buf = [] def __call__(self, level, msg): self.buf.append((level, msg)) def __iter__(self): return iter(self.buf) def pick(self, result, actor, thing): if isinstance(thing, Corpse): com = "{0} plunders the corpse of {1}." name = thing.name.rsplit("_", 1)[0] self.buf.append((2, com.format(actor.name, name))) return if result < 2: com = "{0} picked up {1}({2})." else: com = "{0} is hurt by {1}({2})." self.buf.append((3, com.format(actor.name, thing.name, thing.value))) def dead(self, actor): com = "{0} is dead, sigh!".format(actor.name) self.buf.append((2, com)) def fight(self, attacker, defender): com = "{0} attacks {1}!".format(attacker.name, defender.name) self.buf.append((2, com)) def show(self, level): return (msg for i, msg in self if i <= level) #### def show_parse_errors(pairs): """Gather invalid command infos.""" return " ".join(word if categ != "?" else categ for categ, word in pairs) #### def make_command(parse_info, phrases=('verb', 'obverb', 'object', 'direct')): """Reconstruct a valid command.""" # use verb 'move' as default # check if (ob)verb is already existent use_move = bool(set(('verb', 'obverb')) & set(parse_info)) info = dict(parse_info, **({'verb': 'move'}, {})[use_move]) return [info[key] for key in phrases if key in info] #### def fuzzy_scan(words, lexicon): """Check if words have a resonable similarity to lexicon words.""" matches = [diff.get_close_matches(word, lexicon, n=1) for word in words] if not all(matches): return {'err': " ".join(w for w, m in zip(words, matches) if not m)} else: return {'match': list(it.chain(*matches))} ####
NO_DBG = [] MONSTERS = [6]
random_line_split
qurawl.py
# -*- coding: utf-8 -*- """Qurawl Main""" #### from __future__ import absolute_import from __future__ import unicode_literals import itertools as it import random as rand import difflib as diff #### import common.debugit as debugit import qurawl.regparse as rp from qurawl.level import * from qurawl.items import * import qurawl.zoo as zoo #### __all__ = ['Qurawl', 'Commenter'] #### NO_DBG = [] MONSTERS = [6] dbg = debugit.Debugit(__name__, NO_DBG) #MONSTERS) #### OBSTACLES = ('#',) #### Word Categories names = set(['yip', 'otto', 'xenia']) verbs = set(['move', 'attack', 'use', 'push']) obverbs = set(['drop']) objects = set(['health', 'armor', 'strength', 'mine', 'silver_key', 'gold_key']) directs = set(['up', 'left', 'right', 'down']) # Lookup table (word -> Category) LEXICON = rp.make_lexicon((names, verbs, obverbs, objects, directs), 'NVWOD') #### class Qurawl(object): """Main Game Class""" def __init__(self, conf, lexicon=LEXICON): seed = conf['seed'] if seed > 0: rand.seed(seed) self.conf = conf self.lexicon = lexicon self.commenter = Commenter() def init_all(self): level_map = LevelMap(zoo.make_level(20, 30)) actors = zoo.make_actors() self.act_level = Level(level_map, self.commenter, self.conf, actors=actors, monsters=zoo.make_monsters(), things=zoo.make_things(), obstacles=OBSTACLES) self.name_actors = dict(zip((actor.name for actor in actors), actors)) def start(self): self.init_all() @property def level(self): return self.act_level def input_action(self, tokens): scan_info = fuzzy_scan(tokens, self.lexicon) dbg(4, scan_info, 'scan info', self.input_action) if 'err' in scan_info: self.commenter(1, "Don't know {0}.".format(scan_info['err'])) return parse_info = rp.parse_nvod(scan_info['match'], self.lexicon) dbg(4, parse_info, 'parse info', self.input_action) if 'err' in parse_info: self.commenter(1, "Don't know what to do: {0}".\ format(show_parse_errors(parse_info['err']))) return cmd = make_command(parse_info) verb, args = cmd[0], cmd[1:] try: action_method = getattr(self.level, verb) except AttributeError: self.commenter(1, "Don't know how to '{0}'!".format(verb)) return for name in parse_info['name']: action_method(self.name_actors[name], *args) def action(self, meta_info): self.level.action() if 'quit' == meta_info: self.fin() def get_actor_stats(self): dbg(6, [m.stat for m in self.level.monsters]) return [actor.stat for actor in self.level.actors if not actor.is_dead] def get_comments(self): return self.commenter.show(100) def loop_reset(self): self.commenter.reset() def fin(self): self.commenter(1, "Bye") #### class Commenter(object): """Collect and return state and action comments""" def __init__(self): self.reset() def reset(self): self.buf = [] def __call__(self, level, msg): self.buf.append((level, msg)) def __iter__(self): return iter(self.buf) def pick(self, result, actor, thing): if isinstance(thing, Corpse): com = "{0} plunders the corpse of {1}." name = thing.name.rsplit("_", 1)[0] self.buf.append((2, com.format(actor.name, name))) return if result < 2: com = "{0} picked up {1}({2})." else: com = "{0} is hurt by {1}({2})." self.buf.append((3, com.format(actor.name, thing.name, thing.value))) def dead(self, actor): com = "{0} is dead, sigh!".format(actor.name) self.buf.append((2, com)) def fight(self, attacker, defender): com = "{0} attacks {1}!".format(attacker.name, defender.name) self.buf.append((2, com)) def show(self, level): return (msg for i, msg in self if i <= level) #### def show_parse_errors(pairs): """Gather invalid command infos.""" return " ".join(word if categ != "?" else categ for categ, word in pairs) #### def make_command(parse_info, phrases=('verb', 'obverb', 'object', 'direct')): """Reconstruct a valid command.""" # use verb 'move' as default # check if (ob)verb is already existent use_move = bool(set(('verb', 'obverb')) & set(parse_info)) info = dict(parse_info, **({'verb': 'move'}, {})[use_move]) return [info[key] for key in phrases if key in info] #### def fuzzy_scan(words, lexicon): """Check if words have a resonable similarity to lexicon words.""" matches = [diff.get_close_matches(word, lexicon, n=1) for word in words] if not all(matches):
else: return {'match': list(it.chain(*matches))} ####
return {'err': " ".join(w for w, m in zip(words, matches) if not m)}
conditional_block
qurawl.py
# -*- coding: utf-8 -*- """Qurawl Main""" #### from __future__ import absolute_import from __future__ import unicode_literals import itertools as it import random as rand import difflib as diff #### import common.debugit as debugit import qurawl.regparse as rp from qurawl.level import * from qurawl.items import * import qurawl.zoo as zoo #### __all__ = ['Qurawl', 'Commenter'] #### NO_DBG = [] MONSTERS = [6] dbg = debugit.Debugit(__name__, NO_DBG) #MONSTERS) #### OBSTACLES = ('#',) #### Word Categories names = set(['yip', 'otto', 'xenia']) verbs = set(['move', 'attack', 'use', 'push']) obverbs = set(['drop']) objects = set(['health', 'armor', 'strength', 'mine', 'silver_key', 'gold_key']) directs = set(['up', 'left', 'right', 'down']) # Lookup table (word -> Category) LEXICON = rp.make_lexicon((names, verbs, obverbs, objects, directs), 'NVWOD') #### class Qurawl(object): """Main Game Class""" def __init__(self, conf, lexicon=LEXICON): seed = conf['seed'] if seed > 0: rand.seed(seed) self.conf = conf self.lexicon = lexicon self.commenter = Commenter() def init_all(self): level_map = LevelMap(zoo.make_level(20, 30)) actors = zoo.make_actors() self.act_level = Level(level_map, self.commenter, self.conf, actors=actors, monsters=zoo.make_monsters(), things=zoo.make_things(), obstacles=OBSTACLES) self.name_actors = dict(zip((actor.name for actor in actors), actors)) def start(self): self.init_all() @property def level(self): return self.act_level def input_action(self, tokens): scan_info = fuzzy_scan(tokens, self.lexicon) dbg(4, scan_info, 'scan info', self.input_action) if 'err' in scan_info: self.commenter(1, "Don't know {0}.".format(scan_info['err'])) return parse_info = rp.parse_nvod(scan_info['match'], self.lexicon) dbg(4, parse_info, 'parse info', self.input_action) if 'err' in parse_info: self.commenter(1, "Don't know what to do: {0}".\ format(show_parse_errors(parse_info['err']))) return cmd = make_command(parse_info) verb, args = cmd[0], cmd[1:] try: action_method = getattr(self.level, verb) except AttributeError: self.commenter(1, "Don't know how to '{0}'!".format(verb)) return for name in parse_info['name']: action_method(self.name_actors[name], *args) def action(self, meta_info): self.level.action() if 'quit' == meta_info: self.fin() def get_actor_stats(self): dbg(6, [m.stat for m in self.level.monsters]) return [actor.stat for actor in self.level.actors if not actor.is_dead] def get_comments(self): return self.commenter.show(100) def loop_reset(self): self.commenter.reset() def fin(self): self.commenter(1, "Bye") #### class Commenter(object): """Collect and return state and action comments""" def __init__(self): self.reset() def reset(self): self.buf = [] def __call__(self, level, msg): self.buf.append((level, msg)) def __iter__(self): return iter(self.buf) def pick(self, result, actor, thing): if isinstance(thing, Corpse): com = "{0} plunders the corpse of {1}." name = thing.name.rsplit("_", 1)[0] self.buf.append((2, com.format(actor.name, name))) return if result < 2: com = "{0} picked up {1}({2})." else: com = "{0} is hurt by {1}({2})." self.buf.append((3, com.format(actor.name, thing.name, thing.value))) def dead(self, actor): com = "{0} is dead, sigh!".format(actor.name) self.buf.append((2, com)) def fight(self, attacker, defender): com = "{0} attacks {1}!".format(attacker.name, defender.name) self.buf.append((2, com)) def show(self, level): return (msg for i, msg in self if i <= level) #### def show_parse_errors(pairs):
#### def make_command(parse_info, phrases=('verb', 'obverb', 'object', 'direct')): """Reconstruct a valid command.""" # use verb 'move' as default # check if (ob)verb is already existent use_move = bool(set(('verb', 'obverb')) & set(parse_info)) info = dict(parse_info, **({'verb': 'move'}, {})[use_move]) return [info[key] for key in phrases if key in info] #### def fuzzy_scan(words, lexicon): """Check if words have a resonable similarity to lexicon words.""" matches = [diff.get_close_matches(word, lexicon, n=1) for word in words] if not all(matches): return {'err': " ".join(w for w, m in zip(words, matches) if not m)} else: return {'match': list(it.chain(*matches))} ####
"""Gather invalid command infos.""" return " ".join(word if categ != "?" else categ for categ, word in pairs)
identifier_body
qurawl.py
# -*- coding: utf-8 -*- """Qurawl Main""" #### from __future__ import absolute_import from __future__ import unicode_literals import itertools as it import random as rand import difflib as diff #### import common.debugit as debugit import qurawl.regparse as rp from qurawl.level import * from qurawl.items import * import qurawl.zoo as zoo #### __all__ = ['Qurawl', 'Commenter'] #### NO_DBG = [] MONSTERS = [6] dbg = debugit.Debugit(__name__, NO_DBG) #MONSTERS) #### OBSTACLES = ('#',) #### Word Categories names = set(['yip', 'otto', 'xenia']) verbs = set(['move', 'attack', 'use', 'push']) obverbs = set(['drop']) objects = set(['health', 'armor', 'strength', 'mine', 'silver_key', 'gold_key']) directs = set(['up', 'left', 'right', 'down']) # Lookup table (word -> Category) LEXICON = rp.make_lexicon((names, verbs, obverbs, objects, directs), 'NVWOD') #### class Qurawl(object): """Main Game Class""" def __init__(self, conf, lexicon=LEXICON): seed = conf['seed'] if seed > 0: rand.seed(seed) self.conf = conf self.lexicon = lexicon self.commenter = Commenter() def
(self): level_map = LevelMap(zoo.make_level(20, 30)) actors = zoo.make_actors() self.act_level = Level(level_map, self.commenter, self.conf, actors=actors, monsters=zoo.make_monsters(), things=zoo.make_things(), obstacles=OBSTACLES) self.name_actors = dict(zip((actor.name for actor in actors), actors)) def start(self): self.init_all() @property def level(self): return self.act_level def input_action(self, tokens): scan_info = fuzzy_scan(tokens, self.lexicon) dbg(4, scan_info, 'scan info', self.input_action) if 'err' in scan_info: self.commenter(1, "Don't know {0}.".format(scan_info['err'])) return parse_info = rp.parse_nvod(scan_info['match'], self.lexicon) dbg(4, parse_info, 'parse info', self.input_action) if 'err' in parse_info: self.commenter(1, "Don't know what to do: {0}".\ format(show_parse_errors(parse_info['err']))) return cmd = make_command(parse_info) verb, args = cmd[0], cmd[1:] try: action_method = getattr(self.level, verb) except AttributeError: self.commenter(1, "Don't know how to '{0}'!".format(verb)) return for name in parse_info['name']: action_method(self.name_actors[name], *args) def action(self, meta_info): self.level.action() if 'quit' == meta_info: self.fin() def get_actor_stats(self): dbg(6, [m.stat for m in self.level.monsters]) return [actor.stat for actor in self.level.actors if not actor.is_dead] def get_comments(self): return self.commenter.show(100) def loop_reset(self): self.commenter.reset() def fin(self): self.commenter(1, "Bye") #### class Commenter(object): """Collect and return state and action comments""" def __init__(self): self.reset() def reset(self): self.buf = [] def __call__(self, level, msg): self.buf.append((level, msg)) def __iter__(self): return iter(self.buf) def pick(self, result, actor, thing): if isinstance(thing, Corpse): com = "{0} plunders the corpse of {1}." name = thing.name.rsplit("_", 1)[0] self.buf.append((2, com.format(actor.name, name))) return if result < 2: com = "{0} picked up {1}({2})." else: com = "{0} is hurt by {1}({2})." self.buf.append((3, com.format(actor.name, thing.name, thing.value))) def dead(self, actor): com = "{0} is dead, sigh!".format(actor.name) self.buf.append((2, com)) def fight(self, attacker, defender): com = "{0} attacks {1}!".format(attacker.name, defender.name) self.buf.append((2, com)) def show(self, level): return (msg for i, msg in self if i <= level) #### def show_parse_errors(pairs): """Gather invalid command infos.""" return " ".join(word if categ != "?" else categ for categ, word in pairs) #### def make_command(parse_info, phrases=('verb', 'obverb', 'object', 'direct')): """Reconstruct a valid command.""" # use verb 'move' as default # check if (ob)verb is already existent use_move = bool(set(('verb', 'obverb')) & set(parse_info)) info = dict(parse_info, **({'verb': 'move'}, {})[use_move]) return [info[key] for key in phrases if key in info] #### def fuzzy_scan(words, lexicon): """Check if words have a resonable similarity to lexicon words.""" matches = [diff.get_close_matches(word, lexicon, n=1) for word in words] if not all(matches): return {'err': " ".join(w for w, m in zip(words, matches) if not m)} else: return {'match': list(it.chain(*matches))} ####
init_all
identifier_name
resultviewer.py
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import pandas as pd import matplotlib matplotlib.use("TkAgg") # important to call this right after from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib import style import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mtick try: import Tkinter as tk import ttk import tkFont import tkMessageBox except: import tkinter as tk from tkinter import ttk from tkinter import font as tkFont from tkinter import messagebox as tkMessageBox from auquanToolbox.metrics import metrics, baseline def loadgui(back_data, exchange, base_index, budget, logger): ###################### # Setup data ###################### position = back_data['POSITION'] close = back_data['CLOSE'] # position as % of total portfolio long_position = (position * close).div(back_data['VALUE'], axis=0) short_position = long_position.copy() long_position[long_position < 0] = 0 short_position[short_position > 0] = 0 daily_pnl = back_data['DAILY_PNL'] / budget total_pnl = back_data['TOTAL_PNL'] / budget if base_index: baseline_data = baseline(exchange, base_index, total_pnl.index, logger) stats = metrics(daily_pnl, total_pnl, baseline_data, base_index) else: baseline_data = {} stats = metrics(daily_pnl, total_pnl, {}, base_index) daily_return = daily_pnl.sum(axis=1) total_return = total_pnl.sum(axis=1) long_exposure = long_position.sum(axis=1) short_exposure = short_position.sum(axis=1) zero_line = np.zeros(daily_pnl.index.size) # print to logger for x in stats.keys(): logger.info('%s : %0.2f' % (x, stats[x])) def isDate(val): # Function to validate if a given entry is valid date try: d = pd.to_datetime(val) if d > daily_pnl.index[0] and d < daily_pnl.index[-1]: return True else: return False except ValueError: raise ValueError("Not a Valid Date") return False def newselection(event): # Function to autoupdate chart on new selection from dropdown i = dropdown.current() market = ['TOTAL PORTFOLIO'] + daily_pnl.columns.values.tolist() plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, market[i], box_value2.get(), box_value3.get()) def plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, market='TOTAL PORTFOLIO', start=daily_pnl.index.format()[0], end=daily_pnl.index.format()[-1]): # New plot when custom fields are changed plt.clf() # plt.style.use("seaborn-whitegrid") daily_pnl = daily_pnl.loc[start:end] total_pnl = total_pnl.loc[start:end] long_position = long_position.loc[start:end] short_position = short_position.loc[start:end] if market == 'TOTAL PORTFOLIO': daily_return = daily_pnl.sum(axis=1) total_return = total_pnl.sum(axis=1) long_exposure = long_position.sum(axis=1) short_exposure = short_position.sum(axis=1) else: daily_return = daily_pnl[market] total_return = total_pnl[market] long_exposure = long_position[market] short_exposure = short_position[market] zero_line = np.zeros(daily_pnl.index.size) # f, plot_arr = plt.subplots(3, sharex=True) total_plot = plt.subplot2grid((10, 8), (0, 0), colspan=12, rowspan=4) daily_plot = plt.subplot2grid((10, 8), (5, 0), colspan=12, rowspan=2, sharex=total_plot) position_plot = plt.subplot2grid((10, 8), (8, 0), colspan=12, rowspan=2, sharex=total_plot) ind = np.arange(len(daily_pnl.index)) total_plot.set_title('Total PnL') total_plot.plot(ind, zero_line, 'k') total_plot.plot(ind, total_return.values, 'b', linewidth=0.5, label='strategy') total_plot.legend(loc='upper left') total_plot.autoscale(tight=True) plt.setp(total_plot.get_xticklabels(), visible=False) total_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) total_plot.set_ylabel('Cumulative Performance') total_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) if base_index: total_plot.plot(ind, baseline_data['TOTAL_PNL'], 'g', linewidth=0.5, label=base_index) daily_plot.set_title('Daily PnL') daily_plot.plot(ind, zero_line, 'k') daily_plot.bar(ind, daily_return.values, 0.2, align='center', color='c', label='strategy') daily_plot.legend(loc='upper left') daily_plot.autoscale(tight=True) plt.setp(daily_plot.get_xticklabels(), visible=False) daily_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) daily_plot.set_ylabel('Daily Performance') daily_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) position_plot.set_title('Daily Exposure') position_plot.plot(ind, zero_line, 'k') position_plot.bar(ind, short_exposure.values, 0.3, linewidth=0, align='center', color='r', label='short') position_plot.bar(ind, long_exposure.values, 0.3, linewidth=0, align='center', color='b', label='long') position_plot.legend(loc='upper left') position_plot.autoscale(tight=True) position_plot.xaxis.set_major_formatter(mtick.FuncFormatter(format_date)) position_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) position_plot.set_ylabel('Long/Short %') position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) plt.gcf().canvas.draw() def update_plot(): # Callback Function for plot button try: d1 = pd.to_datetime(box_value2.get()) d2 = pd.to_datetime(box_value3.get()) if d1 >= daily_pnl.index[0] and d2 <= daily_pnl.index[-1]: plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, box_value.get(), box_value2.get(), box_value3.get()) else: tkMessageBox.showinfo("Date out of Range", "Please enter a date from %s to %s" % (daily_pnl.index[0].strftime('%Y-%m-%d'), daily_pnl.index[-1].strftime('%Y-%m-%d'))) except ValueError: raise ValueError("Not a Valid Date") def close_window():
def format_date(x, pos=None): # Format axis ticklabels to dates thisind = np.clip(int(x + 0.5), 0, len(daily_pnl.index) - 1) return daily_pnl.index[thisind].strftime('%b-%y') def format_perc(y, pos=None): # Format axis ticklabels to % if budget > 1: return '{percent:.2%}'.format(percent=y) else: return y def onFrameConfigure(canvas): canvas.configure(scrollregion=canvas.bbox("all")) ###################### # GUI mainloop ###################### # Create widget GUI = tk.Tk() GUI.title('Backtest Results') winCanvas = tk.Canvas(GUI, borderwidth=0, background="#ffffff", width=1500, height=1000) frame = tk.Frame(winCanvas, background="#ffffff") vsb = tk.Scrollbar(GUI, orient="vertical", command=winCanvas.yview) hsb = tk.Scrollbar(GUI, orient="horizontal", command=winCanvas.xview) winCanvas.configure(yscrollcommand=vsb.set) winCanvas.configure(xscrollcommand=hsb.set) vsb.pack(side="left", fill="y") hsb.pack(side="bottom", fill="x") winCanvas.pack(side="right", fill="both", expand=True) winCanvas.create_window((50, 50), window=frame, anchor="nw") frame.bind("<Configure>", lambda event, canvas=winCanvas: onFrameConfigure(winCanvas)) # Create dropdown for market Label_1 = tk.Label(frame, text="Trading Performance:") Label_1.grid(row=0, column=0, sticky=tk.EW) box_value = tk.StringVar() dropdown = ttk.Combobox(frame, textvariable=box_value, state='readonly') dropdown['values'] = ['TOTAL PORTFOLIO'] + daily_pnl.columns.values.tolist() dropdown.grid(row=0, column=1, sticky=tk.EW) dropdown.current(0) dropdown.bind('<<ComboboxSelected>>', newselection) # Create entry field for start date Label_2 = tk.Label(frame, text="Start Date") Label_2.grid(row=0, column=2, sticky=tk.EW) box_value2 = tk.StringVar(frame, value=daily_pnl.index.format()[0]) start = tk.Entry(frame, textvariable=box_value2, validate='key', validatecommand=(GUI.register(isDate), '%P')) start.grid(row=0, column=3, sticky=tk.EW) # Create entry field for end date Label_3 = tk.Label(frame, text="End Date") Label_3.grid(row=0, column=4, sticky=tk.EW) box_value3 = tk.StringVar(frame, value=daily_pnl.index.format()[-1]) end = tk.Entry(frame, textvariable=box_value3, validate='key', validatecommand=(GUI.register(isDate), '%P')) end.grid(row=0, column=5, sticky=tk.EW) # Create Plot button to reload chart button1 = tk.Button(frame, text='PLOT', command=update_plot) button1.grid(row=0, column=6, sticky=tk.EW) # Create text widget with backtest results customFont1 = tkFont.Font(family="Helvetica", size=9, weight="bold") customFont2 = tkFont.Font(family="Helvetica", size=12) text = tk.Text(frame, height=3, width=50, wrap=tk.WORD, bd=5, padx=10, pady=5) text.grid(row=1, column=0, columnspan=7, sticky=tk.EW) String1 = '' String2 = '' for y in stats.keys(): String1 = String1 + y + '\t\t' x = stats[y] if budget > 1 and 'Ratio' not in y: String2 = String2 + '{percent:.2%}'.format(percent=x) + '\t\t' else: String2 = String2 + '%0.2f' % x + '\t\t' text.insert(tk.END, String1) text.insert(tk.END, '\n') text.insert(tk.END, String2) text.tag_add("keys", "1.0", "1.end") text.tag_config("keys", font=customFont1) text.tag_add("values", "2.0", "2.end") text.tag_config("values", foreground="red", font=customFont2) # Create canvas to plot chart f = plt.figure(figsize=(16, 8)) canvas = FigureCanvasTkAgg(f, master=frame) canvas.get_tk_widget().grid(row=2, column=0, columnspan=7, rowspan=1, sticky=tk.NSEW) toolbar_frame = tk.Frame(frame) toolbar_frame.grid(row=4, column=0, columnspan=7) # plot 3 subplots for total position, daily position and exposure plt.style.use("seaborn-whitegrid") total_plot = plt.subplot2grid((10, 8), (0, 0), colspan=12, rowspan=4) daily_plot = plt.subplot2grid((10, 8), (5, 0), colspan=12, rowspan=2, sharex=total_plot) position_plot = plt.subplot2grid((10, 8), (8, 0), colspan=12, rowspan=2, sharex=total_plot) ind = np.arange(len(daily_pnl.index)) total_plot.set_title('Total PnL') total_plot.plot(ind, zero_line, 'k') total_plot.plot(ind, total_return.values, 'b', linewidth=0.5, label='strategy') total_plot.legend(loc='upper left') total_plot.autoscale(tight=True) plt.setp(total_plot.get_xticklabels(), visible=False) total_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) total_plot.set_ylabel('Cumulative Performance') total_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) if base_index: total_plot.plot(ind, baseline_data['TOTAL_PNL'], 'g', linewidth=0.5, label=base_index) daily_plot.set_title('Daily PnL') daily_plot.plot(ind, zero_line, 'k') daily_plot.bar(ind, daily_return.values, 0.2, align='center', color='c', label='strategy') daily_plot.legend(loc='upper left') daily_plot.autoscale(tight=True) plt.setp(daily_plot.get_xticklabels(), visible=False) daily_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) daily_plot.set_ylabel('Daily Performance') daily_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) position_plot.set_title('Daily Exposure') position_plot.plot(ind, zero_line, 'k') position_plot.bar(ind, short_exposure.values, 0.3, linewidth=0, align='center', color='r', label='short') position_plot.bar(ind, long_exposure.values, 0.3, linewidth=0, align='center', color='b', label='long') position_plot.legend(loc='upper left') position_plot.autoscale(tight=True) position_plot.xaxis.set_major_formatter(mtick.FuncFormatter(format_date)) position_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) position_plot.set_ylabel('Long/Short') position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) plt.gcf().canvas.draw() # Create Quit Button button2 = tk.Button(frame, text='QUIT', command=close_window) button2.grid(row=4, column=6, sticky=tk.EW) GUI.mainloop()
# Callback function for Quit Button GUI.destroy() GUI.quit()
random_line_split
resultviewer.py
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import pandas as pd import matplotlib matplotlib.use("TkAgg") # important to call this right after from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib import style import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mtick try: import Tkinter as tk import ttk import tkFont import tkMessageBox except: import tkinter as tk from tkinter import ttk from tkinter import font as tkFont from tkinter import messagebox as tkMessageBox from auquanToolbox.metrics import metrics, baseline def loadgui(back_data, exchange, base_index, budget, logger): ###################### # Setup data ###################### position = back_data['POSITION'] close = back_data['CLOSE'] # position as % of total portfolio long_position = (position * close).div(back_data['VALUE'], axis=0) short_position = long_position.copy() long_position[long_position < 0] = 0 short_position[short_position > 0] = 0 daily_pnl = back_data['DAILY_PNL'] / budget total_pnl = back_data['TOTAL_PNL'] / budget if base_index: baseline_data = baseline(exchange, base_index, total_pnl.index, logger) stats = metrics(daily_pnl, total_pnl, baseline_data, base_index) else: baseline_data = {} stats = metrics(daily_pnl, total_pnl, {}, base_index) daily_return = daily_pnl.sum(axis=1) total_return = total_pnl.sum(axis=1) long_exposure = long_position.sum(axis=1) short_exposure = short_position.sum(axis=1) zero_line = np.zeros(daily_pnl.index.size) # print to logger for x in stats.keys(): logger.info('%s : %0.2f' % (x, stats[x])) def isDate(val): # Function to validate if a given entry is valid date try: d = pd.to_datetime(val) if d > daily_pnl.index[0] and d < daily_pnl.index[-1]: return True else: return False except ValueError: raise ValueError("Not a Valid Date") return False def
(event): # Function to autoupdate chart on new selection from dropdown i = dropdown.current() market = ['TOTAL PORTFOLIO'] + daily_pnl.columns.values.tolist() plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, market[i], box_value2.get(), box_value3.get()) def plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, market='TOTAL PORTFOLIO', start=daily_pnl.index.format()[0], end=daily_pnl.index.format()[-1]): # New plot when custom fields are changed plt.clf() # plt.style.use("seaborn-whitegrid") daily_pnl = daily_pnl.loc[start:end] total_pnl = total_pnl.loc[start:end] long_position = long_position.loc[start:end] short_position = short_position.loc[start:end] if market == 'TOTAL PORTFOLIO': daily_return = daily_pnl.sum(axis=1) total_return = total_pnl.sum(axis=1) long_exposure = long_position.sum(axis=1) short_exposure = short_position.sum(axis=1) else: daily_return = daily_pnl[market] total_return = total_pnl[market] long_exposure = long_position[market] short_exposure = short_position[market] zero_line = np.zeros(daily_pnl.index.size) # f, plot_arr = plt.subplots(3, sharex=True) total_plot = plt.subplot2grid((10, 8), (0, 0), colspan=12, rowspan=4) daily_plot = plt.subplot2grid((10, 8), (5, 0), colspan=12, rowspan=2, sharex=total_plot) position_plot = plt.subplot2grid((10, 8), (8, 0), colspan=12, rowspan=2, sharex=total_plot) ind = np.arange(len(daily_pnl.index)) total_plot.set_title('Total PnL') total_plot.plot(ind, zero_line, 'k') total_plot.plot(ind, total_return.values, 'b', linewidth=0.5, label='strategy') total_plot.legend(loc='upper left') total_plot.autoscale(tight=True) plt.setp(total_plot.get_xticklabels(), visible=False) total_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) total_plot.set_ylabel('Cumulative Performance') total_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) if base_index: total_plot.plot(ind, baseline_data['TOTAL_PNL'], 'g', linewidth=0.5, label=base_index) daily_plot.set_title('Daily PnL') daily_plot.plot(ind, zero_line, 'k') daily_plot.bar(ind, daily_return.values, 0.2, align='center', color='c', label='strategy') daily_plot.legend(loc='upper left') daily_plot.autoscale(tight=True) plt.setp(daily_plot.get_xticklabels(), visible=False) daily_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) daily_plot.set_ylabel('Daily Performance') daily_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) position_plot.set_title('Daily Exposure') position_plot.plot(ind, zero_line, 'k') position_plot.bar(ind, short_exposure.values, 0.3, linewidth=0, align='center', color='r', label='short') position_plot.bar(ind, long_exposure.values, 0.3, linewidth=0, align='center', color='b', label='long') position_plot.legend(loc='upper left') position_plot.autoscale(tight=True) position_plot.xaxis.set_major_formatter(mtick.FuncFormatter(format_date)) position_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) position_plot.set_ylabel('Long/Short %') position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) plt.gcf().canvas.draw() def update_plot(): # Callback Function for plot button try: d1 = pd.to_datetime(box_value2.get()) d2 = pd.to_datetime(box_value3.get()) if d1 >= daily_pnl.index[0] and d2 <= daily_pnl.index[-1]: plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, box_value.get(), box_value2.get(), box_value3.get()) else: tkMessageBox.showinfo("Date out of Range", "Please enter a date from %s to %s" % (daily_pnl.index[0].strftime('%Y-%m-%d'), daily_pnl.index[-1].strftime('%Y-%m-%d'))) except ValueError: raise ValueError("Not a Valid Date") def close_window(): # Callback function for Quit Button GUI.destroy() GUI.quit() def format_date(x, pos=None): # Format axis ticklabels to dates thisind = np.clip(int(x + 0.5), 0, len(daily_pnl.index) - 1) return daily_pnl.index[thisind].strftime('%b-%y') def format_perc(y, pos=None): # Format axis ticklabels to % if budget > 1: return '{percent:.2%}'.format(percent=y) else: return y def onFrameConfigure(canvas): canvas.configure(scrollregion=canvas.bbox("all")) ###################### # GUI mainloop ###################### # Create widget GUI = tk.Tk() GUI.title('Backtest Results') winCanvas = tk.Canvas(GUI, borderwidth=0, background="#ffffff", width=1500, height=1000) frame = tk.Frame(winCanvas, background="#ffffff") vsb = tk.Scrollbar(GUI, orient="vertical", command=winCanvas.yview) hsb = tk.Scrollbar(GUI, orient="horizontal", command=winCanvas.xview) winCanvas.configure(yscrollcommand=vsb.set) winCanvas.configure(xscrollcommand=hsb.set) vsb.pack(side="left", fill="y") hsb.pack(side="bottom", fill="x") winCanvas.pack(side="right", fill="both", expand=True) winCanvas.create_window((50, 50), window=frame, anchor="nw") frame.bind("<Configure>", lambda event, canvas=winCanvas: onFrameConfigure(winCanvas)) # Create dropdown for market Label_1 = tk.Label(frame, text="Trading Performance:") Label_1.grid(row=0, column=0, sticky=tk.EW) box_value = tk.StringVar() dropdown = ttk.Combobox(frame, textvariable=box_value, state='readonly') dropdown['values'] = ['TOTAL PORTFOLIO'] + daily_pnl.columns.values.tolist() dropdown.grid(row=0, column=1, sticky=tk.EW) dropdown.current(0) dropdown.bind('<<ComboboxSelected>>', newselection) # Create entry field for start date Label_2 = tk.Label(frame, text="Start Date") Label_2.grid(row=0, column=2, sticky=tk.EW) box_value2 = tk.StringVar(frame, value=daily_pnl.index.format()[0]) start = tk.Entry(frame, textvariable=box_value2, validate='key', validatecommand=(GUI.register(isDate), '%P')) start.grid(row=0, column=3, sticky=tk.EW) # Create entry field for end date Label_3 = tk.Label(frame, text="End Date") Label_3.grid(row=0, column=4, sticky=tk.EW) box_value3 = tk.StringVar(frame, value=daily_pnl.index.format()[-1]) end = tk.Entry(frame, textvariable=box_value3, validate='key', validatecommand=(GUI.register(isDate), '%P')) end.grid(row=0, column=5, sticky=tk.EW) # Create Plot button to reload chart button1 = tk.Button(frame, text='PLOT', command=update_plot) button1.grid(row=0, column=6, sticky=tk.EW) # Create text widget with backtest results customFont1 = tkFont.Font(family="Helvetica", size=9, weight="bold") customFont2 = tkFont.Font(family="Helvetica", size=12) text = tk.Text(frame, height=3, width=50, wrap=tk.WORD, bd=5, padx=10, pady=5) text.grid(row=1, column=0, columnspan=7, sticky=tk.EW) String1 = '' String2 = '' for y in stats.keys(): String1 = String1 + y + '\t\t' x = stats[y] if budget > 1 and 'Ratio' not in y: String2 = String2 + '{percent:.2%}'.format(percent=x) + '\t\t' else: String2 = String2 + '%0.2f' % x + '\t\t' text.insert(tk.END, String1) text.insert(tk.END, '\n') text.insert(tk.END, String2) text.tag_add("keys", "1.0", "1.end") text.tag_config("keys", font=customFont1) text.tag_add("values", "2.0", "2.end") text.tag_config("values", foreground="red", font=customFont2) # Create canvas to plot chart f = plt.figure(figsize=(16, 8)) canvas = FigureCanvasTkAgg(f, master=frame) canvas.get_tk_widget().grid(row=2, column=0, columnspan=7, rowspan=1, sticky=tk.NSEW) toolbar_frame = tk.Frame(frame) toolbar_frame.grid(row=4, column=0, columnspan=7) # plot 3 subplots for total position, daily position and exposure plt.style.use("seaborn-whitegrid") total_plot = plt.subplot2grid((10, 8), (0, 0), colspan=12, rowspan=4) daily_plot = plt.subplot2grid((10, 8), (5, 0), colspan=12, rowspan=2, sharex=total_plot) position_plot = plt.subplot2grid((10, 8), (8, 0), colspan=12, rowspan=2, sharex=total_plot) ind = np.arange(len(daily_pnl.index)) total_plot.set_title('Total PnL') total_plot.plot(ind, zero_line, 'k') total_plot.plot(ind, total_return.values, 'b', linewidth=0.5, label='strategy') total_plot.legend(loc='upper left') total_plot.autoscale(tight=True) plt.setp(total_plot.get_xticklabels(), visible=False) total_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) total_plot.set_ylabel('Cumulative Performance') total_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) if base_index: total_plot.plot(ind, baseline_data['TOTAL_PNL'], 'g', linewidth=0.5, label=base_index) daily_plot.set_title('Daily PnL') daily_plot.plot(ind, zero_line, 'k') daily_plot.bar(ind, daily_return.values, 0.2, align='center', color='c', label='strategy') daily_plot.legend(loc='upper left') daily_plot.autoscale(tight=True) plt.setp(daily_plot.get_xticklabels(), visible=False) daily_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) daily_plot.set_ylabel('Daily Performance') daily_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) position_plot.set_title('Daily Exposure') position_plot.plot(ind, zero_line, 'k') position_plot.bar(ind, short_exposure.values, 0.3, linewidth=0, align='center', color='r', label='short') position_plot.bar(ind, long_exposure.values, 0.3, linewidth=0, align='center', color='b', label='long') position_plot.legend(loc='upper left') position_plot.autoscale(tight=True) position_plot.xaxis.set_major_formatter(mtick.FuncFormatter(format_date)) position_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) position_plot.set_ylabel('Long/Short') position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) plt.gcf().canvas.draw() # Create Quit Button button2 = tk.Button(frame, text='QUIT', command=close_window) button2.grid(row=4, column=6, sticky=tk.EW) GUI.mainloop()
newselection
identifier_name
resultviewer.py
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import pandas as pd import matplotlib matplotlib.use("TkAgg") # important to call this right after from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib import style import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mtick try: import Tkinter as tk import ttk import tkFont import tkMessageBox except: import tkinter as tk from tkinter import ttk from tkinter import font as tkFont from tkinter import messagebox as tkMessageBox from auquanToolbox.metrics import metrics, baseline def loadgui(back_data, exchange, base_index, budget, logger): ###################### # Setup data ###################### position = back_data['POSITION'] close = back_data['CLOSE'] # position as % of total portfolio long_position = (position * close).div(back_data['VALUE'], axis=0) short_position = long_position.copy() long_position[long_position < 0] = 0 short_position[short_position > 0] = 0 daily_pnl = back_data['DAILY_PNL'] / budget total_pnl = back_data['TOTAL_PNL'] / budget if base_index: baseline_data = baseline(exchange, base_index, total_pnl.index, logger) stats = metrics(daily_pnl, total_pnl, baseline_data, base_index) else: baseline_data = {} stats = metrics(daily_pnl, total_pnl, {}, base_index) daily_return = daily_pnl.sum(axis=1) total_return = total_pnl.sum(axis=1) long_exposure = long_position.sum(axis=1) short_exposure = short_position.sum(axis=1) zero_line = np.zeros(daily_pnl.index.size) # print to logger for x in stats.keys(): logger.info('%s : %0.2f' % (x, stats[x])) def isDate(val): # Function to validate if a given entry is valid date try: d = pd.to_datetime(val) if d > daily_pnl.index[0] and d < daily_pnl.index[-1]: return True else: return False except ValueError: raise ValueError("Not a Valid Date") return False def newselection(event): # Function to autoupdate chart on new selection from dropdown i = dropdown.current() market = ['TOTAL PORTFOLIO'] + daily_pnl.columns.values.tolist() plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, market[i], box_value2.get(), box_value3.get()) def plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, market='TOTAL PORTFOLIO', start=daily_pnl.index.format()[0], end=daily_pnl.index.format()[-1]): # New plot when custom fields are changed plt.clf() # plt.style.use("seaborn-whitegrid") daily_pnl = daily_pnl.loc[start:end] total_pnl = total_pnl.loc[start:end] long_position = long_position.loc[start:end] short_position = short_position.loc[start:end] if market == 'TOTAL PORTFOLIO': daily_return = daily_pnl.sum(axis=1) total_return = total_pnl.sum(axis=1) long_exposure = long_position.sum(axis=1) short_exposure = short_position.sum(axis=1) else: daily_return = daily_pnl[market] total_return = total_pnl[market] long_exposure = long_position[market] short_exposure = short_position[market] zero_line = np.zeros(daily_pnl.index.size) # f, plot_arr = plt.subplots(3, sharex=True) total_plot = plt.subplot2grid((10, 8), (0, 0), colspan=12, rowspan=4) daily_plot = plt.subplot2grid((10, 8), (5, 0), colspan=12, rowspan=2, sharex=total_plot) position_plot = plt.subplot2grid((10, 8), (8, 0), colspan=12, rowspan=2, sharex=total_plot) ind = np.arange(len(daily_pnl.index)) total_plot.set_title('Total PnL') total_plot.plot(ind, zero_line, 'k') total_plot.plot(ind, total_return.values, 'b', linewidth=0.5, label='strategy') total_plot.legend(loc='upper left') total_plot.autoscale(tight=True) plt.setp(total_plot.get_xticklabels(), visible=False) total_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) total_plot.set_ylabel('Cumulative Performance') total_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) if base_index: total_plot.plot(ind, baseline_data['TOTAL_PNL'], 'g', linewidth=0.5, label=base_index) daily_plot.set_title('Daily PnL') daily_plot.plot(ind, zero_line, 'k') daily_plot.bar(ind, daily_return.values, 0.2, align='center', color='c', label='strategy') daily_plot.legend(loc='upper left') daily_plot.autoscale(tight=True) plt.setp(daily_plot.get_xticklabels(), visible=False) daily_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) daily_plot.set_ylabel('Daily Performance') daily_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) position_plot.set_title('Daily Exposure') position_plot.plot(ind, zero_line, 'k') position_plot.bar(ind, short_exposure.values, 0.3, linewidth=0, align='center', color='r', label='short') position_plot.bar(ind, long_exposure.values, 0.3, linewidth=0, align='center', color='b', label='long') position_plot.legend(loc='upper left') position_plot.autoscale(tight=True) position_plot.xaxis.set_major_formatter(mtick.FuncFormatter(format_date)) position_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) position_plot.set_ylabel('Long/Short %') position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) plt.gcf().canvas.draw() def update_plot(): # Callback Function for plot button try: d1 = pd.to_datetime(box_value2.get()) d2 = pd.to_datetime(box_value3.get()) if d1 >= daily_pnl.index[0] and d2 <= daily_pnl.index[-1]: plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, box_value.get(), box_value2.get(), box_value3.get()) else: tkMessageBox.showinfo("Date out of Range", "Please enter a date from %s to %s" % (daily_pnl.index[0].strftime('%Y-%m-%d'), daily_pnl.index[-1].strftime('%Y-%m-%d'))) except ValueError: raise ValueError("Not a Valid Date") def close_window(): # Callback function for Quit Button GUI.destroy() GUI.quit() def format_date(x, pos=None): # Format axis ticklabels to dates thisind = np.clip(int(x + 0.5), 0, len(daily_pnl.index) - 1) return daily_pnl.index[thisind].strftime('%b-%y') def format_perc(y, pos=None): # Format axis ticklabels to % if budget > 1: return '{percent:.2%}'.format(percent=y) else: return y def onFrameConfigure(canvas):
###################### # GUI mainloop ###################### # Create widget GUI = tk.Tk() GUI.title('Backtest Results') winCanvas = tk.Canvas(GUI, borderwidth=0, background="#ffffff", width=1500, height=1000) frame = tk.Frame(winCanvas, background="#ffffff") vsb = tk.Scrollbar(GUI, orient="vertical", command=winCanvas.yview) hsb = tk.Scrollbar(GUI, orient="horizontal", command=winCanvas.xview) winCanvas.configure(yscrollcommand=vsb.set) winCanvas.configure(xscrollcommand=hsb.set) vsb.pack(side="left", fill="y") hsb.pack(side="bottom", fill="x") winCanvas.pack(side="right", fill="both", expand=True) winCanvas.create_window((50, 50), window=frame, anchor="nw") frame.bind("<Configure>", lambda event, canvas=winCanvas: onFrameConfigure(winCanvas)) # Create dropdown for market Label_1 = tk.Label(frame, text="Trading Performance:") Label_1.grid(row=0, column=0, sticky=tk.EW) box_value = tk.StringVar() dropdown = ttk.Combobox(frame, textvariable=box_value, state='readonly') dropdown['values'] = ['TOTAL PORTFOLIO'] + daily_pnl.columns.values.tolist() dropdown.grid(row=0, column=1, sticky=tk.EW) dropdown.current(0) dropdown.bind('<<ComboboxSelected>>', newselection) # Create entry field for start date Label_2 = tk.Label(frame, text="Start Date") Label_2.grid(row=0, column=2, sticky=tk.EW) box_value2 = tk.StringVar(frame, value=daily_pnl.index.format()[0]) start = tk.Entry(frame, textvariable=box_value2, validate='key', validatecommand=(GUI.register(isDate), '%P')) start.grid(row=0, column=3, sticky=tk.EW) # Create entry field for end date Label_3 = tk.Label(frame, text="End Date") Label_3.grid(row=0, column=4, sticky=tk.EW) box_value3 = tk.StringVar(frame, value=daily_pnl.index.format()[-1]) end = tk.Entry(frame, textvariable=box_value3, validate='key', validatecommand=(GUI.register(isDate), '%P')) end.grid(row=0, column=5, sticky=tk.EW) # Create Plot button to reload chart button1 = tk.Button(frame, text='PLOT', command=update_plot) button1.grid(row=0, column=6, sticky=tk.EW) # Create text widget with backtest results customFont1 = tkFont.Font(family="Helvetica", size=9, weight="bold") customFont2 = tkFont.Font(family="Helvetica", size=12) text = tk.Text(frame, height=3, width=50, wrap=tk.WORD, bd=5, padx=10, pady=5) text.grid(row=1, column=0, columnspan=7, sticky=tk.EW) String1 = '' String2 = '' for y in stats.keys(): String1 = String1 + y + '\t\t' x = stats[y] if budget > 1 and 'Ratio' not in y: String2 = String2 + '{percent:.2%}'.format(percent=x) + '\t\t' else: String2 = String2 + '%0.2f' % x + '\t\t' text.insert(tk.END, String1) text.insert(tk.END, '\n') text.insert(tk.END, String2) text.tag_add("keys", "1.0", "1.end") text.tag_config("keys", font=customFont1) text.tag_add("values", "2.0", "2.end") text.tag_config("values", foreground="red", font=customFont2) # Create canvas to plot chart f = plt.figure(figsize=(16, 8)) canvas = FigureCanvasTkAgg(f, master=frame) canvas.get_tk_widget().grid(row=2, column=0, columnspan=7, rowspan=1, sticky=tk.NSEW) toolbar_frame = tk.Frame(frame) toolbar_frame.grid(row=4, column=0, columnspan=7) # plot 3 subplots for total position, daily position and exposure plt.style.use("seaborn-whitegrid") total_plot = plt.subplot2grid((10, 8), (0, 0), colspan=12, rowspan=4) daily_plot = plt.subplot2grid((10, 8), (5, 0), colspan=12, rowspan=2, sharex=total_plot) position_plot = plt.subplot2grid((10, 8), (8, 0), colspan=12, rowspan=2, sharex=total_plot) ind = np.arange(len(daily_pnl.index)) total_plot.set_title('Total PnL') total_plot.plot(ind, zero_line, 'k') total_plot.plot(ind, total_return.values, 'b', linewidth=0.5, label='strategy') total_plot.legend(loc='upper left') total_plot.autoscale(tight=True) plt.setp(total_plot.get_xticklabels(), visible=False) total_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) total_plot.set_ylabel('Cumulative Performance') total_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) if base_index: total_plot.plot(ind, baseline_data['TOTAL_PNL'], 'g', linewidth=0.5, label=base_index) daily_plot.set_title('Daily PnL') daily_plot.plot(ind, zero_line, 'k') daily_plot.bar(ind, daily_return.values, 0.2, align='center', color='c', label='strategy') daily_plot.legend(loc='upper left') daily_plot.autoscale(tight=True) plt.setp(daily_plot.get_xticklabels(), visible=False) daily_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) daily_plot.set_ylabel('Daily Performance') daily_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) position_plot.set_title('Daily Exposure') position_plot.plot(ind, zero_line, 'k') position_plot.bar(ind, short_exposure.values, 0.3, linewidth=0, align='center', color='r', label='short') position_plot.bar(ind, long_exposure.values, 0.3, linewidth=0, align='center', color='b', label='long') position_plot.legend(loc='upper left') position_plot.autoscale(tight=True) position_plot.xaxis.set_major_formatter(mtick.FuncFormatter(format_date)) position_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) position_plot.set_ylabel('Long/Short') position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) plt.gcf().canvas.draw() # Create Quit Button button2 = tk.Button(frame, text='QUIT', command=close_window) button2.grid(row=4, column=6, sticky=tk.EW) GUI.mainloop()
canvas.configure(scrollregion=canvas.bbox("all"))
identifier_body
resultviewer.py
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import pandas as pd import matplotlib matplotlib.use("TkAgg") # important to call this right after from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib import style import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mtick try: import Tkinter as tk import ttk import tkFont import tkMessageBox except: import tkinter as tk from tkinter import ttk from tkinter import font as tkFont from tkinter import messagebox as tkMessageBox from auquanToolbox.metrics import metrics, baseline def loadgui(back_data, exchange, base_index, budget, logger): ###################### # Setup data ###################### position = back_data['POSITION'] close = back_data['CLOSE'] # position as % of total portfolio long_position = (position * close).div(back_data['VALUE'], axis=0) short_position = long_position.copy() long_position[long_position < 0] = 0 short_position[short_position > 0] = 0 daily_pnl = back_data['DAILY_PNL'] / budget total_pnl = back_data['TOTAL_PNL'] / budget if base_index: baseline_data = baseline(exchange, base_index, total_pnl.index, logger) stats = metrics(daily_pnl, total_pnl, baseline_data, base_index) else: baseline_data = {} stats = metrics(daily_pnl, total_pnl, {}, base_index) daily_return = daily_pnl.sum(axis=1) total_return = total_pnl.sum(axis=1) long_exposure = long_position.sum(axis=1) short_exposure = short_position.sum(axis=1) zero_line = np.zeros(daily_pnl.index.size) # print to logger for x in stats.keys(): logger.info('%s : %0.2f' % (x, stats[x])) def isDate(val): # Function to validate if a given entry is valid date try: d = pd.to_datetime(val) if d > daily_pnl.index[0] and d < daily_pnl.index[-1]: return True else: return False except ValueError: raise ValueError("Not a Valid Date") return False def newselection(event): # Function to autoupdate chart on new selection from dropdown i = dropdown.current() market = ['TOTAL PORTFOLIO'] + daily_pnl.columns.values.tolist() plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, market[i], box_value2.get(), box_value3.get()) def plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, market='TOTAL PORTFOLIO', start=daily_pnl.index.format()[0], end=daily_pnl.index.format()[-1]): # New plot when custom fields are changed plt.clf() # plt.style.use("seaborn-whitegrid") daily_pnl = daily_pnl.loc[start:end] total_pnl = total_pnl.loc[start:end] long_position = long_position.loc[start:end] short_position = short_position.loc[start:end] if market == 'TOTAL PORTFOLIO': daily_return = daily_pnl.sum(axis=1) total_return = total_pnl.sum(axis=1) long_exposure = long_position.sum(axis=1) short_exposure = short_position.sum(axis=1) else: daily_return = daily_pnl[market] total_return = total_pnl[market] long_exposure = long_position[market] short_exposure = short_position[market] zero_line = np.zeros(daily_pnl.index.size) # f, plot_arr = plt.subplots(3, sharex=True) total_plot = plt.subplot2grid((10, 8), (0, 0), colspan=12, rowspan=4) daily_plot = plt.subplot2grid((10, 8), (5, 0), colspan=12, rowspan=2, sharex=total_plot) position_plot = plt.subplot2grid((10, 8), (8, 0), colspan=12, rowspan=2, sharex=total_plot) ind = np.arange(len(daily_pnl.index)) total_plot.set_title('Total PnL') total_plot.plot(ind, zero_line, 'k') total_plot.plot(ind, total_return.values, 'b', linewidth=0.5, label='strategy') total_plot.legend(loc='upper left') total_plot.autoscale(tight=True) plt.setp(total_plot.get_xticklabels(), visible=False) total_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) total_plot.set_ylabel('Cumulative Performance') total_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) if base_index: total_plot.plot(ind, baseline_data['TOTAL_PNL'], 'g', linewidth=0.5, label=base_index) daily_plot.set_title('Daily PnL') daily_plot.plot(ind, zero_line, 'k') daily_plot.bar(ind, daily_return.values, 0.2, align='center', color='c', label='strategy') daily_plot.legend(loc='upper left') daily_plot.autoscale(tight=True) plt.setp(daily_plot.get_xticklabels(), visible=False) daily_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) daily_plot.set_ylabel('Daily Performance') daily_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) position_plot.set_title('Daily Exposure') position_plot.plot(ind, zero_line, 'k') position_plot.bar(ind, short_exposure.values, 0.3, linewidth=0, align='center', color='r', label='short') position_plot.bar(ind, long_exposure.values, 0.3, linewidth=0, align='center', color='b', label='long') position_plot.legend(loc='upper left') position_plot.autoscale(tight=True) position_plot.xaxis.set_major_formatter(mtick.FuncFormatter(format_date)) position_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) position_plot.set_ylabel('Long/Short %') position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) plt.gcf().canvas.draw() def update_plot(): # Callback Function for plot button try: d1 = pd.to_datetime(box_value2.get()) d2 = pd.to_datetime(box_value3.get()) if d1 >= daily_pnl.index[0] and d2 <= daily_pnl.index[-1]: plot(daily_pnl, total_pnl, long_position, short_position, baseline_data, base_index, box_value.get(), box_value2.get(), box_value3.get()) else: tkMessageBox.showinfo("Date out of Range", "Please enter a date from %s to %s" % (daily_pnl.index[0].strftime('%Y-%m-%d'), daily_pnl.index[-1].strftime('%Y-%m-%d'))) except ValueError: raise ValueError("Not a Valid Date") def close_window(): # Callback function for Quit Button GUI.destroy() GUI.quit() def format_date(x, pos=None): # Format axis ticklabels to dates thisind = np.clip(int(x + 0.5), 0, len(daily_pnl.index) - 1) return daily_pnl.index[thisind].strftime('%b-%y') def format_perc(y, pos=None): # Format axis ticklabels to % if budget > 1: return '{percent:.2%}'.format(percent=y) else: return y def onFrameConfigure(canvas): canvas.configure(scrollregion=canvas.bbox("all")) ###################### # GUI mainloop ###################### # Create widget GUI = tk.Tk() GUI.title('Backtest Results') winCanvas = tk.Canvas(GUI, borderwidth=0, background="#ffffff", width=1500, height=1000) frame = tk.Frame(winCanvas, background="#ffffff") vsb = tk.Scrollbar(GUI, orient="vertical", command=winCanvas.yview) hsb = tk.Scrollbar(GUI, orient="horizontal", command=winCanvas.xview) winCanvas.configure(yscrollcommand=vsb.set) winCanvas.configure(xscrollcommand=hsb.set) vsb.pack(side="left", fill="y") hsb.pack(side="bottom", fill="x") winCanvas.pack(side="right", fill="both", expand=True) winCanvas.create_window((50, 50), window=frame, anchor="nw") frame.bind("<Configure>", lambda event, canvas=winCanvas: onFrameConfigure(winCanvas)) # Create dropdown for market Label_1 = tk.Label(frame, text="Trading Performance:") Label_1.grid(row=0, column=0, sticky=tk.EW) box_value = tk.StringVar() dropdown = ttk.Combobox(frame, textvariable=box_value, state='readonly') dropdown['values'] = ['TOTAL PORTFOLIO'] + daily_pnl.columns.values.tolist() dropdown.grid(row=0, column=1, sticky=tk.EW) dropdown.current(0) dropdown.bind('<<ComboboxSelected>>', newselection) # Create entry field for start date Label_2 = tk.Label(frame, text="Start Date") Label_2.grid(row=0, column=2, sticky=tk.EW) box_value2 = tk.StringVar(frame, value=daily_pnl.index.format()[0]) start = tk.Entry(frame, textvariable=box_value2, validate='key', validatecommand=(GUI.register(isDate), '%P')) start.grid(row=0, column=3, sticky=tk.EW) # Create entry field for end date Label_3 = tk.Label(frame, text="End Date") Label_3.grid(row=0, column=4, sticky=tk.EW) box_value3 = tk.StringVar(frame, value=daily_pnl.index.format()[-1]) end = tk.Entry(frame, textvariable=box_value3, validate='key', validatecommand=(GUI.register(isDate), '%P')) end.grid(row=0, column=5, sticky=tk.EW) # Create Plot button to reload chart button1 = tk.Button(frame, text='PLOT', command=update_plot) button1.grid(row=0, column=6, sticky=tk.EW) # Create text widget with backtest results customFont1 = tkFont.Font(family="Helvetica", size=9, weight="bold") customFont2 = tkFont.Font(family="Helvetica", size=12) text = tk.Text(frame, height=3, width=50, wrap=tk.WORD, bd=5, padx=10, pady=5) text.grid(row=1, column=0, columnspan=7, sticky=tk.EW) String1 = '' String2 = '' for y in stats.keys(): String1 = String1 + y + '\t\t' x = stats[y] if budget > 1 and 'Ratio' not in y:
else: String2 = String2 + '%0.2f' % x + '\t\t' text.insert(tk.END, String1) text.insert(tk.END, '\n') text.insert(tk.END, String2) text.tag_add("keys", "1.0", "1.end") text.tag_config("keys", font=customFont1) text.tag_add("values", "2.0", "2.end") text.tag_config("values", foreground="red", font=customFont2) # Create canvas to plot chart f = plt.figure(figsize=(16, 8)) canvas = FigureCanvasTkAgg(f, master=frame) canvas.get_tk_widget().grid(row=2, column=0, columnspan=7, rowspan=1, sticky=tk.NSEW) toolbar_frame = tk.Frame(frame) toolbar_frame.grid(row=4, column=0, columnspan=7) # plot 3 subplots for total position, daily position and exposure plt.style.use("seaborn-whitegrid") total_plot = plt.subplot2grid((10, 8), (0, 0), colspan=12, rowspan=4) daily_plot = plt.subplot2grid((10, 8), (5, 0), colspan=12, rowspan=2, sharex=total_plot) position_plot = plt.subplot2grid((10, 8), (8, 0), colspan=12, rowspan=2, sharex=total_plot) ind = np.arange(len(daily_pnl.index)) total_plot.set_title('Total PnL') total_plot.plot(ind, zero_line, 'k') total_plot.plot(ind, total_return.values, 'b', linewidth=0.5, label='strategy') total_plot.legend(loc='upper left') total_plot.autoscale(tight=True) plt.setp(total_plot.get_xticklabels(), visible=False) total_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) total_plot.set_ylabel('Cumulative Performance') total_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) if base_index: total_plot.plot(ind, baseline_data['TOTAL_PNL'], 'g', linewidth=0.5, label=base_index) daily_plot.set_title('Daily PnL') daily_plot.plot(ind, zero_line, 'k') daily_plot.bar(ind, daily_return.values, 0.2, align='center', color='c', label='strategy') daily_plot.legend(loc='upper left') daily_plot.autoscale(tight=True) plt.setp(daily_plot.get_xticklabels(), visible=False) daily_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) daily_plot.set_ylabel('Daily Performance') daily_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) position_plot.set_title('Daily Exposure') position_plot.plot(ind, zero_line, 'k') position_plot.bar(ind, short_exposure.values, 0.3, linewidth=0, align='center', color='r', label='short') position_plot.bar(ind, long_exposure.values, 0.3, linewidth=0, align='center', color='b', label='long') position_plot.legend(loc='upper left') position_plot.autoscale(tight=True) position_plot.xaxis.set_major_formatter(mtick.FuncFormatter(format_date)) position_plot.yaxis.set_major_formatter(mtick.FuncFormatter(format_perc)) position_plot.set_ylabel('Long/Short') position_plot.legend(bbox_to_anchor=(0.03, 0.97), loc='lower left', borderaxespad=0.) plt.gcf().canvas.draw() # Create Quit Button button2 = tk.Button(frame, text='QUIT', command=close_window) button2.grid(row=4, column=6, sticky=tk.EW) GUI.mainloop()
String2 = String2 + '{percent:.2%}'.format(percent=x) + '\t\t'
conditional_block
main.py
from collections import deque class Node(tuple): ##### ^ -- backwad ##### v -- forward ##### <-- left ##### --> right LEFT,RIGHT,TOP,BOTTOM,FORWARD,BACKWARD = range(6) def __new__(cls, r, c, five): return tuple.__new__(cls, (r,c,five)) def __init__(self, r, c, five): pass def neighbors(self, mat, n): r,c,_ = self if r > 0 and mat[r-1][c] != '*': yield self.roll_backwards() if c > 0 and mat[r][c-1] != '*': yield self.roll_left() if r < n-1 and mat[r+1][c] != '*': yield self.roll_forward() if c < n-1 and mat[r][c+1] != '*': yield self.roll_right() def roll_forward(self): r,c,five = self if five == Node.FORWARD: five = Node.BOTTOM elif five == Node.BOTTOM: five = Node.BACKWARD elif five == Node.BACKWARD: five = Node.TOP elif five == Node.TOP: five = Node.FORWARD return Node(r+1, c, five) def
(self): r,c,five = self if five == Node.FORWARD: five = Node.TOP elif five == Node.BOTTOM: five = Node.FORWARD elif five == Node.BACKWARD: five = Node.BOTTOM elif five == Node.TOP: five = Node.BACKWARD return Node(r-1, c, five) def roll_left(self): r,c,five = self if five == Node.LEFT: five = Node.BOTTOM elif five == Node.BOTTOM: five = Node.RIGHT elif five == Node.RIGHT: five = Node.TOP elif five == Node.TOP: five = Node.LEFT return Node(r, c-1, five) def roll_right(self): r,c,five = self if five == Node.LEFT: five = Node.TOP elif five == Node.BOTTOM: five = Node.LEFT elif five == Node.RIGHT: five = Node.BOTTOM elif five == Node.TOP: five = Node.RIGHT return Node(r, c+1, five) def find_ends(mat): start, end = None, None for r, row in enumerate(mat): for c, x in enumerate(row): if x == 'S': start = Node(r,c,Node.LEFT) if end: return start,end elif x == 'H': end = Node(r,c,Node.BOTTOM) if start: return start, end def dfs(mat,n,start,end): stack = deque() stack.append(start) visited = {start} while stack: curr = stack.pop() if curr == end: return True for neighbor in curr.neighbors(mat,n): if neighbor not in visited: visited.add(neighbor) stack.append(neighbor) return False def main(): for _ in range(int(input())): n = int(input()) mat = [input() for _ in range(n)] start,end = find_ends(mat) print('Yes' if dfs(mat,n,start,end) else 'No') if __name__ == "__main__": main()
roll_backwards
identifier_name
main.py
from collections import deque class Node(tuple): ##### ^ -- backwad ##### v -- forward ##### <-- left ##### --> right LEFT,RIGHT,TOP,BOTTOM,FORWARD,BACKWARD = range(6) def __new__(cls, r, c, five): return tuple.__new__(cls, (r,c,five)) def __init__(self, r, c, five): pass def neighbors(self, mat, n): r,c,_ = self if r > 0 and mat[r-1][c] != '*': yield self.roll_backwards() if c > 0 and mat[r][c-1] != '*': yield self.roll_left() if r < n-1 and mat[r+1][c] != '*': yield self.roll_forward() if c < n-1 and mat[r][c+1] != '*': yield self.roll_right() def roll_forward(self): r,c,five = self if five == Node.FORWARD: five = Node.BOTTOM elif five == Node.BOTTOM: five = Node.BACKWARD elif five == Node.BACKWARD: five = Node.TOP elif five == Node.TOP: five = Node.FORWARD return Node(r+1, c, five) def roll_backwards(self): r,c,five = self if five == Node.FORWARD: five = Node.TOP elif five == Node.BOTTOM: five = Node.FORWARD elif five == Node.BACKWARD: five = Node.BOTTOM elif five == Node.TOP: five = Node.BACKWARD return Node(r-1, c, five) def roll_left(self):
def roll_right(self): r,c,five = self if five == Node.LEFT: five = Node.TOP elif five == Node.BOTTOM: five = Node.LEFT elif five == Node.RIGHT: five = Node.BOTTOM elif five == Node.TOP: five = Node.RIGHT return Node(r, c+1, five) def find_ends(mat): start, end = None, None for r, row in enumerate(mat): for c, x in enumerate(row): if x == 'S': start = Node(r,c,Node.LEFT) if end: return start,end elif x == 'H': end = Node(r,c,Node.BOTTOM) if start: return start, end def dfs(mat,n,start,end): stack = deque() stack.append(start) visited = {start} while stack: curr = stack.pop() if curr == end: return True for neighbor in curr.neighbors(mat,n): if neighbor not in visited: visited.add(neighbor) stack.append(neighbor) return False def main(): for _ in range(int(input())): n = int(input()) mat = [input() for _ in range(n)] start,end = find_ends(mat) print('Yes' if dfs(mat,n,start,end) else 'No') if __name__ == "__main__": main()
r,c,five = self if five == Node.LEFT: five = Node.BOTTOM elif five == Node.BOTTOM: five = Node.RIGHT elif five == Node.RIGHT: five = Node.TOP elif five == Node.TOP: five = Node.LEFT return Node(r, c-1, five)
identifier_body
main.py
from collections import deque class Node(tuple): ##### ^ -- backwad ##### v -- forward ##### <-- left ##### --> right LEFT,RIGHT,TOP,BOTTOM,FORWARD,BACKWARD = range(6) def __new__(cls, r, c, five): return tuple.__new__(cls, (r,c,five))
r,c,_ = self if r > 0 and mat[r-1][c] != '*': yield self.roll_backwards() if c > 0 and mat[r][c-1] != '*': yield self.roll_left() if r < n-1 and mat[r+1][c] != '*': yield self.roll_forward() if c < n-1 and mat[r][c+1] != '*': yield self.roll_right() def roll_forward(self): r,c,five = self if five == Node.FORWARD: five = Node.BOTTOM elif five == Node.BOTTOM: five = Node.BACKWARD elif five == Node.BACKWARD: five = Node.TOP elif five == Node.TOP: five = Node.FORWARD return Node(r+1, c, five) def roll_backwards(self): r,c,five = self if five == Node.FORWARD: five = Node.TOP elif five == Node.BOTTOM: five = Node.FORWARD elif five == Node.BACKWARD: five = Node.BOTTOM elif five == Node.TOP: five = Node.BACKWARD return Node(r-1, c, five) def roll_left(self): r,c,five = self if five == Node.LEFT: five = Node.BOTTOM elif five == Node.BOTTOM: five = Node.RIGHT elif five == Node.RIGHT: five = Node.TOP elif five == Node.TOP: five = Node.LEFT return Node(r, c-1, five) def roll_right(self): r,c,five = self if five == Node.LEFT: five = Node.TOP elif five == Node.BOTTOM: five = Node.LEFT elif five == Node.RIGHT: five = Node.BOTTOM elif five == Node.TOP: five = Node.RIGHT return Node(r, c+1, five) def find_ends(mat): start, end = None, None for r, row in enumerate(mat): for c, x in enumerate(row): if x == 'S': start = Node(r,c,Node.LEFT) if end: return start,end elif x == 'H': end = Node(r,c,Node.BOTTOM) if start: return start, end def dfs(mat,n,start,end): stack = deque() stack.append(start) visited = {start} while stack: curr = stack.pop() if curr == end: return True for neighbor in curr.neighbors(mat,n): if neighbor not in visited: visited.add(neighbor) stack.append(neighbor) return False def main(): for _ in range(int(input())): n = int(input()) mat = [input() for _ in range(n)] start,end = find_ends(mat) print('Yes' if dfs(mat,n,start,end) else 'No') if __name__ == "__main__": main()
def __init__(self, r, c, five): pass def neighbors(self, mat, n):
random_line_split
main.py
from collections import deque class Node(tuple): ##### ^ -- backwad ##### v -- forward ##### <-- left ##### --> right LEFT,RIGHT,TOP,BOTTOM,FORWARD,BACKWARD = range(6) def __new__(cls, r, c, five): return tuple.__new__(cls, (r,c,five)) def __init__(self, r, c, five): pass def neighbors(self, mat, n): r,c,_ = self if r > 0 and mat[r-1][c] != '*': yield self.roll_backwards() if c > 0 and mat[r][c-1] != '*': yield self.roll_left() if r < n-1 and mat[r+1][c] != '*': yield self.roll_forward() if c < n-1 and mat[r][c+1] != '*': yield self.roll_right() def roll_forward(self): r,c,five = self if five == Node.FORWARD: five = Node.BOTTOM elif five == Node.BOTTOM: five = Node.BACKWARD elif five == Node.BACKWARD: five = Node.TOP elif five == Node.TOP: five = Node.FORWARD return Node(r+1, c, five) def roll_backwards(self): r,c,five = self if five == Node.FORWARD: five = Node.TOP elif five == Node.BOTTOM: five = Node.FORWARD elif five == Node.BACKWARD: five = Node.BOTTOM elif five == Node.TOP: five = Node.BACKWARD return Node(r-1, c, five) def roll_left(self): r,c,five = self if five == Node.LEFT: five = Node.BOTTOM elif five == Node.BOTTOM: five = Node.RIGHT elif five == Node.RIGHT: five = Node.TOP elif five == Node.TOP: five = Node.LEFT return Node(r, c-1, five) def roll_right(self): r,c,five = self if five == Node.LEFT: five = Node.TOP elif five == Node.BOTTOM: five = Node.LEFT elif five == Node.RIGHT: five = Node.BOTTOM elif five == Node.TOP: five = Node.RIGHT return Node(r, c+1, five) def find_ends(mat): start, end = None, None for r, row in enumerate(mat): for c, x in enumerate(row): if x == 'S': start = Node(r,c,Node.LEFT) if end: return start,end elif x == 'H': end = Node(r,c,Node.BOTTOM) if start:
def dfs(mat,n,start,end): stack = deque() stack.append(start) visited = {start} while stack: curr = stack.pop() if curr == end: return True for neighbor in curr.neighbors(mat,n): if neighbor not in visited: visited.add(neighbor) stack.append(neighbor) return False def main(): for _ in range(int(input())): n = int(input()) mat = [input() for _ in range(n)] start,end = find_ends(mat) print('Yes' if dfs(mat,n,start,end) else 'No') if __name__ == "__main__": main()
return start, end
conditional_block
test-cases-decorator.ts
import "reflect-metadata"; import { TEST_CASES } from "./_metadata-keys"; import { Unused } from "../unused"; import { markPropertyAsTest } from "./mark-property-as-test"; import { deprecate } from "../maintenance/deprecate"; function
( caseArguments: | (() => IterableIterator<any> | Array<Array<any>>) | IterableIterator<any> | Array<Array<any>> ): Array<Array<any>> { if (null === caseArguments || undefined === caseArguments) { return []; } if (caseArguments instanceof Function) { return GetTestCases(caseArguments()); } if (caseArguments instanceof Array) { return [...caseArguments]; } else { return Array.from(caseArguments); } } export function TestCases( caseArguments: | (() => IterableIterator<any> | Array<Array<any>>) | IterableIterator<any> | Array<Array<any>> ): ( target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any> ) => void { deprecate("TestCases", "5.0.0", "Please switch to using the new TestProperties decorator."); return ( target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any> ) => { Unused(descriptor); markPropertyAsTest(propertyKey, target); const testCases = GetTestCases(caseArguments).reduce((acc, val) => { // add the test case to the list return [ ...acc, { caseArguments: val } ]; }, (Reflect.getMetadata(TEST_CASES, target, propertyKey) as Array<any>) || []); // update the list of test cases Reflect.defineMetadata(TEST_CASES, testCases, target, propertyKey); }; }
GetTestCases
identifier_name
test-cases-decorator.ts
import "reflect-metadata"; import { TEST_CASES } from "./_metadata-keys"; import { Unused } from "../unused"; import { markPropertyAsTest } from "./mark-property-as-test"; import { deprecate } from "../maintenance/deprecate"; function GetTestCases( caseArguments: | (() => IterableIterator<any> | Array<Array<any>>) | IterableIterator<any> | Array<Array<any>> ): Array<Array<any>> { if (null === caseArguments || undefined === caseArguments) { return []; } if (caseArguments instanceof Function) { return GetTestCases(caseArguments()); } if (caseArguments instanceof Array)
else { return Array.from(caseArguments); } } export function TestCases( caseArguments: | (() => IterableIterator<any> | Array<Array<any>>) | IterableIterator<any> | Array<Array<any>> ): ( target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any> ) => void { deprecate("TestCases", "5.0.0", "Please switch to using the new TestProperties decorator."); return ( target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any> ) => { Unused(descriptor); markPropertyAsTest(propertyKey, target); const testCases = GetTestCases(caseArguments).reduce((acc, val) => { // add the test case to the list return [ ...acc, { caseArguments: val } ]; }, (Reflect.getMetadata(TEST_CASES, target, propertyKey) as Array<any>) || []); // update the list of test cases Reflect.defineMetadata(TEST_CASES, testCases, target, propertyKey); }; }
{ return [...caseArguments]; }
conditional_block
test-cases-decorator.ts
import "reflect-metadata"; import { TEST_CASES } from "./_metadata-keys"; import { Unused } from "../unused"; import { markPropertyAsTest } from "./mark-property-as-test"; import { deprecate } from "../maintenance/deprecate"; function GetTestCases( caseArguments: | (() => IterableIterator<any> | Array<Array<any>>) | IterableIterator<any> | Array<Array<any>> ): Array<Array<any>>
export function TestCases( caseArguments: | (() => IterableIterator<any> | Array<Array<any>>) | IterableIterator<any> | Array<Array<any>> ): ( target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any> ) => void { deprecate("TestCases", "5.0.0", "Please switch to using the new TestProperties decorator."); return ( target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any> ) => { Unused(descriptor); markPropertyAsTest(propertyKey, target); const testCases = GetTestCases(caseArguments).reduce((acc, val) => { // add the test case to the list return [ ...acc, { caseArguments: val } ]; }, (Reflect.getMetadata(TEST_CASES, target, propertyKey) as Array<any>) || []); // update the list of test cases Reflect.defineMetadata(TEST_CASES, testCases, target, propertyKey); }; }
{ if (null === caseArguments || undefined === caseArguments) { return []; } if (caseArguments instanceof Function) { return GetTestCases(caseArguments()); } if (caseArguments instanceof Array) { return [...caseArguments]; } else { return Array.from(caseArguments); } }
identifier_body
test-cases-decorator.ts
import "reflect-metadata"; import { TEST_CASES } from "./_metadata-keys"; import { Unused } from "../unused"; import { markPropertyAsTest } from "./mark-property-as-test"; import { deprecate } from "../maintenance/deprecate"; function GetTestCases( caseArguments: | (() => IterableIterator<any> | Array<Array<any>>) | IterableIterator<any> | Array<Array<any>> ): Array<Array<any>> { if (null === caseArguments || undefined === caseArguments) { return []; } if (caseArguments instanceof Function) { return GetTestCases(caseArguments()); } if (caseArguments instanceof Array) { return [...caseArguments]; } else { return Array.from(caseArguments); } } export function TestCases( caseArguments: | (() => IterableIterator<any> | Array<Array<any>>) | IterableIterator<any> | Array<Array<any>> ): ( target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any> ) => void { deprecate("TestCases", "5.0.0", "Please switch to using the new TestProperties decorator."); return ( target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any> ) => { Unused(descriptor); markPropertyAsTest(propertyKey, target); const testCases = GetTestCases(caseArguments).reduce((acc, val) => { // add the test case to the list return [ ...acc, { caseArguments: val } ]; }, (Reflect.getMetadata(TEST_CASES, target, propertyKey) as Array<any>) || []); // update the list of test cases Reflect.defineMetadata(TEST_CASES, testCases, target, propertyKey); };
}
random_line_split
fancy_getopt.py
"""distutils.fancy_getopt Wrapper around the standard getopt module that provides the following additional features: * short and long options are tied together * options have help strings, so fancy_getopt could potentially create a complete usage summary * options set attributes of a passed-in object """ __revision__ = "$Id: fancy_getopt.py 58495 2007-10-16 18:12:55Z guido.van.rossum $" import sys, string, re import getopt from distutils.errors import * # Much like command_re in distutils.core, this is close to but not quite # the same as a Python NAME -- except, in the spirit of most GNU # utilities, we use '-' in place of '_'. (The spirit of LISP lives on!) # The similarities to NAME are again not a coincidence... longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)' longopt_re = re.compile(r'^%s$' % longopt_pat) # For recognizing "negative alias" options, eg. "quiet=!verbose" neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat)) # This is used to translate long options to legitimate Python identifiers # (for use as attributes of some object). longopt_xlate = lambda s: s.replace('-', '_') class FancyGetopt: """Wrapper around the standard 'getopt()' module that provides some handy extra functionality: * short and long options are tied together * options have help strings, and help text can be assembled from them * options set attributes of a passed-in object * boolean options can have "negative aliases" -- eg. if --quiet is the "negative alias" of --verbose, then "--quiet" on the command line sets 'verbose' to false """ def __init__(self, option_table=None): # The option table is (currently) a list of tuples. The # tuples may have 3 or four values: # (long_option, short_option, help_string [, repeatable]) # if an option takes an argument, its long_option should have '=' # appended; short_option should just be a single character, no ':' # in any case. If a long_option doesn't have a corresponding # short_option, short_option should be None. All option tuples # must have long options. self.option_table = option_table # 'option_index' maps long option names to entries in the option # table (ie. those 3-tuples). self.option_index = {} if self.option_table: self._build_index() # 'alias' records (duh) alias options; {'foo': 'bar'} means # --foo is an alias for --bar self.alias = {} # 'negative_alias' keeps track of options that are the boolean # opposite of some other option self.negative_alias = {} # These keep track of the information in the option table. We # don't actually populate these structures until we're ready to # parse the command-line, since the 'option_table' passed in here # isn't necessarily the final word. self.short_opts = [] self.long_opts = [] self.short2long = {} self.attr_name = {} self.takes_arg = {} # And 'option_order' is filled up in 'getopt()'; it records the # original order of options (and their values) on the command-line, # but expands short options, converts aliases, etc. self.option_order = [] def _build_index(self): self.option_index.clear() for option in self.option_table: self.option_index[option[0]] = option def set_option_table(self, option_table): self.option_table = option_table self._build_index() def add_option(self, long_option, short_option=None, help_string=None): if long_option in self.option_index: raise DistutilsGetoptError( "option conflict: already an option '%s'" % long_option) else: option = (long_option, short_option, help_string) self.option_table.append(option) self.option_index[long_option] = option def has_option(self, long_option): """Return true if the option table for this parser has an option with long name 'long_option'.""" return long_option in self.option_index def get_attr_name(self, long_option): """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" return longopt_xlate(long_option) def _check_alias_dict(self, aliases, what): assert isinstance(aliases, dict) for (alias, opt) in aliases.items(): if alias not in self.option_index: raise DistutilsGetoptError(("invalid %s '%s': " "option '%s' not defined") % (what, alias, alias)) if opt not in self.option_index: raise DistutilsGetoptError(("invalid %s '%s': " "aliased option '%s' not defined") % (what, alias, opt)) def set_aliases(self, alias): """Set the aliases for this option parser.""" self._check_alias_dict(alias, "alias") self.alias = alias def set_negative_aliases(self, negative_alias): """Set the negative aliases for this option parser. 'negative_alias' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.""" self._check_alias_dict(negative_alias, "negative alias") self.negative_alias = negative_alias def _grok_option_table(self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. """ self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {} for option in self.option_table: if len(option) == 3: long, short, help = option repeat = 0 elif len(option) == 4: long, short, help, repeat = option else: # the option table is part of the code, so simply # assert that it is correct raise ValueError("invalid option tuple: %r" % (option,)) # Type- and value-check the option names if not isinstance(long, str) or len(long) < 2: raise DistutilsGetoptError(("invalid long option '%s': " "must be a string of length >= 2") % long) if (not ((short is None) or (isinstance(short, str) and len(short) == 1))): raise DistutilsGetoptError("invalid short option '%s': " "must a single character or None" % short) self.repeat[long] = repeat self.long_opts.append(long) if long[-1] == '=': # option takes an argument? if short: short = short + ':' long = long[0:-1] self.takes_arg[long] = 1 else: # Is option is a "negative alias" for some other option (eg. # "quiet" == "!verbose")? alias_to = self.negative_alias.get(long) if alias_to is not None: if self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid negative alias '%s': " "aliased option '%s' takes a value" % (long, alias_to)) self.long_opts[-1] = long # XXX redundant?! self.takes_arg[long] = 0 # If this is an alias option, make sure its "takes arg" flag is # the same as the option it's aliased to. alias_to = self.alias.get(long) if alias_to is not None: if self.takes_arg[long] != self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid alias '%s': inconsistent with " "aliased option '%s' (one of them takes a value, " "the other doesn't" % (long, alias_to)) # Now enforce some bondage on the long option name, so we can # later translate it to an attribute name on some object. Have # to do this a bit late to make sure we've removed any trailing # '='. if not longopt_re.match(long): raise DistutilsGetoptError( "invalid long option name '%s' " "(must be letters, numbers, hyphens only" % long) self.attr_name[long] = self.get_attr_name(long) if short: self.short_opts.append(short) self.short2long[short[0]] = long def getopt(self, args=None, object=None): """Parse command-line options in args. Store as attributes on object. If 'args' is None or not supplied, uses 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new OptionDummy object, stores option values there, and returns a tuple (args, object). If 'object' is supplied, it is modified in place and 'getopt()' just returns 'args'; in both cases, the returned 'args' is a modified copy of the passed-in 'args' list, which is left untouched. """ if args is None: args = sys.argv[1:] if object is None: object = OptionDummy() created_object = True else: created_object = False self._grok_option_table() short_opts = ' '.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) except getopt.error as msg: raise DistutilsArgError(msg) for opt, val in opts: if len(opt) == 2 and opt[0] == '-': # it's a short option opt = self.short2long[opt[1]] else: assert len(opt) > 2 and opt[:2] == '--' opt = opt[2:] alias = self.alias.get(opt) if alias: opt = alias if not self.takes_arg[opt]: # boolean option? assert val == '', "boolean option can't have value" alias = self.negative_alias.get(opt) if alias: opt = alias val = 0 else: val = 1 attr = self.attr_name[opt] # The only repeating option at the moment is 'verbose'. # It has a negative option -q quiet, which should set verbose = 0. if val and self.repeat.get(attr) is not None: val = getattr(object, attr, 0) + 1 setattr(object, attr, val) self.option_order.append((opt, val)) # for opts if created_object: return args, object else: return args def get_option_order(self): """Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet. """ if self.option_order is None: raise RuntimeError("'getopt()' hasn't been called yet") else: return self.option_order def generate_help(self, header=None): """Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object. """ # Blithely assume the option table is good: probably wouldn't call # 'generate_help()' unless you've already called 'getopt()'. # First pass: determine maximum length of long option names max_opt = 0 for option in self.option_table: long = option[0] short = option[1] l = len(long) if long[-1] == '=': l = l - 1 if short is not None: l = l + 5 # " (-x)" where short == 'x' if l > max_opt: max_opt = l opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter # Typical help block looks like this: # --foo controls foonabulation # Help block for longest option looks like this: # --flimflam set the flim-flam level # and with wrapped text: # --flimflam set the flim-flam level (must be between # 0 and 100, except on Tuesdays) # Options with short names will have the short name shown (but # it doesn't contribute to max_opt): # --foo (-f) controls foonabulation # If adding the short option would make the left column too wide, # we push the explanation off to the next line # --flimflam (-l) # set the flim-flam level # Important parameters: # - 2 spaces before option block start lines # - 2 dashes for each long option name # - min. 2 spaces between option and explanation (gutter) # - 5 characters (incl. space) for short option name # Now generate lines of help text. (If 80 columns were good enough # for Jesus, then 78 columns are good enough for me!) line_width = 78 text_width = line_width - opt_width big_indent = ' ' * opt_width if header: lines = [header] else: lines = ['Option summary:'] for option in self.option_table: long, short, help = option[:3] text = wrap_text(help, text_width) if long[-1] == '=': long = long[0:-1] # Case 1: no short option at all (makes life easy) if short is None: if text: lines.append(" --%-*s %s" % (max_opt, long, text[0])) else: lines.append(" --%-*s " % (max_opt, long)) # Case 2: we have a short option, so we have to include it # just after the long option else: opt_names = "%s (-%s)" % (long, short) if text: lines.append(" --%-*s %s" % (max_opt, opt_names, text[0])) else: lines.append(" --%-*s" % opt_names) for l in text[1:]: lines.append(big_indent + l) return lines def print_help(self, header=None, file=None): if file is None: file = sys.stdout for line in self.generate_help(header): file.write(line + "\n") def fancy_getopt(options, negative_opt, object, args): parser = FancyGetopt(options) parser.set_negative_aliases(negative_opt) return parser.getopt(args, object) WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace} def wrap_text(text, width): """wrap_text(text : string, width : int) -> [string] Split 'text' into multiple lines of no more than 'width' characters each, and return the list of strings that results. """ if text is None: return [] if len(text) <= width: return [text] text = text.expandtabs() text = text.translate(WS_TRANS) chunks = re.split(r'( +|-+)', text) chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings lines = [] while chunks: cur_line = [] # list of chunks (to-be-joined) cur_len = 0 # length of current line while chunks: l = len(chunks[0]) if cur_len + l <= width: # can squeeze (at least) this chunk in cur_line.append(chunks[0]) del chunks[0] cur_len = cur_len + l else: # this line is full # drop last chunk if all space if cur_line and cur_line[-1][0] == ' ':
break if chunks: # any chunks left to process? # if the current line is still empty, then we had a single # chunk that's too big too fit on a line -- so we break # down and break it up at the line width if cur_len == 0: cur_line.append(chunks[0][0:width]) chunks[0] = chunks[0][width:] # all-whitespace chunks at the end of a line can be discarded # (and we know from the re.split above that if a chunk has # *any* whitespace, it is *all* whitespace) if chunks[0][0] == ' ': del chunks[0] # and store this line in the list-of-all-lines -- as a single # string, of course! lines.append(''.join(cur_line)) return lines def translate_longopt(opt): """Convert a long option name to a valid Python identifier by changing "-" to "_". """ return longopt_xlate(opt) class OptionDummy: """Dummy class just used as a place to hold command-line option values as instance attributes.""" def __init__(self, options=[]): """Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None.""" for opt in options: setattr(self, opt, None) if __name__ == "__main__": text = """\ Tra-la-la, supercalifragilisticexpialidocious. How *do* you spell that odd word, anyways? (Someone ask Mary -- she'll know [or she'll say, "How should I know?"].)""" for w in (10, 20, 30, 40): print("width: %d" % w) print("\n".join(wrap_text(text, w))) print()
del cur_line[-1]
conditional_block
fancy_getopt.py
"""distutils.fancy_getopt Wrapper around the standard getopt module that provides the following additional features: * short and long options are tied together * options have help strings, so fancy_getopt could potentially create a complete usage summary * options set attributes of a passed-in object """ __revision__ = "$Id: fancy_getopt.py 58495 2007-10-16 18:12:55Z guido.van.rossum $" import sys, string, re import getopt from distutils.errors import * # Much like command_re in distutils.core, this is close to but not quite # the same as a Python NAME -- except, in the spirit of most GNU # utilities, we use '-' in place of '_'. (The spirit of LISP lives on!) # The similarities to NAME are again not a coincidence... longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)' longopt_re = re.compile(r'^%s$' % longopt_pat) # For recognizing "negative alias" options, eg. "quiet=!verbose" neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat)) # This is used to translate long options to legitimate Python identifiers # (for use as attributes of some object). longopt_xlate = lambda s: s.replace('-', '_') class FancyGetopt: """Wrapper around the standard 'getopt()' module that provides some handy extra functionality: * short and long options are tied together * options have help strings, and help text can be assembled from them * options set attributes of a passed-in object * boolean options can have "negative aliases" -- eg. if --quiet is the "negative alias" of --verbose, then "--quiet" on the command line sets 'verbose' to false """ def
(self, option_table=None): # The option table is (currently) a list of tuples. The # tuples may have 3 or four values: # (long_option, short_option, help_string [, repeatable]) # if an option takes an argument, its long_option should have '=' # appended; short_option should just be a single character, no ':' # in any case. If a long_option doesn't have a corresponding # short_option, short_option should be None. All option tuples # must have long options. self.option_table = option_table # 'option_index' maps long option names to entries in the option # table (ie. those 3-tuples). self.option_index = {} if self.option_table: self._build_index() # 'alias' records (duh) alias options; {'foo': 'bar'} means # --foo is an alias for --bar self.alias = {} # 'negative_alias' keeps track of options that are the boolean # opposite of some other option self.negative_alias = {} # These keep track of the information in the option table. We # don't actually populate these structures until we're ready to # parse the command-line, since the 'option_table' passed in here # isn't necessarily the final word. self.short_opts = [] self.long_opts = [] self.short2long = {} self.attr_name = {} self.takes_arg = {} # And 'option_order' is filled up in 'getopt()'; it records the # original order of options (and their values) on the command-line, # but expands short options, converts aliases, etc. self.option_order = [] def _build_index(self): self.option_index.clear() for option in self.option_table: self.option_index[option[0]] = option def set_option_table(self, option_table): self.option_table = option_table self._build_index() def add_option(self, long_option, short_option=None, help_string=None): if long_option in self.option_index: raise DistutilsGetoptError( "option conflict: already an option '%s'" % long_option) else: option = (long_option, short_option, help_string) self.option_table.append(option) self.option_index[long_option] = option def has_option(self, long_option): """Return true if the option table for this parser has an option with long name 'long_option'.""" return long_option in self.option_index def get_attr_name(self, long_option): """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" return longopt_xlate(long_option) def _check_alias_dict(self, aliases, what): assert isinstance(aliases, dict) for (alias, opt) in aliases.items(): if alias not in self.option_index: raise DistutilsGetoptError(("invalid %s '%s': " "option '%s' not defined") % (what, alias, alias)) if opt not in self.option_index: raise DistutilsGetoptError(("invalid %s '%s': " "aliased option '%s' not defined") % (what, alias, opt)) def set_aliases(self, alias): """Set the aliases for this option parser.""" self._check_alias_dict(alias, "alias") self.alias = alias def set_negative_aliases(self, negative_alias): """Set the negative aliases for this option parser. 'negative_alias' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.""" self._check_alias_dict(negative_alias, "negative alias") self.negative_alias = negative_alias def _grok_option_table(self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. """ self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {} for option in self.option_table: if len(option) == 3: long, short, help = option repeat = 0 elif len(option) == 4: long, short, help, repeat = option else: # the option table is part of the code, so simply # assert that it is correct raise ValueError("invalid option tuple: %r" % (option,)) # Type- and value-check the option names if not isinstance(long, str) or len(long) < 2: raise DistutilsGetoptError(("invalid long option '%s': " "must be a string of length >= 2") % long) if (not ((short is None) or (isinstance(short, str) and len(short) == 1))): raise DistutilsGetoptError("invalid short option '%s': " "must a single character or None" % short) self.repeat[long] = repeat self.long_opts.append(long) if long[-1] == '=': # option takes an argument? if short: short = short + ':' long = long[0:-1] self.takes_arg[long] = 1 else: # Is option is a "negative alias" for some other option (eg. # "quiet" == "!verbose")? alias_to = self.negative_alias.get(long) if alias_to is not None: if self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid negative alias '%s': " "aliased option '%s' takes a value" % (long, alias_to)) self.long_opts[-1] = long # XXX redundant?! self.takes_arg[long] = 0 # If this is an alias option, make sure its "takes arg" flag is # the same as the option it's aliased to. alias_to = self.alias.get(long) if alias_to is not None: if self.takes_arg[long] != self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid alias '%s': inconsistent with " "aliased option '%s' (one of them takes a value, " "the other doesn't" % (long, alias_to)) # Now enforce some bondage on the long option name, so we can # later translate it to an attribute name on some object. Have # to do this a bit late to make sure we've removed any trailing # '='. if not longopt_re.match(long): raise DistutilsGetoptError( "invalid long option name '%s' " "(must be letters, numbers, hyphens only" % long) self.attr_name[long] = self.get_attr_name(long) if short: self.short_opts.append(short) self.short2long[short[0]] = long def getopt(self, args=None, object=None): """Parse command-line options in args. Store as attributes on object. If 'args' is None or not supplied, uses 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new OptionDummy object, stores option values there, and returns a tuple (args, object). If 'object' is supplied, it is modified in place and 'getopt()' just returns 'args'; in both cases, the returned 'args' is a modified copy of the passed-in 'args' list, which is left untouched. """ if args is None: args = sys.argv[1:] if object is None: object = OptionDummy() created_object = True else: created_object = False self._grok_option_table() short_opts = ' '.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) except getopt.error as msg: raise DistutilsArgError(msg) for opt, val in opts: if len(opt) == 2 and opt[0] == '-': # it's a short option opt = self.short2long[opt[1]] else: assert len(opt) > 2 and opt[:2] == '--' opt = opt[2:] alias = self.alias.get(opt) if alias: opt = alias if not self.takes_arg[opt]: # boolean option? assert val == '', "boolean option can't have value" alias = self.negative_alias.get(opt) if alias: opt = alias val = 0 else: val = 1 attr = self.attr_name[opt] # The only repeating option at the moment is 'verbose'. # It has a negative option -q quiet, which should set verbose = 0. if val and self.repeat.get(attr) is not None: val = getattr(object, attr, 0) + 1 setattr(object, attr, val) self.option_order.append((opt, val)) # for opts if created_object: return args, object else: return args def get_option_order(self): """Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet. """ if self.option_order is None: raise RuntimeError("'getopt()' hasn't been called yet") else: return self.option_order def generate_help(self, header=None): """Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object. """ # Blithely assume the option table is good: probably wouldn't call # 'generate_help()' unless you've already called 'getopt()'. # First pass: determine maximum length of long option names max_opt = 0 for option in self.option_table: long = option[0] short = option[1] l = len(long) if long[-1] == '=': l = l - 1 if short is not None: l = l + 5 # " (-x)" where short == 'x' if l > max_opt: max_opt = l opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter # Typical help block looks like this: # --foo controls foonabulation # Help block for longest option looks like this: # --flimflam set the flim-flam level # and with wrapped text: # --flimflam set the flim-flam level (must be between # 0 and 100, except on Tuesdays) # Options with short names will have the short name shown (but # it doesn't contribute to max_opt): # --foo (-f) controls foonabulation # If adding the short option would make the left column too wide, # we push the explanation off to the next line # --flimflam (-l) # set the flim-flam level # Important parameters: # - 2 spaces before option block start lines # - 2 dashes for each long option name # - min. 2 spaces between option and explanation (gutter) # - 5 characters (incl. space) for short option name # Now generate lines of help text. (If 80 columns were good enough # for Jesus, then 78 columns are good enough for me!) line_width = 78 text_width = line_width - opt_width big_indent = ' ' * opt_width if header: lines = [header] else: lines = ['Option summary:'] for option in self.option_table: long, short, help = option[:3] text = wrap_text(help, text_width) if long[-1] == '=': long = long[0:-1] # Case 1: no short option at all (makes life easy) if short is None: if text: lines.append(" --%-*s %s" % (max_opt, long, text[0])) else: lines.append(" --%-*s " % (max_opt, long)) # Case 2: we have a short option, so we have to include it # just after the long option else: opt_names = "%s (-%s)" % (long, short) if text: lines.append(" --%-*s %s" % (max_opt, opt_names, text[0])) else: lines.append(" --%-*s" % opt_names) for l in text[1:]: lines.append(big_indent + l) return lines def print_help(self, header=None, file=None): if file is None: file = sys.stdout for line in self.generate_help(header): file.write(line + "\n") def fancy_getopt(options, negative_opt, object, args): parser = FancyGetopt(options) parser.set_negative_aliases(negative_opt) return parser.getopt(args, object) WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace} def wrap_text(text, width): """wrap_text(text : string, width : int) -> [string] Split 'text' into multiple lines of no more than 'width' characters each, and return the list of strings that results. """ if text is None: return [] if len(text) <= width: return [text] text = text.expandtabs() text = text.translate(WS_TRANS) chunks = re.split(r'( +|-+)', text) chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings lines = [] while chunks: cur_line = [] # list of chunks (to-be-joined) cur_len = 0 # length of current line while chunks: l = len(chunks[0]) if cur_len + l <= width: # can squeeze (at least) this chunk in cur_line.append(chunks[0]) del chunks[0] cur_len = cur_len + l else: # this line is full # drop last chunk if all space if cur_line and cur_line[-1][0] == ' ': del cur_line[-1] break if chunks: # any chunks left to process? # if the current line is still empty, then we had a single # chunk that's too big too fit on a line -- so we break # down and break it up at the line width if cur_len == 0: cur_line.append(chunks[0][0:width]) chunks[0] = chunks[0][width:] # all-whitespace chunks at the end of a line can be discarded # (and we know from the re.split above that if a chunk has # *any* whitespace, it is *all* whitespace) if chunks[0][0] == ' ': del chunks[0] # and store this line in the list-of-all-lines -- as a single # string, of course! lines.append(''.join(cur_line)) return lines def translate_longopt(opt): """Convert a long option name to a valid Python identifier by changing "-" to "_". """ return longopt_xlate(opt) class OptionDummy: """Dummy class just used as a place to hold command-line option values as instance attributes.""" def __init__(self, options=[]): """Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None.""" for opt in options: setattr(self, opt, None) if __name__ == "__main__": text = """\ Tra-la-la, supercalifragilisticexpialidocious. How *do* you spell that odd word, anyways? (Someone ask Mary -- she'll know [or she'll say, "How should I know?"].)""" for w in (10, 20, 30, 40): print("width: %d" % w) print("\n".join(wrap_text(text, w))) print()
__init__
identifier_name
fancy_getopt.py
"""distutils.fancy_getopt Wrapper around the standard getopt module that provides the following additional features: * short and long options are tied together * options have help strings, so fancy_getopt could potentially create a complete usage summary * options set attributes of a passed-in object """ __revision__ = "$Id: fancy_getopt.py 58495 2007-10-16 18:12:55Z guido.van.rossum $" import sys, string, re import getopt from distutils.errors import * # Much like command_re in distutils.core, this is close to but not quite # the same as a Python NAME -- except, in the spirit of most GNU # utilities, we use '-' in place of '_'. (The spirit of LISP lives on!) # The similarities to NAME are again not a coincidence... longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)' longopt_re = re.compile(r'^%s$' % longopt_pat) # For recognizing "negative alias" options, eg. "quiet=!verbose" neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat)) # This is used to translate long options to legitimate Python identifiers # (for use as attributes of some object). longopt_xlate = lambda s: s.replace('-', '_') class FancyGetopt: """Wrapper around the standard 'getopt()' module that provides some handy extra functionality: * short and long options are tied together * options have help strings, and help text can be assembled from them * options set attributes of a passed-in object * boolean options can have "negative aliases" -- eg. if --quiet is the "negative alias" of --verbose, then "--quiet" on the command line sets 'verbose' to false """ def __init__(self, option_table=None): # The option table is (currently) a list of tuples. The # tuples may have 3 or four values: # (long_option, short_option, help_string [, repeatable]) # if an option takes an argument, its long_option should have '=' # appended; short_option should just be a single character, no ':' # in any case. If a long_option doesn't have a corresponding # short_option, short_option should be None. All option tuples # must have long options. self.option_table = option_table # 'option_index' maps long option names to entries in the option # table (ie. those 3-tuples). self.option_index = {} if self.option_table: self._build_index() # 'alias' records (duh) alias options; {'foo': 'bar'} means # --foo is an alias for --bar self.alias = {} # 'negative_alias' keeps track of options that are the boolean # opposite of some other option self.negative_alias = {} # These keep track of the information in the option table. We # don't actually populate these structures until we're ready to # parse the command-line, since the 'option_table' passed in here # isn't necessarily the final word. self.short_opts = [] self.long_opts = [] self.short2long = {} self.attr_name = {} self.takes_arg = {} # And 'option_order' is filled up in 'getopt()'; it records the # original order of options (and their values) on the command-line, # but expands short options, converts aliases, etc. self.option_order = [] def _build_index(self): self.option_index.clear() for option in self.option_table: self.option_index[option[0]] = option def set_option_table(self, option_table): self.option_table = option_table self._build_index() def add_option(self, long_option, short_option=None, help_string=None): if long_option in self.option_index: raise DistutilsGetoptError( "option conflict: already an option '%s'" % long_option) else: option = (long_option, short_option, help_string) self.option_table.append(option) self.option_index[long_option] = option def has_option(self, long_option): """Return true if the option table for this parser has an option with long name 'long_option'.""" return long_option in self.option_index def get_attr_name(self, long_option): """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" return longopt_xlate(long_option) def _check_alias_dict(self, aliases, what): assert isinstance(aliases, dict) for (alias, opt) in aliases.items(): if alias not in self.option_index: raise DistutilsGetoptError(("invalid %s '%s': " "option '%s' not defined") % (what, alias, alias)) if opt not in self.option_index: raise DistutilsGetoptError(("invalid %s '%s': " "aliased option '%s' not defined") % (what, alias, opt)) def set_aliases(self, alias):
def set_negative_aliases(self, negative_alias): """Set the negative aliases for this option parser. 'negative_alias' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.""" self._check_alias_dict(negative_alias, "negative alias") self.negative_alias = negative_alias def _grok_option_table(self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. """ self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {} for option in self.option_table: if len(option) == 3: long, short, help = option repeat = 0 elif len(option) == 4: long, short, help, repeat = option else: # the option table is part of the code, so simply # assert that it is correct raise ValueError("invalid option tuple: %r" % (option,)) # Type- and value-check the option names if not isinstance(long, str) or len(long) < 2: raise DistutilsGetoptError(("invalid long option '%s': " "must be a string of length >= 2") % long) if (not ((short is None) or (isinstance(short, str) and len(short) == 1))): raise DistutilsGetoptError("invalid short option '%s': " "must a single character or None" % short) self.repeat[long] = repeat self.long_opts.append(long) if long[-1] == '=': # option takes an argument? if short: short = short + ':' long = long[0:-1] self.takes_arg[long] = 1 else: # Is option is a "negative alias" for some other option (eg. # "quiet" == "!verbose")? alias_to = self.negative_alias.get(long) if alias_to is not None: if self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid negative alias '%s': " "aliased option '%s' takes a value" % (long, alias_to)) self.long_opts[-1] = long # XXX redundant?! self.takes_arg[long] = 0 # If this is an alias option, make sure its "takes arg" flag is # the same as the option it's aliased to. alias_to = self.alias.get(long) if alias_to is not None: if self.takes_arg[long] != self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid alias '%s': inconsistent with " "aliased option '%s' (one of them takes a value, " "the other doesn't" % (long, alias_to)) # Now enforce some bondage on the long option name, so we can # later translate it to an attribute name on some object. Have # to do this a bit late to make sure we've removed any trailing # '='. if not longopt_re.match(long): raise DistutilsGetoptError( "invalid long option name '%s' " "(must be letters, numbers, hyphens only" % long) self.attr_name[long] = self.get_attr_name(long) if short: self.short_opts.append(short) self.short2long[short[0]] = long def getopt(self, args=None, object=None): """Parse command-line options in args. Store as attributes on object. If 'args' is None or not supplied, uses 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new OptionDummy object, stores option values there, and returns a tuple (args, object). If 'object' is supplied, it is modified in place and 'getopt()' just returns 'args'; in both cases, the returned 'args' is a modified copy of the passed-in 'args' list, which is left untouched. """ if args is None: args = sys.argv[1:] if object is None: object = OptionDummy() created_object = True else: created_object = False self._grok_option_table() short_opts = ' '.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) except getopt.error as msg: raise DistutilsArgError(msg) for opt, val in opts: if len(opt) == 2 and opt[0] == '-': # it's a short option opt = self.short2long[opt[1]] else: assert len(opt) > 2 and opt[:2] == '--' opt = opt[2:] alias = self.alias.get(opt) if alias: opt = alias if not self.takes_arg[opt]: # boolean option? assert val == '', "boolean option can't have value" alias = self.negative_alias.get(opt) if alias: opt = alias val = 0 else: val = 1 attr = self.attr_name[opt] # The only repeating option at the moment is 'verbose'. # It has a negative option -q quiet, which should set verbose = 0. if val and self.repeat.get(attr) is not None: val = getattr(object, attr, 0) + 1 setattr(object, attr, val) self.option_order.append((opt, val)) # for opts if created_object: return args, object else: return args def get_option_order(self): """Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet. """ if self.option_order is None: raise RuntimeError("'getopt()' hasn't been called yet") else: return self.option_order def generate_help(self, header=None): """Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object. """ # Blithely assume the option table is good: probably wouldn't call # 'generate_help()' unless you've already called 'getopt()'. # First pass: determine maximum length of long option names max_opt = 0 for option in self.option_table: long = option[0] short = option[1] l = len(long) if long[-1] == '=': l = l - 1 if short is not None: l = l + 5 # " (-x)" where short == 'x' if l > max_opt: max_opt = l opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter # Typical help block looks like this: # --foo controls foonabulation # Help block for longest option looks like this: # --flimflam set the flim-flam level # and with wrapped text: # --flimflam set the flim-flam level (must be between # 0 and 100, except on Tuesdays) # Options with short names will have the short name shown (but # it doesn't contribute to max_opt): # --foo (-f) controls foonabulation # If adding the short option would make the left column too wide, # we push the explanation off to the next line # --flimflam (-l) # set the flim-flam level # Important parameters: # - 2 spaces before option block start lines # - 2 dashes for each long option name # - min. 2 spaces between option and explanation (gutter) # - 5 characters (incl. space) for short option name # Now generate lines of help text. (If 80 columns were good enough # for Jesus, then 78 columns are good enough for me!) line_width = 78 text_width = line_width - opt_width big_indent = ' ' * opt_width if header: lines = [header] else: lines = ['Option summary:'] for option in self.option_table: long, short, help = option[:3] text = wrap_text(help, text_width) if long[-1] == '=': long = long[0:-1] # Case 1: no short option at all (makes life easy) if short is None: if text: lines.append(" --%-*s %s" % (max_opt, long, text[0])) else: lines.append(" --%-*s " % (max_opt, long)) # Case 2: we have a short option, so we have to include it # just after the long option else: opt_names = "%s (-%s)" % (long, short) if text: lines.append(" --%-*s %s" % (max_opt, opt_names, text[0])) else: lines.append(" --%-*s" % opt_names) for l in text[1:]: lines.append(big_indent + l) return lines def print_help(self, header=None, file=None): if file is None: file = sys.stdout for line in self.generate_help(header): file.write(line + "\n") def fancy_getopt(options, negative_opt, object, args): parser = FancyGetopt(options) parser.set_negative_aliases(negative_opt) return parser.getopt(args, object) WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace} def wrap_text(text, width): """wrap_text(text : string, width : int) -> [string] Split 'text' into multiple lines of no more than 'width' characters each, and return the list of strings that results. """ if text is None: return [] if len(text) <= width: return [text] text = text.expandtabs() text = text.translate(WS_TRANS) chunks = re.split(r'( +|-+)', text) chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings lines = [] while chunks: cur_line = [] # list of chunks (to-be-joined) cur_len = 0 # length of current line while chunks: l = len(chunks[0]) if cur_len + l <= width: # can squeeze (at least) this chunk in cur_line.append(chunks[0]) del chunks[0] cur_len = cur_len + l else: # this line is full # drop last chunk if all space if cur_line and cur_line[-1][0] == ' ': del cur_line[-1] break if chunks: # any chunks left to process? # if the current line is still empty, then we had a single # chunk that's too big too fit on a line -- so we break # down and break it up at the line width if cur_len == 0: cur_line.append(chunks[0][0:width]) chunks[0] = chunks[0][width:] # all-whitespace chunks at the end of a line can be discarded # (and we know from the re.split above that if a chunk has # *any* whitespace, it is *all* whitespace) if chunks[0][0] == ' ': del chunks[0] # and store this line in the list-of-all-lines -- as a single # string, of course! lines.append(''.join(cur_line)) return lines def translate_longopt(opt): """Convert a long option name to a valid Python identifier by changing "-" to "_". """ return longopt_xlate(opt) class OptionDummy: """Dummy class just used as a place to hold command-line option values as instance attributes.""" def __init__(self, options=[]): """Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None.""" for opt in options: setattr(self, opt, None) if __name__ == "__main__": text = """\ Tra-la-la, supercalifragilisticexpialidocious. How *do* you spell that odd word, anyways? (Someone ask Mary -- she'll know [or she'll say, "How should I know?"].)""" for w in (10, 20, 30, 40): print("width: %d" % w) print("\n".join(wrap_text(text, w))) print()
"""Set the aliases for this option parser.""" self._check_alias_dict(alias, "alias") self.alias = alias
identifier_body
fancy_getopt.py
"""distutils.fancy_getopt Wrapper around the standard getopt module that provides the following additional features: * short and long options are tied together * options have help strings, so fancy_getopt could potentially create a complete usage summary * options set attributes of a passed-in object """ __revision__ = "$Id: fancy_getopt.py 58495 2007-10-16 18:12:55Z guido.van.rossum $" import sys, string, re import getopt from distutils.errors import * # Much like command_re in distutils.core, this is close to but not quite # the same as a Python NAME -- except, in the spirit of most GNU # utilities, we use '-' in place of '_'. (The spirit of LISP lives on!) # The similarities to NAME are again not a coincidence... longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)' longopt_re = re.compile(r'^%s$' % longopt_pat) # For recognizing "negative alias" options, eg. "quiet=!verbose" neg_alias_re = re.compile("^(%s)=!(%s)$" % (longopt_pat, longopt_pat)) # This is used to translate long options to legitimate Python identifiers # (for use as attributes of some object). longopt_xlate = lambda s: s.replace('-', '_') class FancyGetopt: """Wrapper around the standard 'getopt()' module that provides some handy extra functionality: * short and long options are tied together * options have help strings, and help text can be assembled from them * options set attributes of a passed-in object * boolean options can have "negative aliases" -- eg. if --quiet is the "negative alias" of --verbose, then "--quiet" on the command line sets 'verbose' to false """ def __init__(self, option_table=None): # The option table is (currently) a list of tuples. The # tuples may have 3 or four values: # (long_option, short_option, help_string [, repeatable]) # if an option takes an argument, its long_option should have '=' # appended; short_option should just be a single character, no ':' # in any case. If a long_option doesn't have a corresponding # short_option, short_option should be None. All option tuples # must have long options. self.option_table = option_table # 'option_index' maps long option names to entries in the option # table (ie. those 3-tuples). self.option_index = {} if self.option_table: self._build_index() # 'alias' records (duh) alias options; {'foo': 'bar'} means # --foo is an alias for --bar self.alias = {} # 'negative_alias' keeps track of options that are the boolean # opposite of some other option self.negative_alias = {}
# don't actually populate these structures until we're ready to # parse the command-line, since the 'option_table' passed in here # isn't necessarily the final word. self.short_opts = [] self.long_opts = [] self.short2long = {} self.attr_name = {} self.takes_arg = {} # And 'option_order' is filled up in 'getopt()'; it records the # original order of options (and their values) on the command-line, # but expands short options, converts aliases, etc. self.option_order = [] def _build_index(self): self.option_index.clear() for option in self.option_table: self.option_index[option[0]] = option def set_option_table(self, option_table): self.option_table = option_table self._build_index() def add_option(self, long_option, short_option=None, help_string=None): if long_option in self.option_index: raise DistutilsGetoptError( "option conflict: already an option '%s'" % long_option) else: option = (long_option, short_option, help_string) self.option_table.append(option) self.option_index[long_option] = option def has_option(self, long_option): """Return true if the option table for this parser has an option with long name 'long_option'.""" return long_option in self.option_index def get_attr_name(self, long_option): """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" return longopt_xlate(long_option) def _check_alias_dict(self, aliases, what): assert isinstance(aliases, dict) for (alias, opt) in aliases.items(): if alias not in self.option_index: raise DistutilsGetoptError(("invalid %s '%s': " "option '%s' not defined") % (what, alias, alias)) if opt not in self.option_index: raise DistutilsGetoptError(("invalid %s '%s': " "aliased option '%s' not defined") % (what, alias, opt)) def set_aliases(self, alias): """Set the aliases for this option parser.""" self._check_alias_dict(alias, "alias") self.alias = alias def set_negative_aliases(self, negative_alias): """Set the negative aliases for this option parser. 'negative_alias' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.""" self._check_alias_dict(negative_alias, "negative alias") self.negative_alias = negative_alias def _grok_option_table(self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. """ self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {} for option in self.option_table: if len(option) == 3: long, short, help = option repeat = 0 elif len(option) == 4: long, short, help, repeat = option else: # the option table is part of the code, so simply # assert that it is correct raise ValueError("invalid option tuple: %r" % (option,)) # Type- and value-check the option names if not isinstance(long, str) or len(long) < 2: raise DistutilsGetoptError(("invalid long option '%s': " "must be a string of length >= 2") % long) if (not ((short is None) or (isinstance(short, str) and len(short) == 1))): raise DistutilsGetoptError("invalid short option '%s': " "must a single character or None" % short) self.repeat[long] = repeat self.long_opts.append(long) if long[-1] == '=': # option takes an argument? if short: short = short + ':' long = long[0:-1] self.takes_arg[long] = 1 else: # Is option is a "negative alias" for some other option (eg. # "quiet" == "!verbose")? alias_to = self.negative_alias.get(long) if alias_to is not None: if self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid negative alias '%s': " "aliased option '%s' takes a value" % (long, alias_to)) self.long_opts[-1] = long # XXX redundant?! self.takes_arg[long] = 0 # If this is an alias option, make sure its "takes arg" flag is # the same as the option it's aliased to. alias_to = self.alias.get(long) if alias_to is not None: if self.takes_arg[long] != self.takes_arg[alias_to]: raise DistutilsGetoptError( "invalid alias '%s': inconsistent with " "aliased option '%s' (one of them takes a value, " "the other doesn't" % (long, alias_to)) # Now enforce some bondage on the long option name, so we can # later translate it to an attribute name on some object. Have # to do this a bit late to make sure we've removed any trailing # '='. if not longopt_re.match(long): raise DistutilsGetoptError( "invalid long option name '%s' " "(must be letters, numbers, hyphens only" % long) self.attr_name[long] = self.get_attr_name(long) if short: self.short_opts.append(short) self.short2long[short[0]] = long def getopt(self, args=None, object=None): """Parse command-line options in args. Store as attributes on object. If 'args' is None or not supplied, uses 'sys.argv[1:]'. If 'object' is None or not supplied, creates a new OptionDummy object, stores option values there, and returns a tuple (args, object). If 'object' is supplied, it is modified in place and 'getopt()' just returns 'args'; in both cases, the returned 'args' is a modified copy of the passed-in 'args' list, which is left untouched. """ if args is None: args = sys.argv[1:] if object is None: object = OptionDummy() created_object = True else: created_object = False self._grok_option_table() short_opts = ' '.join(self.short_opts) try: opts, args = getopt.getopt(args, short_opts, self.long_opts) except getopt.error as msg: raise DistutilsArgError(msg) for opt, val in opts: if len(opt) == 2 and opt[0] == '-': # it's a short option opt = self.short2long[opt[1]] else: assert len(opt) > 2 and opt[:2] == '--' opt = opt[2:] alias = self.alias.get(opt) if alias: opt = alias if not self.takes_arg[opt]: # boolean option? assert val == '', "boolean option can't have value" alias = self.negative_alias.get(opt) if alias: opt = alias val = 0 else: val = 1 attr = self.attr_name[opt] # The only repeating option at the moment is 'verbose'. # It has a negative option -q quiet, which should set verbose = 0. if val and self.repeat.get(attr) is not None: val = getattr(object, attr, 0) + 1 setattr(object, attr, val) self.option_order.append((opt, val)) # for opts if created_object: return args, object else: return args def get_option_order(self): """Returns the list of (option, value) tuples processed by the previous run of 'getopt()'. Raises RuntimeError if 'getopt()' hasn't been called yet. """ if self.option_order is None: raise RuntimeError("'getopt()' hasn't been called yet") else: return self.option_order def generate_help(self, header=None): """Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object. """ # Blithely assume the option table is good: probably wouldn't call # 'generate_help()' unless you've already called 'getopt()'. # First pass: determine maximum length of long option names max_opt = 0 for option in self.option_table: long = option[0] short = option[1] l = len(long) if long[-1] == '=': l = l - 1 if short is not None: l = l + 5 # " (-x)" where short == 'x' if l > max_opt: max_opt = l opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter # Typical help block looks like this: # --foo controls foonabulation # Help block for longest option looks like this: # --flimflam set the flim-flam level # and with wrapped text: # --flimflam set the flim-flam level (must be between # 0 and 100, except on Tuesdays) # Options with short names will have the short name shown (but # it doesn't contribute to max_opt): # --foo (-f) controls foonabulation # If adding the short option would make the left column too wide, # we push the explanation off to the next line # --flimflam (-l) # set the flim-flam level # Important parameters: # - 2 spaces before option block start lines # - 2 dashes for each long option name # - min. 2 spaces between option and explanation (gutter) # - 5 characters (incl. space) for short option name # Now generate lines of help text. (If 80 columns were good enough # for Jesus, then 78 columns are good enough for me!) line_width = 78 text_width = line_width - opt_width big_indent = ' ' * opt_width if header: lines = [header] else: lines = ['Option summary:'] for option in self.option_table: long, short, help = option[:3] text = wrap_text(help, text_width) if long[-1] == '=': long = long[0:-1] # Case 1: no short option at all (makes life easy) if short is None: if text: lines.append(" --%-*s %s" % (max_opt, long, text[0])) else: lines.append(" --%-*s " % (max_opt, long)) # Case 2: we have a short option, so we have to include it # just after the long option else: opt_names = "%s (-%s)" % (long, short) if text: lines.append(" --%-*s %s" % (max_opt, opt_names, text[0])) else: lines.append(" --%-*s" % opt_names) for l in text[1:]: lines.append(big_indent + l) return lines def print_help(self, header=None, file=None): if file is None: file = sys.stdout for line in self.generate_help(header): file.write(line + "\n") def fancy_getopt(options, negative_opt, object, args): parser = FancyGetopt(options) parser.set_negative_aliases(negative_opt) return parser.getopt(args, object) WS_TRANS = {ord(_wschar) : ' ' for _wschar in string.whitespace} def wrap_text(text, width): """wrap_text(text : string, width : int) -> [string] Split 'text' into multiple lines of no more than 'width' characters each, and return the list of strings that results. """ if text is None: return [] if len(text) <= width: return [text] text = text.expandtabs() text = text.translate(WS_TRANS) chunks = re.split(r'( +|-+)', text) chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings lines = [] while chunks: cur_line = [] # list of chunks (to-be-joined) cur_len = 0 # length of current line while chunks: l = len(chunks[0]) if cur_len + l <= width: # can squeeze (at least) this chunk in cur_line.append(chunks[0]) del chunks[0] cur_len = cur_len + l else: # this line is full # drop last chunk if all space if cur_line and cur_line[-1][0] == ' ': del cur_line[-1] break if chunks: # any chunks left to process? # if the current line is still empty, then we had a single # chunk that's too big too fit on a line -- so we break # down and break it up at the line width if cur_len == 0: cur_line.append(chunks[0][0:width]) chunks[0] = chunks[0][width:] # all-whitespace chunks at the end of a line can be discarded # (and we know from the re.split above that if a chunk has # *any* whitespace, it is *all* whitespace) if chunks[0][0] == ' ': del chunks[0] # and store this line in the list-of-all-lines -- as a single # string, of course! lines.append(''.join(cur_line)) return lines def translate_longopt(opt): """Convert a long option name to a valid Python identifier by changing "-" to "_". """ return longopt_xlate(opt) class OptionDummy: """Dummy class just used as a place to hold command-line option values as instance attributes.""" def __init__(self, options=[]): """Create a new OptionDummy instance. The attributes listed in 'options' will be initialized to None.""" for opt in options: setattr(self, opt, None) if __name__ == "__main__": text = """\ Tra-la-la, supercalifragilisticexpialidocious. How *do* you spell that odd word, anyways? (Someone ask Mary -- she'll know [or she'll say, "How should I know?"].)""" for w in (10, 20, 30, 40): print("width: %d" % w) print("\n".join(wrap_text(text, w))) print()
# These keep track of the information in the option table. We
random_line_split
dilatedcontext.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import tensorflow as tf from niftynet.layer import layer_util class DilatedTensor(object): """ This context manager makes a wrapper of input_tensor When created, the input_tensor is dilated, the input_tensor resumes to original space when exiting the context. """ def __init__(self, input_tensor, dilation_factor): assert (layer_util.check_spatial_dims( input_tensor, lambda x: x % dilation_factor == 0)) self._tensor = input_tensor self.dilation_factor = dilation_factor # parameters to transform input tensor self.spatial_rank = layer_util.infer_spatial_rank(self._tensor) self.zero_paddings = [[0, 0]] * self.spatial_rank self.block_shape = [dilation_factor] * self.spatial_rank def __enter__(self): if self.dilation_factor > 1: self._tensor = tf.space_to_batch_nd(self._tensor, self.block_shape, self.zero_paddings, name='dilated') return self def __exit__(self, *args): if self.dilation_factor > 1: self._tensor = tf.batch_to_space_nd(self._tensor, self.block_shape, self.zero_paddings, name='de-dilate') @property def tensor(self): return self._tensor @tensor.setter
self._tensor = value
def tensor(self, value):
random_line_split
dilatedcontext.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import tensorflow as tf from niftynet.layer import layer_util class DilatedTensor(object): """ This context manager makes a wrapper of input_tensor When created, the input_tensor is dilated, the input_tensor resumes to original space when exiting the context. """ def __init__(self, input_tensor, dilation_factor): assert (layer_util.check_spatial_dims( input_tensor, lambda x: x % dilation_factor == 0)) self._tensor = input_tensor self.dilation_factor = dilation_factor # parameters to transform input tensor self.spatial_rank = layer_util.infer_spatial_rank(self._tensor) self.zero_paddings = [[0, 0]] * self.spatial_rank self.block_shape = [dilation_factor] * self.spatial_rank def __enter__(self):
def __exit__(self, *args): if self.dilation_factor > 1: self._tensor = tf.batch_to_space_nd(self._tensor, self.block_shape, self.zero_paddings, name='de-dilate') @property def tensor(self): return self._tensor @tensor.setter def tensor(self, value): self._tensor = value
if self.dilation_factor > 1: self._tensor = tf.space_to_batch_nd(self._tensor, self.block_shape, self.zero_paddings, name='dilated') return self
identifier_body
dilatedcontext.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import tensorflow as tf from niftynet.layer import layer_util class DilatedTensor(object): """ This context manager makes a wrapper of input_tensor When created, the input_tensor is dilated, the input_tensor resumes to original space when exiting the context. """ def __init__(self, input_tensor, dilation_factor): assert (layer_util.check_spatial_dims( input_tensor, lambda x: x % dilation_factor == 0)) self._tensor = input_tensor self.dilation_factor = dilation_factor # parameters to transform input tensor self.spatial_rank = layer_util.infer_spatial_rank(self._tensor) self.zero_paddings = [[0, 0]] * self.spatial_rank self.block_shape = [dilation_factor] * self.spatial_rank def __enter__(self): if self.dilation_factor > 1: self._tensor = tf.space_to_batch_nd(self._tensor, self.block_shape, self.zero_paddings, name='dilated') return self def
(self, *args): if self.dilation_factor > 1: self._tensor = tf.batch_to_space_nd(self._tensor, self.block_shape, self.zero_paddings, name='de-dilate') @property def tensor(self): return self._tensor @tensor.setter def tensor(self, value): self._tensor = value
__exit__
identifier_name
dilatedcontext.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import tensorflow as tf from niftynet.layer import layer_util class DilatedTensor(object): """ This context manager makes a wrapper of input_tensor When created, the input_tensor is dilated, the input_tensor resumes to original space when exiting the context. """ def __init__(self, input_tensor, dilation_factor): assert (layer_util.check_spatial_dims( input_tensor, lambda x: x % dilation_factor == 0)) self._tensor = input_tensor self.dilation_factor = dilation_factor # parameters to transform input tensor self.spatial_rank = layer_util.infer_spatial_rank(self._tensor) self.zero_paddings = [[0, 0]] * self.spatial_rank self.block_shape = [dilation_factor] * self.spatial_rank def __enter__(self): if self.dilation_factor > 1:
return self def __exit__(self, *args): if self.dilation_factor > 1: self._tensor = tf.batch_to_space_nd(self._tensor, self.block_shape, self.zero_paddings, name='de-dilate') @property def tensor(self): return self._tensor @tensor.setter def tensor(self, value): self._tensor = value
self._tensor = tf.space_to_batch_nd(self._tensor, self.block_shape, self.zero_paddings, name='dilated')
conditional_block
device.detection.spec.ts
import { isiPhoneX, isiPhoneXR } from './device.detection'; describe('device-detection', () => { describe('iPhone', () => { it('10 mid string lowercase', () => { expect(isiPhoneX('blahiphone10blah')).toBe(true); }); it('10 not true', () => { expect(isiPhoneX('blahiphone11blah')).toBe(false); });
it('11 mid string lowercase', () => { expect(isiPhoneXR('blahiphone11blah')).toBe(true); }); it('11 not true', () => { expect(isiPhoneXR('blahiphone10blah')).toBe(false); }); it('11 proper string', () => { expect(isiPhoneXR('iPhone11,6')).toBe(true); }); }); });
it('10 proper string', () => { expect(isiPhoneX('iPhone10,6')).toBe(true); });
random_line_split
response.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Helpers for decoding and verifying responses for headers. use std::fmt; use ethcore::encoded; use ethcore::header::Header; use light::request::{HashOrNumber, CompleteHeadersRequest as HeadersRequest}; use rlp::DecoderError; use bigint::hash::H256; /// Errors found when decoding headers and verifying with basic constraints. #[derive(Debug, PartialEq)] pub enum BasicError { /// Wrong skip value: expected, found (if any). WrongSkip(u64, Option<u64>), /// Wrong start number. WrongStartNumber(u64, u64), /// Wrong start hash. WrongStartHash(H256, H256), /// Too many headers. TooManyHeaders(usize, usize), /// Decoder error. Decoder(DecoderError), } impl From<DecoderError> for BasicError { fn from(err: DecoderError) -> Self { BasicError::Decoder(err) } } impl fmt::Display for BasicError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Header response verification error: ")?; match *self { BasicError::WrongSkip(ref exp, ref got) => write!(f, "wrong skip (expected {}, got {:?})", exp, got), BasicError::WrongStartNumber(ref exp, ref got) => write!(f, "wrong start number (expected {}, got {})", exp, got), BasicError::WrongStartHash(ref exp, ref got) => write!(f, "wrong start hash (expected {}, got {})", exp, got), BasicError::TooManyHeaders(ref max, ref got) => write!(f, "too many headers (max {}, got {})", max, got), BasicError::Decoder(ref err) => write!(f, "{}", err), } } } /// Request verification constraint. pub trait Constraint { type Error; /// Verify headers against this. fn verify(&self, headers: &[Header], reverse: bool) -> Result<(), Self::Error>; } /// Do basic verification of provided headers against a request. pub fn verify(headers: &[encoded::Header], request: &HeadersRequest) -> Result<Vec<Header>, BasicError> { let headers: Vec<_> = headers.iter().map(|h| h.decode()).collect(); let reverse = request.reverse; Max(request.max as usize).verify(&headers, reverse)?; match request.start { HashOrNumber::Number(ref num) => StartsAtNumber(*num).verify(&headers, reverse)?, HashOrNumber::Hash(ref hash) => StartsAtHash(*hash).verify(&headers, reverse)?, } SkipsBetween(request.skip).verify(&headers, reverse)?; Ok(headers) } struct StartsAtNumber(u64); struct StartsAtHash(H256); struct SkipsBetween(u64); struct Max(usize); impl Constraint for StartsAtNumber { type Error = BasicError; fn verify(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { headers.first().map_or(Ok(()), |h| { if h.number() == self.0 { Ok(()) } else { Err(BasicError::WrongStartNumber(self.0, h.number())) } }) } } impl Constraint for StartsAtHash { type Error = BasicError; fn verify(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { headers.first().map_or(Ok(()), |h| { if h.hash() == self.0 { Ok(()) } else { Err(BasicError::WrongStartHash(self.0, h.hash())) } }) } } impl Constraint for SkipsBetween { type Error = BasicError; fn verify(&self, headers: &[Header], reverse: bool) -> Result<(), BasicError> { for pair in headers.windows(2) { let (low, high) = if reverse { (&pair[1], &pair[0]) } else { (&pair[0], &pair[1]) }; if low.number() >= high.number() { return Err(BasicError::WrongSkip(self.0, None)) } let skip = (high.number() - low.number()) - 1; if skip != self.0 { return Err(BasicError::WrongSkip(self.0, Some(skip))) } } Ok(()) } } impl Constraint for Max { type Error = BasicError; fn verify(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { match headers.len() > self.0 { true => Err(BasicError::TooManyHeaders(self.0, headers.len())), false => Ok(()) } } } #[cfg(test)] mod tests { use ethcore::encoded; use ethcore::header::Header; use light::request::CompleteHeadersRequest as HeadersRequest; use super::*; #[test] fn sequential_forward() { let request = HeadersRequest { start: 10.into(), max: 30, skip: 0, reverse: false, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert!(verify(&headers, &request).is_ok()); } #[test] fn sequential_backward() { let request = HeadersRequest { start: 34.into(), max: 30, skip: 0, reverse: true, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).rev().map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert!(verify(&headers, &request).is_ok()); } #[test] fn too_many() { let request = HeadersRequest { start: 10.into(), max: 20, skip: 0, reverse: false, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert_eq!(verify(&headers, &request), Err(BasicError::TooManyHeaders(20, 25))); } #[test] fn wrong_skip() { let request = HeadersRequest { start: 10.into(), max: 30, skip: 5, reverse: false, }; let headers: Vec<_> = (0..25).map(|x| x * 3).map(|x| x + 10).map(|x| {
assert_eq!(verify(&headers, &request), Err(BasicError::WrongSkip(5, Some(2)))); } }
let mut header = Header::default(); header.set_number(x); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect();
random_line_split
response.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Helpers for decoding and verifying responses for headers. use std::fmt; use ethcore::encoded; use ethcore::header::Header; use light::request::{HashOrNumber, CompleteHeadersRequest as HeadersRequest}; use rlp::DecoderError; use bigint::hash::H256; /// Errors found when decoding headers and verifying with basic constraints. #[derive(Debug, PartialEq)] pub enum BasicError { /// Wrong skip value: expected, found (if any). WrongSkip(u64, Option<u64>), /// Wrong start number. WrongStartNumber(u64, u64), /// Wrong start hash. WrongStartHash(H256, H256), /// Too many headers. TooManyHeaders(usize, usize), /// Decoder error. Decoder(DecoderError), } impl From<DecoderError> for BasicError { fn from(err: DecoderError) -> Self { BasicError::Decoder(err) } } impl fmt::Display for BasicError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Header response verification error: ")?; match *self { BasicError::WrongSkip(ref exp, ref got) => write!(f, "wrong skip (expected {}, got {:?})", exp, got), BasicError::WrongStartNumber(ref exp, ref got) => write!(f, "wrong start number (expected {}, got {})", exp, got), BasicError::WrongStartHash(ref exp, ref got) => write!(f, "wrong start hash (expected {}, got {})", exp, got), BasicError::TooManyHeaders(ref max, ref got) => write!(f, "too many headers (max {}, got {})", max, got), BasicError::Decoder(ref err) => write!(f, "{}", err), } } } /// Request verification constraint. pub trait Constraint { type Error; /// Verify headers against this. fn verify(&self, headers: &[Header], reverse: bool) -> Result<(), Self::Error>; } /// Do basic verification of provided headers against a request. pub fn verify(headers: &[encoded::Header], request: &HeadersRequest) -> Result<Vec<Header>, BasicError> { let headers: Vec<_> = headers.iter().map(|h| h.decode()).collect(); let reverse = request.reverse; Max(request.max as usize).verify(&headers, reverse)?; match request.start { HashOrNumber::Number(ref num) => StartsAtNumber(*num).verify(&headers, reverse)?, HashOrNumber::Hash(ref hash) => StartsAtHash(*hash).verify(&headers, reverse)?, } SkipsBetween(request.skip).verify(&headers, reverse)?; Ok(headers) } struct StartsAtNumber(u64); struct StartsAtHash(H256); struct SkipsBetween(u64); struct Max(usize); impl Constraint for StartsAtNumber { type Error = BasicError; fn verify(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { headers.first().map_or(Ok(()), |h| { if h.number() == self.0 { Ok(()) } else { Err(BasicError::WrongStartNumber(self.0, h.number())) } }) } } impl Constraint for StartsAtHash { type Error = BasicError; fn verify(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { headers.first().map_or(Ok(()), |h| { if h.hash() == self.0 { Ok(()) } else { Err(BasicError::WrongStartHash(self.0, h.hash())) } }) } } impl Constraint for SkipsBetween { type Error = BasicError; fn verify(&self, headers: &[Header], reverse: bool) -> Result<(), BasicError> { for pair in headers.windows(2) { let (low, high) = if reverse { (&pair[1], &pair[0]) } else { (&pair[0], &pair[1]) }; if low.number() >= high.number() { return Err(BasicError::WrongSkip(self.0, None)) } let skip = (high.number() - low.number()) - 1; if skip != self.0 { return Err(BasicError::WrongSkip(self.0, Some(skip))) } } Ok(()) } } impl Constraint for Max { type Error = BasicError; fn
(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { match headers.len() > self.0 { true => Err(BasicError::TooManyHeaders(self.0, headers.len())), false => Ok(()) } } } #[cfg(test)] mod tests { use ethcore::encoded; use ethcore::header::Header; use light::request::CompleteHeadersRequest as HeadersRequest; use super::*; #[test] fn sequential_forward() { let request = HeadersRequest { start: 10.into(), max: 30, skip: 0, reverse: false, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert!(verify(&headers, &request).is_ok()); } #[test] fn sequential_backward() { let request = HeadersRequest { start: 34.into(), max: 30, skip: 0, reverse: true, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).rev().map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert!(verify(&headers, &request).is_ok()); } #[test] fn too_many() { let request = HeadersRequest { start: 10.into(), max: 20, skip: 0, reverse: false, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert_eq!(verify(&headers, &request), Err(BasicError::TooManyHeaders(20, 25))); } #[test] fn wrong_skip() { let request = HeadersRequest { start: 10.into(), max: 30, skip: 5, reverse: false, }; let headers: Vec<_> = (0..25).map(|x| x * 3).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert_eq!(verify(&headers, &request), Err(BasicError::WrongSkip(5, Some(2)))); } }
verify
identifier_name
response.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Helpers for decoding and verifying responses for headers. use std::fmt; use ethcore::encoded; use ethcore::header::Header; use light::request::{HashOrNumber, CompleteHeadersRequest as HeadersRequest}; use rlp::DecoderError; use bigint::hash::H256; /// Errors found when decoding headers and verifying with basic constraints. #[derive(Debug, PartialEq)] pub enum BasicError { /// Wrong skip value: expected, found (if any). WrongSkip(u64, Option<u64>), /// Wrong start number. WrongStartNumber(u64, u64), /// Wrong start hash. WrongStartHash(H256, H256), /// Too many headers. TooManyHeaders(usize, usize), /// Decoder error. Decoder(DecoderError), } impl From<DecoderError> for BasicError { fn from(err: DecoderError) -> Self { BasicError::Decoder(err) } } impl fmt::Display for BasicError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Header response verification error: ")?; match *self { BasicError::WrongSkip(ref exp, ref got) => write!(f, "wrong skip (expected {}, got {:?})", exp, got), BasicError::WrongStartNumber(ref exp, ref got) => write!(f, "wrong start number (expected {}, got {})", exp, got), BasicError::WrongStartHash(ref exp, ref got) => write!(f, "wrong start hash (expected {}, got {})", exp, got), BasicError::TooManyHeaders(ref max, ref got) => write!(f, "too many headers (max {}, got {})", max, got), BasicError::Decoder(ref err) => write!(f, "{}", err), } } } /// Request verification constraint. pub trait Constraint { type Error; /// Verify headers against this. fn verify(&self, headers: &[Header], reverse: bool) -> Result<(), Self::Error>; } /// Do basic verification of provided headers against a request. pub fn verify(headers: &[encoded::Header], request: &HeadersRequest) -> Result<Vec<Header>, BasicError> { let headers: Vec<_> = headers.iter().map(|h| h.decode()).collect(); let reverse = request.reverse; Max(request.max as usize).verify(&headers, reverse)?; match request.start { HashOrNumber::Number(ref num) => StartsAtNumber(*num).verify(&headers, reverse)?, HashOrNumber::Hash(ref hash) => StartsAtHash(*hash).verify(&headers, reverse)?, } SkipsBetween(request.skip).verify(&headers, reverse)?; Ok(headers) } struct StartsAtNumber(u64); struct StartsAtHash(H256); struct SkipsBetween(u64); struct Max(usize); impl Constraint for StartsAtNumber { type Error = BasicError; fn verify(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { headers.first().map_or(Ok(()), |h| { if h.number() == self.0 { Ok(()) } else { Err(BasicError::WrongStartNumber(self.0, h.number())) } }) } } impl Constraint for StartsAtHash { type Error = BasicError; fn verify(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { headers.first().map_or(Ok(()), |h| { if h.hash() == self.0 { Ok(()) } else { Err(BasicError::WrongStartHash(self.0, h.hash())) } }) } } impl Constraint for SkipsBetween { type Error = BasicError; fn verify(&self, headers: &[Header], reverse: bool) -> Result<(), BasicError> { for pair in headers.windows(2) { let (low, high) = if reverse { (&pair[1], &pair[0]) } else { (&pair[0], &pair[1]) }; if low.number() >= high.number() { return Err(BasicError::WrongSkip(self.0, None)) } let skip = (high.number() - low.number()) - 1; if skip != self.0 { return Err(BasicError::WrongSkip(self.0, Some(skip))) } } Ok(()) } } impl Constraint for Max { type Error = BasicError; fn verify(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { match headers.len() > self.0 { true => Err(BasicError::TooManyHeaders(self.0, headers.len())), false => Ok(()) } } } #[cfg(test)] mod tests { use ethcore::encoded; use ethcore::header::Header; use light::request::CompleteHeadersRequest as HeadersRequest; use super::*; #[test] fn sequential_forward()
#[test] fn sequential_backward() { let request = HeadersRequest { start: 34.into(), max: 30, skip: 0, reverse: true, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).rev().map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert!(verify(&headers, &request).is_ok()); } #[test] fn too_many() { let request = HeadersRequest { start: 10.into(), max: 20, skip: 0, reverse: false, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert_eq!(verify(&headers, &request), Err(BasicError::TooManyHeaders(20, 25))); } #[test] fn wrong_skip() { let request = HeadersRequest { start: 10.into(), max: 30, skip: 5, reverse: false, }; let headers: Vec<_> = (0..25).map(|x| x * 3).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert_eq!(verify(&headers, &request), Err(BasicError::WrongSkip(5, Some(2)))); } }
{ let request = HeadersRequest { start: 10.into(), max: 30, skip: 0, reverse: false, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_parent_hash(parent_hash); } parent_hash = Some(header.hash()); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect(); assert!(verify(&headers, &request).is_ok()); }
identifier_body
perlin_2d_colors.rs
#![feature(old_path)] extern crate image; extern crate noise;
use std::num::Float; fn to_color(value: f64, factor: f64) -> u8 { let mut v = value.abs(); if v > 255.0 { v = 255.0 } (v * factor) as u8 } fn main() { let amp = 255.0; let f = 0.01; let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6); let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6); let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6); let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| { let p = (x as f64, y as f64); Rgb([ to_color(noise_r.value(p), 1.0), to_color(noise_g.value(p), 1.0), to_color(noise_b.value(p), 1.0) ]) }); match image.save(&Path::new("output.png")) { Err(e) => panic!("Could not write file! {}", e), Ok(..) => {}, }; }
extern crate rand; use image::{ImageBuffer, Rgb}; use noise::Noise; use noise::blocks::new_perlin_noise_2d;
random_line_split
perlin_2d_colors.rs
#![feature(old_path)] extern crate image; extern crate noise; extern crate rand; use image::{ImageBuffer, Rgb}; use noise::Noise; use noise::blocks::new_perlin_noise_2d; use std::num::Float; fn to_color(value: f64, factor: f64) -> u8 { let mut v = value.abs(); if v > 255.0 { v = 255.0 } (v * factor) as u8 } fn
() { let amp = 255.0; let f = 0.01; let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6); let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6); let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6); let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| { let p = (x as f64, y as f64); Rgb([ to_color(noise_r.value(p), 1.0), to_color(noise_g.value(p), 1.0), to_color(noise_b.value(p), 1.0) ]) }); match image.save(&Path::new("output.png")) { Err(e) => panic!("Could not write file! {}", e), Ok(..) => {}, }; }
main
identifier_name
perlin_2d_colors.rs
#![feature(old_path)] extern crate image; extern crate noise; extern crate rand; use image::{ImageBuffer, Rgb}; use noise::Noise; use noise::blocks::new_perlin_noise_2d; use std::num::Float; fn to_color(value: f64, factor: f64) -> u8
fn main() { let amp = 255.0; let f = 0.01; let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6); let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6); let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6); let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| { let p = (x as f64, y as f64); Rgb([ to_color(noise_r.value(p), 1.0), to_color(noise_g.value(p), 1.0), to_color(noise_b.value(p), 1.0) ]) }); match image.save(&Path::new("output.png")) { Err(e) => panic!("Could not write file! {}", e), Ok(..) => {}, }; }
{ let mut v = value.abs(); if v > 255.0 { v = 255.0 } (v * factor) as u8 }
identifier_body
perlin_2d_colors.rs
#![feature(old_path)] extern crate image; extern crate noise; extern crate rand; use image::{ImageBuffer, Rgb}; use noise::Noise; use noise::blocks::new_perlin_noise_2d; use std::num::Float; fn to_color(value: f64, factor: f64) -> u8 { let mut v = value.abs(); if v > 255.0
(v * factor) as u8 } fn main() { let amp = 255.0; let f = 0.01; let noise_r = new_perlin_noise_2d(rand::random(), amp, f, 6); let noise_g = new_perlin_noise_2d(rand::random(), amp, f, 6); let noise_b = new_perlin_noise_2d(rand::random(), amp, f, 6); let image = ImageBuffer::from_fn(128, 128, |x: u32, y: u32| { let p = (x as f64, y as f64); Rgb([ to_color(noise_r.value(p), 1.0), to_color(noise_g.value(p), 1.0), to_color(noise_b.value(p), 1.0) ]) }); match image.save(&Path::new("output.png")) { Err(e) => panic!("Could not write file! {}", e), Ok(..) => {}, }; }
{ v = 255.0 }
conditional_block
bootstrap.py
import percolation as P import rdflib as r import os import time from rdflib import ConjunctiveGraph TT = time.time() class PercolationServer: def __init__(self, percolationdir="~/.percolation/"): percolationdir = os.path.expanduser(percolationdir) if not os.path.isdir(percolationdir): os.mkdir(percolationdir)
try: percolation_graph.open(dbdir, create=False) except: # get exception type (?) percolation_graph.open(dbdir, create=True) P.percolation_graph = percolation_graph self.percolation_graph = percolation_graph P.percolation_server = self endpoint_url_ = os.getenv("PERCOLATION_ENDPOINT") P.client = None def start(start_session=True, endpoint_url=endpoint_url_): """Startup routine""" c("endpoint url", endpoint_url) if endpoint_url: P.client = P.rdf.sparql.Client(endpoint_url) else: P.client = None PercolationServer() if start_session: P.utils.startSession() # P.utils.aaSession() def close(): # duplicate in legacy/outlines.py P.percolation_graph.close() def check(*args): global TT if not P.QUIET: if args and isinstance(args[0], str) \ and (len(args[0]) == args[0].count("\n")): print("{}{:.3f}".format(args[0], time.time()-TT), *args[1:]) TT = time.time() else: print("{:.3f}".format(time.time()-TT), *args) TT = time.time() if args[0] == "prompt": input("ANY KEY TO CONTINUE") QUIET = False c = check if __name__ == "__main__": start() rdflibok = isinstance(P.percolation_graph, r.ConjunctiveGraph) ntriples = len(P.percolation_graph) c("rdflib in P.percolation_graph:", rdflibok, "ntriples:", ntriples) if endpoint_url_: ntriples = P.client.getNTriples() ngraphs = P.client.getNGraphs() c("connected to endpoint:", endpoint_url_, "with {} graphs \ and {} triples".format(ngraphs, ntriples)) else: c("not connected to any remote endpoint\n\ (relying only on rdflib percolation_graph)") choice = input("print graphs (y/N)") if choice == "y": graphs = P.client.getAllGraphs() ntriples_ = [] for graph in graphs: ntriples_ += [P.client.getNTriples(graph)] c(list(zip(ntriples_, graphs))) choice = input("print triples (y/N)") if choice == "y": c(P.client.getAllTriples())
dbdir = percolationdir+"sleepydb/" if not os.path.isdir(dbdir): os.mkdir(dbdir) percolation_graph = ConjunctiveGraph(store="Sleepycat")
random_line_split
bootstrap.py
import percolation as P import rdflib as r import os import time from rdflib import ConjunctiveGraph TT = time.time() class PercolationServer: def __init__(self, percolationdir="~/.percolation/"): percolationdir = os.path.expanduser(percolationdir) if not os.path.isdir(percolationdir): os.mkdir(percolationdir) dbdir = percolationdir+"sleepydb/" if not os.path.isdir(dbdir): os.mkdir(dbdir) percolation_graph = ConjunctiveGraph(store="Sleepycat") try: percolation_graph.open(dbdir, create=False) except: # get exception type (?) percolation_graph.open(dbdir, create=True) P.percolation_graph = percolation_graph self.percolation_graph = percolation_graph P.percolation_server = self endpoint_url_ = os.getenv("PERCOLATION_ENDPOINT") P.client = None def start(start_session=True, endpoint_url=endpoint_url_):
# P.utils.aaSession() def close(): # duplicate in legacy/outlines.py P.percolation_graph.close() def check(*args): global TT if not P.QUIET: if args and isinstance(args[0], str) \ and (len(args[0]) == args[0].count("\n")): print("{}{:.3f}".format(args[0], time.time()-TT), *args[1:]) TT = time.time() else: print("{:.3f}".format(time.time()-TT), *args) TT = time.time() if args[0] == "prompt": input("ANY KEY TO CONTINUE") QUIET = False c = check if __name__ == "__main__": start() rdflibok = isinstance(P.percolation_graph, r.ConjunctiveGraph) ntriples = len(P.percolation_graph) c("rdflib in P.percolation_graph:", rdflibok, "ntriples:", ntriples) if endpoint_url_: ntriples = P.client.getNTriples() ngraphs = P.client.getNGraphs() c("connected to endpoint:", endpoint_url_, "with {} graphs \ and {} triples".format(ngraphs, ntriples)) else: c("not connected to any remote endpoint\n\ (relying only on rdflib percolation_graph)") choice = input("print graphs (y/N)") if choice == "y": graphs = P.client.getAllGraphs() ntriples_ = [] for graph in graphs: ntriples_ += [P.client.getNTriples(graph)] c(list(zip(ntriples_, graphs))) choice = input("print triples (y/N)") if choice == "y": c(P.client.getAllTriples())
"""Startup routine""" c("endpoint url", endpoint_url) if endpoint_url: P.client = P.rdf.sparql.Client(endpoint_url) else: P.client = None PercolationServer() if start_session: P.utils.startSession()
identifier_body
bootstrap.py
import percolation as P import rdflib as r import os import time from rdflib import ConjunctiveGraph TT = time.time() class PercolationServer: def __init__(self, percolationdir="~/.percolation/"): percolationdir = os.path.expanduser(percolationdir) if not os.path.isdir(percolationdir): os.mkdir(percolationdir) dbdir = percolationdir+"sleepydb/" if not os.path.isdir(dbdir): os.mkdir(dbdir) percolation_graph = ConjunctiveGraph(store="Sleepycat") try: percolation_graph.open(dbdir, create=False) except: # get exception type (?) percolation_graph.open(dbdir, create=True) P.percolation_graph = percolation_graph self.percolation_graph = percolation_graph P.percolation_server = self endpoint_url_ = os.getenv("PERCOLATION_ENDPOINT") P.client = None def start(start_session=True, endpoint_url=endpoint_url_): """Startup routine""" c("endpoint url", endpoint_url) if endpoint_url: P.client = P.rdf.sparql.Client(endpoint_url) else: P.client = None PercolationServer() if start_session: P.utils.startSession() # P.utils.aaSession() def close(): # duplicate in legacy/outlines.py P.percolation_graph.close() def check(*args): global TT if not P.QUIET: if args and isinstance(args[0], str) \ and (len(args[0]) == args[0].count("\n")): print("{}{:.3f}".format(args[0], time.time()-TT), *args[1:]) TT = time.time() else: print("{:.3f}".format(time.time()-TT), *args) TT = time.time() if args[0] == "prompt": input("ANY KEY TO CONTINUE") QUIET = False c = check if __name__ == "__main__": start() rdflibok = isinstance(P.percolation_graph, r.ConjunctiveGraph) ntriples = len(P.percolation_graph) c("rdflib in P.percolation_graph:", rdflibok, "ntriples:", ntriples) if endpoint_url_: ntriples = P.client.getNTriples() ngraphs = P.client.getNGraphs() c("connected to endpoint:", endpoint_url_, "with {} graphs \ and {} triples".format(ngraphs, ntriples)) else: c("not connected to any remote endpoint\n\ (relying only on rdflib percolation_graph)") choice = input("print graphs (y/N)") if choice == "y": graphs = P.client.getAllGraphs() ntriples_ = [] for graph in graphs:
c(list(zip(ntriples_, graphs))) choice = input("print triples (y/N)") if choice == "y": c(P.client.getAllTriples())
ntriples_ += [P.client.getNTriples(graph)]
conditional_block
bootstrap.py
import percolation as P import rdflib as r import os import time from rdflib import ConjunctiveGraph TT = time.time() class PercolationServer: def __init__(self, percolationdir="~/.percolation/"): percolationdir = os.path.expanduser(percolationdir) if not os.path.isdir(percolationdir): os.mkdir(percolationdir) dbdir = percolationdir+"sleepydb/" if not os.path.isdir(dbdir): os.mkdir(dbdir) percolation_graph = ConjunctiveGraph(store="Sleepycat") try: percolation_graph.open(dbdir, create=False) except: # get exception type (?) percolation_graph.open(dbdir, create=True) P.percolation_graph = percolation_graph self.percolation_graph = percolation_graph P.percolation_server = self endpoint_url_ = os.getenv("PERCOLATION_ENDPOINT") P.client = None def start(start_session=True, endpoint_url=endpoint_url_): """Startup routine""" c("endpoint url", endpoint_url) if endpoint_url: P.client = P.rdf.sparql.Client(endpoint_url) else: P.client = None PercolationServer() if start_session: P.utils.startSession() # P.utils.aaSession() def
(): # duplicate in legacy/outlines.py P.percolation_graph.close() def check(*args): global TT if not P.QUIET: if args and isinstance(args[0], str) \ and (len(args[0]) == args[0].count("\n")): print("{}{:.3f}".format(args[0], time.time()-TT), *args[1:]) TT = time.time() else: print("{:.3f}".format(time.time()-TT), *args) TT = time.time() if args[0] == "prompt": input("ANY KEY TO CONTINUE") QUIET = False c = check if __name__ == "__main__": start() rdflibok = isinstance(P.percolation_graph, r.ConjunctiveGraph) ntriples = len(P.percolation_graph) c("rdflib in P.percolation_graph:", rdflibok, "ntriples:", ntriples) if endpoint_url_: ntriples = P.client.getNTriples() ngraphs = P.client.getNGraphs() c("connected to endpoint:", endpoint_url_, "with {} graphs \ and {} triples".format(ngraphs, ntriples)) else: c("not connected to any remote endpoint\n\ (relying only on rdflib percolation_graph)") choice = input("print graphs (y/N)") if choice == "y": graphs = P.client.getAllGraphs() ntriples_ = [] for graph in graphs: ntriples_ += [P.client.getNTriples(graph)] c(list(zip(ntriples_, graphs))) choice = input("print triples (y/N)") if choice == "y": c(P.client.getAllTriples())
close
identifier_name
settings.py
from __future__ import absolute_import import os DEBUG = True BASE_DIR = os.path.dirname(__file__) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' AUTH_PASSWORD_VALIDATORS = [{'NAME': 'testapp.validators.Is666'}] SECRET_KEY = '_' MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', ] INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'templated_mail', 'rest_framework', 'rest_framework.authtoken', 'djoser', 'social_django', 'testapp', ) STATIC_URL = '/static/'
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ), } ROOT_URLCONF = 'urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }, ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'djoser.social.backends.facebook.FacebookOAuth2Override', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.steam.SteamOpenId', ] SOCIAL_AUTH_FACEBOOK_KEY = os.environ.get('FACEBOOK_KEY', '') SOCIAL_AUTH_FACEBOOK_SECRET = os.environ.get('FACEBOOK_SECRET', '') SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } SOCIAL_AUTH_STEAM_API_KEY = os.environ.get('STEAM_API_KEY', '') SOCIAL_AUTH_OPENID_TRUST_ROOT = 'http://test.localhost/' DJOSER = { 'SEND_ACTIVATION_EMAIL': False, 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': ['http://test.localhost/'] } JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, }
random_line_split
main.rs
#![feature(plugin, rustc_private)] #![plugin(docopt_macros)] extern crate cargo; extern crate docopt; extern crate graphviz; extern crate rustc_serialize; use cargo::core::{Resolve, SourceId, PackageId}; use graphviz as dot; use std::borrow::{Cow}; use std::convert::Into; use std::env; use std::io; use std::io::Write; use std::fs::File; use std::path::{Path, PathBuf}; docopt!(Flags, " Generate a graph of package dependencies in graphviz format
cargo dot --help Options: -h, --help Show this message -V, --version Print version info and exit --lock-file=FILE Specify location of input file, default \"Cargo.lock\" --dot-file=FILE Output to file, default prints to stdout --source-labels Use sources for the label instead of package names "); fn main() { let mut argv: Vec<String> = env::args().collect(); if argv.len() > 0 { argv[0] = "cargo".to_string(); } let flags: Flags = Flags::docopt() // cargo passes the exe name first, so we skip it .argv(argv.into_iter()) .version(Some("0.2".to_string())) .decode() .unwrap_or_else(|e| e.exit()); let dot_f_flag = if flags.flag_dot_file.is_empty() { None } else { Some(flags.flag_dot_file) }; let source_labels = flags.flag_source_labels; let lock_path = unless_empty(flags.flag_lock_file, "Cargo.lock"); let lock_path = Path::new(&lock_path); let lock_path_buf = absolutize(lock_path.to_path_buf()); let lock_path = lock_path_buf.as_path(); let proj_dir = lock_path.parent().unwrap(); // TODO: check for None let src_id = SourceId::for_path(&proj_dir).unwrap(); let resolved = cargo::ops::load_lockfile(&lock_path, &src_id).unwrap() .expect("Lock file not found."); let mut graph = Graph::with_root(resolved.root(), source_labels); graph.add_dependencies(&resolved); match dot_f_flag { None => graph.render_to(&mut io::stdout()), Some(dot_file) => graph.render_to(&mut File::create(&Path::new(&dot_file)).unwrap()) }; } fn absolutize(pb: PathBuf) -> PathBuf { if pb.as_path().is_absolute() { pb } else { std::env::current_dir().unwrap().join(&pb.as_path()).clone() } } fn unless_empty(s: String, default: &str) -> String { if s.is_empty() { default.to_string() } else { s } } pub type Nd = usize; pub type Ed = (usize, usize); pub struct Graph<'a> { nodes: Vec<&'a PackageId>, edges: Vec<Ed>, source_labels: bool } impl<'a> Graph<'a> { pub fn with_root(root: &PackageId, source_labels: bool) -> Graph { Graph { nodes: vec![root], edges: vec![], source_labels: source_labels } } pub fn add_dependencies(&mut self, resolved: &'a Resolve) { for crat in resolved.iter() { match resolved.deps(crat) { Some(crate_deps) => { let idl = self.find_or_add(crat); for dep in crate_deps { let idr = self.find_or_add(dep); self.edges.push((idl, idr)); }; }, None => { } } } } fn find_or_add(&mut self, new: &'a PackageId) -> usize { for (i, id) in self.nodes.iter().enumerate() { if *id == new { return i } } self.nodes.push(new); self.nodes.len() - 1 } pub fn render_to<W:Write>(&'a self, output: &mut W) { match dot::render(self, output) { Ok(_) => {}, Err(e) => panic!("error rendering graph: {}", e) } } } impl<'a> dot::Labeller<'a, Nd, Ed> for Graph<'a> { fn graph_id(&self) -> dot::Id<'a> { dot::Id::new(self.nodes[0].name()).unwrap_or(dot::Id::new("dependencies").unwrap()) } fn node_id(&self, n: &Nd) -> dot::Id { // unwrap is safe because N######## is a valid graphviz id dot::Id::new(format!("N{}", *n)).unwrap() } fn node_label(&'a self, i: &Nd) -> dot::LabelText<'a> { if !self.source_labels { dot::LabelText::LabelStr(self.nodes[*i].name().into()) } else { dot::LabelText::LabelStr(self.nodes[*i].source_id().url().to_string().into()) } } } impl<'a> dot::GraphWalk<'a, Nd, Ed> for Graph<'a> { fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() } fn edges(&self) -> dot::Edges<Ed> { Cow::Borrowed(&self.edges[..]) } fn source(&self, &(s, _): &Ed) -> Nd { s } fn target(&self, &(_, t): &Ed) -> Nd { t } }
Usage: cargo dot [options]
random_line_split
main.rs
#![feature(plugin, rustc_private)] #![plugin(docopt_macros)] extern crate cargo; extern crate docopt; extern crate graphviz; extern crate rustc_serialize; use cargo::core::{Resolve, SourceId, PackageId}; use graphviz as dot; use std::borrow::{Cow}; use std::convert::Into; use std::env; use std::io; use std::io::Write; use std::fs::File; use std::path::{Path, PathBuf}; docopt!(Flags, " Generate a graph of package dependencies in graphviz format Usage: cargo dot [options] cargo dot --help Options: -h, --help Show this message -V, --version Print version info and exit --lock-file=FILE Specify location of input file, default \"Cargo.lock\" --dot-file=FILE Output to file, default prints to stdout --source-labels Use sources for the label instead of package names "); fn main()
fn absolutize(pb: PathBuf) -> PathBuf { if pb.as_path().is_absolute() { pb } else { std::env::current_dir().unwrap().join(&pb.as_path()).clone() } } fn unless_empty(s: String, default: &str) -> String { if s.is_empty() { default.to_string() } else { s } } pub type Nd = usize; pub type Ed = (usize, usize); pub struct Graph<'a> { nodes: Vec<&'a PackageId>, edges: Vec<Ed>, source_labels: bool } impl<'a> Graph<'a> { pub fn with_root(root: &PackageId, source_labels: bool) -> Graph { Graph { nodes: vec![root], edges: vec![], source_labels: source_labels } } pub fn add_dependencies(&mut self, resolved: &'a Resolve) { for crat in resolved.iter() { match resolved.deps(crat) { Some(crate_deps) => { let idl = self.find_or_add(crat); for dep in crate_deps { let idr = self.find_or_add(dep); self.edges.push((idl, idr)); }; }, None => { } } } } fn find_or_add(&mut self, new: &'a PackageId) -> usize { for (i, id) in self.nodes.iter().enumerate() { if *id == new { return i } } self.nodes.push(new); self.nodes.len() - 1 } pub fn render_to<W:Write>(&'a self, output: &mut W) { match dot::render(self, output) { Ok(_) => {}, Err(e) => panic!("error rendering graph: {}", e) } } } impl<'a> dot::Labeller<'a, Nd, Ed> for Graph<'a> { fn graph_id(&self) -> dot::Id<'a> { dot::Id::new(self.nodes[0].name()).unwrap_or(dot::Id::new("dependencies").unwrap()) } fn node_id(&self, n: &Nd) -> dot::Id { // unwrap is safe because N######## is a valid graphviz id dot::Id::new(format!("N{}", *n)).unwrap() } fn node_label(&'a self, i: &Nd) -> dot::LabelText<'a> { if !self.source_labels { dot::LabelText::LabelStr(self.nodes[*i].name().into()) } else { dot::LabelText::LabelStr(self.nodes[*i].source_id().url().to_string().into()) } } } impl<'a> dot::GraphWalk<'a, Nd, Ed> for Graph<'a> { fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() } fn edges(&self) -> dot::Edges<Ed> { Cow::Borrowed(&self.edges[..]) } fn source(&self, &(s, _): &Ed) -> Nd { s } fn target(&self, &(_, t): &Ed) -> Nd { t } }
{ let mut argv: Vec<String> = env::args().collect(); if argv.len() > 0 { argv[0] = "cargo".to_string(); } let flags: Flags = Flags::docopt() // cargo passes the exe name first, so we skip it .argv(argv.into_iter()) .version(Some("0.2".to_string())) .decode() .unwrap_or_else(|e| e.exit()); let dot_f_flag = if flags.flag_dot_file.is_empty() { None } else { Some(flags.flag_dot_file) }; let source_labels = flags.flag_source_labels; let lock_path = unless_empty(flags.flag_lock_file, "Cargo.lock"); let lock_path = Path::new(&lock_path); let lock_path_buf = absolutize(lock_path.to_path_buf()); let lock_path = lock_path_buf.as_path(); let proj_dir = lock_path.parent().unwrap(); // TODO: check for None let src_id = SourceId::for_path(&proj_dir).unwrap(); let resolved = cargo::ops::load_lockfile(&lock_path, &src_id).unwrap() .expect("Lock file not found."); let mut graph = Graph::with_root(resolved.root(), source_labels); graph.add_dependencies(&resolved); match dot_f_flag { None => graph.render_to(&mut io::stdout()), Some(dot_file) => graph.render_to(&mut File::create(&Path::new(&dot_file)).unwrap()) }; }
identifier_body
main.rs
#![feature(plugin, rustc_private)] #![plugin(docopt_macros)] extern crate cargo; extern crate docopt; extern crate graphviz; extern crate rustc_serialize; use cargo::core::{Resolve, SourceId, PackageId}; use graphviz as dot; use std::borrow::{Cow}; use std::convert::Into; use std::env; use std::io; use std::io::Write; use std::fs::File; use std::path::{Path, PathBuf}; docopt!(Flags, " Generate a graph of package dependencies in graphviz format Usage: cargo dot [options] cargo dot --help Options: -h, --help Show this message -V, --version Print version info and exit --lock-file=FILE Specify location of input file, default \"Cargo.lock\" --dot-file=FILE Output to file, default prints to stdout --source-labels Use sources for the label instead of package names "); fn main() { let mut argv: Vec<String> = env::args().collect(); if argv.len() > 0 { argv[0] = "cargo".to_string(); } let flags: Flags = Flags::docopt() // cargo passes the exe name first, so we skip it .argv(argv.into_iter()) .version(Some("0.2".to_string())) .decode() .unwrap_or_else(|e| e.exit()); let dot_f_flag = if flags.flag_dot_file.is_empty() { None } else { Some(flags.flag_dot_file) }; let source_labels = flags.flag_source_labels; let lock_path = unless_empty(flags.flag_lock_file, "Cargo.lock"); let lock_path = Path::new(&lock_path); let lock_path_buf = absolutize(lock_path.to_path_buf()); let lock_path = lock_path_buf.as_path(); let proj_dir = lock_path.parent().unwrap(); // TODO: check for None let src_id = SourceId::for_path(&proj_dir).unwrap(); let resolved = cargo::ops::load_lockfile(&lock_path, &src_id).unwrap() .expect("Lock file not found."); let mut graph = Graph::with_root(resolved.root(), source_labels); graph.add_dependencies(&resolved); match dot_f_flag { None => graph.render_to(&mut io::stdout()), Some(dot_file) => graph.render_to(&mut File::create(&Path::new(&dot_file)).unwrap()) }; } fn absolutize(pb: PathBuf) -> PathBuf { if pb.as_path().is_absolute() { pb } else { std::env::current_dir().unwrap().join(&pb.as_path()).clone() } } fn unless_empty(s: String, default: &str) -> String { if s.is_empty() { default.to_string() } else { s } } pub type Nd = usize; pub type Ed = (usize, usize); pub struct Graph<'a> { nodes: Vec<&'a PackageId>, edges: Vec<Ed>, source_labels: bool } impl<'a> Graph<'a> { pub fn with_root(root: &PackageId, source_labels: bool) -> Graph { Graph { nodes: vec![root], edges: vec![], source_labels: source_labels } } pub fn add_dependencies(&mut self, resolved: &'a Resolve) { for crat in resolved.iter() { match resolved.deps(crat) { Some(crate_deps) => { let idl = self.find_or_add(crat); for dep in crate_deps { let idr = self.find_or_add(dep); self.edges.push((idl, idr)); }; }, None => { } } } } fn find_or_add(&mut self, new: &'a PackageId) -> usize { for (i, id) in self.nodes.iter().enumerate() { if *id == new { return i } } self.nodes.push(new); self.nodes.len() - 1 } pub fn render_to<W:Write>(&'a self, output: &mut W) { match dot::render(self, output) { Ok(_) => {}, Err(e) => panic!("error rendering graph: {}", e) } } } impl<'a> dot::Labeller<'a, Nd, Ed> for Graph<'a> { fn graph_id(&self) -> dot::Id<'a> { dot::Id::new(self.nodes[0].name()).unwrap_or(dot::Id::new("dependencies").unwrap()) } fn node_id(&self, n: &Nd) -> dot::Id { // unwrap is safe because N######## is a valid graphviz id dot::Id::new(format!("N{}", *n)).unwrap() } fn node_label(&'a self, i: &Nd) -> dot::LabelText<'a> { if !self.source_labels { dot::LabelText::LabelStr(self.nodes[*i].name().into()) } else { dot::LabelText::LabelStr(self.nodes[*i].source_id().url().to_string().into()) } } } impl<'a> dot::GraphWalk<'a, Nd, Ed> for Graph<'a> { fn nodes(&self) -> dot::Nodes<'a,Nd> { (0..self.nodes.len()).collect() } fn edges(&self) -> dot::Edges<Ed> { Cow::Borrowed(&self.edges[..]) } fn
(&self, &(s, _): &Ed) -> Nd { s } fn target(&self, &(_, t): &Ed) -> Nd { t } }
source
identifier_name
controller.js
// This function will be executed as soon as the page is loaded and is responsable for the main orchestration window.onload = function() { var controller = new Controller(); controller.bindElements(); controller.bindActions(); } // The controller... where all logic is controlled or delegated to other controllers. function
() { // The Data Binder. Where all our "models" are stored. We don't wanna touch the DOM, let the binder do the dirty job. var dataBinder = new DataBinder(); // Binding the relevent elements. This will make sure the view and our "models" are always in sync. Change one, // the other will reflect the change. We don't wanna interact with the DOM directly. this.bindElements = function() { dataBinder.bindById('user-name', 'value', 'user.name'); dataBinder.bindById('user-name-welcome', 'textContent', 'user.name'); dataBinder.bindById('user-age', 'value', 'user.age'); dataBinder.bindById('user-country', 'value', 'user.country'); // Setting a default name for our user model. dataBinder.set('user.name', 'Anonymous'); } // Let's bind all the user actions with some javascript functions this.bindActions = function() { var goButton = document.getElementById('go-button'); goButton.onclick = this.okButtonClicked; } // Called when ok button is clicked (this was binded in the bindActions function) this.okButtonClicked = function() { var message = "Welcome " + dataBinder.get('user.name') + "! I understand you have " + dataBinder.get('user.age') + " years old and your country is " + dataBinder.get('user.country'); alert(message); } }
Controller
identifier_name
controller.js
// This function will be executed as soon as the page is loaded and is responsable for the main orchestration window.onload = function() { var controller = new Controller(); controller.bindElements(); controller.bindActions(); } // The controller... where all logic is controlled or delegated to other controllers. function Controller() { // The Data Binder. Where all our "models" are stored. We don't wanna touch the DOM, let the binder do the dirty job. var dataBinder = new DataBinder(); // Binding the relevent elements. This will make sure the view and our "models" are always in sync. Change one, // the other will reflect the change. We don't wanna interact with the DOM directly. this.bindElements = function() { dataBinder.bindById('user-name', 'value', 'user.name'); dataBinder.bindById('user-name-welcome', 'textContent', 'user.name'); dataBinder.bindById('user-age', 'value', 'user.age'); dataBinder.bindById('user-country', 'value', 'user.country');
// Let's bind all the user actions with some javascript functions this.bindActions = function() { var goButton = document.getElementById('go-button'); goButton.onclick = this.okButtonClicked; } // Called when ok button is clicked (this was binded in the bindActions function) this.okButtonClicked = function() { var message = "Welcome " + dataBinder.get('user.name') + "! I understand you have " + dataBinder.get('user.age') + " years old and your country is " + dataBinder.get('user.country'); alert(message); } }
// Setting a default name for our user model. dataBinder.set('user.name', 'Anonymous'); }
random_line_split
controller.js
// This function will be executed as soon as the page is loaded and is responsable for the main orchestration window.onload = function() { var controller = new Controller(); controller.bindElements(); controller.bindActions(); } // The controller... where all logic is controlled or delegated to other controllers. function Controller()
{ // The Data Binder. Where all our "models" are stored. We don't wanna touch the DOM, let the binder do the dirty job. var dataBinder = new DataBinder(); // Binding the relevent elements. This will make sure the view and our "models" are always in sync. Change one, // the other will reflect the change. We don't wanna interact with the DOM directly. this.bindElements = function() { dataBinder.bindById('user-name', 'value', 'user.name'); dataBinder.bindById('user-name-welcome', 'textContent', 'user.name'); dataBinder.bindById('user-age', 'value', 'user.age'); dataBinder.bindById('user-country', 'value', 'user.country'); // Setting a default name for our user model. dataBinder.set('user.name', 'Anonymous'); } // Let's bind all the user actions with some javascript functions this.bindActions = function() { var goButton = document.getElementById('go-button'); goButton.onclick = this.okButtonClicked; } // Called when ok button is clicked (this was binded in the bindActions function) this.okButtonClicked = function() { var message = "Welcome " + dataBinder.get('user.name') + "! I understand you have " + dataBinder.get('user.age') + " years old and your country is " + dataBinder.get('user.country'); alert(message); } }
identifier_body
car_processor.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from bs4 import BeautifulSoup as bs from sasila.system_normal.spider.spider_core import SpiderCore from sasila.system_normal.pipeline.console_pipeline import ConsolePipeline from sasila.system_normal.processor.base_processor import BaseProcessor from sasila.system_normal.downloader.http.spider_request import Request from sasila.system_normal.utils.decorator import checkResponse import json import time if sys.version_info < (3, 0): reload(sys) sys.setdefaultencoding('utf-8') class Car_Processor(BaseProcessor): spider_id = 'car_spider' spider_name = 'car_spider' allowed_domains = ['che168.com'] start_requests = [Request(url='http://www.che168.com', priority=0)] @checkResponse def process(self, response): soup = bs(response.m_response.content, 'lxml') province_div_list = soup.select('div.city-list div.cap-city > div.fn-clear') for province_div in province_div_list: province_name = province_div.select('span.capital a')[0].text city_list = province_div.select('div.city a') for city in city_list: city_name = city.text pinyin = city['href'].strip('/').split('/')[0] request = Request( url='http://www.che168.com/handler/usedcarlistv5.ashx?action=brandlist&area=%s' % pinyin, priority=1, callback=self.process_page_1) request.meta['province'] = province_name request.meta['city'] = city_name yield request @checkResponse def process_page_1(self, response): brand_list = list(json.loads(response.m_response.content.decode('gb2312'))) for brand in brand_list: brand_dict = dict(brand) brand_name = brand_dict['name'] url = response.nice_join(brand_dict['url']) + '/' request = Request(url=url, priority=2, callback=self.process_page_2) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = brand_name yield request @checkResponse def process_page_2(self, response): soup = bs(response.m_response.content, 'lxml') cars_line_list = soup.select('div#series div.content-area dl.model-list dd a') for cars_line in cars_line_list: cars_line_name = cars_line.text url = 'http://www.che168.com' + cars_line['href'] request = Request(url=url, priority=3, callback=self.process_page_3) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = cars_line_name yield request @checkResponse def process_page_3(self, response):
@checkResponse def process_page_4(self, response): soup = bs(response.m_response.content, 'lxml') # <html><head><title>Object moved</title></head><body> # <h2>Object moved to <a href="/CarDetail/wrong.aspx?errorcode=5&amp;backurl=/&amp;infoid=21415515">here</a>.</h2> # </body></html> if len(soup.select('div.car-title h2')) != 0: car = soup.select('div.car-title h2')[0].text detail_list = soup.select('div.details li') if len(detail_list) == 0: soup = bs(response.m_response.content, 'html5lib') detail_list = soup.select('div.details li') mileage = detail_list[0].select('span')[0].text.replace('万公里', '') first_borad_date = detail_list[1].select('span')[0].text gear = detail_list[2].select('span')[0].text.split('/')[0] displacement = detail_list[2].select('span')[0].text.split('/')[1] price = soup.select('div.car-price ins')[0].text.replace('¥', '') crawl_date = time.strftime('%Y-%m-%d', time.localtime(time.time())) item = dict() item['car'] = car item['mileage'] = mileage item['first_borad_date'] = first_borad_date item['gear'] = gear item['displacement'] = displacement item['price'] = price item['crawl_date'] = crawl_date item['province'] = response.request.meta['province'] item['city'] = response.request.meta['city'] item['brand'] = response.request.meta['brand'] item['cars_line'] = response.request.meta['cars_line'] yield item if __name__ == '__main__': SpiderCore(Car_Processor(), test=True).set_pipeline(ConsolePipeline()).start()
soup = bs(response.m_response.content, 'lxml') car_info_list = soup.select('div#a2 ul#viewlist_ul li a.carinfo') for car_info in car_info_list: url = 'http://www.che168.com' + car_info['href'] request = Request(url=url, priority=4, callback=self.process_page_4) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = response.request.meta['cars_line'] yield request next_page = soup.find(lambda tag: tag.name == 'a' and '下一页' in tag.text) if next_page: url = 'http://www.che168.com' + next_page['href'] request = Request(url=url, priority=3, callback=self.process_page_3) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = response.request.meta['cars_line'] yield request
identifier_body
car_processor.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from bs4 import BeautifulSoup as bs from sasila.system_normal.spider.spider_core import SpiderCore from sasila.system_normal.pipeline.console_pipeline import ConsolePipeline from sasila.system_normal.processor.base_processor import BaseProcessor from sasila.system_normal.downloader.http.spider_request import Request from sasila.system_normal.utils.decorator import checkResponse import json import time if sys.version_info < (3, 0):
class Car_Processor(BaseProcessor): spider_id = 'car_spider' spider_name = 'car_spider' allowed_domains = ['che168.com'] start_requests = [Request(url='http://www.che168.com', priority=0)] @checkResponse def process(self, response): soup = bs(response.m_response.content, 'lxml') province_div_list = soup.select('div.city-list div.cap-city > div.fn-clear') for province_div in province_div_list: province_name = province_div.select('span.capital a')[0].text city_list = province_div.select('div.city a') for city in city_list: city_name = city.text pinyin = city['href'].strip('/').split('/')[0] request = Request( url='http://www.che168.com/handler/usedcarlistv5.ashx?action=brandlist&area=%s' % pinyin, priority=1, callback=self.process_page_1) request.meta['province'] = province_name request.meta['city'] = city_name yield request @checkResponse def process_page_1(self, response): brand_list = list(json.loads(response.m_response.content.decode('gb2312'))) for brand in brand_list: brand_dict = dict(brand) brand_name = brand_dict['name'] url = response.nice_join(brand_dict['url']) + '/' request = Request(url=url, priority=2, callback=self.process_page_2) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = brand_name yield request @checkResponse def process_page_2(self, response): soup = bs(response.m_response.content, 'lxml') cars_line_list = soup.select('div#series div.content-area dl.model-list dd a') for cars_line in cars_line_list: cars_line_name = cars_line.text url = 'http://www.che168.com' + cars_line['href'] request = Request(url=url, priority=3, callback=self.process_page_3) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = cars_line_name yield request @checkResponse def process_page_3(self, response): soup = bs(response.m_response.content, 'lxml') car_info_list = soup.select('div#a2 ul#viewlist_ul li a.carinfo') for car_info in car_info_list: url = 'http://www.che168.com' + car_info['href'] request = Request(url=url, priority=4, callback=self.process_page_4) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = response.request.meta['cars_line'] yield request next_page = soup.find(lambda tag: tag.name == 'a' and '下一页' in tag.text) if next_page: url = 'http://www.che168.com' + next_page['href'] request = Request(url=url, priority=3, callback=self.process_page_3) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = response.request.meta['cars_line'] yield request @checkResponse def process_page_4(self, response): soup = bs(response.m_response.content, 'lxml') # <html><head><title>Object moved</title></head><body> # <h2>Object moved to <a href="/CarDetail/wrong.aspx?errorcode=5&amp;backurl=/&amp;infoid=21415515">here</a>.</h2> # </body></html> if len(soup.select('div.car-title h2')) != 0: car = soup.select('div.car-title h2')[0].text detail_list = soup.select('div.details li') if len(detail_list) == 0: soup = bs(response.m_response.content, 'html5lib') detail_list = soup.select('div.details li') mileage = detail_list[0].select('span')[0].text.replace('万公里', '') first_borad_date = detail_list[1].select('span')[0].text gear = detail_list[2].select('span')[0].text.split('/')[0] displacement = detail_list[2].select('span')[0].text.split('/')[1] price = soup.select('div.car-price ins')[0].text.replace('¥', '') crawl_date = time.strftime('%Y-%m-%d', time.localtime(time.time())) item = dict() item['car'] = car item['mileage'] = mileage item['first_borad_date'] = first_borad_date item['gear'] = gear item['displacement'] = displacement item['price'] = price item['crawl_date'] = crawl_date item['province'] = response.request.meta['province'] item['city'] = response.request.meta['city'] item['brand'] = response.request.meta['brand'] item['cars_line'] = response.request.meta['cars_line'] yield item if __name__ == '__main__': SpiderCore(Car_Processor(), test=True).set_pipeline(ConsolePipeline()).start()
reload(sys) sys.setdefaultencoding('utf-8')
conditional_block
car_processor.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from bs4 import BeautifulSoup as bs from sasila.system_normal.spider.spider_core import SpiderCore from sasila.system_normal.pipeline.console_pipeline import ConsolePipeline from sasila.system_normal.processor.base_processor import BaseProcessor from sasila.system_normal.downloader.http.spider_request import Request from sasila.system_normal.utils.decorator import checkResponse import json import time if sys.version_info < (3, 0): reload(sys) sys.setdefaultencoding('utf-8') class Car_Processor(BaseProcessor): spider_id = 'car_spider' spider_name = 'car_spider' allowed_domains = ['che168.com'] start_requests = [Request(url='http://www.che168.com', priority=0)] @checkResponse def process(self, response): soup = bs(response.m_response.content, 'lxml') province_div_list = soup.select('div.city-list div.cap-city > div.fn-clear') for province_div in province_div_list: province_name = province_div.select('span.capital a')[0].text city_list = province_div.select('div.city a') for city in city_list: city_name = city.text pinyin = city['href'].strip('/').split('/')[0] request = Request( url='http://www.che168.com/handler/usedcarlistv5.ashx?action=brandlist&area=%s' % pinyin, priority=1, callback=self.process_page_1) request.meta['province'] = province_name request.meta['city'] = city_name yield request @checkResponse def process_page_1(self, response): brand_list = list(json.loads(response.m_response.content.decode('gb2312'))) for brand in brand_list: brand_dict = dict(brand) brand_name = brand_dict['name'] url = response.nice_join(brand_dict['url']) + '/' request = Request(url=url, priority=2, callback=self.process_page_2) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = brand_name
@checkResponse def process_page_2(self, response): soup = bs(response.m_response.content, 'lxml') cars_line_list = soup.select('div#series div.content-area dl.model-list dd a') for cars_line in cars_line_list: cars_line_name = cars_line.text url = 'http://www.che168.com' + cars_line['href'] request = Request(url=url, priority=3, callback=self.process_page_3) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = cars_line_name yield request @checkResponse def process_page_3(self, response): soup = bs(response.m_response.content, 'lxml') car_info_list = soup.select('div#a2 ul#viewlist_ul li a.carinfo') for car_info in car_info_list: url = 'http://www.che168.com' + car_info['href'] request = Request(url=url, priority=4, callback=self.process_page_4) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = response.request.meta['cars_line'] yield request next_page = soup.find(lambda tag: tag.name == 'a' and '下一页' in tag.text) if next_page: url = 'http://www.che168.com' + next_page['href'] request = Request(url=url, priority=3, callback=self.process_page_3) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = response.request.meta['cars_line'] yield request @checkResponse def process_page_4(self, response): soup = bs(response.m_response.content, 'lxml') # <html><head><title>Object moved</title></head><body> # <h2>Object moved to <a href="/CarDetail/wrong.aspx?errorcode=5&amp;backurl=/&amp;infoid=21415515">here</a>.</h2> # </body></html> if len(soup.select('div.car-title h2')) != 0: car = soup.select('div.car-title h2')[0].text detail_list = soup.select('div.details li') if len(detail_list) == 0: soup = bs(response.m_response.content, 'html5lib') detail_list = soup.select('div.details li') mileage = detail_list[0].select('span')[0].text.replace('万公里', '') first_borad_date = detail_list[1].select('span')[0].text gear = detail_list[2].select('span')[0].text.split('/')[0] displacement = detail_list[2].select('span')[0].text.split('/')[1] price = soup.select('div.car-price ins')[0].text.replace('¥', '') crawl_date = time.strftime('%Y-%m-%d', time.localtime(time.time())) item = dict() item['car'] = car item['mileage'] = mileage item['first_borad_date'] = first_borad_date item['gear'] = gear item['displacement'] = displacement item['price'] = price item['crawl_date'] = crawl_date item['province'] = response.request.meta['province'] item['city'] = response.request.meta['city'] item['brand'] = response.request.meta['brand'] item['cars_line'] = response.request.meta['cars_line'] yield item if __name__ == '__main__': SpiderCore(Car_Processor(), test=True).set_pipeline(ConsolePipeline()).start()
yield request
random_line_split
car_processor.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from bs4 import BeautifulSoup as bs from sasila.system_normal.spider.spider_core import SpiderCore from sasila.system_normal.pipeline.console_pipeline import ConsolePipeline from sasila.system_normal.processor.base_processor import BaseProcessor from sasila.system_normal.downloader.http.spider_request import Request from sasila.system_normal.utils.decorator import checkResponse import json import time if sys.version_info < (3, 0): reload(sys) sys.setdefaultencoding('utf-8') class
(BaseProcessor): spider_id = 'car_spider' spider_name = 'car_spider' allowed_domains = ['che168.com'] start_requests = [Request(url='http://www.che168.com', priority=0)] @checkResponse def process(self, response): soup = bs(response.m_response.content, 'lxml') province_div_list = soup.select('div.city-list div.cap-city > div.fn-clear') for province_div in province_div_list: province_name = province_div.select('span.capital a')[0].text city_list = province_div.select('div.city a') for city in city_list: city_name = city.text pinyin = city['href'].strip('/').split('/')[0] request = Request( url='http://www.che168.com/handler/usedcarlistv5.ashx?action=brandlist&area=%s' % pinyin, priority=1, callback=self.process_page_1) request.meta['province'] = province_name request.meta['city'] = city_name yield request @checkResponse def process_page_1(self, response): brand_list = list(json.loads(response.m_response.content.decode('gb2312'))) for brand in brand_list: brand_dict = dict(brand) brand_name = brand_dict['name'] url = response.nice_join(brand_dict['url']) + '/' request = Request(url=url, priority=2, callback=self.process_page_2) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = brand_name yield request @checkResponse def process_page_2(self, response): soup = bs(response.m_response.content, 'lxml') cars_line_list = soup.select('div#series div.content-area dl.model-list dd a') for cars_line in cars_line_list: cars_line_name = cars_line.text url = 'http://www.che168.com' + cars_line['href'] request = Request(url=url, priority=3, callback=self.process_page_3) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = cars_line_name yield request @checkResponse def process_page_3(self, response): soup = bs(response.m_response.content, 'lxml') car_info_list = soup.select('div#a2 ul#viewlist_ul li a.carinfo') for car_info in car_info_list: url = 'http://www.che168.com' + car_info['href'] request = Request(url=url, priority=4, callback=self.process_page_4) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = response.request.meta['cars_line'] yield request next_page = soup.find(lambda tag: tag.name == 'a' and '下一页' in tag.text) if next_page: url = 'http://www.che168.com' + next_page['href'] request = Request(url=url, priority=3, callback=self.process_page_3) request.meta['province'] = response.request.meta['province'] request.meta['city'] = response.request.meta['city'] request.meta['brand'] = response.request.meta['brand'] request.meta['cars_line'] = response.request.meta['cars_line'] yield request @checkResponse def process_page_4(self, response): soup = bs(response.m_response.content, 'lxml') # <html><head><title>Object moved</title></head><body> # <h2>Object moved to <a href="/CarDetail/wrong.aspx?errorcode=5&amp;backurl=/&amp;infoid=21415515">here</a>.</h2> # </body></html> if len(soup.select('div.car-title h2')) != 0: car = soup.select('div.car-title h2')[0].text detail_list = soup.select('div.details li') if len(detail_list) == 0: soup = bs(response.m_response.content, 'html5lib') detail_list = soup.select('div.details li') mileage = detail_list[0].select('span')[0].text.replace('万公里', '') first_borad_date = detail_list[1].select('span')[0].text gear = detail_list[2].select('span')[0].text.split('/')[0] displacement = detail_list[2].select('span')[0].text.split('/')[1] price = soup.select('div.car-price ins')[0].text.replace('¥', '') crawl_date = time.strftime('%Y-%m-%d', time.localtime(time.time())) item = dict() item['car'] = car item['mileage'] = mileage item['first_borad_date'] = first_borad_date item['gear'] = gear item['displacement'] = displacement item['price'] = price item['crawl_date'] = crawl_date item['province'] = response.request.meta['province'] item['city'] = response.request.meta['city'] item['brand'] = response.request.meta['brand'] item['cars_line'] = response.request.meta['cars_line'] yield item if __name__ == '__main__': SpiderCore(Car_Processor(), test=True).set_pipeline(ConsolePipeline()).start()
Car_Processor
identifier_name
__init__.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible import constants as C from ansible.errors import AnsibleParserError from ansible.module_utils._text import to_text, to_native from ansible.playbook.play import Play from ansible.playbook.playbook_include import PlaybookInclude from ansible.utils.display import Display display = Display() __all__ = ['Playbook'] class Playbook: def __init__(self, loader): # Entries in the datastructure of a playbook may # be either a play or an include statement self._entries = [] self._basedir = to_text(os.getcwd(), errors='surrogate_or_strict') self._loader = loader self._file_name = None @staticmethod def load(file_name, variable_manager=None, loader=None): pb = Playbook(loader=loader) pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager) return pb def _load_playbook_data(self, file_name, variable_manager, vars=None): if os.path.isabs(file_name): self._basedir = os.path.dirname(file_name)
self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name))) # set the loaders basedir cur_basedir = self._loader.get_basedir() self._loader.set_basedir(self._basedir) self._file_name = file_name try: ds = self._loader.load_from_file(os.path.basename(file_name)) except UnicodeDecodeError as e: raise AnsibleParserError("Could not read playbook (%s) due to encoding issues: %s" % (file_name, to_native(e))) # check for errors and restore the basedir in case this error is caught and handled if not ds: self._loader.set_basedir(cur_basedir) raise AnsibleParserError("Empty playbook, nothing to do", obj=ds) elif not isinstance(ds, list): self._loader.set_basedir(cur_basedir) raise AnsibleParserError("A playbook must be a list of plays, got a %s instead" % type(ds), obj=ds) # Parse the playbook entries. For plays, we simply parse them # using the Play() object, and includes are parsed using the # PlaybookInclude() object for entry in ds: if not isinstance(entry, dict): # restore the basedir in case this error is caught and handled self._loader.set_basedir(cur_basedir) raise AnsibleParserError("playbook entries must be either a valid play or an include statement", obj=entry) if any(action in entry for action in ('import_playbook', 'include')): if 'include' in entry: display.deprecated("'include' for playbook includes. You should use 'import_playbook' instead", version="2.12") pb = PlaybookInclude.load(entry, basedir=self._basedir, variable_manager=variable_manager, loader=self._loader) if pb is not None: self._entries.extend(pb._entries) else: which = entry.get('import_playbook', entry.get('include', entry)) display.display("skipping playbook '%s' due to conditional test failure" % which, color=C.COLOR_SKIP) else: entry_obj = Play.load(entry, variable_manager=variable_manager, loader=self._loader, vars=vars) self._entries.append(entry_obj) # we're done, so restore the old basedir in the loader self._loader.set_basedir(cur_basedir) def get_loader(self): return self._loader def get_plays(self): return self._entries[:]
else:
random_line_split
__init__.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible import constants as C from ansible.errors import AnsibleParserError from ansible.module_utils._text import to_text, to_native from ansible.playbook.play import Play from ansible.playbook.playbook_include import PlaybookInclude from ansible.utils.display import Display display = Display() __all__ = ['Playbook'] class Playbook: def __init__(self, loader): # Entries in the datastructure of a playbook may # be either a play or an include statement self._entries = [] self._basedir = to_text(os.getcwd(), errors='surrogate_or_strict') self._loader = loader self._file_name = None @staticmethod def load(file_name, variable_manager=None, loader=None): pb = Playbook(loader=loader) pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager) return pb def _load_playbook_data(self, file_name, variable_manager, vars=None): if os.path.isabs(file_name): self._basedir = os.path.dirname(file_name) else: self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name))) # set the loaders basedir cur_basedir = self._loader.get_basedir() self._loader.set_basedir(self._basedir) self._file_name = file_name try: ds = self._loader.load_from_file(os.path.basename(file_name)) except UnicodeDecodeError as e: raise AnsibleParserError("Could not read playbook (%s) due to encoding issues: %s" % (file_name, to_native(e))) # check for errors and restore the basedir in case this error is caught and handled if not ds: self._loader.set_basedir(cur_basedir) raise AnsibleParserError("Empty playbook, nothing to do", obj=ds) elif not isinstance(ds, list): self._loader.set_basedir(cur_basedir) raise AnsibleParserError("A playbook must be a list of plays, got a %s instead" % type(ds), obj=ds) # Parse the playbook entries. For plays, we simply parse them # using the Play() object, and includes are parsed using the # PlaybookInclude() object for entry in ds: if not isinstance(entry, dict): # restore the basedir in case this error is caught and handled self._loader.set_basedir(cur_basedir) raise AnsibleParserError("playbook entries must be either a valid play or an include statement", obj=entry) if any(action in entry for action in ('import_playbook', 'include')): if 'include' in entry: display.deprecated("'include' for playbook includes. You should use 'import_playbook' instead", version="2.12") pb = PlaybookInclude.load(entry, basedir=self._basedir, variable_manager=variable_manager, loader=self._loader) if pb is not None: self._entries.extend(pb._entries) else: which = entry.get('import_playbook', entry.get('include', entry)) display.display("skipping playbook '%s' due to conditional test failure" % which, color=C.COLOR_SKIP) else: entry_obj = Play.load(entry, variable_manager=variable_manager, loader=self._loader, vars=vars) self._entries.append(entry_obj) # we're done, so restore the old basedir in the loader self._loader.set_basedir(cur_basedir) def
(self): return self._loader def get_plays(self): return self._entries[:]
get_loader
identifier_name
__init__.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible import constants as C from ansible.errors import AnsibleParserError from ansible.module_utils._text import to_text, to_native from ansible.playbook.play import Play from ansible.playbook.playbook_include import PlaybookInclude from ansible.utils.display import Display display = Display() __all__ = ['Playbook'] class Playbook: def __init__(self, loader): # Entries in the datastructure of a playbook may # be either a play or an include statement self._entries = [] self._basedir = to_text(os.getcwd(), errors='surrogate_or_strict') self._loader = loader self._file_name = None @staticmethod def load(file_name, variable_manager=None, loader=None): pb = Playbook(loader=loader) pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager) return pb def _load_playbook_data(self, file_name, variable_manager, vars=None): if os.path.isabs(file_name): self._basedir = os.path.dirname(file_name) else: self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name))) # set the loaders basedir cur_basedir = self._loader.get_basedir() self._loader.set_basedir(self._basedir) self._file_name = file_name try: ds = self._loader.load_from_file(os.path.basename(file_name)) except UnicodeDecodeError as e: raise AnsibleParserError("Could not read playbook (%s) due to encoding issues: %s" % (file_name, to_native(e))) # check for errors and restore the basedir in case this error is caught and handled if not ds:
elif not isinstance(ds, list): self._loader.set_basedir(cur_basedir) raise AnsibleParserError("A playbook must be a list of plays, got a %s instead" % type(ds), obj=ds) # Parse the playbook entries. For plays, we simply parse them # using the Play() object, and includes are parsed using the # PlaybookInclude() object for entry in ds: if not isinstance(entry, dict): # restore the basedir in case this error is caught and handled self._loader.set_basedir(cur_basedir) raise AnsibleParserError("playbook entries must be either a valid play or an include statement", obj=entry) if any(action in entry for action in ('import_playbook', 'include')): if 'include' in entry: display.deprecated("'include' for playbook includes. You should use 'import_playbook' instead", version="2.12") pb = PlaybookInclude.load(entry, basedir=self._basedir, variable_manager=variable_manager, loader=self._loader) if pb is not None: self._entries.extend(pb._entries) else: which = entry.get('import_playbook', entry.get('include', entry)) display.display("skipping playbook '%s' due to conditional test failure" % which, color=C.COLOR_SKIP) else: entry_obj = Play.load(entry, variable_manager=variable_manager, loader=self._loader, vars=vars) self._entries.append(entry_obj) # we're done, so restore the old basedir in the loader self._loader.set_basedir(cur_basedir) def get_loader(self): return self._loader def get_plays(self): return self._entries[:]
self._loader.set_basedir(cur_basedir) raise AnsibleParserError("Empty playbook, nothing to do", obj=ds)
conditional_block
__init__.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ansible import constants as C from ansible.errors import AnsibleParserError from ansible.module_utils._text import to_text, to_native from ansible.playbook.play import Play from ansible.playbook.playbook_include import PlaybookInclude from ansible.utils.display import Display display = Display() __all__ = ['Playbook'] class Playbook: def __init__(self, loader): # Entries in the datastructure of a playbook may # be either a play or an include statement self._entries = [] self._basedir = to_text(os.getcwd(), errors='surrogate_or_strict') self._loader = loader self._file_name = None @staticmethod def load(file_name, variable_manager=None, loader=None): pb = Playbook(loader=loader) pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager) return pb def _load_playbook_data(self, file_name, variable_manager, vars=None):
def get_loader(self): return self._loader def get_plays(self): return self._entries[:]
if os.path.isabs(file_name): self._basedir = os.path.dirname(file_name) else: self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name))) # set the loaders basedir cur_basedir = self._loader.get_basedir() self._loader.set_basedir(self._basedir) self._file_name = file_name try: ds = self._loader.load_from_file(os.path.basename(file_name)) except UnicodeDecodeError as e: raise AnsibleParserError("Could not read playbook (%s) due to encoding issues: %s" % (file_name, to_native(e))) # check for errors and restore the basedir in case this error is caught and handled if not ds: self._loader.set_basedir(cur_basedir) raise AnsibleParserError("Empty playbook, nothing to do", obj=ds) elif not isinstance(ds, list): self._loader.set_basedir(cur_basedir) raise AnsibleParserError("A playbook must be a list of plays, got a %s instead" % type(ds), obj=ds) # Parse the playbook entries. For plays, we simply parse them # using the Play() object, and includes are parsed using the # PlaybookInclude() object for entry in ds: if not isinstance(entry, dict): # restore the basedir in case this error is caught and handled self._loader.set_basedir(cur_basedir) raise AnsibleParserError("playbook entries must be either a valid play or an include statement", obj=entry) if any(action in entry for action in ('import_playbook', 'include')): if 'include' in entry: display.deprecated("'include' for playbook includes. You should use 'import_playbook' instead", version="2.12") pb = PlaybookInclude.load(entry, basedir=self._basedir, variable_manager=variable_manager, loader=self._loader) if pb is not None: self._entries.extend(pb._entries) else: which = entry.get('import_playbook', entry.get('include', entry)) display.display("skipping playbook '%s' due to conditional test failure" % which, color=C.COLOR_SKIP) else: entry_obj = Play.load(entry, variable_manager=variable_manager, loader=self._loader, vars=vars) self._entries.append(entry_obj) # we're done, so restore the old basedir in the loader self._loader.set_basedir(cur_basedir)
identifier_body
main.rs
extern crate rand; use rand::Rng; fn
() { loop { let (player_one_score, player_two_score) = roll_for_both_players(); if player_one_score != player_two_score { if player_one_score > player_two_score { println!("Player 1 wins!"); } else { println!("Player 2 wins!"); } return; } } } fn roll_for_both_players() -> (i32, i32) { let mut player_one_score = 0; let mut player_two_score = 0; for _ in 0..3 { let roll_for_player_one = rand::thread_rng().gen_range(1, 7); let roll_for_player_two = rand::thread_rng().gen_range(1, 7); println!("Player one rolled {}", roll_for_player_one); println!("Player two rolled {}", roll_for_player_two); player_one_score += roll_for_player_one; player_two_score += roll_for_player_two; } (player_one_score, player_two_score) }
main
identifier_name
main.rs
extern crate rand; use rand::Rng; fn main() { loop { let (player_one_score, player_two_score) = roll_for_both_players(); if player_one_score != player_two_score
} } fn roll_for_both_players() -> (i32, i32) { let mut player_one_score = 0; let mut player_two_score = 0; for _ in 0..3 { let roll_for_player_one = rand::thread_rng().gen_range(1, 7); let roll_for_player_two = rand::thread_rng().gen_range(1, 7); println!("Player one rolled {}", roll_for_player_one); println!("Player two rolled {}", roll_for_player_two); player_one_score += roll_for_player_one; player_two_score += roll_for_player_two; } (player_one_score, player_two_score) }
{ if player_one_score > player_two_score { println!("Player 1 wins!"); } else { println!("Player 2 wins!"); } return; }
conditional_block
main.rs
extern crate rand; use rand::Rng; fn main() { loop { let (player_one_score, player_two_score) = roll_for_both_players(); if player_one_score != player_two_score { if player_one_score > player_two_score { println!("Player 1 wins!"); } else {
} } } fn roll_for_both_players() -> (i32, i32) { let mut player_one_score = 0; let mut player_two_score = 0; for _ in 0..3 { let roll_for_player_one = rand::thread_rng().gen_range(1, 7); let roll_for_player_two = rand::thread_rng().gen_range(1, 7); println!("Player one rolled {}", roll_for_player_one); println!("Player two rolled {}", roll_for_player_two); player_one_score += roll_for_player_one; player_two_score += roll_for_player_two; } (player_one_score, player_two_score) }
println!("Player 2 wins!"); } return;
random_line_split
main.rs
extern crate rand; use rand::Rng; fn main()
fn roll_for_both_players() -> (i32, i32) { let mut player_one_score = 0; let mut player_two_score = 0; for _ in 0..3 { let roll_for_player_one = rand::thread_rng().gen_range(1, 7); let roll_for_player_two = rand::thread_rng().gen_range(1, 7); println!("Player one rolled {}", roll_for_player_one); println!("Player two rolled {}", roll_for_player_two); player_one_score += roll_for_player_one; player_two_score += roll_for_player_two; } (player_one_score, player_two_score) }
{ loop { let (player_one_score, player_two_score) = roll_for_both_players(); if player_one_score != player_two_score { if player_one_score > player_two_score { println!("Player 1 wins!"); } else { println!("Player 2 wins!"); } return; } } }
identifier_body
binaryIndex.js
(function(){var binaryIndexBy = require('./binaryIndexBy'), identity = require('../utility/identity'); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** * Performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest, instead * of the lowest, index at which a value should be inserted into `array`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function binaryIndex(array, value, retHighest)
module.exports = binaryIndex; })();
{ var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (retHighest ? (computed <= value) : (computed < value)) { low = mid + 1; } else { high = mid; } } return high; } return binaryIndexBy(array, value, identity, retHighest); }
identifier_body
binaryIndex.js
(function(){var binaryIndexBy = require('./binaryIndexBy'), identity = require('../utility/identity'); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** * Performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest, instead * of the lowest, index at which a value should be inserted into `array`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function binaryIndex(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (retHighest ? (computed <= value) : (computed < value)) { low = mid + 1; } else
} return high; } return binaryIndexBy(array, value, identity, retHighest); } module.exports = binaryIndex; })();
{ high = mid; }
conditional_block
binaryIndex.js
(function(){var binaryIndexBy = require('./binaryIndexBy'), identity = require('../utility/identity'); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** * Performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest, instead * of the lowest, index at which a value should be inserted into `array`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function
(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (retHighest ? (computed <= value) : (computed < value)) { low = mid + 1; } else { high = mid; } } return high; } return binaryIndexBy(array, value, identity, retHighest); } module.exports = binaryIndex; })();
binaryIndex
identifier_name
binaryIndex.js
(function(){var binaryIndexBy = require('./binaryIndexBy'), identity = require('../utility/identity'); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** * Performs a binary search of `array` to determine the index at which `value`
* @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest, instead * of the lowest, index at which a value should be inserted into `array`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function binaryIndex(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (retHighest ? (computed <= value) : (computed < value)) { low = mid + 1; } else { high = mid; } } return high; } return binaryIndexBy(array, value, identity, retHighest); } module.exports = binaryIndex; })();
* should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect.
random_line_split
setup.py
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import glob import os import sys import ah_bootstrap from setuptools import setup #A dirty hack to get around some early import/configurations ambiguities if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins builtins._ASTROPY_SETUP_ = True from astropy_helpers.setup_helpers import (register_commands, adjust_compiler, get_debug_option, get_package_info, add_command_option) from astropy_helpers.git_helpers import get_git_devstr from astropy_helpers.version_helpers import generate_version_py # Get some values from the setup.cfg from distutils import config conf = config.ConfigParser() conf.read(['setup.cfg']) metadata = dict(conf.items('metadata')) PACKAGENAME = metadata.get('package_name', 'packagename') DESCRIPTION = metadata.get('description', 'Astropy affiliated package') AUTHOR = metadata.get('author', '') AUTHOR_EMAIL = metadata.get('author_email', '') LICENSE = metadata.get('license', 'unknown') URL = metadata.get('url', 'http://astropy.org') # Get the long description from the package's docstring #__import__(PACKAGENAME) #package = sys.modules[PACKAGENAME]
# VERSION should be PEP386 compatible (http://www.python.org/dev/peps/pep-0386) VERSION = '1.5.dev' # Indicates if this version is a release version RELEASE = 'dev' not in VERSION if not RELEASE: VERSION += get_git_devstr(False) # Populate the dict of setup command overrides; this should be done before # invoking any other functionality from distutils since it can potentially # modify distutils' behavior. cmdclassd = register_commands(PACKAGENAME, VERSION, RELEASE) add_command_option('install', 'with-openmp', 'compile TARDIS without OpenMP', is_bool=True) add_command_option('build', 'with-openmp', 'compile TARDIS without OpenMP', is_bool=True) add_command_option('develop', 'with-openmp', 'compile TARDIS without OpenMP', is_bool=True) # Adjust the compiler in case the default on this platform is to use a # broken one. adjust_compiler(PACKAGENAME) # Freeze build information in version.py generate_version_py(PACKAGENAME, VERSION, RELEASE, get_debug_option(PACKAGENAME)) # Treat everything in scripts except README.rst as a script to be installed scripts = [fname for fname in glob.glob(os.path.join('scripts', '*')) if os.path.basename(fname) != 'README.rst'] # Get configuration information from all of the various subpackages. # See the docstring for setup_helpers.update_package_files for more # details. package_info = get_package_info() # Add the project-global data package_info['package_data'].setdefault(PACKAGENAME, []) package_info['package_data'][PACKAGENAME].append('data/*') # Define entry points for command-line scripts entry_points = {} for hook in [('prereleaser', 'middle'), ('releaser', 'middle'), ('postreleaser', 'before'), ('postreleaser', 'middle')]: hook_ep = 'zest.releaser.' + '.'.join(hook) hook_name = 'astropy.release.' + '.'.join(hook) hook_func = 'astropy.utils.release:' + '_'.join(hook) entry_points[hook_ep] = ['%s = %s' % (hook_name, hook_func)] # Include all .c files, recursively, including those generated by # Cython, since we can not do this in MANIFEST.in with a "dynamic" # directory name. c_files = [] for root, dirs, files in os.walk(PACKAGENAME): for filename in files: if filename.endswith('.c'): c_files.append( os.path.join( os.path.relpath(root, PACKAGENAME), filename)) package_info['package_data'][PACKAGENAME].extend(c_files) setup(name=PACKAGENAME + '-sn', version=VERSION, description=DESCRIPTION, scripts=scripts, requires=['astropy'], install_requires=['astropy'], provides=[PACKAGENAME], author=AUTHOR, author_email=AUTHOR_EMAIL, license=LICENSE, url=URL, long_description=LONG_DESCRIPTION, cmdclass=cmdclassd, zip_safe=False, use_2to3=True, entry_points=entry_points, **package_info )
LONG_DESCRIPTION = "" #package.__doc__ # Store the package name in a built-in variable so it's easy # to get from other parts of the setup infrastructure builtins._ASTROPY_PACKAGE_NAME_ = PACKAGENAME
random_line_split
setup.py
#!/usr/bin/env python # Licensed under a 3-clause BSD style license - see LICENSE.rst import glob import os import sys import ah_bootstrap from setuptools import setup #A dirty hack to get around some early import/configurations ambiguities if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins builtins._ASTROPY_SETUP_ = True from astropy_helpers.setup_helpers import (register_commands, adjust_compiler, get_debug_option, get_package_info, add_command_option) from astropy_helpers.git_helpers import get_git_devstr from astropy_helpers.version_helpers import generate_version_py # Get some values from the setup.cfg from distutils import config conf = config.ConfigParser() conf.read(['setup.cfg']) metadata = dict(conf.items('metadata')) PACKAGENAME = metadata.get('package_name', 'packagename') DESCRIPTION = metadata.get('description', 'Astropy affiliated package') AUTHOR = metadata.get('author', '') AUTHOR_EMAIL = metadata.get('author_email', '') LICENSE = metadata.get('license', 'unknown') URL = metadata.get('url', 'http://astropy.org') # Get the long description from the package's docstring #__import__(PACKAGENAME) #package = sys.modules[PACKAGENAME] LONG_DESCRIPTION = "" #package.__doc__ # Store the package name in a built-in variable so it's easy # to get from other parts of the setup infrastructure builtins._ASTROPY_PACKAGE_NAME_ = PACKAGENAME # VERSION should be PEP386 compatible (http://www.python.org/dev/peps/pep-0386) VERSION = '1.5.dev' # Indicates if this version is a release version RELEASE = 'dev' not in VERSION if not RELEASE: VERSION += get_git_devstr(False) # Populate the dict of setup command overrides; this should be done before # invoking any other functionality from distutils since it can potentially # modify distutils' behavior. cmdclassd = register_commands(PACKAGENAME, VERSION, RELEASE) add_command_option('install', 'with-openmp', 'compile TARDIS without OpenMP', is_bool=True) add_command_option('build', 'with-openmp', 'compile TARDIS without OpenMP', is_bool=True) add_command_option('develop', 'with-openmp', 'compile TARDIS without OpenMP', is_bool=True) # Adjust the compiler in case the default on this platform is to use a # broken one. adjust_compiler(PACKAGENAME) # Freeze build information in version.py generate_version_py(PACKAGENAME, VERSION, RELEASE, get_debug_option(PACKAGENAME)) # Treat everything in scripts except README.rst as a script to be installed scripts = [fname for fname in glob.glob(os.path.join('scripts', '*')) if os.path.basename(fname) != 'README.rst'] # Get configuration information from all of the various subpackages. # See the docstring for setup_helpers.update_package_files for more # details. package_info = get_package_info() # Add the project-global data package_info['package_data'].setdefault(PACKAGENAME, []) package_info['package_data'][PACKAGENAME].append('data/*') # Define entry points for command-line scripts entry_points = {} for hook in [('prereleaser', 'middle'), ('releaser', 'middle'), ('postreleaser', 'before'), ('postreleaser', 'middle')]: hook_ep = 'zest.releaser.' + '.'.join(hook) hook_name = 'astropy.release.' + '.'.join(hook) hook_func = 'astropy.utils.release:' + '_'.join(hook) entry_points[hook_ep] = ['%s = %s' % (hook_name, hook_func)] # Include all .c files, recursively, including those generated by # Cython, since we can not do this in MANIFEST.in with a "dynamic" # directory name. c_files = [] for root, dirs, files in os.walk(PACKAGENAME): for filename in files: if filename.endswith('.c'):
package_info['package_data'][PACKAGENAME].extend(c_files) setup(name=PACKAGENAME + '-sn', version=VERSION, description=DESCRIPTION, scripts=scripts, requires=['astropy'], install_requires=['astropy'], provides=[PACKAGENAME], author=AUTHOR, author_email=AUTHOR_EMAIL, license=LICENSE, url=URL, long_description=LONG_DESCRIPTION, cmdclass=cmdclassd, zip_safe=False, use_2to3=True, entry_points=entry_points, **package_info )
c_files.append( os.path.join( os.path.relpath(root, PACKAGENAME), filename))
conditional_block
pdf.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ### 2008-2015 Charlie Barnes. ### This program is free software; you can redistribute it and/or modify ### it under the terms of the GNU General Public License as published by ### the Free Software Foundation; either version 2 of the License, or ### (at your option) any later version. ### This program is distributed in the hope that it will be useful, ### but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### You should have received a copy of the GNU General Public License ### along with this program; if not, write to the Free Software ### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA def repeat_to_length(string_to_expand, length): return (string_to_expand * ((length/len(string_to_expand))+1))[:length] try: from fpdf import FPDF except ImportError: from pyfpdf import FPDF class PDF(FPDF): def
(self, orientation,unit,format): FPDF.__init__(self, orientation=orientation,unit=unit,format=format) self.toc = [] self.numbering = False self.num_page_num = 0 self.toc_page_break_count = 1 self.set_left_margin(10) self.set_right_margin(10) self.do_header = False self.type = None self.toc_length = 0 self.doing_the_list = False self.vcs = [] self.toc_page_num = 2 self.dataset = None self.orientation = orientation self.orientation_changes = [0] def p_add_page(self): #if(self.numbering): self.add_page() self.num_page_num = self.num_page_num + 1 def num_page_no(self): return self.num_page_num def startPageNums(self): self.numbering = True def stopPageNums(self): self.numbering = False def TOC_Entry(self, txt, level=0): self.toc.append({'t':txt, 'l':level, 'p':str(self.num_page_no()+self.toc_length)}) def insertTOC(self, location=1, labelSize=20, entrySize=10, tocfont='Helvetica', label='Table of Contents'): #make toc at end self.stopPageNums() self.section = 'Contents' self.p_add_page() tocstart = self.page self.set_font('Helvetica', '', 20) self.multi_cell(0, 20, 'Contents', 0, 'J', False) used_pages = [] link_abscissa = {} for t in self.toc: #Offset level = t['l'] if level > 0: self.cell(level*8) weight = '' if level == 0: weight = 'B' txxt = t['t'] self.set_font(tocfont, weight, entrySize) strsize = self.get_string_width(txxt) self.cell(strsize+2, self.font_size+2, txxt, 0, 0, '', False) #store the TOC links & position for later use if self.page_no() not in link_abscissa.keys(): link_abscissa[self.page_no()] = [] link_abscissa[self.page_no()].append([int(t['p']), self.y]) #Filling dots self.set_font(tocfont, '', entrySize) PageCellSize = self.get_string_width(t['p'])+2 w = self.w-self.l_margin-self.r_margin-PageCellSize-(level*8)-(strsize+2) nb = w/self.get_string_width('.') dots = repeat_to_length('.', int(nb)) self.cell(w, self.font_size+2, dots, 0, 0, 'R') #Page number of the toc entry self.cell(PageCellSize, self.font_size+2, str(int(t['p'])), 0, 1, 'R') if self.toc_page_break_count%2 != 0: self.section = '' self.toc_page_break_count = self.toc_page_break_count + 1 self.p_add_page() #Grab it and move to selected location n = self.page ntoc = n - tocstart + 1 last = [] #store toc pages i = tocstart while i <= n: last.append(self.pages[i]) i = i + 1 #move pages i = tocstart while i >= (location-1): self.pages[i+ntoc] = self.pages[i] i = i - 1 #Put toc pages at insert point i = 0 while i < ntoc: self.pages[location + i] = last[i] #loop through all the TOC links for this page and add them try: for linkdata in link_abscissa[tocstart+i]: self.page = location + i link = self.add_link() self.set_link(link, y=0, page=linkdata[0]) self.link(x=self.l_margin, y=linkdata[1], w=self.w-self.r_margin, h=self.font_size+2, link=link) except KeyError: pass i = i + 1 self.page = n def header(self): if self.do_header: self.set_font('Helvetica', '', 8) self.set_text_color(0, 0, 0) self.set_line_width(0.1) if (self.section <> 'Contents' and self.page_no()%2 == 0) or (self.section == 'Contents' and self.toc_page_break_count%2 == 0): self.cell(0, 5, self.section, 'B', 0, 'L', 0) # even page header self.cell(0, 5, self.title.replace('\n', ' - '), 'B', 1, 'R', 0) # even page header elif (self.section <> 'Contents' and self.page_no()%2 == 1) or (self.section == 'Contents' and self.toc_page_break_count%2 == 1): self.cell(0, 5, self.section, 'B', 1, 'R', 0) #odd page header if self.type == 'list' and self.doing_the_list == True: col_width = 12.7#((self.w - self.l_margin - self.r_margin)/2)/7.5 #vc headings self.set_font('Helvetica', '', 10) self.set_line_width(0.0) self.set_y(20) self.set_x(self.w-(7+col_width+(((col_width*3)+(col_width/4))*len(self.vcs)))) self.cell(col_width, 5, '', '0', 0, 'C', 0) for vc in sorted(self.vcs): if vc == None: vc_head_text = '' else: vc_head_text = ''.join(['VC',vc]) self.cell((col_width*3), 5, vc_head_text, '0', 0, 'C', 0) self.cell(col_width/4, 5, '', '0', 0, 'C', 0) self.ln() self.set_x(self.w-(7+col_width+(((col_width*3)+(col_width/4))*len(self.vcs)))) self.set_font('Helvetica', '', 8) self.cell(col_width, 5, '', '0', 0, 'C', 0) for vc in sorted(self.vcs): #colum headings self.cell(col_width, 5, ' '.join([self.dataset.config.get('List', 'distribution_unit'), 'sqs']), '0', 0, 'C', 0) self.cell(col_width, 5, 'Records', '0', 0, 'C', 0) self.cell(col_width, 5, 'Last in', '0', 0, 'C', 0) self.cell(col_width/4, 5, '', '0', 0, 'C', 0) self.y0 = self.get_y() if self.section == 'Contributors' or self.section == 'Contents': self.set_y(self.y0 + 20) def footer(self): self.set_y(-20) self.set_font('Helvetica','',8) #only show page numbers in the main body #if self.num_page_no() >= 4 and self.section != 'Contents' and self.section != 'Index' and self.section != 'Contributors' and self.section != 'References' and self.section != 'Introduction' and self.section != '': if self.num_page_no() >= 5 and self.section != 'Contents' and self.section != '' and self.section != 'Index' and self.section != 'Contributors' and self.section != 'References' and self.section != 'Introduction': self.cell(0, 10, str(self.num_page_no()+self.toc_length), '', 0, 'C') def setcol(self, col): self.col = col x = 10 + (col*100) self.set_left_margin(x) self.set_x(x) def accept_page_break(self): if self.section == 'Contents': self.toc_page_break_count = self.toc_page_break_count + 1 if self.section == 'Contributors': self.set_y(self.y0+20) if self.section == 'Index': if (self.orientation == 'Portrait' and self.col == 0) or (self.orientation == 'Landscape' and (self.col == 0 or self.col == 1)) : self.setcol(self.col + 1) self.set_y(self.y0+20) return False else: self.setcol(0) self.p_add_page() self.set_y(self.y0+20) return False else: return True
__init__
identifier_name
pdf.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ### 2008-2015 Charlie Barnes. ### This program is free software; you can redistribute it and/or modify ### it under the terms of the GNU General Public License as published by ### the Free Software Foundation; either version 2 of the License, or ### (at your option) any later version. ### This program is distributed in the hope that it will be useful, ### but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### You should have received a copy of the GNU General Public License ### along with this program; if not, write to the Free Software ### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA def repeat_to_length(string_to_expand, length): return (string_to_expand * ((length/len(string_to_expand))+1))[:length] try: from fpdf import FPDF except ImportError: from pyfpdf import FPDF class PDF(FPDF): def __init__(self, orientation,unit,format): FPDF.__init__(self, orientation=orientation,unit=unit,format=format) self.toc = [] self.numbering = False self.num_page_num = 0 self.toc_page_break_count = 1 self.set_left_margin(10) self.set_right_margin(10) self.do_header = False self.type = None self.toc_length = 0 self.doing_the_list = False self.vcs = [] self.toc_page_num = 2 self.dataset = None self.orientation = orientation self.orientation_changes = [0] def p_add_page(self): #if(self.numbering): self.add_page() self.num_page_num = self.num_page_num + 1 def num_page_no(self): return self.num_page_num def startPageNums(self): self.numbering = True def stopPageNums(self): self.numbering = False def TOC_Entry(self, txt, level=0): self.toc.append({'t':txt, 'l':level, 'p':str(self.num_page_no()+self.toc_length)}) def insertTOC(self, location=1, labelSize=20, entrySize=10, tocfont='Helvetica', label='Table of Contents'): #make toc at end self.stopPageNums() self.section = 'Contents' self.p_add_page() tocstart = self.page self.set_font('Helvetica', '', 20) self.multi_cell(0, 20, 'Contents', 0, 'J', False) used_pages = [] link_abscissa = {} for t in self.toc: #Offset level = t['l'] if level > 0: self.cell(level*8) weight = '' if level == 0: weight = 'B' txxt = t['t'] self.set_font(tocfont, weight, entrySize) strsize = self.get_string_width(txxt) self.cell(strsize+2, self.font_size+2, txxt, 0, 0, '', False) #store the TOC links & position for later use if self.page_no() not in link_abscissa.keys(): link_abscissa[self.page_no()] = [] link_abscissa[self.page_no()].append([int(t['p']), self.y]) #Filling dots self.set_font(tocfont, '', entrySize) PageCellSize = self.get_string_width(t['p'])+2 w = self.w-self.l_margin-self.r_margin-PageCellSize-(level*8)-(strsize+2) nb = w/self.get_string_width('.') dots = repeat_to_length('.', int(nb)) self.cell(w, self.font_size+2, dots, 0, 0, 'R') #Page number of the toc entry self.cell(PageCellSize, self.font_size+2, str(int(t['p'])), 0, 1, 'R') if self.toc_page_break_count%2 != 0: self.section = '' self.toc_page_break_count = self.toc_page_break_count + 1 self.p_add_page() #Grab it and move to selected location n = self.page ntoc = n - tocstart + 1 last = [] #store toc pages i = tocstart while i <= n: last.append(self.pages[i]) i = i + 1 #move pages i = tocstart while i >= (location-1):
#Put toc pages at insert point i = 0 while i < ntoc: self.pages[location + i] = last[i] #loop through all the TOC links for this page and add them try: for linkdata in link_abscissa[tocstart+i]: self.page = location + i link = self.add_link() self.set_link(link, y=0, page=linkdata[0]) self.link(x=self.l_margin, y=linkdata[1], w=self.w-self.r_margin, h=self.font_size+2, link=link) except KeyError: pass i = i + 1 self.page = n def header(self): if self.do_header: self.set_font('Helvetica', '', 8) self.set_text_color(0, 0, 0) self.set_line_width(0.1) if (self.section <> 'Contents' and self.page_no()%2 == 0) or (self.section == 'Contents' and self.toc_page_break_count%2 == 0): self.cell(0, 5, self.section, 'B', 0, 'L', 0) # even page header self.cell(0, 5, self.title.replace('\n', ' - '), 'B', 1, 'R', 0) # even page header elif (self.section <> 'Contents' and self.page_no()%2 == 1) or (self.section == 'Contents' and self.toc_page_break_count%2 == 1): self.cell(0, 5, self.section, 'B', 1, 'R', 0) #odd page header if self.type == 'list' and self.doing_the_list == True: col_width = 12.7#((self.w - self.l_margin - self.r_margin)/2)/7.5 #vc headings self.set_font('Helvetica', '', 10) self.set_line_width(0.0) self.set_y(20) self.set_x(self.w-(7+col_width+(((col_width*3)+(col_width/4))*len(self.vcs)))) self.cell(col_width, 5, '', '0', 0, 'C', 0) for vc in sorted(self.vcs): if vc == None: vc_head_text = '' else: vc_head_text = ''.join(['VC',vc]) self.cell((col_width*3), 5, vc_head_text, '0', 0, 'C', 0) self.cell(col_width/4, 5, '', '0', 0, 'C', 0) self.ln() self.set_x(self.w-(7+col_width+(((col_width*3)+(col_width/4))*len(self.vcs)))) self.set_font('Helvetica', '', 8) self.cell(col_width, 5, '', '0', 0, 'C', 0) for vc in sorted(self.vcs): #colum headings self.cell(col_width, 5, ' '.join([self.dataset.config.get('List', 'distribution_unit'), 'sqs']), '0', 0, 'C', 0) self.cell(col_width, 5, 'Records', '0', 0, 'C', 0) self.cell(col_width, 5, 'Last in', '0', 0, 'C', 0) self.cell(col_width/4, 5, '', '0', 0, 'C', 0) self.y0 = self.get_y() if self.section == 'Contributors' or self.section == 'Contents': self.set_y(self.y0 + 20) def footer(self): self.set_y(-20) self.set_font('Helvetica','',8) #only show page numbers in the main body #if self.num_page_no() >= 4 and self.section != 'Contents' and self.section != 'Index' and self.section != 'Contributors' and self.section != 'References' and self.section != 'Introduction' and self.section != '': if self.num_page_no() >= 5 and self.section != 'Contents' and self.section != '' and self.section != 'Index' and self.section != 'Contributors' and self.section != 'References' and self.section != 'Introduction': self.cell(0, 10, str(self.num_page_no()+self.toc_length), '', 0, 'C') def setcol(self, col): self.col = col x = 10 + (col*100) self.set_left_margin(x) self.set_x(x) def accept_page_break(self): if self.section == 'Contents': self.toc_page_break_count = self.toc_page_break_count + 1 if self.section == 'Contributors': self.set_y(self.y0+20) if self.section == 'Index': if (self.orientation == 'Portrait' and self.col == 0) or (self.orientation == 'Landscape' and (self.col == 0 or self.col == 1)) : self.setcol(self.col + 1) self.set_y(self.y0+20) return False else: self.setcol(0) self.p_add_page() self.set_y(self.y0+20) return False else: return True
self.pages[i+ntoc] = self.pages[i] i = i - 1
conditional_block
pdf.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ### 2008-2015 Charlie Barnes. ### This program is free software; you can redistribute it and/or modify ### it under the terms of the GNU General Public License as published by ### the Free Software Foundation; either version 2 of the License, or ### (at your option) any later version. ### This program is distributed in the hope that it will be useful, ### but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### You should have received a copy of the GNU General Public License ### along with this program; if not, write to the Free Software ### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA def repeat_to_length(string_to_expand, length): return (string_to_expand * ((length/len(string_to_expand))+1))[:length] try: from fpdf import FPDF except ImportError: from pyfpdf import FPDF class PDF(FPDF): def __init__(self, orientation,unit,format): FPDF.__init__(self, orientation=orientation,unit=unit,format=format) self.toc = [] self.numbering = False self.num_page_num = 0 self.toc_page_break_count = 1 self.set_left_margin(10) self.set_right_margin(10) self.do_header = False self.type = None self.toc_length = 0 self.doing_the_list = False self.vcs = [] self.toc_page_num = 2 self.dataset = None self.orientation = orientation self.orientation_changes = [0] def p_add_page(self): #if(self.numbering): self.add_page() self.num_page_num = self.num_page_num + 1 def num_page_no(self): return self.num_page_num def startPageNums(self): self.numbering = True def stopPageNums(self): self.numbering = False def TOC_Entry(self, txt, level=0): self.toc.append({'t':txt, 'l':level, 'p':str(self.num_page_no()+self.toc_length)}) def insertTOC(self, location=1, labelSize=20, entrySize=10, tocfont='Helvetica', label='Table of Contents'): #make toc at end self.stopPageNums() self.section = 'Contents' self.p_add_page() tocstart = self.page self.set_font('Helvetica', '', 20) self.multi_cell(0, 20, 'Contents', 0, 'J', False) used_pages = [] link_abscissa = {} for t in self.toc: #Offset level = t['l'] if level > 0: self.cell(level*8) weight = '' if level == 0: weight = 'B' txxt = t['t'] self.set_font(tocfont, weight, entrySize) strsize = self.get_string_width(txxt) self.cell(strsize+2, self.font_size+2, txxt, 0, 0, '', False) #store the TOC links & position for later use if self.page_no() not in link_abscissa.keys(): link_abscissa[self.page_no()] = [] link_abscissa[self.page_no()].append([int(t['p']), self.y]) #Filling dots self.set_font(tocfont, '', entrySize) PageCellSize = self.get_string_width(t['p'])+2 w = self.w-self.l_margin-self.r_margin-PageCellSize-(level*8)-(strsize+2) nb = w/self.get_string_width('.') dots = repeat_to_length('.', int(nb)) self.cell(w, self.font_size+2, dots, 0, 0, 'R') #Page number of the toc entry self.cell(PageCellSize, self.font_size+2, str(int(t['p'])), 0, 1, 'R') if self.toc_page_break_count%2 != 0: self.section = '' self.toc_page_break_count = self.toc_page_break_count + 1 self.p_add_page() #Grab it and move to selected location n = self.page ntoc = n - tocstart + 1 last = [] #store toc pages i = tocstart while i <= n: last.append(self.pages[i]) i = i + 1 #move pages i = tocstart while i >= (location-1): self.pages[i+ntoc] = self.pages[i] i = i - 1 #Put toc pages at insert point i = 0 while i < ntoc: self.pages[location + i] = last[i] #loop through all the TOC links for this page and add them try: for linkdata in link_abscissa[tocstart+i]: self.page = location + i link = self.add_link() self.set_link(link, y=0, page=linkdata[0]) self.link(x=self.l_margin, y=linkdata[1], w=self.w-self.r_margin, h=self.font_size+2, link=link) except KeyError: pass i = i + 1 self.page = n def header(self): if self.do_header: self.set_font('Helvetica', '', 8) self.set_text_color(0, 0, 0) self.set_line_width(0.1) if (self.section <> 'Contents' and self.page_no()%2 == 0) or (self.section == 'Contents' and self.toc_page_break_count%2 == 0): self.cell(0, 5, self.section, 'B', 0, 'L', 0) # even page header self.cell(0, 5, self.title.replace('\n', ' - '), 'B', 1, 'R', 0) # even page header elif (self.section <> 'Contents' and self.page_no()%2 == 1) or (self.section == 'Contents' and self.toc_page_break_count%2 == 1): self.cell(0, 5, self.section, 'B', 1, 'R', 0) #odd page header if self.type == 'list' and self.doing_the_list == True: col_width = 12.7#((self.w - self.l_margin - self.r_margin)/2)/7.5 #vc headings self.set_font('Helvetica', '', 10) self.set_line_width(0.0) self.set_y(20) self.set_x(self.w-(7+col_width+(((col_width*3)+(col_width/4))*len(self.vcs)))) self.cell(col_width, 5, '', '0', 0, 'C', 0) for vc in sorted(self.vcs): if vc == None: vc_head_text = '' else: vc_head_text = ''.join(['VC',vc]) self.cell((col_width*3), 5, vc_head_text, '0', 0, 'C', 0) self.cell(col_width/4, 5, '', '0', 0, 'C', 0) self.ln() self.set_x(self.w-(7+col_width+(((col_width*3)+(col_width/4))*len(self.vcs)))) self.set_font('Helvetica', '', 8) self.cell(col_width, 5, '', '0', 0, 'C', 0) for vc in sorted(self.vcs): #colum headings self.cell(col_width, 5, ' '.join([self.dataset.config.get('List', 'distribution_unit'), 'sqs']), '0', 0, 'C', 0) self.cell(col_width, 5, 'Records', '0', 0, 'C', 0) self.cell(col_width, 5, 'Last in', '0', 0, 'C', 0) self.cell(col_width/4, 5, '', '0', 0, 'C', 0) self.y0 = self.get_y() if self.section == 'Contributors' or self.section == 'Contents': self.set_y(self.y0 + 20) def footer(self): self.set_y(-20) self.set_font('Helvetica','',8) #only show page numbers in the main body #if self.num_page_no() >= 4 and self.section != 'Contents' and self.section != 'Index' and self.section != 'Contributors' and self.section != 'References' and self.section != 'Introduction' and self.section != '': if self.num_page_no() >= 5 and self.section != 'Contents' and self.section != '' and self.section != 'Index' and self.section != 'Contributors' and self.section != 'References' and self.section != 'Introduction': self.cell(0, 10, str(self.num_page_no()+self.toc_length), '', 0, 'C') def setcol(self, col): self.col = col x = 10 + (col*100) self.set_left_margin(x) self.set_x(x) def accept_page_break(self): if self.section == 'Contents': self.toc_page_break_count = self.toc_page_break_count + 1 if self.section == 'Contributors': self.set_y(self.y0+20) if self.section == 'Index': if (self.orientation == 'Portrait' and self.col == 0) or (self.orientation == 'Landscape' and (self.col == 0 or self.col == 1)) : self.setcol(self.col + 1) self.set_y(self.y0+20) return False else: self.setcol(0) self.p_add_page()
self.set_y(self.y0+20) return False else: return True
random_line_split
pdf.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ### 2008-2015 Charlie Barnes. ### This program is free software; you can redistribute it and/or modify ### it under the terms of the GNU General Public License as published by ### the Free Software Foundation; either version 2 of the License, or ### (at your option) any later version. ### This program is distributed in the hope that it will be useful, ### but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### You should have received a copy of the GNU General Public License ### along with this program; if not, write to the Free Software ### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA def repeat_to_length(string_to_expand, length): return (string_to_expand * ((length/len(string_to_expand))+1))[:length] try: from fpdf import FPDF except ImportError: from pyfpdf import FPDF class PDF(FPDF): def __init__(self, orientation,unit,format):
def p_add_page(self): #if(self.numbering): self.add_page() self.num_page_num = self.num_page_num + 1 def num_page_no(self): return self.num_page_num def startPageNums(self): self.numbering = True def stopPageNums(self): self.numbering = False def TOC_Entry(self, txt, level=0): self.toc.append({'t':txt, 'l':level, 'p':str(self.num_page_no()+self.toc_length)}) def insertTOC(self, location=1, labelSize=20, entrySize=10, tocfont='Helvetica', label='Table of Contents'): #make toc at end self.stopPageNums() self.section = 'Contents' self.p_add_page() tocstart = self.page self.set_font('Helvetica', '', 20) self.multi_cell(0, 20, 'Contents', 0, 'J', False) used_pages = [] link_abscissa = {} for t in self.toc: #Offset level = t['l'] if level > 0: self.cell(level*8) weight = '' if level == 0: weight = 'B' txxt = t['t'] self.set_font(tocfont, weight, entrySize) strsize = self.get_string_width(txxt) self.cell(strsize+2, self.font_size+2, txxt, 0, 0, '', False) #store the TOC links & position for later use if self.page_no() not in link_abscissa.keys(): link_abscissa[self.page_no()] = [] link_abscissa[self.page_no()].append([int(t['p']), self.y]) #Filling dots self.set_font(tocfont, '', entrySize) PageCellSize = self.get_string_width(t['p'])+2 w = self.w-self.l_margin-self.r_margin-PageCellSize-(level*8)-(strsize+2) nb = w/self.get_string_width('.') dots = repeat_to_length('.', int(nb)) self.cell(w, self.font_size+2, dots, 0, 0, 'R') #Page number of the toc entry self.cell(PageCellSize, self.font_size+2, str(int(t['p'])), 0, 1, 'R') if self.toc_page_break_count%2 != 0: self.section = '' self.toc_page_break_count = self.toc_page_break_count + 1 self.p_add_page() #Grab it and move to selected location n = self.page ntoc = n - tocstart + 1 last = [] #store toc pages i = tocstart while i <= n: last.append(self.pages[i]) i = i + 1 #move pages i = tocstart while i >= (location-1): self.pages[i+ntoc] = self.pages[i] i = i - 1 #Put toc pages at insert point i = 0 while i < ntoc: self.pages[location + i] = last[i] #loop through all the TOC links for this page and add them try: for linkdata in link_abscissa[tocstart+i]: self.page = location + i link = self.add_link() self.set_link(link, y=0, page=linkdata[0]) self.link(x=self.l_margin, y=linkdata[1], w=self.w-self.r_margin, h=self.font_size+2, link=link) except KeyError: pass i = i + 1 self.page = n def header(self): if self.do_header: self.set_font('Helvetica', '', 8) self.set_text_color(0, 0, 0) self.set_line_width(0.1) if (self.section <> 'Contents' and self.page_no()%2 == 0) or (self.section == 'Contents' and self.toc_page_break_count%2 == 0): self.cell(0, 5, self.section, 'B', 0, 'L', 0) # even page header self.cell(0, 5, self.title.replace('\n', ' - '), 'B', 1, 'R', 0) # even page header elif (self.section <> 'Contents' and self.page_no()%2 == 1) or (self.section == 'Contents' and self.toc_page_break_count%2 == 1): self.cell(0, 5, self.section, 'B', 1, 'R', 0) #odd page header if self.type == 'list' and self.doing_the_list == True: col_width = 12.7#((self.w - self.l_margin - self.r_margin)/2)/7.5 #vc headings self.set_font('Helvetica', '', 10) self.set_line_width(0.0) self.set_y(20) self.set_x(self.w-(7+col_width+(((col_width*3)+(col_width/4))*len(self.vcs)))) self.cell(col_width, 5, '', '0', 0, 'C', 0) for vc in sorted(self.vcs): if vc == None: vc_head_text = '' else: vc_head_text = ''.join(['VC',vc]) self.cell((col_width*3), 5, vc_head_text, '0', 0, 'C', 0) self.cell(col_width/4, 5, '', '0', 0, 'C', 0) self.ln() self.set_x(self.w-(7+col_width+(((col_width*3)+(col_width/4))*len(self.vcs)))) self.set_font('Helvetica', '', 8) self.cell(col_width, 5, '', '0', 0, 'C', 0) for vc in sorted(self.vcs): #colum headings self.cell(col_width, 5, ' '.join([self.dataset.config.get('List', 'distribution_unit'), 'sqs']), '0', 0, 'C', 0) self.cell(col_width, 5, 'Records', '0', 0, 'C', 0) self.cell(col_width, 5, 'Last in', '0', 0, 'C', 0) self.cell(col_width/4, 5, '', '0', 0, 'C', 0) self.y0 = self.get_y() if self.section == 'Contributors' or self.section == 'Contents': self.set_y(self.y0 + 20) def footer(self): self.set_y(-20) self.set_font('Helvetica','',8) #only show page numbers in the main body #if self.num_page_no() >= 4 and self.section != 'Contents' and self.section != 'Index' and self.section != 'Contributors' and self.section != 'References' and self.section != 'Introduction' and self.section != '': if self.num_page_no() >= 5 and self.section != 'Contents' and self.section != '' and self.section != 'Index' and self.section != 'Contributors' and self.section != 'References' and self.section != 'Introduction': self.cell(0, 10, str(self.num_page_no()+self.toc_length), '', 0, 'C') def setcol(self, col): self.col = col x = 10 + (col*100) self.set_left_margin(x) self.set_x(x) def accept_page_break(self): if self.section == 'Contents': self.toc_page_break_count = self.toc_page_break_count + 1 if self.section == 'Contributors': self.set_y(self.y0+20) if self.section == 'Index': if (self.orientation == 'Portrait' and self.col == 0) or (self.orientation == 'Landscape' and (self.col == 0 or self.col == 1)) : self.setcol(self.col + 1) self.set_y(self.y0+20) return False else: self.setcol(0) self.p_add_page() self.set_y(self.y0+20) return False else: return True
FPDF.__init__(self, orientation=orientation,unit=unit,format=format) self.toc = [] self.numbering = False self.num_page_num = 0 self.toc_page_break_count = 1 self.set_left_margin(10) self.set_right_margin(10) self.do_header = False self.type = None self.toc_length = 0 self.doing_the_list = False self.vcs = [] self.toc_page_num = 2 self.dataset = None self.orientation = orientation self.orientation_changes = [0]
identifier_body
InMoov2.minimal.py
#file : InMoov2.minimal.py # this will run with versions of MRL above 1695 # a very minimal script for InMoov # although this script is very short you can still # do voice control of a right hand or finger box # for any command which you say - you will be required to say a confirmation # e.g. you say -> open hand, InMoov will ask -> "Did you say open hand?", you will need to # respond with a confirmation ("yes","correct","yeah","ya") rightPort = "COM8" i01 = Runtime.createAndStart("i01", "InMoov") # starting parts i01.startEar() i01.startMouth() #to tweak the default voice i01.mouth.setGoogleURI("http://thehackettfamily.org/Voice_api/api2.php?voice=Ryan&txt=") ############## i01.startRightHand(rightPort) # tweaking defaults settings of right hand #i01.rightHand.thumb.setMinMax(55,135) #i01.rightHand.index.setMinMax(0,160)
#i01.rightHand.ringFinger.setMinMax(48,145) #i01.rightHand.pinky.setMinMax(45,146) #i01.rightHand.thumb.map(0,180,55,135) #i01.rightHand.index.map(0,180,0,160) #i01.rightHand.majeure.map(0,180,0,140) #i01.rightHand.ringFinger.map(0,180,48,145) #i01.rightHand.pinky.map(0,180,45,146) ################# # verbal commands ear = i01.ear ear.addCommand("attach right hand", "i01.rightHand", "attach") ear.addCommand("disconnect right hand", "i01.rightHand", "detach") ear.addCommand("rest", i01.getName(), "rest") ear.addCommand("open hand", "python", "handopen") ear.addCommand("close hand", "python", "handclose") ear.addCommand("capture gesture", ear.getName(), "captureGesture") ear.addCommand("manual", ear.getName(), "lockOutAllGrammarExcept", "voice control") ear.addCommand("voice control", ear.getName(), "clearLock") ear.addComfirmations("yes","correct","yeah","ya") ear.addNegations("no","wrong","nope","nah") ear.startListening() def handopen(): i01.moveHand("left",0,0,0,0,0) i01.moveHand("right",0,0,0,0,0) def handclose(): i01.moveHand("left",180,180,180,180,180) i01.moveHand("right",180,180,180,180,180)
#i01.rightHand.majeure.setMinMax(0,140)
random_line_split
InMoov2.minimal.py
#file : InMoov2.minimal.py # this will run with versions of MRL above 1695 # a very minimal script for InMoov # although this script is very short you can still # do voice control of a right hand or finger box # for any command which you say - you will be required to say a confirmation # e.g. you say -> open hand, InMoov will ask -> "Did you say open hand?", you will need to # respond with a confirmation ("yes","correct","yeah","ya") rightPort = "COM8" i01 = Runtime.createAndStart("i01", "InMoov") # starting parts i01.startEar() i01.startMouth() #to tweak the default voice i01.mouth.setGoogleURI("http://thehackettfamily.org/Voice_api/api2.php?voice=Ryan&txt=") ############## i01.startRightHand(rightPort) # tweaking defaults settings of right hand #i01.rightHand.thumb.setMinMax(55,135) #i01.rightHand.index.setMinMax(0,160) #i01.rightHand.majeure.setMinMax(0,140) #i01.rightHand.ringFinger.setMinMax(48,145) #i01.rightHand.pinky.setMinMax(45,146) #i01.rightHand.thumb.map(0,180,55,135) #i01.rightHand.index.map(0,180,0,160) #i01.rightHand.majeure.map(0,180,0,140) #i01.rightHand.ringFinger.map(0,180,48,145) #i01.rightHand.pinky.map(0,180,45,146) ################# # verbal commands ear = i01.ear ear.addCommand("attach right hand", "i01.rightHand", "attach") ear.addCommand("disconnect right hand", "i01.rightHand", "detach") ear.addCommand("rest", i01.getName(), "rest") ear.addCommand("open hand", "python", "handopen") ear.addCommand("close hand", "python", "handclose") ear.addCommand("capture gesture", ear.getName(), "captureGesture") ear.addCommand("manual", ear.getName(), "lockOutAllGrammarExcept", "voice control") ear.addCommand("voice control", ear.getName(), "clearLock") ear.addComfirmations("yes","correct","yeah","ya") ear.addNegations("no","wrong","nope","nah") ear.startListening() def handopen():
def handclose(): i01.moveHand("left",180,180,180,180,180) i01.moveHand("right",180,180,180,180,180)
i01.moveHand("left",0,0,0,0,0) i01.moveHand("right",0,0,0,0,0)
identifier_body
InMoov2.minimal.py
#file : InMoov2.minimal.py # this will run with versions of MRL above 1695 # a very minimal script for InMoov # although this script is very short you can still # do voice control of a right hand or finger box # for any command which you say - you will be required to say a confirmation # e.g. you say -> open hand, InMoov will ask -> "Did you say open hand?", you will need to # respond with a confirmation ("yes","correct","yeah","ya") rightPort = "COM8" i01 = Runtime.createAndStart("i01", "InMoov") # starting parts i01.startEar() i01.startMouth() #to tweak the default voice i01.mouth.setGoogleURI("http://thehackettfamily.org/Voice_api/api2.php?voice=Ryan&txt=") ############## i01.startRightHand(rightPort) # tweaking defaults settings of right hand #i01.rightHand.thumb.setMinMax(55,135) #i01.rightHand.index.setMinMax(0,160) #i01.rightHand.majeure.setMinMax(0,140) #i01.rightHand.ringFinger.setMinMax(48,145) #i01.rightHand.pinky.setMinMax(45,146) #i01.rightHand.thumb.map(0,180,55,135) #i01.rightHand.index.map(0,180,0,160) #i01.rightHand.majeure.map(0,180,0,140) #i01.rightHand.ringFinger.map(0,180,48,145) #i01.rightHand.pinky.map(0,180,45,146) ################# # verbal commands ear = i01.ear ear.addCommand("attach right hand", "i01.rightHand", "attach") ear.addCommand("disconnect right hand", "i01.rightHand", "detach") ear.addCommand("rest", i01.getName(), "rest") ear.addCommand("open hand", "python", "handopen") ear.addCommand("close hand", "python", "handclose") ear.addCommand("capture gesture", ear.getName(), "captureGesture") ear.addCommand("manual", ear.getName(), "lockOutAllGrammarExcept", "voice control") ear.addCommand("voice control", ear.getName(), "clearLock") ear.addComfirmations("yes","correct","yeah","ya") ear.addNegations("no","wrong","nope","nah") ear.startListening() def handopen(): i01.moveHand("left",0,0,0,0,0) i01.moveHand("right",0,0,0,0,0) def
(): i01.moveHand("left",180,180,180,180,180) i01.moveHand("right",180,180,180,180,180)
handclose
identifier_name
profesor.js
/**
* * @param {String} id ID de la etiqueta HTML asociada. * @param {Boolean revisor ¿Sólo se buscarán revisores? * @returns {Profesor} */ function Profesor(id, revisor) { /** * Establece la etiqueta HTML asociada a esta plantilla. */ this.id = id; /** * Establece si la plantilla de búsqueda sólo buscará revisores en * el servidor o no. */ this.revisor = false; if (typeof revisor !== 'undefined') { this.revisor = revisor; } /** * Devuelve la etiqueta HTML asociada. * * @returns {jQuery} */ this.objeto = function () { return $('input#' + this.id); }; /** * Inicializa el INPUT como un objeto Select2. */ this.inicializar = function () { revisor = this.revisor; this.objeto().select2( { placeholder: 'Elija un profesor', minimumInputLength: 1, minimumResultsForSearch: 1, formatSearching: 'Buscando...', formatAjaxError: 'Ha habido un error en la petición', dropdownCssClass: 'bigdrop', dropdownAutoWidth: true, ajax: { url: '/index/select2Profesor', dataType: 'json', type: 'POST', async: false, data: function (cadena) { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), cadena, 2); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } console.log(this.revisor); console.log(datos); return datos; }, results: function (datos) { return {results: obtenerDatosSelect2(datos)}; } }, formatResult: function (objeto) { return objeto['nombreCompleto']; }, formatSelection: function (objeto) { return objeto['nombreCompleto']; }, initSelection: function (elemento, callback) { var id = $(elemento).val(); if (id !== '') { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), id, 1); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } $.ajax('/index/select2Profesor', { dataType: 'json', type: 'POST', async: false, data: datos }).done(function (datos) { callback(obtenerDatosSelect2(datos)[0]); }); } } }); }; /** * Desplaza las etiquetas HTML Select2 que se usan para este profesor. */ this.moverSelect2 = function () { this.objeto().parent().append($('div#s2id_' + this.id)); }; }
* Clase que permite trabajar con la plantilla del profesor.
random_line_split
profesor.js
/** * Clase que permite trabajar con la plantilla del profesor. * * @param {String} id ID de la etiqueta HTML asociada. * @param {Boolean revisor ¿Sólo se buscarán revisores? * @returns {Profesor} */ function Profesor(id, revisor) {
/** * Establece la etiqueta HTML asociada a esta plantilla. */ this.id = id; /** * Establece si la plantilla de búsqueda sólo buscará revisores en * el servidor o no. */ this.revisor = false; if (typeof revisor !== 'undefined') { this.revisor = revisor; } /** * Devuelve la etiqueta HTML asociada. * * @returns {jQuery} */ this.objeto = function () { return $('input#' + this.id); }; /** * Inicializa el INPUT como un objeto Select2. */ this.inicializar = function () { revisor = this.revisor; this.objeto().select2( { placeholder: 'Elija un profesor', minimumInputLength: 1, minimumResultsForSearch: 1, formatSearching: 'Buscando...', formatAjaxError: 'Ha habido un error en la petición', dropdownCssClass: 'bigdrop', dropdownAutoWidth: true, ajax: { url: '/index/select2Profesor', dataType: 'json', type: 'POST', async: false, data: function (cadena) { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), cadena, 2); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } console.log(this.revisor); console.log(datos); return datos; }, results: function (datos) { return {results: obtenerDatosSelect2(datos)}; } }, formatResult: function (objeto) { return objeto['nombreCompleto']; }, formatSelection: function (objeto) { return objeto['nombreCompleto']; }, initSelection: function (elemento, callback) { var id = $(elemento).val(); if (id !== '') { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), id, 1); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } $.ajax('/index/select2Profesor', { dataType: 'json', type: 'POST', async: false, data: datos }).done(function (datos) { callback(obtenerDatosSelect2(datos)[0]); }); } } }); }; /** * Desplaza las etiquetas HTML Select2 que se usan para este profesor. */ this.moverSelect2 = function () { this.objeto().parent().append($('div#s2id_' + this.id)); }; }
identifier_body
profesor.js
/** * Clase que permite trabajar con la plantilla del profesor. * * @param {String} id ID de la etiqueta HTML asociada. * @param {Boolean revisor ¿Sólo se buscarán revisores? * @returns {Profesor} */ function Pro
, revisor) { /** * Establece la etiqueta HTML asociada a esta plantilla. */ this.id = id; /** * Establece si la plantilla de búsqueda sólo buscará revisores en * el servidor o no. */ this.revisor = false; if (typeof revisor !== 'undefined') { this.revisor = revisor; } /** * Devuelve la etiqueta HTML asociada. * * @returns {jQuery} */ this.objeto = function () { return $('input#' + this.id); }; /** * Inicializa el INPUT como un objeto Select2. */ this.inicializar = function () { revisor = this.revisor; this.objeto().select2( { placeholder: 'Elija un profesor', minimumInputLength: 1, minimumResultsForSearch: 1, formatSearching: 'Buscando...', formatAjaxError: 'Ha habido un error en la petición', dropdownCssClass: 'bigdrop', dropdownAutoWidth: true, ajax: { url: '/index/select2Profesor', dataType: 'json', type: 'POST', async: false, data: function (cadena) { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), cadena, 2); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } console.log(this.revisor); console.log(datos); return datos; }, results: function (datos) { return {results: obtenerDatosSelect2(datos)}; } }, formatResult: function (objeto) { return objeto['nombreCompleto']; }, formatSelection: function (objeto) { return objeto['nombreCompleto']; }, initSelection: function (elemento, callback) { var id = $(elemento).val(); if (id !== '') { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), id, 1); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } $.ajax('/index/select2Profesor', { dataType: 'json', type: 'POST', async: false, data: datos }).done(function (datos) { callback(obtenerDatosSelect2(datos)[0]); }); } } }); }; /** * Desplaza las etiquetas HTML Select2 que se usan para este profesor. */ this.moverSelect2 = function () { this.objeto().parent().append($('div#s2id_' + this.id)); }; }
fesor(id
identifier_name
profesor.js
/** * Clase que permite trabajar con la plantilla del profesor. * * @param {String} id ID de la etiqueta HTML asociada. * @param {Boolean revisor ¿Sólo se buscarán revisores? * @returns {Profesor} */ function Profesor(id, revisor) { /** * Establece la etiqueta HTML asociada a esta plantilla. */ this.id = id; /** * Establece si la plantilla de búsqueda sólo buscará revisores en * el servidor o no. */ this.revisor = false; if (typeof revisor !== 'undefined') { this.revisor = revisor; } /** * Devuelve la etiqueta HTML asociada. * * @returns {jQuery} */ this.objeto = function () { return $('input#' + this.id); }; /** * Inicializa el INPUT como un objeto Select2. */ this.inicializar = function () { revisor = this.revisor; this.objeto().select2( { placeholder: 'Elija un profesor', minimumInputLength: 1, minimumResultsForSearch: 1, formatSearching: 'Buscando...', formatAjaxError: 'Ha habido un error en la petición', dropdownCssClass: 'bigdrop', dropdownAutoWidth: true, ajax: { url: '/index/select2Profesor', dataType: 'json', type: 'POST', async: false, data: function (cadena) { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), cadena, 2); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } console.log(this.revisor); console.log(datos); return datos; }, results: function (datos) { return {results: obtenerDatosSelect2(datos)}; } }, formatResult: function (objeto) { return objeto['nombreCompleto']; }, formatSelection: function (objeto) { return objeto['nombreCompleto']; }, initSelection: function (elemento, callback) { var id = $(elemento).val(); if (id !== '') { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), id, 1); if (revisor) {
$.ajax('/index/select2Profesor', { dataType: 'json', type: 'POST', async: false, data: datos }).done(function (datos) { callback(obtenerDatosSelect2(datos)[0]); }); } } }); }; /** * Desplaza las etiquetas HTML Select2 que se usan para este profesor. */ this.moverSelect2 = function () { this.objeto().parent().append($('div#s2id_' + this.id)); }; }
datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; }
conditional_block
rte.js
odoo.define('website.tour.rte', function (require) { 'use strict'; var ajax = require('web.ajax'); var session = require('web.session'); var tour = require('web_tour.tour'); var Wysiwyg = require('web_editor.wysiwyg.root'); var domReady = new Promise(function (resolve) { $(resolve); }); var ready = Promise.all([domReady, session.is_bound, ajax.loadXML()]); tour.register('rte_translator', { test: true, url: '/fr_BE', wait_for: ready, }, [{ content : "click language dropdown", trigger : '.js_language_selector .dropdown-toggle', }, { content: "go to english version", trigger: '.js_language_selector a[data-url_code="en"]', extra_trigger: 'html[lang*="fr"]', }, { content: "Open new page menu", trigger: '#new-content-menu > a', extra_trigger: 'a[data-action="edit"]', }, { content: "click on new page", trigger: 'a[data-action="new_page"]', }, { content: "insert page name", trigger: '#editor_new_page input[type="text"]', run: 'text rte_translator', }, { content: "create page", trigger: 'button.btn-continue', extra_trigger: 'input[type="text"]:propValue(rte_translator)', }, { content: "drop a snippet", trigger: "#snippet_structure .oe_snippet:eq(1) .oe_snippet_thumbnail", run: 'drag_and_drop #wrap', }, { content: "change content", trigger: '#wrap', run: function () { $("#wrap p:first").replaceWith('<p>Write one or <font style="background-color: yellow;">two paragraphs <b>describing</b></font> your product or\ <font style="color: rgb(255, 0, 0);">services</font>. To be successful your content needs to be\ useful to your <a href="/999">readers</a>.</p> <input placeholder="test translate placeholder"/>\ <p>&lt;b&gt;&lt;/b&gt; is an HTML&nbsp;tag &amp; is empty</p>'); $("#wrap img").attr("title", "test translate image title"); } }, { content: "save", trigger: 'button[data-action=save]', extra_trigger: '#wrap p:first b', }, { content : "click language dropdown", trigger : '.js_language_selector .dropdown-toggle', extra_trigger: 'body:not(.o_wait_reload):not(:has(.note-editor)) a[data-action="edit"]', }, { content: "click on french version", trigger: '.js_language_selector a[data-url_code="fr_BE"]', extra_trigger: 'html[lang*="en"]:not(:has(button[data-action=save]))', }, { content: "translate", trigger: 'html:not(:has(#wrap p span)) .o_menu_systray a[data-action="translate"]', }, { content: "close modal", trigger: '.modal-footer .btn-secondary', }, { content: "check if translation is activate", trigger: '[data-oe-translation-id]', }, { content: "translate text", trigger: '#wrap p font:first', run: function (action_helper) {
}, }, { content: "translate text with special char", trigger: '#wrap input + p span:first', run: function (action_helper) { action_helper.click(); this.$anchor.prepend('&lt;{translated}&gt;'); Wysiwyg.setRange(this.$anchor.contents()[0], 0); this.$anchor.trigger($.Event( "keyup", {key: '_', keyCode: 95})); this.$anchor.trigger('input'); }, }, { content: "click on input", trigger: '#wrap input:first', extra_trigger: '#wrap .o_dirty font:first:contains(translated french text)', run: 'click', }, { content: "translate placeholder", trigger: 'input:first', run: 'text test french placeholder', }, { content: "close modal", trigger: '.modal-footer .btn-primary', extra_trigger: '.modal input:propValue(test french placeholder)', }, { content: "save translation", trigger: 'button[data-action=save]', }, { content: "check: content is translated", trigger: '#wrap p font:first:contains(translated french text)', extra_trigger: 'body:not(.o_wait_reload):not(:has(.note-editor)) a[data-action="edit_master"]', run: function () {}, // it's a check }, { content: "check: content with special char is translated", trigger: "#wrap input + p:contains(<{translated}><b></b> is an HTML\xa0tag & )", run: function () {}, // it's a check }, { content: "check: placeholder translation", trigger: 'input[placeholder="test french placeholder"]', run: function () {}, // it's a check }, { content: "open language selector", trigger: '.js_language_selector button:first', extra_trigger: 'html[lang*="fr"]:not(:has(#wrap p span))', }, { content: "return to english version", trigger: '.js_language_selector a[data-url_code="en"]', }, { content: "edit english version", trigger: 'a[data-action=edit]', extra_trigger: 'body:not(:has(#wrap p font:first:containsExact(paragraphs <b>describing</b>)))', }, { content: "select text", extra_trigger: '#oe_snippets.o_loaded', trigger: '#wrap p', run: function (action_helper) { action_helper.click(); var el = this.$anchor[0]; var mousedown = document.createEvent('MouseEvents'); mousedown.initMouseEvent('mousedown', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, el); el.dispatchEvent(mousedown); var mouseup = document.createEvent('MouseEvents'); Wysiwyg.setRange(el.childNodes[2], 6, el.childNodes[2], 13); mouseup.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, el); el.dispatchEvent(mouseup); }, }, { content: "underline", trigger: '.note-air-popover button[data-event="underline"]', }, { content: "save new change", trigger: 'button[data-action=save]', extra_trigger: '#wrap.o_dirty p u', }, { content : "click language dropdown", trigger : '.js_language_selector .dropdown-toggle', extra_trigger: 'body:not(.o_wait_reload):not(:has(.note-editor)) a[data-action="edit"]', }, { content: "return in french", trigger : 'html[lang="en-US"] .js_language_selector .js_change_lang[data-url_code="fr_BE"]', }, { content: "check bis: content is translated", trigger: '#wrap p font:first:contains(translated french text)', extra_trigger: 'html[lang*="fr"] body:not(:has(button[data-action=save]))', }, { content: "check bis: placeholder translation", trigger: 'input[placeholder="test french placeholder"]', }, { content: "Open customize menu", trigger: "#customize-menu > .dropdown-toggle", }, { content: "Open HTML editor", trigger: "[data-action='ace']", }, { content: "Check that the editor is not showing translated content (1)", trigger: '.ace_text-layer .ace_line:contains("an HTML")', run: function (actions) { var lineEscapedText = $(this.$anchor.text()).text(); if (lineEscapedText !== "&lt;b&gt;&lt;/b&gt; is an HTML&nbsp;tag &amp; is empty") { console.error('The HTML editor should display the correct untranslated content'); $('body').addClass('rte_translator_error'); } }, }, { content: "Check that the editor is not showing translated content (2)", trigger: 'body:not(.rte_translator_error)', run: function () {}, }]); });
action_helper.text('translated french text'); Wysiwyg.setRange(this.$anchor.contents()[0], 22); this.$anchor.trigger($.Event( "keyup", {key: '_', keyCode: 95})); this.$anchor.trigger('input');
random_line_split
rte.js
odoo.define('website.tour.rte', function (require) { 'use strict'; var ajax = require('web.ajax'); var session = require('web.session'); var tour = require('web_tour.tour'); var Wysiwyg = require('web_editor.wysiwyg.root'); var domReady = new Promise(function (resolve) { $(resolve); }); var ready = Promise.all([domReady, session.is_bound, ajax.loadXML()]); tour.register('rte_translator', { test: true, url: '/fr_BE', wait_for: ready, }, [{ content : "click language dropdown", trigger : '.js_language_selector .dropdown-toggle', }, { content: "go to english version", trigger: '.js_language_selector a[data-url_code="en"]', extra_trigger: 'html[lang*="fr"]', }, { content: "Open new page menu", trigger: '#new-content-menu > a', extra_trigger: 'a[data-action="edit"]', }, { content: "click on new page", trigger: 'a[data-action="new_page"]', }, { content: "insert page name", trigger: '#editor_new_page input[type="text"]', run: 'text rte_translator', }, { content: "create page", trigger: 'button.btn-continue', extra_trigger: 'input[type="text"]:propValue(rte_translator)', }, { content: "drop a snippet", trigger: "#snippet_structure .oe_snippet:eq(1) .oe_snippet_thumbnail", run: 'drag_and_drop #wrap', }, { content: "change content", trigger: '#wrap', run: function () { $("#wrap p:first").replaceWith('<p>Write one or <font style="background-color: yellow;">two paragraphs <b>describing</b></font> your product or\ <font style="color: rgb(255, 0, 0);">services</font>. To be successful your content needs to be\ useful to your <a href="/999">readers</a>.</p> <input placeholder="test translate placeholder"/>\ <p>&lt;b&gt;&lt;/b&gt; is an HTML&nbsp;tag &amp; is empty</p>'); $("#wrap img").attr("title", "test translate image title"); } }, { content: "save", trigger: 'button[data-action=save]', extra_trigger: '#wrap p:first b', }, { content : "click language dropdown", trigger : '.js_language_selector .dropdown-toggle', extra_trigger: 'body:not(.o_wait_reload):not(:has(.note-editor)) a[data-action="edit"]', }, { content: "click on french version", trigger: '.js_language_selector a[data-url_code="fr_BE"]', extra_trigger: 'html[lang*="en"]:not(:has(button[data-action=save]))', }, { content: "translate", trigger: 'html:not(:has(#wrap p span)) .o_menu_systray a[data-action="translate"]', }, { content: "close modal", trigger: '.modal-footer .btn-secondary', }, { content: "check if translation is activate", trigger: '[data-oe-translation-id]', }, { content: "translate text", trigger: '#wrap p font:first', run: function (action_helper) { action_helper.text('translated french text'); Wysiwyg.setRange(this.$anchor.contents()[0], 22); this.$anchor.trigger($.Event( "keyup", {key: '_', keyCode: 95})); this.$anchor.trigger('input'); }, }, { content: "translate text with special char", trigger: '#wrap input + p span:first', run: function (action_helper) { action_helper.click(); this.$anchor.prepend('&lt;{translated}&gt;'); Wysiwyg.setRange(this.$anchor.contents()[0], 0); this.$anchor.trigger($.Event( "keyup", {key: '_', keyCode: 95})); this.$anchor.trigger('input'); }, }, { content: "click on input", trigger: '#wrap input:first', extra_trigger: '#wrap .o_dirty font:first:contains(translated french text)', run: 'click', }, { content: "translate placeholder", trigger: 'input:first', run: 'text test french placeholder', }, { content: "close modal", trigger: '.modal-footer .btn-primary', extra_trigger: '.modal input:propValue(test french placeholder)', }, { content: "save translation", trigger: 'button[data-action=save]', }, { content: "check: content is translated", trigger: '#wrap p font:first:contains(translated french text)', extra_trigger: 'body:not(.o_wait_reload):not(:has(.note-editor)) a[data-action="edit_master"]', run: function () {}, // it's a check }, { content: "check: content with special char is translated", trigger: "#wrap input + p:contains(<{translated}><b></b> is an HTML\xa0tag & )", run: function () {}, // it's a check }, { content: "check: placeholder translation", trigger: 'input[placeholder="test french placeholder"]', run: function () {}, // it's a check }, { content: "open language selector", trigger: '.js_language_selector button:first', extra_trigger: 'html[lang*="fr"]:not(:has(#wrap p span))', }, { content: "return to english version", trigger: '.js_language_selector a[data-url_code="en"]', }, { content: "edit english version", trigger: 'a[data-action=edit]', extra_trigger: 'body:not(:has(#wrap p font:first:containsExact(paragraphs <b>describing</b>)))', }, { content: "select text", extra_trigger: '#oe_snippets.o_loaded', trigger: '#wrap p', run: function (action_helper) { action_helper.click(); var el = this.$anchor[0]; var mousedown = document.createEvent('MouseEvents'); mousedown.initMouseEvent('mousedown', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, el); el.dispatchEvent(mousedown); var mouseup = document.createEvent('MouseEvents'); Wysiwyg.setRange(el.childNodes[2], 6, el.childNodes[2], 13); mouseup.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, el); el.dispatchEvent(mouseup); }, }, { content: "underline", trigger: '.note-air-popover button[data-event="underline"]', }, { content: "save new change", trigger: 'button[data-action=save]', extra_trigger: '#wrap.o_dirty p u', }, { content : "click language dropdown", trigger : '.js_language_selector .dropdown-toggle', extra_trigger: 'body:not(.o_wait_reload):not(:has(.note-editor)) a[data-action="edit"]', }, { content: "return in french", trigger : 'html[lang="en-US"] .js_language_selector .js_change_lang[data-url_code="fr_BE"]', }, { content: "check bis: content is translated", trigger: '#wrap p font:first:contains(translated french text)', extra_trigger: 'html[lang*="fr"] body:not(:has(button[data-action=save]))', }, { content: "check bis: placeholder translation", trigger: 'input[placeholder="test french placeholder"]', }, { content: "Open customize menu", trigger: "#customize-menu > .dropdown-toggle", }, { content: "Open HTML editor", trigger: "[data-action='ace']", }, { content: "Check that the editor is not showing translated content (1)", trigger: '.ace_text-layer .ace_line:contains("an HTML")', run: function (actions) { var lineEscapedText = $(this.$anchor.text()).text(); if (lineEscapedText !== "&lt;b&gt;&lt;/b&gt; is an HTML&nbsp;tag &amp; is empty")
}, }, { content: "Check that the editor is not showing translated content (2)", trigger: 'body:not(.rte_translator_error)', run: function () {}, }]); });
{ console.error('The HTML editor should display the correct untranslated content'); $('body').addClass('rte_translator_error'); }
conditional_block
app.js
/** * Created by nickrickenbach on 8/11/15. */ var app = angular.module('BLANG', ['ngRoute', 'ngResource', 'ngSanitize', 'angularSpinner']); app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: HomeController, resolve: HomeController.resolve }) .when('/home', { templateUrl: 'views/home.html', controller: HomeController, resolve: HomeController.resolve }) .when('/projects', { templateUrl: 'views/projects.html', controller: ProjectsController, resolve: WorkController.resolve }) .when('/projects/:project', { templateUrl: 'views/project.html', controller: ProjectController, resolve: WorkController.resolve }) .otherwise({ redirectTo: '/' }); //$locationProvider.html5Mode(true); }]); app.run(['$rootScope', 'usSpinnerService', function ($rootScope, usSpinnerService) { $rootScope.startSpin = function (_spin) { usSpinnerService.spin(_spin); }; $rootScope.stopSpin = function (_spin) { usSpinnerService.stop(_spin); }; }]); app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location, $urlRouter) { $rootScope.$on('$routeChangeStart', function (event, next, current) { }); }]); app.directive('workimg',function(){ return { restrict: 'A', link: function(scope, element, attrs) { console.log('found'); element.find('img.bg-img-hide').bind('load', function() { element.removeClass("inactive"); //TweenMax.to(element,1,{opacity:1}); TweenMax.to(element.parent().parent().find(".spinner"),1,{opacity:0}); $(".site").scroll($rootScope.workScroll); }); } }; }); function getResolve(_url) { return { datasets : function ($rootScope, $q, $http, $location, $route) { _url = ($route.current.params.project) ? _url+"&project="+$route.current.params.project : _url; if (TweenMax)
else { setTimeout(function () { getResolve(_url); }, 200); } } } }
{ // showLoader TweenMax.to($('#main-overlay'), 0.2, { autoAlpha:1 }); TweenMax.set($('#main-overlay').find('span'), { marginTop:'0', opacity:0, rotationX:90 }); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop:'-65px', rotationX:0, opacity:1, ease:'Cubic.easeInOut', delay:0.2 }); // start Spinner $rootScope.startSpin('spinner-main'); var deferred = $q.defer(); TweenMax.to($(".site"),0.5,{scrollTop:0,onComplete:function() { $http.get(_url). success(function (data, status, headers, config) { // hide Loader TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0}); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop: '-130px', rotationZ: -180, ease: 'Cubic.easeInOut' }); deferred.resolve(data); }). error(function (data, status, headers, config) { // hide Loader TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0}); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop: '-130px', rotationZ: -180, ease: 'Cubic.easeInOut' }); deferred.resolve('error') }); }}); return deferred.promise; }
conditional_block
app.js
/** * Created by nickrickenbach on 8/11/15. */ var app = angular.module('BLANG', ['ngRoute', 'ngResource', 'ngSanitize', 'angularSpinner']); app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: HomeController, resolve: HomeController.resolve }) .when('/home', { templateUrl: 'views/home.html', controller: HomeController, resolve: HomeController.resolve }) .when('/projects', { templateUrl: 'views/projects.html', controller: ProjectsController, resolve: WorkController.resolve }) .when('/projects/:project', { templateUrl: 'views/project.html', controller: ProjectController, resolve: WorkController.resolve }) .otherwise({ redirectTo: '/' }); //$locationProvider.html5Mode(true); }]); app.run(['$rootScope', 'usSpinnerService', function ($rootScope, usSpinnerService) { $rootScope.startSpin = function (_spin) { usSpinnerService.spin(_spin); }; $rootScope.stopSpin = function (_spin) { usSpinnerService.stop(_spin); }; }]); app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location, $urlRouter) { $rootScope.$on('$routeChangeStart', function (event, next, current) { }); }]); app.directive('workimg',function(){ return { restrict: 'A', link: function(scope, element, attrs) { console.log('found'); element.find('img.bg-img-hide').bind('load', function() { element.removeClass("inactive"); //TweenMax.to(element,1,{opacity:1}); TweenMax.to(element.parent().parent().find(".spinner"),1,{opacity:0}); $(".site").scroll($rootScope.workScroll); }); } };
function getResolve(_url) { return { datasets : function ($rootScope, $q, $http, $location, $route) { _url = ($route.current.params.project) ? _url+"&project="+$route.current.params.project : _url; if (TweenMax) { // showLoader TweenMax.to($('#main-overlay'), 0.2, { autoAlpha:1 }); TweenMax.set($('#main-overlay').find('span'), { marginTop:'0', opacity:0, rotationX:90 }); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop:'-65px', rotationX:0, opacity:1, ease:'Cubic.easeInOut', delay:0.2 }); // start Spinner $rootScope.startSpin('spinner-main'); var deferred = $q.defer(); TweenMax.to($(".site"),0.5,{scrollTop:0,onComplete:function() { $http.get(_url). success(function (data, status, headers, config) { // hide Loader TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0}); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop: '-130px', rotationZ: -180, ease: 'Cubic.easeInOut' }); deferred.resolve(data); }). error(function (data, status, headers, config) { // hide Loader TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0}); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop: '-130px', rotationZ: -180, ease: 'Cubic.easeInOut' }); deferred.resolve('error') }); }}); return deferred.promise; }else { setTimeout(function () { getResolve(_url); }, 200); } } } }
});
random_line_split
app.js
/** * Created by nickrickenbach on 8/11/15. */ var app = angular.module('BLANG', ['ngRoute', 'ngResource', 'ngSanitize', 'angularSpinner']); app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: HomeController, resolve: HomeController.resolve }) .when('/home', { templateUrl: 'views/home.html', controller: HomeController, resolve: HomeController.resolve }) .when('/projects', { templateUrl: 'views/projects.html', controller: ProjectsController, resolve: WorkController.resolve }) .when('/projects/:project', { templateUrl: 'views/project.html', controller: ProjectController, resolve: WorkController.resolve }) .otherwise({ redirectTo: '/' }); //$locationProvider.html5Mode(true); }]); app.run(['$rootScope', 'usSpinnerService', function ($rootScope, usSpinnerService) { $rootScope.startSpin = function (_spin) { usSpinnerService.spin(_spin); }; $rootScope.stopSpin = function (_spin) { usSpinnerService.stop(_spin); }; }]); app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location, $urlRouter) { $rootScope.$on('$routeChangeStart', function (event, next, current) { }); }]); app.directive('workimg',function(){ return { restrict: 'A', link: function(scope, element, attrs) { console.log('found'); element.find('img.bg-img-hide').bind('load', function() { element.removeClass("inactive"); //TweenMax.to(element,1,{opacity:1}); TweenMax.to(element.parent().parent().find(".spinner"),1,{opacity:0}); $(".site").scroll($rootScope.workScroll); }); } }; }); function
(_url) { return { datasets : function ($rootScope, $q, $http, $location, $route) { _url = ($route.current.params.project) ? _url+"&project="+$route.current.params.project : _url; if (TweenMax) { // showLoader TweenMax.to($('#main-overlay'), 0.2, { autoAlpha:1 }); TweenMax.set($('#main-overlay').find('span'), { marginTop:'0', opacity:0, rotationX:90 }); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop:'-65px', rotationX:0, opacity:1, ease:'Cubic.easeInOut', delay:0.2 }); // start Spinner $rootScope.startSpin('spinner-main'); var deferred = $q.defer(); TweenMax.to($(".site"),0.5,{scrollTop:0,onComplete:function() { $http.get(_url). success(function (data, status, headers, config) { // hide Loader TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0}); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop: '-130px', rotationZ: -180, ease: 'Cubic.easeInOut' }); deferred.resolve(data); }). error(function (data, status, headers, config) { // hide Loader TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0}); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop: '-130px', rotationZ: -180, ease: 'Cubic.easeInOut' }); deferred.resolve('error') }); }}); return deferred.promise; }else { setTimeout(function () { getResolve(_url); }, 200); } } } }
getResolve
identifier_name
app.js
/** * Created by nickrickenbach on 8/11/15. */ var app = angular.module('BLANG', ['ngRoute', 'ngResource', 'ngSanitize', 'angularSpinner']); app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/home.html', controller: HomeController, resolve: HomeController.resolve }) .when('/home', { templateUrl: 'views/home.html', controller: HomeController, resolve: HomeController.resolve }) .when('/projects', { templateUrl: 'views/projects.html', controller: ProjectsController, resolve: WorkController.resolve }) .when('/projects/:project', { templateUrl: 'views/project.html', controller: ProjectController, resolve: WorkController.resolve }) .otherwise({ redirectTo: '/' }); //$locationProvider.html5Mode(true); }]); app.run(['$rootScope', 'usSpinnerService', function ($rootScope, usSpinnerService) { $rootScope.startSpin = function (_spin) { usSpinnerService.spin(_spin); }; $rootScope.stopSpin = function (_spin) { usSpinnerService.stop(_spin); }; }]); app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location, $urlRouter) { $rootScope.$on('$routeChangeStart', function (event, next, current) { }); }]); app.directive('workimg',function(){ return { restrict: 'A', link: function(scope, element, attrs) { console.log('found'); element.find('img.bg-img-hide').bind('load', function() { element.removeClass("inactive"); //TweenMax.to(element,1,{opacity:1}); TweenMax.to(element.parent().parent().find(".spinner"),1,{opacity:0}); $(".site").scroll($rootScope.workScroll); }); } }; }); function getResolve(_url)
{ return { datasets : function ($rootScope, $q, $http, $location, $route) { _url = ($route.current.params.project) ? _url+"&project="+$route.current.params.project : _url; if (TweenMax) { // showLoader TweenMax.to($('#main-overlay'), 0.2, { autoAlpha:1 }); TweenMax.set($('#main-overlay').find('span'), { marginTop:'0', opacity:0, rotationX:90 }); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop:'-65px', rotationX:0, opacity:1, ease:'Cubic.easeInOut', delay:0.2 }); // start Spinner $rootScope.startSpin('spinner-main'); var deferred = $q.defer(); TweenMax.to($(".site"),0.5,{scrollTop:0,onComplete:function() { $http.get(_url). success(function (data, status, headers, config) { // hide Loader TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0}); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop: '-130px', rotationZ: -180, ease: 'Cubic.easeInOut' }); deferred.resolve(data); }). error(function (data, status, headers, config) { // hide Loader TweenMax.to($('#main-overlay'), 0.5, {autoAlpha: 0}); TweenMax.to($('#main-overlay').find('span'), 0.5, { marginTop: '-130px', rotationZ: -180, ease: 'Cubic.easeInOut' }); deferred.resolve('error') }); }}); return deferred.promise; }else { setTimeout(function () { getResolve(_url); }, 200); } } } }
identifier_body
cookiecutter.py
# -*- coding: utf-8 -*- """ Extension that integrates cookiecutter templates into PyScaffold. """ from __future__ import absolute_import import argparse from ..api.helpers import register, logger from ..api import Extension from ..contrib.six import raise_from class Cookiecutter(Extension): """Additionally apply a Cookiecutter template""" mutually_exclusive = True def augment_cli(self, parser): """Add an option to parser that enables the Cookiecutter extension Args: parser (argparse.ArgumentParser): CLI parser object """ parser.add_argument( self.flag, dest=self.name, action=create_cookiecutter_parser(self), metavar="TEMPLATE", help="additionally apply a Cookiecutter template. " "Note that not all templates are suitable for PyScaffold. " "Please refer to the docs for more information.")
Returns: list: updated list of actions """ # `get_default_options` uses passed options to compute derived ones, # so it is better to prepend actions that modify options. actions = register(actions, enforce_cookiecutter_options, before='get_default_options') # `apply_update_rules` uses CWD information, # so it is better to prepend actions that modify it. actions = register(actions, create_cookiecutter, before='apply_update_rules') return actions def create_cookiecutter_parser(obj_ref): """Create a Cookiecutter parser. Args: obj_ref (Extension): object reference to the actual extension Returns: NamespaceParser: parser for namespace cli argument """ class CookiecutterParser(argparse.Action): """Consumes the values provided, but also append the extension function to the extensions list. """ def __call__(self, parser, namespace, values, option_string=None): # First ensure the extension function is stored inside the # 'extensions' attribute: extensions = getattr(namespace, 'extensions', []) extensions.append(obj_ref) setattr(namespace, 'extensions', extensions) # Now the extra parameters can be stored setattr(namespace, self.dest, values) # save the cookiecutter cli argument for later obj_ref.args = values return CookiecutterParser def enforce_cookiecutter_options(struct, opts): """Make sure options reflect the cookiecutter usage. Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ opts['force'] = True return struct, opts def create_cookiecutter(struct, opts): """Create a cookie cutter template Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ try: from cookiecutter.main import cookiecutter except Exception as e: raise_from(NotInstalled, e) extra_context = dict(full_name=opts['author'], author=opts['author'], email=opts['email'], project_name=opts['project'], package_name=opts['package'], repo_name=opts['package'], project_short_description=opts['description'], release_date=opts['release_date'], version='unknown', # will be replaced later year=opts['year']) if 'cookiecutter' not in opts: raise MissingTemplate logger.report('run', 'cookiecutter ' + opts['cookiecutter']) if not opts.get('pretend'): cookiecutter(opts['cookiecutter'], no_input=True, extra_context=extra_context) return struct, opts class NotInstalled(RuntimeError): """This extension depends on the ``cookiecutter`` package.""" DEFAULT_MESSAGE = ("cookiecutter is not installed, " "run: pip install cookiecutter") def __init__(self, message=DEFAULT_MESSAGE, *args, **kwargs): super(NotInstalled, self).__init__(message, *args, **kwargs) class MissingTemplate(RuntimeError): """A cookiecutter template (git url) is required.""" DEFAULT_MESSAGE = "missing `cookiecutter` option" def __init__(self, message=DEFAULT_MESSAGE, *args, **kwargs): super(MissingTemplate, self).__init__(message, *args, **kwargs)
def activate(self, actions): """Register before_create hooks to generate project using Cookiecutter Args: actions (list): list of actions to perform
random_line_split
cookiecutter.py
# -*- coding: utf-8 -*- """ Extension that integrates cookiecutter templates into PyScaffold. """ from __future__ import absolute_import import argparse from ..api.helpers import register, logger from ..api import Extension from ..contrib.six import raise_from class Cookiecutter(Extension): """Additionally apply a Cookiecutter template""" mutually_exclusive = True def augment_cli(self, parser): """Add an option to parser that enables the Cookiecutter extension Args: parser (argparse.ArgumentParser): CLI parser object """ parser.add_argument( self.flag, dest=self.name, action=create_cookiecutter_parser(self), metavar="TEMPLATE", help="additionally apply a Cookiecutter template. " "Note that not all templates are suitable for PyScaffold. " "Please refer to the docs for more information.") def activate(self, actions): """Register before_create hooks to generate project using Cookiecutter Args: actions (list): list of actions to perform Returns: list: updated list of actions """ # `get_default_options` uses passed options to compute derived ones, # so it is better to prepend actions that modify options. actions = register(actions, enforce_cookiecutter_options, before='get_default_options') # `apply_update_rules` uses CWD information, # so it is better to prepend actions that modify it. actions = register(actions, create_cookiecutter, before='apply_update_rules') return actions def create_cookiecutter_parser(obj_ref): """Create a Cookiecutter parser. Args: obj_ref (Extension): object reference to the actual extension Returns: NamespaceParser: parser for namespace cli argument """ class CookiecutterParser(argparse.Action): """Consumes the values provided, but also append the extension function to the extensions list. """ def __call__(self, parser, namespace, values, option_string=None): # First ensure the extension function is stored inside the # 'extensions' attribute: extensions = getattr(namespace, 'extensions', []) extensions.append(obj_ref) setattr(namespace, 'extensions', extensions) # Now the extra parameters can be stored setattr(namespace, self.dest, values) # save the cookiecutter cli argument for later obj_ref.args = values return CookiecutterParser def enforce_cookiecutter_options(struct, opts): """Make sure options reflect the cookiecutter usage. Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ opts['force'] = True return struct, opts def create_cookiecutter(struct, opts): """Create a cookie cutter template Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ try: from cookiecutter.main import cookiecutter except Exception as e: raise_from(NotInstalled, e) extra_context = dict(full_name=opts['author'], author=opts['author'], email=opts['email'], project_name=opts['project'], package_name=opts['package'], repo_name=opts['package'], project_short_description=opts['description'], release_date=opts['release_date'], version='unknown', # will be replaced later year=opts['year']) if 'cookiecutter' not in opts:
logger.report('run', 'cookiecutter ' + opts['cookiecutter']) if not opts.get('pretend'): cookiecutter(opts['cookiecutter'], no_input=True, extra_context=extra_context) return struct, opts class NotInstalled(RuntimeError): """This extension depends on the ``cookiecutter`` package.""" DEFAULT_MESSAGE = ("cookiecutter is not installed, " "run: pip install cookiecutter") def __init__(self, message=DEFAULT_MESSAGE, *args, **kwargs): super(NotInstalled, self).__init__(message, *args, **kwargs) class MissingTemplate(RuntimeError): """A cookiecutter template (git url) is required.""" DEFAULT_MESSAGE = "missing `cookiecutter` option" def __init__(self, message=DEFAULT_MESSAGE, *args, **kwargs): super(MissingTemplate, self).__init__(message, *args, **kwargs)
raise MissingTemplate
conditional_block
cookiecutter.py
# -*- coding: utf-8 -*- """ Extension that integrates cookiecutter templates into PyScaffold. """ from __future__ import absolute_import import argparse from ..api.helpers import register, logger from ..api import Extension from ..contrib.six import raise_from class Cookiecutter(Extension): """Additionally apply a Cookiecutter template""" mutually_exclusive = True def augment_cli(self, parser): """Add an option to parser that enables the Cookiecutter extension Args: parser (argparse.ArgumentParser): CLI parser object """ parser.add_argument( self.flag, dest=self.name, action=create_cookiecutter_parser(self), metavar="TEMPLATE", help="additionally apply a Cookiecutter template. " "Note that not all templates are suitable for PyScaffold. " "Please refer to the docs for more information.") def activate(self, actions): """Register before_create hooks to generate project using Cookiecutter Args: actions (list): list of actions to perform Returns: list: updated list of actions """ # `get_default_options` uses passed options to compute derived ones, # so it is better to prepend actions that modify options. actions = register(actions, enforce_cookiecutter_options, before='get_default_options') # `apply_update_rules` uses CWD information, # so it is better to prepend actions that modify it. actions = register(actions, create_cookiecutter, before='apply_update_rules') return actions def create_cookiecutter_parser(obj_ref): """Create a Cookiecutter parser. Args: obj_ref (Extension): object reference to the actual extension Returns: NamespaceParser: parser for namespace cli argument """ class CookiecutterParser(argparse.Action): """Consumes the values provided, but also append the extension function to the extensions list. """ def __call__(self, parser, namespace, values, option_string=None): # First ensure the extension function is stored inside the # 'extensions' attribute: extensions = getattr(namespace, 'extensions', []) extensions.append(obj_ref) setattr(namespace, 'extensions', extensions) # Now the extra parameters can be stored setattr(namespace, self.dest, values) # save the cookiecutter cli argument for later obj_ref.args = values return CookiecutterParser def enforce_cookiecutter_options(struct, opts): """Make sure options reflect the cookiecutter usage. Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ opts['force'] = True return struct, opts def create_cookiecutter(struct, opts):
class NotInstalled(RuntimeError): """This extension depends on the ``cookiecutter`` package.""" DEFAULT_MESSAGE = ("cookiecutter is not installed, " "run: pip install cookiecutter") def __init__(self, message=DEFAULT_MESSAGE, *args, **kwargs): super(NotInstalled, self).__init__(message, *args, **kwargs) class MissingTemplate(RuntimeError): """A cookiecutter template (git url) is required.""" DEFAULT_MESSAGE = "missing `cookiecutter` option" def __init__(self, message=DEFAULT_MESSAGE, *args, **kwargs): super(MissingTemplate, self).__init__(message, *args, **kwargs)
"""Create a cookie cutter template Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ try: from cookiecutter.main import cookiecutter except Exception as e: raise_from(NotInstalled, e) extra_context = dict(full_name=opts['author'], author=opts['author'], email=opts['email'], project_name=opts['project'], package_name=opts['package'], repo_name=opts['package'], project_short_description=opts['description'], release_date=opts['release_date'], version='unknown', # will be replaced later year=opts['year']) if 'cookiecutter' not in opts: raise MissingTemplate logger.report('run', 'cookiecutter ' + opts['cookiecutter']) if not opts.get('pretend'): cookiecutter(opts['cookiecutter'], no_input=True, extra_context=extra_context) return struct, opts
identifier_body
cookiecutter.py
# -*- coding: utf-8 -*- """ Extension that integrates cookiecutter templates into PyScaffold. """ from __future__ import absolute_import import argparse from ..api.helpers import register, logger from ..api import Extension from ..contrib.six import raise_from class Cookiecutter(Extension): """Additionally apply a Cookiecutter template""" mutually_exclusive = True def augment_cli(self, parser): """Add an option to parser that enables the Cookiecutter extension Args: parser (argparse.ArgumentParser): CLI parser object """ parser.add_argument( self.flag, dest=self.name, action=create_cookiecutter_parser(self), metavar="TEMPLATE", help="additionally apply a Cookiecutter template. " "Note that not all templates are suitable for PyScaffold. " "Please refer to the docs for more information.") def activate(self, actions): """Register before_create hooks to generate project using Cookiecutter Args: actions (list): list of actions to perform Returns: list: updated list of actions """ # `get_default_options` uses passed options to compute derived ones, # so it is better to prepend actions that modify options. actions = register(actions, enforce_cookiecutter_options, before='get_default_options') # `apply_update_rules` uses CWD information, # so it is better to prepend actions that modify it. actions = register(actions, create_cookiecutter, before='apply_update_rules') return actions def create_cookiecutter_parser(obj_ref): """Create a Cookiecutter parser. Args: obj_ref (Extension): object reference to the actual extension Returns: NamespaceParser: parser for namespace cli argument """ class CookiecutterParser(argparse.Action): """Consumes the values provided, but also append the extension function to the extensions list. """ def __call__(self, parser, namespace, values, option_string=None): # First ensure the extension function is stored inside the # 'extensions' attribute: extensions = getattr(namespace, 'extensions', []) extensions.append(obj_ref) setattr(namespace, 'extensions', extensions) # Now the extra parameters can be stored setattr(namespace, self.dest, values) # save the cookiecutter cli argument for later obj_ref.args = values return CookiecutterParser def
(struct, opts): """Make sure options reflect the cookiecutter usage. Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ opts['force'] = True return struct, opts def create_cookiecutter(struct, opts): """Create a cookie cutter template Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ try: from cookiecutter.main import cookiecutter except Exception as e: raise_from(NotInstalled, e) extra_context = dict(full_name=opts['author'], author=opts['author'], email=opts['email'], project_name=opts['project'], package_name=opts['package'], repo_name=opts['package'], project_short_description=opts['description'], release_date=opts['release_date'], version='unknown', # will be replaced later year=opts['year']) if 'cookiecutter' not in opts: raise MissingTemplate logger.report('run', 'cookiecutter ' + opts['cookiecutter']) if not opts.get('pretend'): cookiecutter(opts['cookiecutter'], no_input=True, extra_context=extra_context) return struct, opts class NotInstalled(RuntimeError): """This extension depends on the ``cookiecutter`` package.""" DEFAULT_MESSAGE = ("cookiecutter is not installed, " "run: pip install cookiecutter") def __init__(self, message=DEFAULT_MESSAGE, *args, **kwargs): super(NotInstalled, self).__init__(message, *args, **kwargs) class MissingTemplate(RuntimeError): """A cookiecutter template (git url) is required.""" DEFAULT_MESSAGE = "missing `cookiecutter` option" def __init__(self, message=DEFAULT_MESSAGE, *args, **kwargs): super(MissingTemplate, self).__init__(message, *args, **kwargs)
enforce_cookiecutter_options
identifier_name
graphs.rs
extern crate rand; extern crate timely; extern crate differential_dataflow; use std::rc::Rc; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use differential_dataflow::input::Input; use differential_dataflow::Collection; use differential_dataflow::operators::*; use differential_dataflow::trace::Trace; use differential_dataflow::operators::arrange::ArrangeByKey; use differential_dataflow::operators::arrange::ArrangeBySelf; use differential_dataflow::trace::implementations::spine_fueled::Spine; type Node = usize; use differential_dataflow::trace::implementations::ord::OrdValBatch; // use differential_dataflow::trace::implementations::ord::OrdValSpine; // type GraphTrace<N> = Spine<usize, N, (), isize, Rc<GraphBatch<N>>>; type GraphTrace = Spine<Node, Node, (), isize, Rc<OrdValBatch<Node, Node, (), isize>>>; fn main() { let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap(); let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap(); // Our setting involves four read query types, and two updatable base relations. // // Q1: Point lookup: reads "state" associated with a node. // Q2: One-hop lookup: reads "state" associated with neighbors of a node. // Q3: Two-hop lookup: reads "state" associated with n-of-n's of a node. // Q4: Shortest path: reports hop count between two query nodes. // // R1: "State": a pair of (node, T) for some type T that I don't currently know. // R2: "Graph": pairs (node, node) indicating linkage between the two nodes. timely::execute_from_args(std::env::args().skip(3), move |worker| { let index = worker.index(); let peers = worker.peers(); let timer = ::std::time::Instant::now(); let (mut graph, mut trace) = worker.dataflow(|scope| { let (graph_input, graph) = scope.new_collection(); let graph_indexed = graph.arrange_by_key(); // let graph_indexed = graph.arrange_by_key(); (graph_input, graph_indexed.trace) }); let seed: &[_] = &[1, 2, 3, index]; let mut rng1: StdRng = SeedableRng::from_seed(seed); // rng for edge additions // let mut rng2: StdRng = SeedableRng::from_seed(seed); // rng for edge deletions if index == 0 { println!("performing workload on random graph with {} nodes, {} edges:", nodes, edges); } let worker_edges = edges/peers + if index < (edges % peers) { 1 } else { 0 }; for _ in 0 .. worker_edges { graph.insert((rng1.gen_range(0, nodes) as Node, rng1.gen_range(0, nodes) as Node)); } graph.close(); while worker.step() { } if index == 0 { println!("{:?}\tgraph loaded", timer.elapsed()); } // Phase 2: Reachability. let mut roots = worker.dataflow(|scope| { let (roots_input, roots) = scope.new_collection(); reach(&mut trace, roots); roots_input }); if index == 0 { roots.insert(0); } roots.close(); while worker.step() { } if index == 0 { println!("{:?}\treach complete", timer.elapsed()); } // Phase 3: Breadth-first distance labeling. let mut roots = worker.dataflow(|scope| { let (roots_input, roots) = scope.new_collection(); bfs(&mut trace, roots); roots_input }); if index == 0 { roots.insert(0); } roots.close(); while worker.step() { } if index == 0 { println!("{:?}\tbfs complete", timer.elapsed()); } }).unwrap(); } // use differential_dataflow::trace::implementations::ord::OrdValSpine; use differential_dataflow::operators::arrange::TraceAgent; type TraceHandle = TraceAgent<Node, Node, (), isize, GraphTrace>; fn reach<G: Scope<Timestamp = ()>> ( graph: &mut TraceHandle, roots: Collection<G, Node> ) -> Collection<G, Node>
fn bfs<G: Scope<Timestamp = ()>> ( graph: &mut TraceHandle, roots: Collection<G, Node> ) -> Collection<G, (Node, u32)> { let graph = graph.import(&roots.scope()); let roots = roots.map(|r| (r,0)); roots.iterate(|inner| { let graph = graph.enter(&inner.scope()); let roots = roots.enter(&inner.scope()); graph.join_map(&inner, |_src,&dest,&dist| (dest, dist+1)) .concat(&roots) .reduce(|_key, input, output| output.push((*input[0].0,1))) }) } // fn connected_components<G: Scope<Timestamp = ()>>( // graph: &mut TraceHandle<Node> // ) -> Collection<G, (Node, Node)> { // // each edge (x,y) means that we need at least a label for the min of x and y. // let nodes = // graph // .as_collection(|&k,&v| { // let min = std::cmp::min(k,v); // (min, min) // }) // .consolidate(); // // each edge should exist in both directions. // let edges = edges.map_in_place(|x| mem::swap(&mut x.0, &mut x.1)) // .concat(&edges); // // don't actually use these labels, just grab the type // nodes.filter(|_| false) // .iterate(|inner| { // let edges = edges.enter(&inner.scope()); // let nodes = nodes.enter_at(&inner.scope(), |r| 256 * (64 - r.1.leading_zeros() as u64)); // inner.join_map(&edges, |_k,l,d| (*d,*l)) // .concat(&nodes) // .group(|_, s, t| { t.push((*s[0].0, 1)); } ) // }) // }
{ let graph = graph.import(&roots.scope()); roots.iterate(|inner| { let graph = graph.enter(&inner.scope()); let roots = roots.enter(&inner.scope()); // let reach = inner.concat(&roots).distinct_total().arrange_by_self(); // graph.join_core(&reach, |_src,&dst,&()| Some(dst)) graph.join_core(&inner.arrange_by_self(), |_src,&dst,&()| Some(dst)) .concat(&roots) .distinct_total() }) }
identifier_body