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
hr_timesheet.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
def _getEmployeeUnit(self, cr, uid, context=None): emp_obj = self.pool.get('hr.employee') if context is None: context = {} emp_id = emp_obj.search(cr, uid, [('user_id', '=', context.get('user_id', uid))], context=context) if emp_id: emp = emp_obj.browse(cr, ...
if context is None: context = {} emp_obj = self.pool.get('hr.employee') emp_id = emp_obj.search(cr, uid, [('user_id', '=', context.get('user_id', uid))], context=context) if emp_id: emp = emp_obj.browse(cr, uid, emp_id[0], context=context) if emp.product_id: ...
identifier_body
hr_timesheet.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
# update unit of measurement if prod_id: uom = self.pool.get('product.product').browse(cr, uid, prod_id, context=context) if uom.uom_id: res['value'].update({'product_uom_id': uom.uom_id.id}) else: res['value'].update({'product_uom_id': False}...
res.update(r)
conditional_block
hr_timesheet.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
(self, cr, uid, context=None): emp_obj = self.pool.get('hr.employee') if context is None: context = {} emp_id = emp_obj.search(cr, uid, [('user_id', '=', context.get('user_id', uid))], context=context) if emp_id: emp = emp_obj.browse(cr, uid, emp_id[0], context=co...
_getEmployeeUnit
identifier_name
end_contract.py
#-*- coding: utf-8 -*- from openerp.osv import fields, osv class finance_contract_rachat(osv.osv_memory): _name = "finance.contract.rachat" _columns = { 'date': fields.date('Date de rachat'), 'date_dem': fields.date('Date de la demande'), 'motif': fields.text('Motif'), 'mem...
obj = self.browse(cr, uid, ids[0], context=context) vals = { 'res_reason': obj.motif and obj.motif or False, 'res_memo': obj.memo and obj.memo or False, 'res_date': obj.date and obj.date or False, 'res_dated': obj.date_dem and obj.date_dem or False, 'r...
identifier_body
end_contract.py
#-*- coding: utf-8 -*- from openerp.osv import fields, osv class finance_contract_rachat(osv.osv_memory): _name = "finance.contract.rachat" _columns = { 'date': fields.date('Date de rachat'), 'date_dem': fields.date('Date de la demande'), 'motif': fields.text('Motif'), 'mem...
(self, cr, uid, ids, context=None): obj = self.browse(cr, uid, ids[0], context=context) vals = { 'res_reason': obj.motif and obj.motif or False, 'res_memo': obj.memo and obj.memo or False, 'res_date': obj.date and obj.date or False, 'res_dated': obj.date_d...
set_rachat
identifier_name
end_contract.py
#-*- coding: utf-8 -*- from openerp.osv import fields, osv class finance_contract_rachat(osv.osv_memory): _name = "finance.contract.rachat" _columns = { 'date': fields.date('Date de rachat'), 'date_dem': fields.date('Date de la demande'), 'motif': fields.text('Motif'), 'memo...
'rachat': obj.act_rachat } return self.pool.get('finance.contract').save_rachat(cr, uid, obj.contract_id.id, vals)
random_line_split
rinco-parse-template.js
/* jslint node: true */ /*! * rinco - include templates * Copyright(c) 2014 Allan Esquina * MIT Licensed */ 'use strict'; var rinco = require('../rinco'); var it = require('../interpreter'); var Markdown = require('markdown').markdown; var md = require('markdown-it')({ html: true, linkify: true, typographer:...
tpl = md.render(tpl.toString()); } return tpl; } else { return "File: " + rinco.fs.path.join(config.INCLUDE_DIR, filename); } }); return has ? r(content) : content...
if (rinco.fs.path.extname(filename) === ".md") {
random_line_split
rinco-parse-template.js
/* jslint node: true */ /*! * rinco - include templates * Copyright(c) 2014 Allan Esquina * MIT Licensed */ 'use strict'; var rinco = require('../rinco'); var it = require('../interpreter'); var Markdown = require('markdown').markdown; var md = require('markdown-it')({ html: true, linkify: true, typographer:...
(content) { var has = false; content = it.parse(content, tag, function (prc) { var filename = prc.trim(); var tpl = rinco.fs.file.read(rinco.fs.path.join(config.INCLUDE_DIR, filename)); has = true; if(tpl) { if ...
r
identifier_name
rinco-parse-template.js
/* jslint node: true */ /*! * rinco - include templates * Copyright(c) 2014 Allan Esquina * MIT Licensed */ 'use strict'; var rinco = require('../rinco'); var it = require('../interpreter'); var Markdown = require('markdown').markdown; var md = require('markdown-it')({ html: true, linkify: true, typographer:...
else { return "File: " + rinco.fs.path.join(config.INCLUDE_DIR, filename); } }); return has ? r(content) : content; } content = r(content.toString()); }); next(content); });
{ if (rinco.fs.path.extname(filename) === ".md") { tpl = md.render(tpl.toString()); } return tpl; }
conditional_block
rinco-parse-template.js
/* jslint node: true */ /*! * rinco - include templates * Copyright(c) 2014 Allan Esquina * MIT Licensed */ 'use strict'; var rinco = require('../rinco'); var it = require('../interpreter'); var Markdown = require('markdown').markdown; var md = require('markdown-it')({ html: true, linkify: true, typographer:...
content = r(content.toString()); }); next(content); });
{ var has = false; content = it.parse(content, tag, function (prc) { var filename = prc.trim(); var tpl = rinco.fs.file.read(rinco.fs.path.join(config.INCLUDE_DIR, filename)); has = true; if(tpl) { if (rinco.fs....
identifier_body
setup.py
#!/usr/bin/env python from distutils.core import setup from DistUtilsExtra.command import * import glob import os setup(name='unattended-upgrades', version='0.1', scripts=['unattended-upgrade'], data_files=[ ('../etc/apt/apt.conf.d/', ["data/50unattended-upgrades"]), ...
)
"build_i18n" : build_i18n.build_i18n }
random_line_split
import_accessibility.py
import os import zipfile import csv from django.core.management.base import BaseCommand from django.db import transaction from django.conf import settings from ...models import Service def get_service(row): for region in 'EA', 'EM', 'WM', 'SE', 'SW': col = 'TNDS-' + region if row[col]: ...
for row in csv.DictReader(line.decode() for line in open_file): service = get_service(row) if service: if row['HighFloor'] == 'LF': low_floor = True elif row['HighFloor'] == 'HF': low_floor = False else: low_floor = ...
def handle_file(open_file):
random_line_split
import_accessibility.py
import os import zipfile import csv from django.core.management.base import BaseCommand from django.db import transaction from django.conf import settings from ...models import Service def get_service(row): for region in 'EA', 'EM', 'WM', 'SE', 'SW': col = 'TNDS-' + region if row[col]: ...
@transaction.atomic def handle(self, *args, **options): path = os.path.join(settings.DATA_DIR, 'accessibility-data.zip') with zipfile.ZipFile(path) as archive: for path in archive.namelist(): if 'IF145' in path: with archive.open(path, 'r') as open_fil...
identifier_body
import_accessibility.py
import os import zipfile import csv from django.core.management.base import BaseCommand from django.db import transaction from django.conf import settings from ...models import Service def get_service(row): for region in 'EA', 'EM', 'WM', 'SE', 'SW': col = 'TNDS-' + region if row[col]: ...
(BaseCommand): @transaction.atomic def handle(self, *args, **options): path = os.path.join(settings.DATA_DIR, 'accessibility-data.zip') with zipfile.ZipFile(path) as archive: for path in archive.namelist(): if 'IF145' in path: with archive.open(pat...
Command
identifier_name
import_accessibility.py
import os import zipfile import csv from django.core.management.base import BaseCommand from django.db import transaction from django.conf import settings from ...models import Service def get_service(row): for region in 'EA', 'EM', 'WM', 'SE', 'SW': col = 'TNDS-' + region if row[col]: ...
elif row['HighFloor'] == 'HF': low_floor = False else: low_floor = None service.update(wheelchair=row['Wheelchair Access'] == 'TRUE', low_floor=low_floor, assistance_service=row['Assistance Service...
low_floor = True
conditional_block
reject_assignments.py
import argparse, json import simpleamt if __name__ == '__main__': parser = argparse.ArgumentParser(parents=[simpleamt.get_parent_parser()]) args = parser.parse_args() mtc = simpleamt.get_mturk_connection_from_args(args) reject_ids = [] if args.hit_ids_file is None: parser.error('Must specify --hit_ids_...
print ('This will reject %d assignments with ' 'sandbox=%s' % (len(reject_ids), str(args.sandbox))) print 'Continue?' s = raw_input('(Y/N): ') if s == 'Y' or s == 'y': print 'Rejecting assignments' for idx, assignment_id in enumerate(reject_ids): print 'Rejecting assignment %d / %d' % (...
hit_ids = [line.strip() for line in f] for hit_id in hit_ids: for a in mtc.get_assignments(hit_id): reject_ids.append(a.AssignmentId)
random_line_split
reject_assignments.py
import argparse, json import simpleamt if __name__ == '__main__': parser = argparse.ArgumentParser(parents=[simpleamt.get_parent_parser()]) args = parser.parse_args() mtc = simpleamt.get_mturk_connection_from_args(args) reject_ids = [] if args.hit_ids_file is None:
with open(args.hit_ids_file, 'r') as f: hit_ids = [line.strip() for line in f] for hit_id in hit_ids: for a in mtc.get_assignments(hit_id): reject_ids.append(a.AssignmentId) print ('This will reject %d assignments with ' 'sandbox=%s' % (len(reject_ids), str(args.sandbox))) print 'Co...
parser.error('Must specify --hit_ids_file.')
conditional_block
SGD_regressor.py
from ..base import model from gradient_descent import stochastic_gradient_descent from ..util import loss_functions import numpy from ..util.preprocessing import as_matrix class SGD_regressor(model): def __init__(self, function=loss_functions.linear, dfunction=loss_functions.dli...
return self.function(as_matrix(data), self.theta)
conditional_block
SGD_regressor.py
from ..base import model from gradient_descent import stochastic_gradient_descent from ..util import loss_functions import numpy from ..util.preprocessing import as_matrix class SGD_regressor(model): def __init__(self, function=loss_functions.linear, dfunction=loss_functions.dli...
if self.fit_intercept: tmp = as_matrix(data) x = numpy.ones((tmp.shape[0], tmp.shape[1] + 1)) x[:, 1:] = tmp return self.function(x, self.theta) else: return self.function(as_matrix(data), self.theta)
identifier_body
SGD_regressor.py
from ..base import model from gradient_descent import stochastic_gradient_descent from ..util import loss_functions import numpy from ..util.preprocessing import as_matrix class
(model): def __init__(self, function=loss_functions.linear, dfunction=loss_functions.dlinear, theta=None, learning_rate=.01, fit_intercept=True): self.theta = theta self.learning_rate = learning_rate self....
SGD_regressor
identifier_name
SGD_regressor.py
from ..base import model from gradient_descent import stochastic_gradient_descent from ..util import loss_functions import numpy from ..util.preprocessing import as_matrix class SGD_regressor(model): def __init__(self, function=loss_functions.linear, dfunction=loss_functions.dli...
return self.function(x, self.theta) else: return self.function(as_matrix(data), self.theta)
random_line_split
fckconfig.js
* == END LICENSE == * * Editor configuration settings. * * Follow this link for more information: * http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options */ FCKConfig.CustomConfigurationsPath = '' ; FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ;...
* * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html *
random_line_split
cnetwork_tree_node.py
""" Specify the NetworkNode with its action, context-menus """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import os # Enthought library imports from traits.api im...
(self): """ Standard menus for network nodes """ menu_actions = [] return Menu( *menu_actions)
_menu_default
identifier_name
cnetwork_tree_node.py
""" Specify the NetworkNode with its action, context-menus """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import os # Enthought library imports from traits.api im...
# a default icons # Name of group item icon icon_group = Str('home.png') # Name of leaf item icon icon_item=Str('home.png') # Name of opened group item icon icon_open=Str('home.png') # labels label='dname' ### # Private Traits # activate / deactivate logic ...
parent = Any # the network associated with this node node_for=[CNetwork]
random_line_split
cnetwork_tree_node.py
""" Specify the NetworkNode with its action, context-menus """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import os # Enthought library imports from traits.api im...
""" Standard menus for network nodes """ menu_actions = [] return Menu( *menu_actions)
identifier_body
producer.py
import logging import gevent import nsq.master import nsq.node_collection import nsq.connection _logger = logging.getLogger(__name__) class Producer(nsq.master.Master): def __init__(self, node_collection, tls_ca_bundle_filepath=None, tls_auth_pair=None, compression=False, identify=None, ...
def mpublish(self, topic, messages): self.connection_election.elect_connection().mpub(topic, messages)
self.connection_election.elect_connection().pub(topic, message)
identifier_body
producer.py
import logging import gevent import nsq.master import nsq.node_collection import nsq.connection _logger = logging.getLogger(__name__) class Producer(nsq.master.Master): def __init__(self, node_collection, tls_ca_bundle_filepath=None, tls_auth_pair=None, compression=False, identify=None, ...
(self, topic, messages): self.connection_election.elect_connection().mpub(topic, messages)
mpublish
identifier_name
producer.py
import logging import gevent import nsq.master import nsq.node_collection import nsq.connection _logger = logging.getLogger(__name__) class Producer(nsq.master.Master): def __init__(self, node_collection, tls_ca_bundle_filepath=None, tls_auth_pair=None, compression=False, identify=None, ...
if compression: if compression is True: compression = None self.set_compression(compression) # Technically, any node can have a context. The elements in our current # context named-tuple just aren't relevant for anything but a consumer. contex...
if tls_ca_bundle_filepath is None: raise ValueError("Please provide a CA bundle.") nsq.connection.TLS_CA_BUNDLE_FILEPATH = tls_ca_bundle_filepath nsq.connection.TLS_AUTH_PAIR = tls_auth_pair self.identify.set_tls_v1()
conditional_block
producer.py
import logging import gevent import nsq.master import nsq.node_collection import nsq.connection _logger = logging.getLogger(__name__) class Producer(nsq.master.Master): def __init__(self, node_collection, tls_ca_bundle_filepath=None, tls_auth_pair=None, compression=False, identify=None, ...
self.identify.set_tls_v1() if compression: if compression is True: compression = None self.set_compression(compression) # Technically, any node can have a context. The elements in our current # context named-tuple just aren't relevant for a...
random_line_split
instance.py
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
def ZonalComputeUrl(project, zone, collection, name): return ''.join([COMPUTE_URL_BASE, 'projects/', project, '/zones/', zone, '/', collection, '/', name]) def GenerateConfig(context): """Generate configuration.""" base_name = context.properties['instanceName'] items = [] for key, val...
return ''.join([COMPUTE_URL_BASE, 'projects/', project, '/global/', collection, '/', name])
identifier_body
instance.py
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
}], 'disks': [{ 'deviceName': 'boot', 'type': 'PERSISTENT', 'autoDelete': True, 'boot': True, 'initializeParams': { 'diskName': base_name + '-disk', 'sourceImage': GlobalComputeUrl( 'debian-cloud', 'images', ...
'serviceAccounts': [{ 'email': 'default', 'scopes': context.properties['scopes']
random_line_split
instance.py
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
(context): """Generate configuration.""" base_name = context.properties['instanceName'] items = [] for key, value in context.properties['metadata'].iteritems(): items.append({ 'key': key, 'value': value }) metadata = {'items': items} # Properties for the container-based instan...
GenerateConfig
identifier_name
instance.py
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
metadata = {'items': items} # Properties for the container-based instance. instance = { 'zone': context.properties['zone'], 'machineType': ZonalComputeUrl( context.env['project'], context.properties['zone'], 'machineTypes', 'f1-micro'), 'metadata': metadata, 'serviceA...
items.append({ 'key': key, 'value': value })
conditional_block
lib.rs
extern crate piston_truetype; use std::ptr::{null_mut}; use piston_truetype::*; fn expect_glyph(letter: char, expected: String) { unsafe { let bs = include_bytes!("Tuffy_Bold.ttf"); let s = 20.0; let mut w = 0; let mut h = 0; let offset = get_font_offset_for_index(bs.as_p...
panic!("The `A` is malformed.\n\n\nExpected:\n{}|\n\nGot:\n{}|", result, expected); } } } #[test] fn draw_capital_a() { expect_glyph('A', String::new() + " VMM \n" + " @@@i \n" + " i@@@M \n" + " M@o@@. \n" + " .@@.V@o \n" + ...
println!("\n{:?}", expected); println!("{:?}", result);
random_line_split
lib.rs
extern crate piston_truetype; use std::ptr::{null_mut}; use piston_truetype::*; fn expect_glyph(letter: char, expected: String) { unsafe { let bs = include_bytes!("Tuffy_Bold.ttf"); let s = 20.0; let mut w = 0; let mut h = 0; let offset = get_font_offset_for_index(bs.as_p...
() { expect_glyph('A', String::new() + " VMM \n" + " @@@i \n" + " i@@@M \n" + " M@o@@. \n" + " .@@.V@o \n" + " o@M i@@ \n" + " M@i .@@. \n" + " .@@@@@@@o \n" + " o@@@@@@@@ \n" + " @@o .@@: \n" + ...
draw_capital_a
identifier_name
lib.rs
extern crate piston_truetype; use std::ptr::{null_mut}; use piston_truetype::*; fn expect_glyph(letter: char, expected: String) { unsafe { let bs = include_bytes!("Tuffy_Bold.ttf"); let s = 20.0; let mut w = 0; let mut h = 0; let offset = get_font_offset_for_index(bs.as_p...
#[test] fn draw_capital_g() { expect_glyph('G', String::new() + " . \n" + " o@@@V. \n" + " M@@M@@@ \n" + " i@@: Vo. \n" + " @@o \n" + ".@@. \n" + ".@@ .oooo:\n" + ".@@ .@@@@i\n" + " @@: iiM@i\n" + " M@o ...
{ expect_glyph('A', String::new() + " VMM \n" + " @@@i \n" + " i@@@M \n" + " M@o@@. \n" + " .@@.V@o \n" + " o@M i@@ \n" + " M@i .@@. \n" + " .@@@@@@@o \n" + " o@@@@@@@@ \n" + " @@o .@@: \n" + ":...
identifier_body
lib.rs
extern crate piston_truetype; use std::ptr::{null_mut}; use piston_truetype::*; fn expect_glyph(letter: char, expected: String) { unsafe { let bs = include_bytes!("Tuffy_Bold.ttf"); let s = 20.0; let mut w = 0; let mut h = 0; let offset = get_font_offset_for_index(bs.as_p...
} } #[test] fn draw_capital_a() { expect_glyph('A', String::new() + " VMM \n" + " @@@i \n" + " i@@@M \n" + " M@o@@. \n" + " .@@.V@o \n" + " o@M i@@ \n" + " M@i .@@. \n" + " .@@@@@@@o \n" + " o@@@@@@@@ \n" ...
{ println!("\n{:?}", expected); println!("{:?}", result); panic!("The `A` is malformed.\n\n\nExpected:\n{}|\n\nGot:\n{}|", result, expected); }
conditional_block
parallel.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Implements parallel traversal over the DOM tree. //! //! This traversal is based on Rayon, and therefore its s...
let tls = ScopedTLS::<D::ThreadLocalContext>::new(queue); let root = root.as_node().opaque(); queue.install(|| { rayon::scope(|scope| { traverse_nodes(nodes, root, traversal_data, scope, traversal, &tls); }); }); // Dump statistics to stdout if requested. if Travers...
{ // Handle Gecko's eager initial styling. We don't currently support it // in conjunction with bottom-up traversal. If we did, we'd need to put // it on the context to make it available to the bottom-up phase. let (nodes, depth) = if token.traverse_unstyled_children_only() { debug_assert!(!D::n...
identifier_body
parallel.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Implements parallel traversal over the DOM tree. //! //! This traversal is based on Rayon, and therefore its s...
} } } if let Some(ref mut depth) = traversal_data.current_dom_depth { *depth += 1; } traverse_nodes(discovered_child_nodes, root, traversal_data, scope, traversal, tls); } fn traverse_nodes<'a, 'scope, E, D>(nodes: Vec<SendNode<E::ConcreteNode>>, root: OpaqueNode, ...
{ // Otherwise record the number of children to process when the // time comes. node.as_element().unwrap().store_children_to_process(children_to_process); }
conditional_block
parallel.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Implements parallel traversal over the DOM tree. //! //! This traversal is based on Rayon, and therefore its s...
if node.opaque() == root { break; } let parent = match node.parent_element() { None => unreachable!("How can this happen after the break above?"), Some(parent) => parent, }; let remaining = parent.did_process_child(); if remaining != ...
// Perform the appropriate operation. traversal.process_postorder(thread_local, node);
random_line_split
parallel.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Implements parallel traversal over the DOM tree. //! //! This traversal is based on Rayon, and therefore its s...
<'a, 'scope, E, D>(nodes: Vec<SendNode<E::ConcreteNode>>, root: OpaqueNode, traversal_data: PerLevelTraversalData, scope: &'a rayon::Scope<'scope>, traversal: &'scope D, tls: &...
traverse_nodes
identifier_name
ntpath.py
1:] else: path += b elif path[-1] == ":": path += b elif b: if b[0] in "/\\": path += b else: path += "\\" + b else: # path is not em...
"""Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.""" if '$' not in path and '%' not in path: return path import string varchars = string.ascii_letters + string.digits + '_-' res = '' index = 0 pathlen = len(path) while...
identifier_body
ntpath.py
drive letter, or cases 4 and 5. b_wins = 1 # Else path has a drive letter, and b doesn't but is absolute. elif len(path) > 3 or (len(path) == 3 and path[-1] not in "/\\"): # case 3 b_wins = 1 i...
return path # Split a path in a drive specification (a drive letter followed by a # colon) and the path specification. # It is always true that drivespec + pathspec == p def splitdrive(p): """Split a pathname into drive and path specifiers. Returns a 2-tuple "(drive,path)"; either part may be emp...
assert len(path) > 0 if path[-1] in "/\\": if b and b[0] in "/\\": path += b[1:] else: path += b elif path[-1] == ":": path += b elif b: if b[0] in "/\\": ...
conditional_block
ntpath.py
will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern,...
_abspath_split
identifier_name
ntpath.py
drive letter, or cases 4 and 5. b_wins = 1 # Else path has a drive letter, and b doesn't but is absolute. elif len(path) > 3 or (len(path) == 3 and path[-1] not in "/\\"):
path = b else: # Join, and ensure there's a separator. assert len(path) > 0 if path[-1] in "/\\": if b and b[0] in "/\\": path += b[1:] else: path += b elif path[-1] == ":...
# case 3 b_wins = 1 if b_wins:
random_line_split
eigenstates[eps=0.25].py
dimension = 2 ncomponents = 1 potential = "henon_heiles" eigenstate_of_level = 0 eigenstates_indices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] starting_point = [0.5, 0.5] eps = 0.25 hawp_template = { "type": "HagedornWavepacket", "dimension": dimension, "ncomponents": 1, "eps": eps, ...
'dimension': dimension, 'qr_rules': [{'dimension': 1, 'order': 32, 'type': 'GaussHermiteQR'}, {'dimension': 1, 'order': 32, 'type': 'GaussHermiteQR'}] } } }
'qr': { 'type': 'TensorProductQR',
random_line_split
workout-detail.component.ts
import {Component, OnInit} from "@angular/core"; import {WorkoutsService} from "../services/workouts.service"; import {ActivatedRoute, Params} from "@angular/router"; import {Workout} from "../models/workout"; @Component ({ selector: 'app-root', templateUrl: 'workout-detail.component.html', styleUrls: ['workout-...
}
{ this.route.params.forEach((params: Params) => { var id = params["id"]; console.log("ngOnInit = id", id); this.workoutsService.getWorkout(id) .then((workout) => { console.log("got workout", workout); this.workout = workout; }); }); }
identifier_body
workout-detail.component.ts
import {Component, OnInit} from "@angular/core"; import {WorkoutsService} from "../services/workouts.service"; import {ActivatedRoute, Params} from "@angular/router"; import {Workout} from "../models/workout"; @Component ({ selector: 'app-root', templateUrl: 'workout-detail.component.html', styleUrls: ['workout-...
() { this.route.params.forEach((params: Params) => { var id = params["id"]; console.log("ngOnInit = id", id); this.workoutsService.getWorkout(id) .then((workout) => { console.log("got workout", workout); this.workout = workout; }); }); } }
ngOnInit
identifier_name
multipart.py
''' Classes for using multipart form data from Python, which does not (at the time of writing) support this directly. To use this, make an instance of Multipart and add parts to it via the factory methods field and file. When you are done, get the content via the get method. @author: Stacy Prowell (http://stacyprowe...
lines.append('') lines.append(self._body) return lines class Multipart(object): ''' Encapsulate multipart form data. To use this, make an instance and then add parts to it via the two methods (field and file). When done, you can get the result via the get method. See ht...
lines.append(str('%s: %s' % (key, val)))
conditional_block
multipart.py
''' Classes for using multipart form data from Python, which does not (at the time of writing) support this directly. To use this, make an instance of Multipart and add parts to it via the factory methods field and file. When you are done, get the content via the get method. @author: Stacy Prowell (http://stacyprowe...
Get the multipart form data. This returns the content type, which specifies the boundary marker, and also returns the body containing all parts and bondary markers. @return: content type, body @rtype: tuple ''' all = [] for part in self.parts: ...
def get(self): '''
random_line_split
multipart.py
''' Classes for using multipart form data from Python, which does not (at the time of writing) support this directly. To use this, make an instance of Multipart and add parts to it via the factory methods field and file. When you are done, get the content via the get method. @author: Stacy Prowell (http://stacyprowe...
def get(self): ''' Get the multipart form data. This returns the content type, which specifies the boundary marker, and also returns the body containing all parts and bondary markers. @return: content type, body @rtype: tuple ''' all = [] f...
''' Create and append a file part. THis kind of part has a field name, a filename, and a value. @param name: The field name. @type name: str @param value: The field value. @type value: str @param headers: Headers to set in addition to disposition. @type ...
identifier_body
multipart.py
''' Classes for using multipart form data from Python, which does not (at the time of writing) support this directly. To use this, make an instance of Multipart and add parts to it via the factory methods field and file. When you are done, get the content via the get method. @author: Stacy Prowell (http://stacyprowe...
(self, name, filename, value, headers={}): ''' Create and append a file part. THis kind of part has a field name, a filename, and a value. @param name: The field name. @type name: str @param value: The field value. @type value: str @param headers: Header...
file
identifier_name
lib.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied, modified, or distributed // except according to those terms. // // Simple Prometheus suppo...
{ cache: Arc<RwLock<LruCache<i64, promo_proto::MetricFamily>>>, host_and_port: &'static str, } impl PrometheusReporter { pub fn new(host_and_port: &'static str) -> Self { PrometheusReporter { // TODO make it configurable cache: Arc::new(RwLock::new(LruCache::new(86400))), ...
PrometheusReporter
identifier_name
lib.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied, modified, or distributed // except according to those terms. // // Simple Prometheus suppo...
use protobuf::Message; use std::sync::{Arc, RwLock}; use std::thread; // http handler storage #[derive(Copy, Clone)] struct HandlerStorage; // refer to https://prometheus.io/docs/instrumenting/exposition_formats/ const CONTENT_TYPE: &'static str = "application/vnd.google.protobuf; \ ...
use router::Router; use iron::typemap::Key; use iron::prelude::*; use iron::status; use lru_cache::LruCache;
random_line_split
test_name_id.py
# Copyright 2013 IBM Corp. # # 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 t...
def test_name_id_same(self): """New volume should have same 'id' and 'name_id'.""" vol_ref = testutils.create_volume(self.ctxt, size=1) self.assertEqual(vol_ref['name_id'], vol_ref['id']) expected_name = CONF.volume_name_template % vol_ref['id'] self.assertEqual(vol_ref['na...
super(NameIDsTestCase, self).tearDown()
identifier_body
test_name_id.py
# Copyright 2013 IBM Corp. # # 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 t...
(self): """Change name ID to mimic volume after migration.""" vol_ref = testutils.create_volume(self.ctxt, size=1) db.volume_update(self.ctxt, vol_ref['id'], {'name_id': 'fake'}) vol_ref = db.volume_get(self.ctxt, vol_ref['id']) expected_name = CONF.volume_name_template % 'fake' ...
test_name_id_diff
identifier_name
test_name_id.py
# Copyright 2013 IBM Corp. # # 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 t...
def setUp(self): super(NameIDsTestCase, self).setUp() self.ctxt = context.RequestContext(user_id='user_id', project_id='project_id') def tearDown(self): super(NameIDsTestCase, self).tearDown() def test_name_id_same(self): """New v...
class NameIDsTestCase(test.TestCase): """Test cases for naming volumes with name_id."""
random_line_split
linearize.py
#!/usr/bin/python # # linearize.py: Construct a linear, no-fork, best version of the blockchain. # # # Copyright (c) 2013 The Carboncoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct i...
def get_blocks(settings): rpc = CarboncoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpassword']) outf = open(settings['output'], 'ab') for height in xrange(settings['min_height'], settings['max_height']+1): data = getblock(rpc, settings, height) outhdr = settings['netmagic...
hash = rpc.getblockhash(n) hexdata = rpc.getblock(hash, False) data = hexdata.decode('hex') return data
identifier_body
linearize.py
#!/usr/bin/python # # linearize.py: Construct a linear, no-fork, best version of the blockchain. # # # Copyright (c) 2013 The Carboncoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct i...
(rpc, settings, n): hash = rpc.getblockhash(n) hexdata = rpc.getblock(hash, False) data = hexdata.decode('hex') return data def get_blocks(settings): rpc = CarboncoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpassword']) outf = open(settings['output'], 'ab') for height in x...
getblock
identifier_name
linearize.py
#!/usr/bin/python # # linearize.py: Construct a linear, no-fork, best version of the blockchain. # # # Copyright (c) 2013 The Carboncoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct i...
else: obj['params'] = params self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) resp = self.conn.getresponse() if resp is None: print "JSON-RPC: no response" return None body = resp.read() resp_obj = json.loads(body) ...
obj['params'] = []
conditional_block
linearize.py
#!/usr/bin/python # # linearize.py: Construct a linear, no-fork, best version of the blockchain. # # # Copyright (c) 2013 The Carboncoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct i...
hexdata = rpc.getblock(hash, False) data = hexdata.decode('hex') return data def get_blocks(settings): rpc = CarboncoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpassword']) outf = open(settings['output'], 'ab') for height in xrange(settings['min_height'], settings['max_heig...
random_line_split
update_general.py
# import libraries import urllib.request from feedgen.feed import FeedGenerator from post_parser import post_title, post_author, post_time, post_files_num from misc import is_number # info baseurl = 'http://phya.snu.ac.kr/xe/underbbs/' url ='http://phya.snu.ac.kr/xe/index.php?mid=underbbs&category=372' # notices + gen...
atomfeed = fg.atom_str(pretty=True) fg.atom_file('general.xml') print('Added ' + str(count_new) + ' posts to feed.') else: print('Posts are up-to-date.')
print('Parsing post #' + srl + '...') fe = fg.add_entry() fe.id(baseurl + srl) fe.title(post_title(srl)) fe.author({'name':post_author(srl),'email':'unknown'}) fe.link(href = baseurl + srl)
conditional_block
update_general.py
# import libraries import urllib.request from feedgen.feed import FeedGenerator from post_parser import post_title, post_author, post_time, post_files_num from misc import is_number # info baseurl = 'http://phya.snu.ac.kr/xe/underbbs/' url ='http://phya.snu.ac.kr/xe/index.php?mid=underbbs&category=372' # notices + gen...
print('Parsing post #' + srl + '...') fe = fg.add_entry() fe.id(baseurl + srl) fe.title(post_title(srl)) fe.author({'name':post_author(srl),'email':'unknown'}) fe.link(href = baseurl + srl) atomfeed = fg.atom_str(pretty=True) fg.atom_file('general.xml') print('Added ' + str(count_new) + ' posts to feed....
fg.language('ko') for srl in srl_arr_general:
random_line_split
updater.py
red = centred def update(self): pos = self.pos font = py.font.Font(self.font, self.size) if not self.variable: label = font.render(self.text, 1, self.colour) if self.variable: label = font.render(str(getattr(v, self.text)), 1, self.colour) ...
(py.sprite.Sprite): def __init__(self, text, pos, size, hovercolour, normalcolour, font, ID, centred = False, bsize=(0,0)): super().__init__() self.ID = ID self.hovered = False self.text = text self.pos = pos self.hcolour = hovercolour self.ncolour = n...
Button
identifier_name
updater.py
v = var() import pygame as py class textLabel(py.sprite.Sprite): def __init__(self, text, pos, colour, font, size, variable = False, centred = False): super().__init__() self.text = text self.pos = pos self.colour = colour self.font = font self.size =...
def __init__(self): self.screen = None
identifier_body
updater.py
def update(self): pos = self.pos font = py.font.Font(self.font, self.size) if not self.variable: label = font.render(self.text, 1, self.colour) if self.variable: label = font.render(str(getattr(v, self.text)), 1, self.colour) if self.c...
self.centred = centred
random_line_split
updater.py
red = centred def update(self): pos = self.pos font = py.font.Font(self.font, self.size) if not self.variable: label = font.render(self.text, 1, self.colour) if self.variable: label = font.render(str(getattr(v, self.text)), 1, self.colour) ...
py.display.flip() else: v.screen.fill((20, 20, 20)) t = textLabel("No Update!", (320, 250), (255, 0, 0), theFont, 70, False, True) v.current = current t.update() py.display.update() if __name__ == "__main__": py.time.wait(2000) ...
for button in buttons: if button.pressed(): id = button.ID if id == "Y": global tries tries = 0 download() ...
conditional_block
hero-form.component.ts
// #docplaster // #docregion // #docregion first, final import { Component } from '@angular/core'; import { NgForm } from '@angular/common'; import { Hero } from './hero'; @Component({ selector: 'hero-form', templateUrl: 'app/hero-form.component.html' }) export class HeroFormComponent { powers = ['Really...
// to be removed/re-added in a tick via NgIf // TODO: Workaround until NgForm has a reset method (#6822) // #docregion new-hero active = true; // #docregion new-hero-v1 newHero() { this.model = new Hero(42, '', ''); // #enddocregion new-hero-v1 this.active = false; setTimeout(()=> this.active...
// Reset the form with a new hero AND restore 'pristine' class state // by toggling 'active' flag which causes the form
random_line_split
hero-form.component.ts
// #docplaster // #docregion // #docregion first, final import { Component } from '@angular/core'; import { NgForm } from '@angular/common'; import { Hero } from './hero'; @Component({ selector: 'hero-form', templateUrl: 'app/hero-form.component.html' }) export class HeroFormComponent { powers = ['Really...
() { return JSON.stringify(this.model); } // #enddocregion first // #docregion final // Reset the form with a new hero AND restore 'pristine' class state // by toggling 'active' flag which causes the form // to be removed/re-added in a tick via NgIf // TODO: Workaround until NgForm has a reset method (#682...
diagnostic
identifier_name
hero-form.component.ts
// #docplaster // #docregion // #docregion first, final import { Component } from '@angular/core'; import { NgForm } from '@angular/common'; import { Hero } from './hero'; @Component({ selector: 'hero-form', templateUrl: 'app/hero-form.component.html' }) export class HeroFormComponent { powers = ['Really...
// #enddocregion submitted // #enddocregion final // TODO: Remove this when we're done get diagnostic() { return JSON.stringify(this.model); } // #enddocregion first // #docregion final // Reset the form with a new hero AND restore 'pristine' class state // by toggling 'active' flag which causes the ...
{ this.submitted = true; }
identifier_body
lib.rs
)] const RAND_BENCH_N: u64 = 100; pub mod distributions; pub mod isaac; pub mod chacha; pub mod reseeding; mod rand_impls; /// A type that can be randomly generated using an `Rng`. pub trait Rand : Sized { /// Generates a random instance of this type using the specified source of /// randomness. fn rand<R...
<T>(&mut self, values: &mut [T]) { let mut i = values.len(); while i >= 2 { // invariant: elements with index >= i have been locked in place. i -= 1; // lock element i in place. values.swap(i, self.gen_range(0, i + 1)); } } } /// Iterator whic...
shuffle
identifier_name
lib.rs
self) -> f64 { const MANTISSA_BITS: usize = 53; const IGNORED_BITS: usize = 11; const SCALE: f64 = (1u64 << MANTISSA_BITS) as f64; (self.next_u64() >> IGNORED_BITS) as f64 / SCALE } /// Fill `dest` with random data. /// /// This has a default implementation in terms of...
random_line_split
lib.rs
)] const RAND_BENCH_N: u64 = 100; pub mod distributions; pub mod isaac; pub mod chacha; pub mod reseeding; mod rand_impls; /// A type that can be randomly generated using an `Rng`. pub trait Rand : Sized { /// Generates a random instance of this type using the specified source of /// randomness. fn rand<R...
} /// Shuffle a mutable slice in place. fn shuffle<T>(&mut self, values: &mut [T]) { let mut i = values.len(); while i >= 2 { // invariant: elements with index >= i have been locked in place. i -= 1; // lock element i in place. values.swap(i,...
{ Some(&values[self.gen_range(0, values.len())]) }
conditional_block
lib.rs
)] const RAND_BENCH_N: u64 = 100; pub mod distributions; pub mod isaac; pub mod chacha; pub mod reseeding; mod rand_impls; /// A type that can be randomly generated using an `Rng`. pub trait Rand : Sized { /// Generates a random instance of this type using the specified source of /// randomness. fn rand<R...
/// Return a bool with a 1 in n chance of true fn gen_weighted_bool(&mut self, n: usize) -> bool { n <= 1 || self.gen_range(0, n) == 0 } /// Return an iterator of random characters from the set A-Z,a-z,0-9. fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> { AsciiGe...
{ assert!(low < high, "Rng.gen_range called with low >= high"); Range::new(low, high).ind_sample(self) }
identifier_body
test_security_groups.py
# Copyright 2013 NTT Data # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# Fetch all security groups for non-admin user with 'all_tenants' # search filter fetched_list = (self.client.list_security_groups(all_tenants='true') ['security_groups']) # Now check if all created Security Groups are present in fetched list for sec_gro...
self.assertIn(sec_group['id'], sec_group_id_list)
conditional_block
test_security_groups.py
# Copyright 2013 NTT Data # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
name = data_utils.rand_name('securitygroup') description = data_utils.rand_name('description') adm_securitygroup = self.adm_client.create_security_group( name=name, description=description)['security_group'] self.addCleanup(self._delete_security_group, ...
for i in range(2):
random_line_split
test_security_groups.py
# Copyright 2013 NTT Data # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
name = data_utils.rand_name('securitygroup') description = data_utils.rand_name('description') securitygroup = self.client.create_security_group( name=name, description=description)['security_group'] self.addCleanup(self._delete_security_group, ...
@classmethod def setup_clients(cls): super(SecurityGroupsTestAdminJSON, cls).setup_clients() cls.adm_client = cls.os_adm.compute_security_groups_client cls.client = cls.security_groups_client def _delete_security_group(self, securitygroup_id, admin=True): if admin: s...
identifier_body
test_security_groups.py
# Copyright 2013 NTT Data # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
(cls): super(SecurityGroupsTestAdminJSON, cls).setup_clients() cls.adm_client = cls.os_adm.compute_security_groups_client cls.client = cls.security_groups_client def _delete_security_group(self, securitygroup_id, admin=True): if admin: self.adm_client.delete_security_gro...
setup_clients
identifier_name
ob.py
#!/usr/bin/env python # coding:utf-8 class Ob(object): def __init__(self, *args, **kwds): for i in args: self.__dict__.update(args) self.__dict__.update(kwds) def __getattr__(self, name): return self.__dict__.get(name, '') def __setattr__(self, name, value): ...
(self, name): return self.__dict__.__contains__(name) def __eq__(self, other): return self.__dict__ == other.__dict__ class StripOb(Ob): def __init__(self, *args, **kwds): super(StripJsOb, self).__init__(*args, **kwds) d = self.__dict__ for k, v in d.items(): ...
__contains__
identifier_name
ob.py
#!/usr/bin/env python # coding:utf-8 class Ob(object): def __init__(self, *args, **kwds): for i in args: self.__dict__.update(args) self.__dict__.update(kwds) def __getattr__(self, name): return self.__dict__.get(name, '') def __setattr__(self, name, value): ...
if __name__ == '__main__': ob1 = Ob(a=1, b=2) # ob1.xx = None # print(ob1.__dict__) # del ob1.a # print(ob1.__dict__) # o = Ob(a='张沈鹏') # print(o) # for k, v in o: # print(k, v) # print(dict) # print(dict(iter(o)))
if isinstance(v, str): if "\n" not in v: _v = v.strip() if _v != v: d[k] = _v
conditional_block
ob.py
#!/usr/bin/env python # coding:utf-8 class Ob(object): def __init__(self, *args, **kwds): for i in args: self.__dict__.update(args) self.__dict__.update(kwds) def __getattr__(self, name): return self.__dict__.get(name, '') def __setattr__(self, name, value): ...
class StripOb(Ob): def __init__(self, *args, **kwds): super(StripJsOb, self).__init__(*args, **kwds) d = self.__dict__ for k, v in d.items(): if isinstance(v, str): if "\n" not in v: _v = v.strip() if _v != v: ...
return self.__dict__ == other.__dict__
identifier_body
ob.py
#!/usr/bin/env python # coding:utf-8 class Ob(object): def __init__(self, *args, **kwds): for i in args: self.__dict__.update(args) self.__dict__.update(kwds) def __getattr__(self, name): return self.__dict__.get(name, '') def __setattr__(self, name, value): ...
# print(dict) # print(dict(iter(o)))
# print(o) # for k, v in o: # print(k, v)
random_line_split
file-download-utils.js
goog.module('grrUi.core.fileDownloadUtils'); goog.module.declareLegacyNamespace(); var AFF4_PREFIXES = { 'OS': 'fs/os', // PathSpec.PathType.OS 'TSK': 'fs/tsk', // PathSpec.PathType.TSK 'REGISTRY': 'registry', // PathSpec.PathType.REGISTRY 'TMPFILE': 'temp', // PathSpec.PathType.TMPF...
} return result; }; /** * Converts a given pathspec to an AFF4 path pointing to a VFS location on a * given client. * * @param {Object} pathspec Typed pathspec value. * @param {string} clientId Client id that will be used a base for an AFF4 path. * @return {string} AFF4 path built. * @export */ exports.p...
{ break; }
conditional_block
file-download-utils.js
goog.module('grrUi.core.fileDownloadUtils'); goog.module.declareLegacyNamespace(); var AFF4_PREFIXES = { 'OS': 'fs/os', // PathSpec.PathType.OS 'TSK': 'fs/tsk', // PathSpec.PathType.TSK 'REGISTRY': 'registry', // PathSpec.PathType.REGISTRY 'TMPFILE': 'temp', // PathSpec.PathType.TMPF...
start = 1; } else { result = ['aff4:', clientId, AFF4_PREFIXES[firstComponent['pathtype']['value']]]; start = 0; } for (var i = start; i < components.length; ++i) { var p = components[i]; var component = p['path']['value']; if (component.startsWith('/')) { component = component.subs...
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRgexf(RPackage):
"""Create, read and write GEXF (Graph Exchange XML Format) graph files (used in Gephi and others). Using the XML package, it allows the user to easily build/read graph files including attributes, GEXF viz attributes (such as color, size, and position), network dynamics (for both edges and nodes) and edg...
identifier_body
package.py
# Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRgexf(RPackage): """Create, read and write GEXF (Graph Exchange XML Format) graph files (used in Gephi and others). Using the XML package, it allows the user t...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class
(RPackage): """Create, read and write GEXF (Graph Exchange XML Format) graph files (used in Gephi and others). Using the XML package, it allows the user to easily build/read graph files including attributes, GEXF viz attributes (such as color, size, and position), network dynamics (for both edges and ...
RRgexf
identifier_name
settings.py
import os import pkg_resources import yaml from fget.utils import fgetprint from fget.resource.root import Root class CachedSettings(object): def __init__(self, cache_dir): self.cache_dir = cache_dir def init(self): settings_filename = 'fget.yaml' cached_filename = 'fget.jobs' ...
fgetprint('Initiating. Finished.') else: with open(cached_settings_file) as f: for line in f: if line.startswith('http://'): url = line.strip() self.cached_settings[url] = [] con...
f.write(value + '\n')
conditional_block
settings.py
import os import pkg_resources import yaml from fget.utils import fgetprint from fget.resource.root import Root
class CachedSettings(object): def __init__(self, cache_dir): self.cache_dir = cache_dir def init(self): settings_filename = 'fget.yaml' cached_filename = 'fget.jobs' cached_settings_file = os.path.join(self.cache_dir, cached_filename) self.cached_settings = {} ...
random_line_split
settings.py
import os import pkg_resources import yaml from fget.utils import fgetprint from fget.resource.root import Root class
(object): def __init__(self, cache_dir): self.cache_dir = cache_dir def init(self): settings_filename = 'fget.yaml' cached_filename = 'fget.jobs' cached_settings_file = os.path.join(self.cache_dir, cached_filename) self.cached_settings = {} if not os.path.isf...
CachedSettings
identifier_name
settings.py
import os import pkg_resources import yaml from fget.utils import fgetprint from fget.resource.root import Root class CachedSettings(object): def __init__(self, cache_dir): self.cache_dir = cache_dir def init(self):
for job in root_resource.get_jobs(): if url not in self.cached_settings: self.cached_settings[url] = [] self.cached_settings[url].append(str(job['name'])) with open(cached_settings_file, 'w') as f: for key in sel...
settings_filename = 'fget.yaml' cached_filename = 'fget.jobs' cached_settings_file = os.path.join(self.cache_dir, cached_filename) self.cached_settings = {} if not os.path.isfile(cached_settings_file): fgetprint('Initiating. Please wait...') settings_file = \ ...
identifier_body
test_sob.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from __future__ import division, absolute_import import os import sys from textwrap import dedent from twisted.trial import unittest from twisted.persisted import sob from twisted.python import components from twisted.persisted.styles import Ep...
(self): """ Restore __main__ to its original value """ sys.modules['__main__'] = self.realMain
tearDown
identifier_name
test_sob.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from __future__ import division, absolute_import import os import sys from textwrap import dedent from twisted.trial import unittest from twisted.persisted import sob from twisted.python import components from twisted.persisted.styles import Ep...
def testEverythingEphemeralGetattr(self): """ L{_EverythingEphermal.__getattr__} will proxy the __main__ module as an L{Ephemeral} object, and during load will be transparent, but after load will return L{Ephemeral} objects from any accessed attributes. """ self.fak...
self.assertRaises(KeyError, sob.guessType, "file.blah") self.assertEqual('python', sob.guessType("file.py")) self.assertEqual('python', sob.guessType("file.tac")) self.assertEqual('python', sob.guessType("file.etac")) self.assertEqual('pickle', sob.guessType("file.tap")) self.ass...
identifier_body
test_sob.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from __future__ import division, absolute_import import os import sys from textwrap import dedent from twisted.trial import unittest from twisted.persisted import sob from twisted.python import components from twisted.persisted.styles import Ep...
pass objects = [ 1, "hello", (1, "hello"), [1, "hello"], {1:"hello"}, ] class FakeModule(object): pass class PersistTests(unittest.TestCase): def testStyles(self): for o in objects: p = sob.Persistent(o, '') for style in 'source pickle'.split(): p.setStyle(...
class Dummy(components.Componentized):
random_line_split
test_sob.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from __future__ import division, absolute_import import os import sys from textwrap import dedent from twisted.trial import unittest from twisted.persisted import sob from twisted.python import components from twisted.persisted.styles import Ep...
def testPassphraseError(self): """ Calling save() with a passphrase is an error. """ p = sob.Persistant(None, 'object') self.assertRaises( TypeError, p.save, 'filename.pickle', passphrase='abc') def testNames(self): o = [1,2,3] p = sob.Per...
sob.IPersistable(o).setStyle(style) sob.IPersistable(o).save(filename='lala.'+style) o1 = sob.load('lala.'+style, style) self.assertEqual(o.foo, o1.foo) self.assertEqual(sob.IPersistable(o1).style, style)
conditional_block
core.py
: out = source.read(chunk) if len(out) == 0: break target.write(out) def tail(self, path, size=1024): """ Return last bytes of file """ length = self.du(path)[ensure_trailing_slash(path)] if size > length: ...
_genline
identifier_name
core.py
(cap - used) / cap} def get_block_locations(self, path, start=0, length=0): """ Fetch physical locations of blocks """ if not self._handle: raise IOError("Filesystem not connected") start = int(start) or 0 length = int(length) or self.info(path)['size'] nblocks ...
raise FileNotFoundError(path)
conditional_block
core.py
: int Replication factor; if zero, use system default (only on write) buf: int (=0) Client buffer size (bytes); if 0, use default. block_size: int Size of data-node blocks if writing """ if not self._handle: raise IOError("Filesystem not co...
raise IOError('Set replication failed: {}'.format(msg)) def mv(self, path1, path2): """ Move file at path1 to path2 """ if not self.exists(path1): raise FileNotFoundError(path1) out = _lib.hdfsRename(self._handle, ensure_bytes(path1), en...
ctypes.c_int16(int(replication))) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()).split('\n')[0]
random_line_split
core.py
pars : {str: str} any parameters for hadoop, that you can find in hdfs-site.xml, https://hadoop.apache.org/docs/r2.6.0/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml This dict looks exactly like the one produced by conf - you can, for example, remove any problem...
""" Connection to an HDFS namenode >>> hdfs = HDFileSystem(host='127.0.0.1', port=8020) # doctest: +SKIP """ _first_pid = None def __init__(self, host=MyNone, port=MyNone, connect=True, autoconf=True, pars=None, **kwargs): """ Parameters ---------- hos...
identifier_body
trial.py
#! /usr/python
/////////////////////////////////////////////////////////// // Permission is hereby granted, free of charge, // to any person obtaining a copy of // this software and associated documentation files // (the "Software"), to deal in the Software without // restriction, including without limitation the rights // to u...
'''
random_line_split