code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def map_representer(dumper, value):
value = ODict(value.items())
if len(value.keys()) == 1:
key = list(value.keys())[0]
if key in CONVERTED_SUFFIXES:
return fn_representer(dumper, key, value[key])
if key.startswith(FN_PREFIX):
return fn_representer(dumper, key[4:]... | Deal with !Ref style function format and OrderedDict |
def VCLibraries(self):
if self.vc_ver >= 15.0:
arch_subdir = self.pi.target_dir(x64=True)
else:
arch_subdir = self.pi.target_dir(hidex86=True)
paths = ['Lib%s' % arch_subdir, r'ATLMFC\Lib%s' % arch_subdir]
if self.vc_ver >= 14.0:
paths += [r'Lib\store%... | Microsoft Visual C++ & Microsoft Foundation Class Libraries |
def _prune_invalid_time_reductions(spec):
valid_reductions = []
if not spec['var'].def_time and spec['dtype_out_time'] is not None:
for reduction in spec['dtype_out_time']:
if reduction not in _TIME_DEFINED_REDUCTIONS:
valid_reductions.append(reduction)
else:
... | Prune time reductions of spec with no time dimension. |
def _split_after_delimiter(self, item, indent_amt):
self._delete_whitespace()
if self.fits_on_current_line(item.size):
return
last_space = None
for item in reversed(self._lines):
if (
last_space and
(not isinstance(item, Atom) or no... | Split the line only after a delimiter. |
def do_print(filename):
with open(filename) as cmake_file:
body = ast.parse(cmake_file.read())
word_print = _print_details(lambda n: "{0} {1}".format(n.type,
n.contents))
ast_visitor.recurse(body,
whil... | Print the AST of filename. |
def cli_forms(self, *args):
forms = []
missing = []
for key, item in schemastore.items():
if 'form' in item and len(item['form']) > 0:
forms.append(key)
else:
missing.append(key)
self.log('Schemata with form:', forms)
self.l... | List all available form definitions |
def _handle_interrupt(self, fileno, val):
val = int(val)
edge = self._map_fileno_to_options[fileno]["edge"]
if (edge == 'rising' and val == 0) or (edge == 'falling' and val == 1):
return
debounce = self._map_fileno_to_options[fileno]["debounce_timeout_s"]
if debounce:... | Internally distributes interrupts to all attached callbacks |
def gen_enum_completions(self, arg_name):
try:
for choice in self.cmdtab[self.current_command].arguments[arg_name].choices:
if self.validate_completion(choice):
yield Completion(choice, -len(self.unfinished_word))
except TypeError:
pass | generates dynamic enumeration completions |
def _filter_list_to_conjunction_expression(filter_list):
if not isinstance(filter_list, list):
raise AssertionError(u'Expected `list`, Received: {}.'.format(filter_list))
if any((not isinstance(filter_block, Filter) for filter_block in filter_list)):
raise AssertionError(u'Expected list of Filte... | Convert a list of filters to an Expression that is the conjunction of all of them. |
def build_from_yamlstr(cls, yamlstr):
top_dict = yaml.safe_load(yamlstr)
coordsys = top_dict.pop('coordsys')
output_list = []
for e_key, e_dict in sorted(top_dict.items()):
if e_key == 'coordsys':
continue
e_dict = top_dict[e_key]
e_dic... | Build a list of components from a yaml string |
def parse_sentence(obj: dict) -> BioCSentence:
sentence = BioCSentence()
sentence.offset = obj['offset']
sentence.infons = obj['infons']
sentence.text = obj['text']
for annotation in obj['annotations']:
sentence.add_annotation(parse_annotation(annotation))
for relation in obj['rel... | Deserialize a dict obj to a BioCSentence object |
def log_status(plugin, filename, status):
display = ':'.join((plugin, filename)) + ' '
log.info('%s [%s]', '{:.<70}'.format(display), status) | Properly display a migration status line |
def _populateHistogram(self):
try :
buildHistogram.populate1DHist(self._data, self.histogram,
self.minValue, self.maxValue, self.binWidth)
except:
if ((self._data.max() - self._data.min()) < self.binWidth):
raise ValueError("In histogram1d class, t... | Call the C-code that actually populates the histogram |
def reset_dirty_flags(self):
for sm_id, sm in self.state_machines.items():
sm.marked_dirty = False | Set all marked_dirty flags of the state machine to false. |
def grow_use_function(self, depth=0):
"Select either function or terminal in grow method"
if depth == 0:
return False
if depth == self._depth:
return True
return np.random.random() < 0.5 | Select either function or terminal in grow method |
def prepare_input(self, extracted_str):
if self.options['remove_whitespace']:
optimized_str = re.sub(' +', '', extracted_str)
else:
optimized_str = extracted_str
if self.options['remove_accents']:
optimized_str = unidecode(optimized_str)
if self.option... | Input raw string and do transformations, as set in template file. |
def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None):
vld = vld or [str]
return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp) | Prompts the user for a string. |
def send(
self,
to=None,
subject=None,
contents=None,
attachments=None,
cc=None,
bcc=None,
preview_only=False,
headers=None,
newline_to_break=True,
):
self.login()
recipients, msg_string = self.prepare_send(
... | Use this to send an email with gmail |
def create_post(self, path, **kw):
content = kw.pop('content', None)
onefile = kw.pop('onefile', False)
kw.pop('is_page', False)
metadata = {}
metadata.update(self.default_metadata)
metadata.update(kw)
makedirs(os.path.dirname(path))
if not content.endswit... | Create a new post. |
def reset(self):
for proxy in list(self.dead):
self.dead.remove(proxy)
self.unchecked.add(proxy) | Mark all dead proxies as unchecked |
def layer_iter(layers, layer_names):
if use_caffe:
for layer_idx, layer in enumerate(layers):
layer_name = re.sub('[-/]', '_', layer_names[layer_idx])
layer_type = layer.type
layer_blobs = layer.blobs
yield (layer_name, layer_type, layer_blobs)
else:
... | Iterate over all layers |
def setup_kojiclient(profile):
opts = koji.read_config(profile)
for k, v in opts.iteritems():
opts[k] = os.path.expanduser(v) if type(v) is str else v
kojiclient = koji.ClientSession(opts['server'], opts=opts)
kojiclient.ssl_login(opts['cert'], None, opts['serverca'])
return kojiclient | Setup koji client session |
def _AbortTerminate(self):
for pid, process in iter(self._processes_per_pid.items()):
if not process.is_alive():
continue
logger.warning('Terminating process: {0:s} (PID: {1:d}).'.format(
process.name, pid))
process.terminate() | Aborts all registered processes by sending a SIGTERM or equivalent. |
def config(self):
if not hasattr(self, '_config'):
raw_config = configparser.RawConfigParser()
f = self._open()
if f:
raw_config.readfp(f)
f.close()
self._config = raw_config
return self._config | load the passwords from the config file |
def message(msg, indent=False, mtype='standard', caption=False):
if caption:
msg = '\n' + msg + '\n' + '-'*len(msg) + '\n'
if mtype == 'warning':
msg = colorlog('Warning: ' + msg, 'yellow')
if mtype == 'error':
msg = colorlog('Error: ' + msg, 'red')
if mtype == 'debug':
... | Writes messages in verbose mode |
def _domain_event_pmwakeup_cb(conn, domain, reason, opaque):
_salt_send_domain_event(opaque, conn, domain, opaque['event'], {
'reason': 'unknown'
}) | Domain wakeup events handler |
def validate_address(value):
if is_bytes(value):
if not is_binary_address(value):
raise InvalidAddress("Address must be 20 bytes when input type is bytes", value)
return
if not isinstance(value, str):
raise TypeError('Address {} must be provided as a string'.format(value))
... | Helper function for validating an address |
def override_build_kwarg(workflow, k, v, platform=None):
key = OrchestrateBuildPlugin.key
workspace = workflow.plugin_workspace.setdefault(key, {})
override_kwargs = workspace.setdefault(WORKSPACE_KEY_OVERRIDE_KWARGS, {})
override_kwargs.setdefault(platform, {})
override_kwargs[platform][k] = v | Override a build-kwarg for all worker builds |
def match(pattern):
regex = re.compile(pattern)
def validate(value):
if not regex.match(value):
return e("{} does not match the pattern {}", value, pattern)
return validate | Validates that a field value matches the regex given to this validator. |
def add_exec_to_user(
self,
name,
env,
command,
args,
**attrs
):
exec_options = {
'command': command,
'env': env,
'args': args,
}
exec_options.update(attrs)
self.add_to_user(name=name, exec=exec_... | Add an exec option to your user. |
def upper_lower_none(arg):
if not arg:
return arg
arg = arg.strip().lower()
if arg in ['upper', 'lower']:
return arg
raise ValueError('argument must be "upper", "lower" or None') | Validate arg value as "upper", "lower", or None. |
def _pred_sets_are_in_conflict(pred_set_a, pred_set_b):
for pred_a, bool_a in pred_set_a:
for pred_b, bool_b in pred_set_b:
if pred_a is pred_b and bool_a != bool_b:
return False
return True | Find conflict in sets, return conflict if found, else None. |
def _get_magnitude_scaling_term(self, C, mag):
if mag < 6.75:
return C["a1_lo"] + C["a2_lo"] * mag + C["a3"] *\
((8.5 - mag) ** 2.0)
else:
return C["a1_hi"] + C["a2_hi"] * mag + C["a3"] *\
((8.5 - mag) ** 2.0) | Returns the magnitude scaling term defined in equation 3 |
def sample_list(args):
if args.entity_type and args.entity:
if args.entity_type == 'sample':
return [ args.entity.strip() ]
elif args.entity_type == 'participant':
samples = _entity_paginator(args.project, args.workspace,
'sample', page_si... | List samples within a container. |
def post_helper(form_tag=True, edit_mode=False):
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
'text',
css_class='small-12'
),
),
]
... | Post's form layout helper |
def pop():
pid = os.getpid()
thread = threading.current_thread()
Wdb._instances.pop((pid, thread)) | Remove instance from instance list |
def write(self, x):
if self._new_lines:
if not self._first_write:
self.stream.write('\n' * self._new_lines)
self.code_lineno += self._new_lines
if self._write_debug_info is not None:
self.debug_info.append((self._write_debug_info,
... | Write a string into the output stream. |
def fetch_album_name(self):
response = get_lastfm('track.getInfo', artist=self.artist,
track=self.title)
if response:
try:
self.album = response['track']['album']['title']
logger.debug('Found album %s from lastfm', self.album)
... | Get the name of the album from lastfm. |
def write(self, file, text, subvars={}, trim_leading_lf=True):
file.write(self.substitute(text, subvars=subvars, trim_leading_lf=trim_leading_lf)) | write to a file with variable substitution |
def cmd_build(conf: Config, run_tests: bool=False):
build_context = BuildContext(conf)
populate_targets_graph(build_context, conf)
build_context.build_graph(run_tests=run_tests)
build_context.write_artifacts_metadata() | Build requested targets, and their dependencies. |
async def enable(self):
await self.controller.enable_user(self.username)
self._user_info.disabled = False | Re-enable this user. |
def main_photo(self):
if not self._main_photo:
self._main_photo = self.photos_factory()
return self._main_photo | Return user's main photo. |
def rowsWithin(self, bbox):
'return list of deduped rows within bbox'
ret = {}
for y in range(bbox.ymin, bbox.ymax+1):
for x in range(bbox.xmin, bbox.xmax+1):
for attr, rows in self.pixels[y][x].items():
if attr not in self.hiddenAttrs:
... | return list of deduped rows within bbox |
def write(self, file_handle):
for k, v in self.inputs.write_values().items():
self.set('config', k, v)
self.set('config', 'namespace', self.namespace)
self.manifest.write(file_handle) | write the current state to a file manifest |
def _decode(frame, tab):
blocks = []
while frame:
length, endseq = tab[frame[0]]
blocks.extend([frame[1:length], endseq])
frame = frame[length:]
if blocks and len(blocks[-1]) > 0:
blocks[-1] = blocks[-1][:-1]
return ''.join(blocks) | Decode a frame with the help of the table. |
def adjust_status(info: dict) -> dict:
modified_info = deepcopy(info)
modified_info.update({
'level':
get_nearest_by_numeric_key(STATUS_MAP, int(info['level'])),
'level2':
STATUS_MAP[99] if info['level2'] is None else
get_nearest_by_numeric_key(STATUS_MAP, int... | Apply status mapping to a raw API result. |
def task_status(self, task_id):
data = {
'task_ids': task_id,
}
return self._perform_post_request(self.task_status_endpoint, data, self.token_header) | Find the status of a task. |
def modelnumericfunctions(self):
lines = Lines()
lines.extend(self.solve)
lines.extend(self.calculate_single_terms)
lines.extend(self.calculate_full_terms)
lines.extend(self.get_point_states)
lines.extend(self.set_point_states)
lines.extend(self.set_result_states)... | Numerical functions of the model class. |
def _single_function_inclusion_filter_builder(func: str) -> NodePredicate:
def function_inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:
return node.function == func
return function_inclusion_filter | Build a function inclusion filter for a single function. |
def write_directory (zfile, directory):
for dirpath, dirnames, filenames in os.walk(directory):
zfile.write(dirpath)
for filename in filenames:
zfile.write(os.path.join(dirpath, filename)) | Write recursively all directories and filenames to zipfile instance. |
def extract_presets(app_config):
return {
x.lower()[10:]: app_config.get(x)
for x in filter(lambda x: x.startswith("SANIC_JWT"), app_config)
} | Pull the application's configurations for Sanic JWT |
def _decode_time(self, text):
if self._kp.version >= (4, 0):
try:
return (
datetime(year=1, month=1, day=1, tzinfo=tz.gettz('UTC')) +
timedelta(
seconds = struct.unpack('<Q', base64.b64decode(text))[0]
... | Convert base64 time or plaintext time to datetime |
def copy_global_values(data):
for k, v in data['values'].items():
if not data.get(k):
data[k] = v
else:
puts("There is both a worksheet and a "
"value named '{0}'. The worksheet data "
"will be preserved.".format(k))
data.pop("values", No... | Copy values worksheet into global namespace. |
def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True):
try:
with self:
_LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response)
self._conn.writeCharacteristic(handle, value, withResponse=w... | Write a GATT Command without callback - not utf-8. |
def definition(self, name, tags=None):
def wrapper(obj):
self.definition_models.append(SwaggerDefinition(name, obj,
tags=tags))
return obj
return wrapper | Decorator to add class based definitions |
def __make_request_method(self, teststep_dict, entry_json):
method = entry_json["request"].get("method")
if not method:
logging.exception("method missed in request.")
sys.exit(1)
teststep_dict["request"]["method"] = method | parse HAR entry request method, and make teststep method. |
def process(self, msg, kwargs):
prefixed_dict = {}
prefixed_dict['repo_vcs'] = self.bin_name
prefixed_dict['repo_name'] = self.name
kwargs["extra"] = prefixed_dict
return msg, kwargs | Add additional context information for loggers. |
def read_all(self, count=-1):
res = []
while count != 0:
count -= 1
p = self.read_packet()
if p is None:
break
res.append(p)
return res | return a list of all packets in the pcap file |
def to_python(self, value):
if value in self.empty_values:
try:
return self.empty_value
except AttributeError:
return u''
return bleach.clean(value, **self.bleach_options) | Strips any dodgy HTML tags from the input |
def _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None):
if schema is None:
schema = google.datalab.bigquery.Schema.from_data(source)
fields = get_field_list(fields, schema)
rows = []
if count < 0:
count = len(source.index)
df_slice = source.reset_index(drop=True)[first_ro... | Helper function for _get_data that handles Pandas DataFrames. |
def invalidate(self):
for row in self.rows:
for key in row.keys:
key.state = 0 | Rests all keys states. |
def cli(ctx, all, top, nostyle, nowarn, warn, project_dir):
exit_code = SCons(project_dir).lint({
'all': all,
'top': top,
'nostyle': nostyle,
'nowarn': nowarn,
'warn': warn
})
ctx.exit(exit_code) | Lint the verilog code. |
def _make_command_filename(self, exe):
outfn = os.path.join(self.commons['cmddir'], self.name(),
self._mangle_command(exe))
if os.path.exists(outfn):
inc = 2
while True:
newfn = "%s_%d" % (outfn, inc)
if not os.path.exi... | The internal function to build up a filename based on a command. |
def rlmb_base_sv2p():
hparams = rlmb_base()
hparams.learning_rate_bump = 1.0
hparams.generative_model = "next_frame_sv2p"
hparams.generative_model_params = "next_frame_sv2p_atari"
return hparams | Base setting with sv2p as world model. |
def build():
try:
cloud_config = CloudConfig()
config_data = cloud_config.config_data('cluster')
cloud_init = CloudInit()
print(cloud_init.build(config_data))
except CloudComposeException as ex:
print(ex) | builds the cloud_init script |
def groff2man(data):
width = get_width()
cmd = 'groff -t -Tascii -m man -rLL=%dn -rLT=%dn' % (width, width)
handle = subprocess.Popen(
cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
man_text, stderr = handle.communicate(data)
return man_text | Read groff-formatted text and output man pages. |
def add_material(self, material):
if self.has_material(material):
return
self.materials.append(material) | Add a material to the mesh, IF it's not already present. |
def section_branch_orders(neurites, neurite_type=NeuriteType.all):
return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type) | section branch orders in a collection of neurites |
def get(self, template_name):
template = db.Template.find_one(template_name=template_name)
if not template:
return self.make_response('No such template found', HTTP.NOT_FOUND)
return self.make_response({'template': template}) | Get a specific template |
def open(self):
try:
self.project.open_main(self.filename)
except UnicodeDecodeError:
with open(self.filename, 'rb') as openfile:
encoding = get_encoding(openfile.read())
try:
self.project.open_main(self.filename, encoding)
... | Open the subtitle file into an Aeidon project. |
def available_actions(self, obs):
available_actions = set()
hide_specific_actions = self._agent_interface_format.hide_specific_actions
for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE):
if func.avail_fn(obs):
available_actions.add(i)
for a in obs.abilities:
if a.ability_id no... | Return the list of available action ids. |
def run(self):
self.logger.debug(f'Running command: {self.cmd}')
def execute(cmd):
output = ""
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True, shell=True)
for stdout_line in ... | Run command and report errors to Sentry. |
def timeout_keep_alive_handler(self):
if not self.transport.is_closing():
event = h11.ConnectionClosed()
self.conn.send(event)
self.transport.close() | Called on a keep-alive connection if no new data is received after a short delay. |
def make_quality_report(data):
if "bcbiornaseq" not in dd.get_tools_on(data):
return data
upload_dir = tz.get_in(("upload", "dir"), data)
report_dir = os.path.join(upload_dir, "bcbioRNASeq")
safe_makedir(report_dir)
quality_rmd = os.path.join(report_dir, "quality_control.Rmd")
quality_ht... | create and render the bcbioRNASeq quality report |
def load_template(self, template: str) -> Template:
env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False)
jinja2_ext = ".jinja2"
if not template.endswith(jinja2_ext):
self._log.error("Template file name must end with %s" % jinja2_ext)
raise ValueEr... | Load a Jinja2 template from the source directory. |
def __xd_iterator_pass_on(arr, view, fun):
iterations = [[None] if dim in view else list(range(arr.shape[dim])) for dim in range(arr.ndim)]
passon = None
for indices in itertools.product(*iterations):
slicer = [slice(None) if idx is None else slice(idx, idx + 1) for idx in indices]
passon = ... | Like xd_iterator, but the fun return values are always passed on to the next and only the last returned. |
def send_packed_virtual_touch_event(xpos, ypos, phase, device_id, finger):
message = create(protobuf.SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE)
event = message.inner()
event.data = xpos.to_bytes(2, byteorder='little')
event.data += ypos.to_bytes(2, byteorder='little')
event.data += phase.to_bytes(2, b... | Create a new WAKE_DEVICE_MESSAGE. |
def _operator_generator(index, conj):
pterm = PauliTerm('I', 0, 1.0)
Zstring = PauliTerm('I', 0, 1.0)
for j in range(index):
Zstring = Zstring*PauliTerm('Z', j, 1.0)
pterm1 = Zstring*PauliTerm('X', index, 0.5)
scalar = 0.5 * conj * 1.0j
pterm2 = Zstring*PauliT... | Internal method to generate the appropriate operator |
def _get_index_for_insert(self, key, instance):
if instance == 0:
index = self.keys().index(key)
else:
occurrence = -1
for index, k in enumerate(self.keys()):
if k == key:
occurrence += 1
if occurrence == instanc... | Get the index of the key to insert before or after |
def validate_uses_tls_for_keystone(audit_options):
section = _config_section(audit_options, 'keystone_authtoken')
assert section is not None, "Missing section 'keystone_authtoken'"
assert not section.get('insecure') and \
"https://" in section.get("auth_uri"), \
"TLS is not used for Keystone... | Verify that TLS is used to communicate with Keystone. |
def show_help(name):
print('Usage: python3 {} [OPTIONS]... '.format(name))
print('ISO8583 message client')
print(' -v, --verbose\t\tRun transactions verbosely')
print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default')
print(' -s, --server=[IP]\t\tIP of the ISO host to connect to, 12... | Show help and basic usage |
def delete_and_rm_options(*args, **kwargs):
def inner_decorator(f, supports_batch=True, default_enable_globs=False):
f = click.option(
"--recursive", "-r", is_flag=True, help="Recursively delete dirs"
)(f)
f = click.option(
"--ignore-missing",
"-f",
... | Options which apply both to `globus delete` and `globus rm` |
def _wrapper_find_one(self, filter_=None, *args, **kwargs):
return self.__collect.find_one(filter_, *args, **kwargs) | Convert record to a dict that has no key error |
def process_input(self, character):
func = None
try:
func = getattr(self, "handle_%s" % chr(character), None)
except:
pass
if func:
func() | A subclassable method for dealing with input characters. |
def cross_successors(state, last_action=None):
centres, edges = state
acts = sum([
[s, s.inverse(), s * 2] for s in
map(Step, "RUFDRB".replace(last_action.face if last_action else "", "", 1))
], [])
for step in acts:
yield step, (centres, CrossSolv... | Successors function for solving the cross. |
def indent(text, amount, ch=' '):
padding = amount * ch
return ''.join(padding+line for line in text.splitlines(True)) | Indents a string by the given amount of characters. |
def _find_entry_call(self, frames):
back_i = 0
pout_path = self._get_src_file(self.modname)
for frame_i, frame in enumerate(frames):
if frame[1] == pout_path:
back_i = frame_i
return Call(frames[back_i]) | attempts to auto-discover the correct frame |
def check_schedule():
all_items = prefetch_schedule_items()
for validator, _type, _msg in SCHEDULE_ITEM_VALIDATORS:
if validator(all_items):
return False
all_slots = prefetch_slots()
for validator, _type, _msg in SLOT_VALIDATORS:
if validator(all_slots):
return Fa... | Helper routine to easily test if the schedule is valid |
def extend(self, tasks):
self._tasks.extend(tasks)
for task in tasks:
current = self.map
modules = task.fullname.split('.')
for module in modules[:-1]:
if not isinstance(current[module], Shovel):
logger.warn('Overriding task %s with... | Add tasks to this particular shovel |
def run_container():
os.chdir(my_directory)
cmd = [
'docker', 'run',
'-it', '--rm',
'-v', '{}:/cauldron'.format(my_directory),
'-p', '5010:5010',
'cauldron_app',
'/bin/bash'
]
return os.system(' '.join(cmd)) | Runs an interactive container |
def visit_generatorexp(self, node):
return "(%s %s)" % (
node.elt.accept(self),
" ".join(n.accept(self) for n in node.generators),
) | return an astroid.GeneratorExp node as string |
def touchz(self, path):
self.client.write(path, data='', overwrite=False) | To touchz using the web hdfs "write" cmd. |
def search_range(self, value):
if value == 0 or not value % 16:
self._search_range = value
else:
raise InvalidSearchRangeError("Search range must be a multiple of "
"16.")
self._replace_bm() | Set private ``_search_range`` and reset ``_block_matcher``. |
def generate_fetch_ivy(cls, jars, ivyxml, confs, resolve_hash_name):
org = IvyUtils.INTERNAL_ORG_NAME
name = resolve_hash_name
extra_configurations = [conf for conf in confs if conf and conf != 'default']
jars_by_key = OrderedDict()
for jar in jars:
jars_by_key.setdefault((jar.org, jar.name, j... | Generates an ivy xml with all jars marked as intransitive using the all conflict manager. |
def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]:
_assert_valid_sexpr(sexpr)
for child in sexpr[1:]:
if _is_sexpr(child) and child[0] in tags:
return child
return None | Search for a tag among direct children of the s-expression. |
def _handle_authentication_error(self):
response = make_response('Access Denied')
response.headers['WWW-Authenticate'] = self.auth.get_authenticate_header()
response.status_code = 401
return response | Return an authentication error. |
def feed(self):
"Feed a line from the contents of the GPS log to the daemon."
line = self.testload.sentences[self.index % len(self.testload.sentences)]
if "%Delay:" in line:
delay = line.split()[1]
time.sleep(int(delay))
self.write(line)
if self.progress:
... | Feed a line from the contents of the GPS log to the daemon. |
def load(cls, path):
assert os.path.exists(path), "No such file: %r" % path
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
wave = Waveform(None)
wave._path = path
return wave | Load Waveform from file. |
def load(self, _from):
def load_rec(inode, config):
for k in config:
if isinstance(config[k], dict) and \
k not in ['value', 'default']:
if k in inode:
load_rec(inode[k], config[k])
else:
... | Load the configuration dictionary from file. |
def _count_counters(self, counter):
if getattr(self, 'as_set', False):
return len(set(counter))
else:
return sum(counter.values()) | Return all elements count from Counter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.