file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
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 o...
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_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. ...
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 o...
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_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 o...
(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):...
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 comp...
(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) newScri...
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 comp...
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); } ...
{ 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 comp...
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; } } ComponentLo...
}); newScriptTag.addEventListener('error', function(ev) {
random_line_split
lazy-components.js
!(function() { 'use strict'; function ComponentLoader($window, $q)
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...
{ 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.pe...
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. *---------------------------------------------------------------...
} 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 || '')); ...
{ 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.p...
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. *---------------------------------------------------------------...
// 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 = a...
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. *---------------------------------------------------------------...
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. *---------------------------------------------------------------...
(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
07071200*__") #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/s...
#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=="EuropeCana...
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
7071200*__") #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/sa...
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] - loc...
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 ag...
// //////////////////////////////////////////////////////////////////////////////// //! 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_si...
// 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 ag...
() -> 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.t...
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 ag...
{ 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(), ...
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 * ...
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', 'l...
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 * ...
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 * ...
#### 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'}, {})[us...
"""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 * ...
(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) ...
init_all
identifier_name
resultviewer.py
.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.i...
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...
# Callback function for Quit Button GUI.destroy() GUI.quit()
random_line_split
resultviewer.py
.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.i...
(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...
newselection
identifier_name
resultviewer.py
.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.i...
###################### # 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(G...
canvas.configure(scrollregion=canvas.bbox("all"))
identifier_body
resultviewer.py
: 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...
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): ...
(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, fi...
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): ...
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,...
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 ...
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): ...
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) ...
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 (caseArg...
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>>) ...
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...
{ 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>>) ...
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 TestPrope...
{ 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>>) ...
}
random_line_split
fancy_getopt.py
"!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...
del cur_line[-1]
conditional_block
fancy_getopt.py
(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 ju...
__init__
identifier_name
fancy_getopt.py
{'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 act...
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(ne...
"""Set the aliases for this option parser.""" self._check_alias_dict(alias, "alias") self.alias = alias
identifier_body
fancy_getopt.py
{'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.tak...
# 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 or...
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 or...
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='...
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 or...
(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') @...
__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 or...
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, ...
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 lat...
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 lat...
(&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::CompleteHeadersReque...
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 lat...
}).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 ...
{ 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_par...
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...
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 * f...
() { 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| { le...
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 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, ...
{ 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): ...
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_ = o...
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): ...
# 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.ti...
"""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): ...
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): ...
(): # 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 =...
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_PASSW...
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ), } ROOT_URLCONF = 'urls'...
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...
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 ins...
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...
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); ...
{ 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()) ...
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...
(&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...
() { // 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. W...
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...
// 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 = f...
// 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...
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...
{ // 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 d...
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.sys...
@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></...
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) reques...
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.sys...
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') ...
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.sys...
@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.che1...
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.sys...
(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 ...
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) an...
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_...
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) an...
(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) an...
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...
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) an...
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 ...
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(sel...
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!"); } ...
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 {...
{ 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...
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...
{ 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!"); } ...
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` ...
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 =...
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` ...
} 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` ...
(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) : (compute...
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` ...
* @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...
* 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_...
# 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 # invoki...
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_...
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, ...
c_files.append( os.path.join( os.path.relpath(root, PACKAGENAME), filename))
conditional_block
pdf.py
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 rece...
(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...
__init__
identifier_name
pdf.py
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 rece...
#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.pages[i+ntoc] = self.pages[i] i = i - 1
conditional_block
pdf.py
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 s...
self.set_y(self.y0+20) return False else: return True
random_line_split
pdf.py
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 rece...
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 d...
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 ...
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, InM...
#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 ...
#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, InM...
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, InM...
(): 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 pla...
* 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) {
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 profe...
/** * 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; } ...
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 = revi...
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 plantil...
$.ajax('/index/select2Profesor', { dataType: 'json', type: 'POST', async: false, data: datos ...
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([d...
}, }, { 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( ...
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([d...
}, }, { 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.h...
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...
{ // showLoader TweenMax.to($('#main-overlay'), 0.2, { autoAlpha:1 }); TweenMax.set($('#main-overlay').find('span'), { marginTop:'0', opacity:0, rotationX:90 }); TweenMax.to($('#...
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.h...
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...
});
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.h...
(_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, { aut...
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.h...
}); // 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, s...
{ 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:...
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 appl...
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_...
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 appl...
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 o...
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 appl...
package_name=opts['package'], repo_name=opts['package'], project_short_description=opts['description'], release_date=opts['release_date'], version='unknown', # will be replaced later ...
"""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 ""...
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 appl...
(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 pro...
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...
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 = root...
{ 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)) ...
identifier_body
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...
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 = Seedabl...
let index = worker.index(); let peers = worker.peers(); let timer = ::std::time::Instant::now(); let (mut graph, mut trace) = worker.dataflow(|scope| {
random_line_split