code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _read(self, limit = None):
while True:
if not self._fh:
return False
dataread = os.read(self._fh.fileno(), limit or 65535)
if len(dataread) > 0:
self._buf += dataread
if limit is not None:
return True
else:
return False | module function_definition identifier parameters identifier default_parameter identifier none block while_statement true block if_statement not_operator attribute identifier identifier block return_statement false expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list boolean_operator identifier integer if_statement comparison_operator call identifier argument_list identifier integer block expression_statement augmented_assignment attribute identifier identifier identifier if_statement comparison_operator identifier none block return_statement true else_clause block return_statement false | Checks the file for new data and refills the buffer if it finds any. |
def slices_to_global_coords(self, slices):
bbox = self.bbox_to_mip(slices, self.mip, 0)
return bbox.to_slices() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier integer return_statement call attribute identifier identifier argument_list | Used to convert from a higher mip level into mip 0 resolution. |
def install(self, tmp_container, font_tmpdir, css_content):
with open(self.webfont_settings['csspart_path'], 'w') as css_file:
css_file.write(css_content)
if os.path.exists(self.webfont_settings['fontdir_path']):
shutil.rmtree(self.webfont_settings['fontdir_path'])
font_srcdir = os.path.join(tmp_container, font_tmpdir)
self._debug("* Installing font")
self._debug(" - From: {}", font_srcdir)
self._debug(" - To: {}", self.webfont_settings['fontdir_path'])
shutil.copytree(font_srcdir, self.webfont_settings['fontdir_path'])
manifest_src = os.path.join(tmp_container,
settings.ICOMOON_MANIFEST_FILENAME)
self._debug("* Installing manifest")
self._debug(" - From: {}", manifest_src)
self._debug(" - To: {}", self.webfont_settings['fontdir_path'])
shutil.copy(manifest_src, self.webfont_settings['fontdir_path'])
self._debug("* Removing temporary dir")
shutil.rmtree(tmp_container) | module function_definition identifier parameters identifier identifier identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | Install extracted files and builded css |
def _get_stripped_text_from_node(self, node):
return (
node.text_content()
.replace(u"\u00A0", " ")
.replace("\t", "")
.replace("\n", "")
.strip()
) | module function_definition identifier parameters identifier identifier block return_statement parenthesized_expression call attribute call attribute call attribute call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end identifier argument_list string string_start string_content escape_sequence string_end string string_start string_end identifier argument_list string string_start string_content escape_sequence string_end string string_start string_end identifier argument_list | Return the stripped text content of a node. |
def check_config(db, level):
if level == 'global':
configuration = config.read(config.HOMEDIR, '.passpierc')
elif level == 'local':
configuration = config.read(os.path.join(db.path))
elif level == 'current':
configuration = db.config
if configuration:
click.echo(yaml.safe_dump(configuration, default_flow_style=False)) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier false | Show current configuration for shell |
def _move_stream_endpoint(coordinator, position):
stream_arn = coordinator.stream_arn
coordinator.roots.clear()
coordinator.active.clear()
coordinator.buffer.clear()
current_shards = coordinator.session.describe_stream(stream_arn=stream_arn)["Shards"]
current_shards = unpack_shards(current_shards, stream_arn, coordinator.session)
coordinator.roots.extend(shard for shard in current_shards.values() if not shard.parent)
if position == "trim_horizon":
for shard in coordinator.roots:
shard.jump_to(iterator_type="trim_horizon")
coordinator.active.extend(coordinator.roots)
else:
for root in coordinator.roots:
for shard in root.walk_tree():
if not shard.children:
shard.jump_to(iterator_type="latest")
coordinator.active.append(shard) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier generator_expression identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause not_operator attribute identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier else_clause block for_statement identifier attribute identifier identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Move to the "trim_horizon" or "latest" of the entire stream. |
def key_str(self, match):
ret = {}
for status, keys in six.iteritems(self.name_match(match)):
ret[status] = {}
for key in salt.utils.data.sorted_ignorecase(keys):
path = os.path.join(self.opts['pki_dir'], status, key)
with salt.utils.files.fopen(path, 'r') as fp_:
ret[status][key] = \
salt.utils.stringutils.to_unicode(fp_.read())
return ret | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier block expression_statement assignment subscript identifier identifier dictionary for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier identifier with_statement with_clause with_item as_pattern call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment subscript subscript identifier identifier identifier line_continuation call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Return the specified public key or keys based on a glob |
def fetch_push_logs():
for repo in Repository.objects.filter(dvcs_type='hg',
active_status="active"):
fetch_hg_push_log.apply_async(
args=(repo.name, repo.url),
queue='pushlog'
) | module function_definition identifier parameters block for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list keyword_argument identifier tuple attribute identifier identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end | Run several fetch_hg_push_log subtasks, one per repository |
def process_refs_for_node(cls, manifest, current_project, node):
target_model = None
target_model_name = None
target_model_package = None
for ref in node.refs:
if len(ref) == 1:
target_model_name = ref[0]
elif len(ref) == 2:
target_model_package, target_model_name = ref
target_model = cls.resolve_ref(
manifest,
target_model_name,
target_model_package,
current_project,
node.get('package_name'))
if target_model is None or target_model is cls.DISABLED:
node.config['enabled'] = False
dbt.utils.invalid_ref_fail_unless_test(
node, target_model_name, target_model_package,
disabled=(target_model is cls.DISABLED)
)
continue
target_model_id = target_model.get('unique_id')
node.depends_on['nodes'].append(target_model_id)
manifest.nodes[node['unique_id']] = node | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier none expression_statement assignment identifier none expression_statement assignment identifier none for_statement identifier attribute identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier integer elif_clause comparison_operator call identifier argument_list identifier integer block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator identifier none comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end false expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier keyword_argument identifier parenthesized_expression comparison_operator identifier attribute identifier identifier continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier subscript identifier string string_start string_content string_end identifier | Given a manifest and a node in that manifest, process its refs |
async def nodes(self, text, opts=None, user=None):
return [n async for n in self.eval(text, opts=opts, user=user)] | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block return_statement list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier | A simple non-streaming way to return a list of nodes. |
def load_hdu(self, hdu):
image = AstroImage.AstroImage(logger=self.logger)
image.load_hdu(hdu)
self.set_image(image) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Load an HDU into the viewer. |
def _add_tag_files(
zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count
):
tag_info_list = []
_add_tag_file(zip_file, dir_name, tag_info_list, _gen_bagit_text_file_tup())
_add_tag_file(
zip_file,
dir_name,
tag_info_list,
_gen_bag_info_file_tup(payload_byte_count, payload_file_count),
)
_add_tag_file(
zip_file, dir_name, tag_info_list, _gen_pid_mapping_file_tup(payload_info_list)
)
return tag_info_list | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier list expression_statement call identifier argument_list identifier identifier identifier call identifier argument_list expression_statement call identifier argument_list identifier identifier identifier call identifier argument_list identifier identifier expression_statement call identifier argument_list identifier identifier identifier call identifier argument_list identifier return_statement identifier | Generate the tag files and add them to the zip. |
def remove_resource(self):
self.mark_current_profile_as_pending()
for item in self.resources_list.selectedItems():
self.resources_list.takeItem(self.resources_list.row(item)) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier | Remove the currently selected resource. |
def _delAccountRights(sidObject, user_right):
try:
_polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS)
user_rights_list = [user_right]
_ret = win32security.LsaRemoveAccountRights(_polHandle, sidObject, False, user_rights_list)
return True
except Exception as e:
log.exception('Error attempting to delete account right')
return False | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list none attribute identifier identifier expression_statement assignment identifier list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier false identifier return_statement true except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false | helper function to remove an account right from a user |
def name(self):
if self.chosen_name:
return self.chosen_name
else:
pane = self.active_pane
if pane:
return pane.name
return '' | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier if_statement identifier block return_statement attribute identifier identifier return_statement string string_start string_end | The name for this window as it should be displayed in the status bar. |
def getyrdoy(date):
try:
doy = date.toordinal()-datetime(date.year,1,1).toordinal()+1
except AttributeError:
raise AttributeError("Must supply a pandas datetime object or " +
"equivalent")
else:
return date.year, doy | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier binary_operator binary_operator call attribute identifier identifier argument_list call attribute call identifier argument_list attribute identifier identifier integer integer identifier argument_list integer except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end else_clause block return_statement expression_list attribute identifier identifier identifier | Return a tuple of year, day of year for a supplied datetime object. |
def displayformat(codes=[], fg=None, bg=None):
if isinstance(codes, basestring):
codes = [codes]
else:
codes = list(codes)
for code in codes:
if code not in Magic.DISPLAY.keys():
raise ValueError("'%s' not a valid display value" % code)
for color in (fg, bg):
if color != None:
if color not in Magic.COLORS.keys():
raise ValueError("'%s' not a valid color" % color)
return [codes, fg, bg] | module function_definition identifier parameters default_parameter identifier list default_parameter identifier none default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block if_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier for_statement identifier tuple identifier identifier block if_statement comparison_operator identifier none block if_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement list identifier identifier identifier | Makes sure all arguments are valid |
def statichttp(container = None):
"wrap a WSGI-style function to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(event):
return _handler(container, event, func)
if hasattr(func, '__self__'):
handler.__self__ = func.__self__
return handler
return decorator | module function_definition identifier parameters default_parameter identifier none block expression_statement string string_start string_content string_end function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters identifier block return_statement call identifier argument_list identifier identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement identifier return_statement identifier | wrap a WSGI-style function to a HTTPRequest event handler |
def container_logs(name, tail, follow, timestamps):
if follow:
return _get_docker().attach(
name,
stdout=True,
stderr=True,
stream=True
)
return _docker.logs(
name,
stdout=True,
stderr=True,
tail=tail,
timestamps=timestamps,
) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement identifier block return_statement call attribute call identifier argument_list identifier argument_list identifier keyword_argument identifier true keyword_argument identifier true keyword_argument identifier true return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true keyword_argument identifier true keyword_argument identifier identifier keyword_argument identifier identifier | Wrapper for docker logs, attach commands. |
def delete_os_dummy_rtr(self, tenant_id, fw_dict, is_fw_virt=False):
ret = True
tenant_name = fw_dict.get('tenant_name')
try:
rtr_id = fw_dict.get('router_id')
if not rtr_id:
LOG.error("Invalid router id, deleting dummy interface"
" failed")
return False
if not is_fw_virt:
ret = self._delete_dummy_intf_rtr(tenant_id, tenant_name,
rtr_id)
except Exception as exc:
LOG.error("Deletion of Openstack Router failed tenant "
"%(tenant)s, Exception %(exc)s",
{'tenant': tenant_id, 'exc': str(exc)})
ret = False
if ret:
res = fw_const.OS_DUMMY_RTR_DEL_SUCCESS
else:
res = fw_const.OS_DUMMY_RTR_DEL_FAIL
self.update_fw_db_result(tenant_id, os_status=res)
return ret | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier true expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement false if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end call identifier argument_list identifier expression_statement assignment identifier false if_statement identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Delete the Openstack Dummy router and store the info in DB. |
def portfolio(self) -> List[PortfolioItem]:
account = self.wrapper.accounts[0]
return [v for v in self.wrapper.portfolio[account].values()] | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier integer return_statement list_comprehension identifier for_in_clause identifier call attribute subscript attribute attribute identifier identifier identifier identifier identifier argument_list | List of portfolio items of the default account. |
def fetch_events(self) -> List[dict]:
try:
return self.inner.rtm_read()
except TimeoutError:
log.debug('Lost connection to the Slack API, attempting to '
'reconnect')
self.connect_with_retry()
return [] | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block try_statement block return_statement call attribute attribute identifier identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list return_statement list | Fetch new RTM events from the API. |
def x10_all_units_off(self, housecode):
if isinstance(housecode, str):
housecode = housecode.upper()
else:
raise TypeError('Housecode must be a string')
msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_UNITS_OFF)
self.send_msg(msg)
self._x10_command_to_device(housecode, X10_COMMAND_ALL_UNITS_OFF, msg) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Send the X10 All Units Off command. |
def release_value_set(self):
if self._remotelib:
self._remotelib.run_keyword('release_value_set', [self._my_id], {})
else:
_PabotLib.release_value_set(self, self._my_id) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end list attribute identifier identifier dictionary else_clause block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier | Release a reserved value set so that other executions can use it also. |
def finish(self, msg=None):
if self._finished or self.disable:
return
self._finished = True
if msg is not None:
self(msg)
self._new_msg("< Exiting %s, total time: %0.4f ms",
self._name, (ptime.time() - self._firstTime) * 1000)
type(self)._depth -= 1
if self._depth < 1:
self.flush() | module function_definition identifier parameters identifier default_parameter identifier none block if_statement boolean_operator attribute identifier identifier attribute identifier identifier block return_statement expression_statement assignment attribute identifier identifier true if_statement comparison_operator identifier none block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier binary_operator parenthesized_expression binary_operator call attribute identifier identifier argument_list attribute identifier identifier integer expression_statement augmented_assignment attribute call identifier argument_list identifier identifier integer if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list | Add a final message; flush the message list if no parent profiler. |
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs):
awm = ArrayWithMask.createFromMaskedArray(maskedArray)
maskIdx = awm.maskIndex()
validData = awm.data[~maskIdx]
if len(validData) >= 1:
result = np.nanpercentile(validData, percentiles, *args, **kwargs)
else:
result = len(percentiles) * [np.nan]
assert len(result) == len(percentiles), \
"shape mismatch: {} != {}".format(len(result), len(percentiles))
return result | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript attribute identifier identifier unary_operator identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier else_clause block expression_statement assignment identifier binary_operator call identifier argument_list identifier list attribute identifier identifier assert_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier call identifier argument_list identifier return_statement identifier | Calculates np.nanpercentile on the non-masked values |
def _cache_key_select_sample_type(method, self, allow_blank=True, multiselect=False, style=None):
key = update_timer(), allow_blank, multiselect, style
return key | module function_definition identifier parameters identifier identifier default_parameter identifier true default_parameter identifier false default_parameter identifier none block expression_statement assignment identifier expression_list call identifier argument_list identifier identifier identifier return_statement identifier | This function returns the key used to decide if method select_sample_type has to be recomputed |
def lock_area(self, code, index):
logger.debug("locking area code %s index %s" % (code, index))
return self.library.Srv_LockArea(self.pointer, code, index) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier identifier | Locks a shared memory area. |
def getDatabaseFileSize(self):
if DISABLE_PERSISTENT_CACHING:
return "?"
size = os.path.getsize(self.__db_filepath)
if size > 1000000000:
size = "%0.3fGB" % (size / 1000000000)
elif size > 1000000:
size = "%0.2fMB" % (size / 1000000)
elif size > 1000:
size = "%uKB" % (size // 1000)
else:
size = "%uB" % (size)
return size | module function_definition identifier parameters identifier block if_statement identifier block return_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier integer elif_clause comparison_operator identifier integer block expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier integer elif_clause comparison_operator identifier integer block expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier integer else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression identifier return_statement identifier | Return the file size of the database as a pretty string. |
def _is_chinese_char(self, cp):
if ((cp >= 0x4E00 and cp <= 0x9FFF) or
(cp >= 0x3400 and cp <= 0x4DBF) or
(cp >= 0x20000 and cp <= 0x2A6DF) or
(cp >= 0x2A700 and cp <= 0x2B73F) or
(cp >= 0x2B740 and cp <= 0x2B81F) or
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or
(cp >= 0x2F800 and cp <= 0x2FA1F)):
return True
return False | module function_definition identifier parameters identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer block return_statement true return_statement false | Checks whether CP is the codepoint of a CJK character. |
def progress(self, *msg):
label = colors.purple("Progress")
self._msg(label, *msg) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier list_splat identifier | Prints a progress message |
def setup_venv(self):
venv = self.opts.venv
if not venv:
venv = os.environ.get('CRONY_VENV')
if not venv and self.config['crony']:
venv = self.config['crony'].get('venv')
if venv:
if not venv.endswith('activate'):
add_path = os.path.join('bin', 'activate')
self.logger.debug(f'Venv directory given, adding {add_path}')
venv = os.path.join(venv, add_path)
self.logger.debug(f'Adding sourcing virtualenv {venv}')
self.cmd = f'. {venv} && {self.cmd}' | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator not_operator identifier subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end if_statement identifier block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content interpolation identifier string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content interpolation identifier string_end expression_statement assignment attribute identifier identifier string string_start string_content interpolation identifier string_content interpolation attribute identifier identifier string_end | Setup virtualenv if necessary. |
def new_named_args(self, cur_named_args: Dict[str, Any]) -> Dict[str, Any]:
named_args = cur_named_args.copy()
named_args.update(self.matchdict)
return named_args | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | create new named args updating current name args |
def _htfile(username, password, **kwargs):
filetype = kwargs.get('filetype', 'htpasswd').lower()
try:
import passlib
kwargs['passlib_version'] = passlib.__version__
except ImportError:
log.error('salt.auth.file: The python-passlib library is required '
'for %s filetype', filetype)
return False
if filetype == 'htdigest':
return _htdigest(username, password, **kwargs)
else:
return _htpasswd(username, password, **kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list try_statement block import_statement dotted_name identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier return_statement false if_statement comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list identifier identifier dictionary_splat identifier else_clause block return_statement call identifier argument_list identifier identifier dictionary_splat identifier | Gate function for _htpasswd and _htdigest authentication backends |
def parse_xml_point(elem):
point = {}
units = {}
for data in elem.findall('data'):
name = data.get('name')
unit = data.get('units')
point[name] = float(data.text) if name != 'date' else parse_iso_date(data.text)
if unit:
units[name] = unit
return point, units | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier identifier conditional_expression call identifier argument_list attribute identifier identifier comparison_operator identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier if_statement identifier block expression_statement assignment subscript identifier identifier identifier return_statement expression_list identifier identifier | Parse an XML point tag. |
def _init_jobs_table():
_jobs_table = sqlalchemy.Table(
'jobs', _METADATA,
sqlalchemy.Column('job_id', sqlalchemy.UnicodeText, primary_key=True),
sqlalchemy.Column('job_type', sqlalchemy.UnicodeText),
sqlalchemy.Column('status', sqlalchemy.UnicodeText, index=True),
sqlalchemy.Column('data', sqlalchemy.UnicodeText),
sqlalchemy.Column('error', sqlalchemy.UnicodeText),
sqlalchemy.Column('requested_timestamp', sqlalchemy.DateTime),
sqlalchemy.Column('finished_timestamp', sqlalchemy.DateTime),
sqlalchemy.Column('sent_data', sqlalchemy.UnicodeText),
sqlalchemy.Column('result_url', sqlalchemy.UnicodeText),
sqlalchemy.Column('api_key', sqlalchemy.UnicodeText),
sqlalchemy.Column('job_key', sqlalchemy.UnicodeText),
)
return _jobs_table | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier keyword_argument identifier true call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier keyword_argument identifier true call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier return_statement identifier | Initialise the "jobs" table in the db. |
def parse_torrent_file(torrent):
link_re = re.compile(r'^(http?s|ftp)')
if link_re.match(torrent):
response = requests.get(torrent, headers=HEADERS, timeout=20)
data = parse_torrent_buffer(response.content)
elif os.path.isfile(torrent):
with open(torrent, 'rb') as f:
data = parse_torrent_buffer(f.read())
else:
data = None
return data | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier integer expression_statement assignment identifier call identifier argument_list attribute identifier identifier elif_clause call attribute attribute identifier identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier none return_statement identifier | parse local or remote torrent file |
def _verify_config(self):
if not self.config_dict:
self._raise_config_exception('No config found')
for dev_os, dev_config in self.config_dict.items():
if not dev_config:
log.warning('No config found for %s', dev_os)
continue
self._verify_config_dict(CONFIG.VALID_CONFIG, dev_config, dev_os)
log.debug('Read the config without error') | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier continue_statement expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Verify that the config is correct |
def hidden(self):
members = [self.member_info(item["_id"]) for item in self.members()]
result = []
for member in members:
if member['rsInfo'].get('hidden'):
server_id = member['server_id']
result.append({
'_id': member['_id'],
'host': self._servers.hostname(server_id),
'server_id': server_id})
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end for_in_clause identifier call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement identifier identifier block if_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier pair string string_start string_content string_end identifier return_statement identifier | return list of hidden members |
def add(self, quantity):
newvalue = self._value + quantity
self.set(newvalue.deg) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Adds an angle to the value |
def make_api_call(self, call, params):
if not isinstance(params, dict):
raise ValueError("params argument must be a dictionary")
kw = dict(
params=params,
headers={"Origin": BASE_URL, "Referer": f"{BASE_URL}/r/{self.room.name}"},
)
return self.get(BASE_REST_URL + call, **kw).json() | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start interpolation identifier string_content interpolation attribute attribute identifier identifier identifier string_end return_statement call attribute call attribute identifier identifier argument_list binary_operator identifier identifier dictionary_splat identifier identifier argument_list | Make a REST API call |
def addQuickElement(self, name, contents=None, attrs=None, escape=True, cdata=False):
if attrs is None:
attrs = {}
self.startElement(name, attrs)
if contents is not None:
self.characters(contents, escape=escape, cdata=cdata)
self.endElement(name) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier true default_parameter identifier false block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Convenience method for adding an element with no children. |
def __generate_tree(self, top, src, resources, models, ctrls, views, utils):
res = self.__mkdir(top)
for fn in (src, models, ctrls, views, utils): res = self.__mkpkg(fn) or res
res = self.__mkdir(resources) or res
res = self.__mkdir(os.path.join(resources, "ui", "builder")) or res
res = self.__mkdir(os.path.join(resources, "ui", "styles")) or res
res = self.__mkdir(os.path.join(resources, "external")) or res
return res | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier tuple identifier identifier identifier identifier identifier block expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end identifier return_statement identifier | Creates directories and packages |
def clean(self, value):
if value:
value = value.replace('-', '').replace(' ', '')
self.card_type = verify_credit_card(value)
if self.card_type is None:
raise forms.ValidationError("Invalid credit card number.")
return value | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment attribute identifier identifier call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Raises a ValidationError if the card is not valid and stashes card type. |
def install_hook(path):
git = op.join(path, '.git', 'hooks')
hg = op.join(path, '.hg')
if op.exists(git):
install_git(git)
LOGGER.warn('Git hook has been installed.')
elif op.exists(hg):
install_hg(hg)
LOGGER.warn('Mercurial hook has been installed.')
else:
LOGGER.error('VCS has not found. Check your path.')
sys.exit(1) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list identifier block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end elif_clause call attribute identifier identifier argument_list identifier block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer | Auto definition of SCM and hook installation. |
def _restore_vxlan_entries(self, switch_ip, vlans):
count = 1
conf_str = ''
vnsegment_sent = 0
path_str, conf_str = self.driver.start_create_vlan()
while vnsegment_sent < const.CREATE_VLAN_BATCH and vlans:
vlan_id, vni = vlans.pop(0)
conf_str = self.driver.get_create_vlan(
switch_ip, vlan_id, vni, conf_str)
if (count == const.CREATE_VLAN_SEND_SIZE):
conf_str = self.driver.end_create_vlan(conf_str)
self.driver.send_edit_string(switch_ip, path_str, conf_str)
vnsegment_sent += count
conf_str = ''
count = 1
else:
count += 1
if conf_str:
vnsegment_sent += count
conf_str = self.driver.end_create_vlan(conf_str)
self.driver.send_edit_string(switch_ip, path_str, conf_str)
conf_str = ''
LOG.debug("Switch %s VLAN vn-segment replay summary: %d",
switch_ip, vnsegment_sent) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier string string_start string_end expression_statement assignment identifier integer expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list while_statement boolean_operator comparison_operator identifier attribute identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier if_statement parenthesized_expression comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier expression_statement augmented_assignment identifier identifier expression_statement assignment identifier string string_start string_end expression_statement assignment identifier integer else_clause block expression_statement augmented_assignment identifier integer if_statement identifier block expression_statement augmented_assignment identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier string string_start string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier | Restore vxlan entries on a Nexus switch. |
def all_terminated():
instances_found = False
for i in all_instances():
instances_found = True
if i.state not in (remote_dispatcher.STATE_TERMINATED,
remote_dispatcher.STATE_DEAD):
return False
return instances_found | module function_definition identifier parameters block expression_statement assignment identifier false for_statement identifier call identifier argument_list block expression_statement assignment identifier true if_statement comparison_operator attribute identifier identifier tuple attribute identifier identifier attribute identifier identifier block return_statement false return_statement identifier | For each remote shell determine if its terminated |
def handle_battery_level(msg):
if not msg.gateway.is_sensor(msg.node_id):
return None
msg.gateway.sensors[msg.node_id].battery_level = msg.payload
msg.gateway.alert(msg)
return None | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block return_statement none expression_statement assignment attribute subscript attribute attribute identifier identifier identifier attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement none | Process an internal battery level message. |
def _exit_handling(self):
def close_asyncio_loop():
loop = None
try:
loop = asyncio.get_event_loop()
except AttributeError:
pass
if loop is not None:
loop.close()
atexit.register(close_asyncio_loop) | module function_definition identifier parameters identifier block function_definition identifier parameters block expression_statement assignment identifier none try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block pass_statement if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier | Makes sure the asyncio loop is closed. |
def run(self):
while True:
if self._dismissed.isSet():
break
request = self._requests_queue.get()
if self._dismissed.isSet():
self._requests_queue.put(request)
break
try:
result = request.callable(*request.args, **request.kwds)
if request.callback:
request.callback(request, result)
del result
self._requests_queue.task_done()
except:
request.exception = True
if request.exc_callback:
request.exc_callback(request)
self._requests_queue.task_done()
finally:
request.self_destruct() | module function_definition identifier parameters identifier block while_statement true block if_statement call attribute attribute identifier identifier identifier argument_list block break_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list identifier break_statement try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list list_splat attribute identifier identifier dictionary_splat attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier delete_statement identifier expression_statement call attribute attribute identifier identifier identifier argument_list except_clause block expression_statement assignment attribute identifier identifier true if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list finally_clause block expression_statement call attribute identifier identifier argument_list | Repeatedly process the job queue until told to exit. |
def _memorize(func):
def _wrapper(self, *args, **kwargs):
if self.use_cache:
cache = load_cache(self.cache_filename)
original_key = ':'.join([
self.__class__.__name__,
func.__name__,
'_'.join([str(a) for a in args]),
'_'.join([str(w) for w in kwargs.values()])])
cache_key = hashlib.md5(original_key.encode('utf-8')).hexdigest()
cached_val = cache.get(cache_key)
if cached_val:
return cached_val
val = func(self, *args, **kwargs)
if self.use_cache:
cache.set(cache_key, val)
return val
return _wrapper | module function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list attribute attribute identifier identifier identifier attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block return_statement identifier expression_statement assignment identifier call identifier argument_list identifier list_splat identifier dictionary_splat identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier return_statement identifier return_statement identifier | Decorator to cache the given function's output. |
def clean_security_hash(self):
security_hash_dict = {
'content_type': self.data.get("content_type", ""),
'object_pk': self.data.get("object_pk", ""),
'timestamp': self.data.get("timestamp", ""),
}
expected_hash = self.generate_security_hash(**security_hash_dict)
actual_hash = self.cleaned_data["security_hash"]
if not constant_time_compare(expected_hash, actual_hash):
raise forms.ValidationError("Security hash check failed.")
return actual_hash | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement not_operator call identifier argument_list identifier identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Check the security hash. |
def put(self):
try:
self.cloudwatch.put_metric_data(
Namespace=self.namespace,
MetricData=[{
'MetricName': self.name,
'Value': self.value,
'Timestamp': self.timestamp
}]
)
except Exception:
logging.exception("Error pushing {0} to CloudWatch.".format(str(self))) | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier list dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier | Push the info represented by this ``Metric`` to CloudWatch. |
def _validate_rfilter(self, rfilter, letter="d"):
if letter == "d":
pexdoc.exh.addai(
"dfilter",
(
(not self._has_header)
and any([not isinstance(item, int) for item in rfilter.keys()])
),
)
else:
pexdoc.exh.addai(
"rfilter",
(
(not self._has_header)
and any([not isinstance(item, int) for item in rfilter.keys()])
),
)
for key in rfilter:
self._in_header(key)
rfilter[key] = (
[rfilter[key]] if isinstance(rfilter[key], str) else rfilter[key]
) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end parenthesized_expression boolean_operator parenthesized_expression not_operator attribute identifier identifier call identifier argument_list list_comprehension not_operator call identifier argument_list identifier identifier for_in_clause identifier call attribute identifier identifier argument_list else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end parenthesized_expression boolean_operator parenthesized_expression not_operator attribute identifier identifier call identifier argument_list list_comprehension not_operator call identifier argument_list identifier identifier for_in_clause identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier parenthesized_expression conditional_expression list subscript identifier identifier call identifier argument_list subscript identifier identifier identifier subscript identifier identifier | Validate that all columns in filter are in header. |
async def delete(self, *args, **kwargs):
pk = self.pk_type(kwargs['pk'])
result = await self._meta.object_class.delete_entries(db=self.db, query={self.pk: pk})
if result.acknowledged:
if result.deleted_count == 0:
raise NotFound()
else:
raise BadRequest('Failed to delete object') | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier await call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier dictionary pair attribute identifier identifier identifier if_statement attribute identifier identifier block if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Corresponds to DELETE request with a resource identifier, deleting a single document from the database |
def template_sunmoon(self, **kwargs):
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))
kwargs_copy['component'] = kwargs.get(
'component', self.component(**kwargs))
self._replace_none(kwargs_copy)
localpath = NameFactory.templatesunmoon_format.format(**kwargs_copy)
if kwargs.get('fullpath', False):
return self.fullpath(localpath=localpath)
return localpath | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end false block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement identifier | return the file name for sun or moon template files |
def update_available(self, name):
quota = self.usages.get(name, {}).get('quota', float('inf'))
available = quota - self.usages[name]['used']
if available < 0:
available = 0
self.usages[name]['available'] = available | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier dictionary identifier argument_list string string_start string_content string_end call identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator identifier subscript subscript attribute identifier identifier identifier string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement assignment identifier integer expression_statement assignment subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier | Updates the "available" metric for the given quota. |
def _enforce_bounds(self, x):
assert len(x) == len(self.bounds)
x_enforced = []
for x_i, (lb, ub) in zip(x, self.bounds):
if x_i < lb:
if x_i > lb - (ub-lb)/1e10:
x_enforced.append(lb)
else:
x_enforced.append(x_i)
elif x_i > ub:
if x_i < ub + (ub-lb)/1e10:
x_enforced.append(ub)
else:
x_enforced.append(x_i)
else:
x_enforced.append(x_i)
return np.array(x_enforced) | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator call identifier argument_list identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier tuple_pattern identifier identifier call identifier argument_list identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block if_statement comparison_operator identifier binary_operator identifier binary_operator parenthesized_expression binary_operator identifier identifier float block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block if_statement comparison_operator identifier binary_operator identifier binary_operator parenthesized_expression binary_operator identifier identifier float block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Enforce the bounds on x if only infinitesimal violations occurs |
def inflect(self):
if self._inflect is None:
import inflect
self._inflect = inflect.engine()
return self._inflect | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block import_statement dotted_name identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list return_statement attribute identifier identifier | Return instance of inflect. |
def for_entity(obj, check_commentable=False):
if check_commentable and not is_commentable(obj):
return []
return getattr(obj, ATTRIBUTE) | module function_definition identifier parameters identifier default_parameter identifier false block if_statement boolean_operator identifier not_operator call identifier argument_list identifier block return_statement list return_statement call identifier argument_list identifier identifier | Return comments on an entity. |
def a_connection_timeout(ctx):
prompt = ctx.ctrl.after
ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
ctx.device.connected = False
ctx.finished = True
raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment attribute attribute identifier identifier identifier false expression_statement assignment attribute identifier identifier true raise_statement call identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier | Check the prompt and update the drivers. |
def windows_process_priority_format(instance):
class_suffix_re = re.compile(r'.+_CLASS$')
for key, obj in instance['objects'].items():
if 'type' in obj and obj['type'] == 'process':
try:
priority = obj['extensions']['windows-process-ext']['priority']
except KeyError:
continue
if not class_suffix_re.match(priority):
yield JSONError("The 'priority' property of object '%s' should"
" end in '_CLASS'." % key, instance['id'],
'windows-process-priority-format') | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block try_statement block expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end except_clause identifier block continue_statement if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement yield call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier subscript identifier string string_start string_content string_end string string_start string_content string_end | Ensure the 'priority' property of windows-process-ext ends in '_CLASS'. |
def fetch(self):
if self._file_path is not None:
return self._file_path
temp_path = self.context.work_path
if self._content_hash is not None:
self._file_path = storage.load_file(self._content_hash,
temp_path=temp_path)
return self._file_path
if self.response is not None:
self._file_path = random_filename(temp_path)
content_hash = sha1()
with open(self._file_path, 'wb') as fh:
for chunk in self.response.iter_content(chunk_size=8192):
content_hash.update(chunk)
fh.write(chunk)
self._remove_file = True
chash = content_hash.hexdigest()
self._content_hash = storage.archive_file(self._file_path,
content_hash=chash)
if self.http.cache and self.ok:
self.context.set_tag(self.request_id, self.serialize())
self.retrieved_at = datetime.utcnow().isoformat()
return self._file_path | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement attribute identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier return_statement attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier true expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier if_statement boolean_operator attribute attribute identifier identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list return_statement attribute identifier identifier | Lazily trigger download of the data when requested. |
def _add_route(self, method, path, middleware=None):
if middleware is not None:
self.add(method, path, middleware)
return self
else:
return lambda func: (
self.add(method, path, func),
func
)[1] | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier identifier identifier return_statement identifier else_clause block return_statement lambda lambda_parameters identifier subscript tuple call attribute identifier identifier argument_list identifier identifier identifier identifier integer | The implementation of adding a route |
def find_program (program):
if os.name == 'nt':
path = os.environ['PATH']
path = append_to_path(path, get_nt_7z_dir())
path = append_to_path(path, get_nt_mac_dir())
path = append_to_path(path, get_nt_winrar_dir())
else:
path = None
return which(program, path=path) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list else_clause block expression_statement assignment identifier none return_statement call identifier argument_list identifier keyword_argument identifier identifier | Look for program in environment PATH variable. |
def read_questions(self):
format = '!HH'
length = struct.calcsize(format)
for i in range(0, self.num_questions):
name = self.read_name()
info = struct.unpack(format,
self.data[self.offset:self.offset + length])
self.offset += length
question = DNSQuestion(name, info[0], info[1])
self.questions.append(question) | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list integer attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript attribute identifier identifier slice attribute identifier identifier binary_operator attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier subscript identifier integer subscript identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Reads questions section of packet |
def _irc_upper(self, in_string):
conv_string = self._translate(in_string)
if self._upper_trans is not None:
conv_string = in_string.translate(self._upper_trans)
return str.upper(conv_string) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier | Convert us to our upper-case equivalent, given our std. |
def init_pool(self):
if self.pool is None:
if self.nproc > 1:
self.pool = mp.Pool(processes=self.nproc)
else:
self.pool = None
else:
print('pool already initialized?') | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier else_clause block expression_statement assignment attribute identifier identifier none else_clause block expression_statement call identifier argument_list string string_start string_content string_end | Initialize multiprocessing pool if necessary. |
def traverse(self, id_=None):
if id_ is None:
id_ = self.group
nodes = r_client.smembers(_children_key(id_))
while nodes:
current_id = nodes.pop()
details = r_client.get(current_id)
if details is None:
r_client.srem(_children_key(id_), current_id)
continue
details = self._decode(details)
if details['type'] == 'group':
children = r_client.smembers(_children_key(details['id']))
if children is not None:
nodes.update(children)
yield details | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier while_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier expression_statement yield identifier | Traverse groups and yield info dicts for jobs |
def reset(self):
try:
os.remove(self._user_config_file)
except FileNotFoundError:
pass
for section_name in self.sections():
self.remove_section(section_name)
self.read_defaults() | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list attribute identifier identifier except_clause identifier block pass_statement for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Restore the default configuration and remove the user's config file. |
def open_last_closed(self):
editorstack = self.get_current_editorstack()
last_closed_files = editorstack.get_last_closed_files()
if (len(last_closed_files) > 0):
file_to_open = last_closed_files[0]
last_closed_files.remove(file_to_open)
editorstack.set_last_closed_files(last_closed_files)
self.load(file_to_open) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement parenthesized_expression comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier integer expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Reopens the last closed tab. |
def accounts(self):
response = self.graph.get('%s/accounts' % self.id)
accounts = []
for item in response['data']:
account = Structure(
page = Page(
id = item['id'],
name = item['name'],
category = item['category']
),
access_token = item['access_token'],
permissions = item['perms']
)
accounts.append(account)
return accounts | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier list for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list keyword_argument identifier call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | A list of structures describing apps and pages owned by this user. |
def print_active_threads (self):
debug = log.is_debug(LOG_CHECK)
if debug:
first = True
for name in self.get_check_threads():
if first:
log.info(LOG_CHECK, _("These URLs are still active:"))
first = False
log.info(LOG_CHECK, name[12:])
args = dict(
num=len([x for x in self.threads if x.getName().startswith("CheckThread-")]),
timeout=strformat.strduration_long(self.config["aborttimeout"]),
)
log.info(LOG_CHECK, _("%(num)d URLs are still active. After a timeout of %(timeout)s the active URLs will stop.") % args) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier true for_statement identifier call attribute identifier identifier argument_list block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier false expression_statement call attribute identifier identifier argument_list identifier subscript identifier slice integer expression_statement assignment identifier call identifier argument_list keyword_argument identifier call identifier argument_list list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier binary_operator call identifier argument_list string string_start string_content string_end identifier | Log all currently active threads. |
def emit_answer_event(sender, instance, **kwargs):
if not issubclass(sender, Answer) or not kwargs['created']:
return
logger = get_events_logger()
logger.emit('answer', {
"user_id": instance.user_id,
"is_correct": instance.item_asked_id == instance.item_answered_id,
"context_id": [instance.context_id] if instance.context_id else [],
"item_id": instance.item_id,
"response_time_ms": instance.response_time,
"params": {
"session_id": instance.session_id,
"guess": instance.guess,
"practice_set_id": instance.practice_set_id,
"config_id": instance.config_id,
}}
) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block if_statement boolean_operator not_operator call identifier argument_list identifier identifier not_operator subscript identifier string string_start string_content string_end block return_statement expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end comparison_operator attribute identifier identifier attribute identifier identifier pair string string_start string_content string_end conditional_expression list attribute identifier identifier attribute identifier identifier list pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier | Save answer event to log file. |
def group_by_types(self):
for t in self.types_of_specie:
for site in self:
if site.specie == t:
yield site | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement yield identifier | Iterate over species grouped by type |
def _filter_image(self, url):
"The param is the image URL, which is returned if it passes all the filters."
return reduce(lambda f, g: f and g(f),
[
filters.AdblockURLFilter()(url),
filters.NoImageFilter(),
filters.SizeImageFilter(),
filters.MonoImageFilter(),
filters.FormatImageFilter(),
]) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end return_statement call identifier argument_list lambda lambda_parameters identifier identifier boolean_operator identifier call identifier argument_list identifier list call call attribute identifier identifier argument_list argument_list identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list | The param is the image URL, which is returned if it passes all the filters. |
def _monomer_pattern_label(mp):
site_strs = []
for site, cond in mp.site_conditions.items():
if isinstance(cond, tuple) or isinstance(cond, list):
assert len(cond) == 2
if cond[1] == WILD:
site_str = '%s_%s' % (site, cond[0])
else:
site_str = '%s_%s%s' % (site, cond[0], cond[1])
elif isinstance(cond, numbers.Real):
continue
else:
site_str = '%s_%s' % (site, cond)
site_strs.append(site_str)
return '%s_%s' % (mp.monomer.name, '_'.join(site_strs)) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block assert_statement comparison_operator call identifier argument_list identifier integer if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier subscript identifier integer else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier subscript identifier integer subscript identifier integer elif_clause call identifier argument_list identifier attribute identifier identifier block continue_statement else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement binary_operator string string_start string_content string_end tuple attribute attribute identifier identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier | Return a string label for a MonomerPattern. |
def barrier(events, sid, kind='neighbour'):
events[sid].set()
if kind=='neighbour':
if sid > 0:
logging.debug("{0} is waiting for {1}".format(sid, sid - 1))
events[sid - 1].wait()
if sid < len(bkg_events) - 1:
logging.debug("{0} is waiting for {1}".format(sid, sid + 1))
events[sid + 1].wait()
else:
[e.wait() for e in events]
return | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement call attribute subscript identifier identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier binary_operator identifier integer expression_statement call attribute subscript identifier binary_operator identifier integer identifier argument_list if_statement comparison_operator identifier binary_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier binary_operator identifier integer expression_statement call attribute subscript identifier binary_operator identifier integer identifier argument_list else_clause block expression_statement list_comprehension call attribute identifier identifier argument_list for_in_clause identifier identifier return_statement | act as a multiprocessing barrier |
def limit_(self, r=5):
try:
return self._duplicate_(self.df[:r])
except Exception as e:
self.err(e, "Can not limit data") | module function_definition identifier parameters identifier default_parameter identifier integer block try_statement block return_statement call attribute identifier identifier argument_list subscript attribute identifier identifier slice identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end | Returns a DataSwim instance with limited selection |
def _scale_tile(self, value, width, height):
try:
return self._scale_cache[value, width, height]
except KeyError:
tile = pygame.transform.smoothscale(self.tiles[value], (width, height))
self._scale_cache[value, width, height] = tile
return tile | module function_definition identifier parameters identifier identifier identifier identifier block try_statement block return_statement subscript attribute identifier identifier identifier identifier identifier except_clause identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier identifier tuple identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier identifier identifier return_statement identifier | Return the prescaled tile if already exists, otherwise scale and store it. |
def _lookupIterator(self, val):
if val is None:
return lambda el, *args: el
return val if _.isCallable(val) else lambda obj, *args: obj[val] | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement lambda lambda_parameters identifier list_splat_pattern identifier identifier return_statement conditional_expression identifier call attribute identifier identifier argument_list identifier lambda lambda_parameters identifier list_splat_pattern identifier subscript identifier identifier | An internal function to generate lookup iterators. |
def add_comment(self, post=None, name=None, email=None, pub_date=None,
website=None, body=None):
if post is None:
if not self.posts:
raise CommandError("Cannot add comments without posts")
post = self.posts[-1]
post["comments"].append({
"user_name": name,
"user_email": email,
"submit_date": pub_date,
"user_url": website,
"comment": body,
}) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier unary_operator integer expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Adds a comment to the post provided. |
async def promote(self, name, user, info=None):
task = asyncio.current_task()
synt = getattr(task, '_syn_task', None)
if synt is not None:
if synt.root is None:
return synt
synt.root.kids.pop(synt.iden)
synt.root = None
return synt
return await s_task.Task.anit(self, task, name, user, info=info) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement comparison_operator identifier none block if_statement comparison_operator attribute identifier identifier none block return_statement identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier none return_statement identifier return_statement await call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier keyword_argument identifier identifier | Promote the currently running task. |
def create_symlinks(d):
data = loadJson(d)
outDir = prepare_output(d)
unseen = data["pages"].keys()
while len(unseen) > 0:
latest = work = unseen[0]
while work in unseen:
unseen.remove(work)
if "prev" in data["pages"][work]:
work = data["pages"][work]["prev"]
print("Latest page: %s" % (latest))
order = []
work = latest
while work in data["pages"]:
order.extend(data["pages"][work]["images"].values())
if "prev" in data["pages"][work]:
work = data["pages"][work]["prev"]
else:
work = None
order.reverse()
for i, img in enumerate(order):
os.symlink(os.path.join('..', img), os.path.join(outDir, '%05i_%s' % (i, img))) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list while_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier assignment identifier subscript identifier integer while_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end subscript subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier expression_statement assignment identifier list expression_statement assignment identifier identifier while_statement comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute subscript subscript subscript identifier string string_start string_content string_end identifier string string_start string_content string_end identifier argument_list if_statement comparison_operator string string_start string_content string_end subscript subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end identifier string string_start string_content string_end else_clause block expression_statement assignment identifier none expression_statement call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier call attribute attribute identifier identifier identifier argument_list identifier binary_operator string string_start string_content string_end tuple identifier identifier | Create new symbolic links in output directory. |
def remove(self, i, change_time=True):
if i < 0 or i >= self.count():
print("Invalid fence point number %u" % i)
self.points.pop(i)
if i == 1:
self.points[self.count()-1].lat = self.points[1].lat
self.points[self.count()-1].lng = self.points[1].lng
if i == self.count():
self.points[1].lat = self.points[self.count()-1].lat
self.points[1].lng = self.points[self.count()-1].lng
if change_time:
self.last_change = time.time() | module function_definition identifier parameters identifier identifier default_parameter identifier true block if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement assignment attribute subscript attribute identifier identifier binary_operator call attribute identifier identifier argument_list integer identifier attribute subscript attribute identifier identifier integer identifier expression_statement assignment attribute subscript attribute identifier identifier binary_operator call attribute identifier identifier argument_list integer identifier attribute subscript attribute identifier identifier integer identifier if_statement comparison_operator identifier call attribute identifier identifier argument_list block expression_statement assignment attribute subscript attribute identifier identifier integer identifier attribute subscript attribute identifier identifier binary_operator call attribute identifier identifier argument_list integer identifier expression_statement assignment attribute subscript attribute identifier identifier integer identifier attribute subscript attribute identifier identifier binary_operator call attribute identifier identifier argument_list integer identifier if_statement identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list | remove a fence point |
def call_env_check_consistency(cls, kb_app, builder: StandaloneHTMLBuilder,
sphinx_env: BuildEnvironment):
for callback in EventAction.get_callbacks(kb_app,
SphinxEvent.ECC):
callback(kb_app, builder, sphinx_env) | module function_definition identifier parameters identifier identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block for_statement identifier call attribute identifier identifier argument_list identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier identifier | On env-check-consistency, do callbacks |
def sign_request(self, signature_method, consumer, token):
if not self.is_form_encoded:
if not self.body:
self.body = ''
self['oauth_body_hash'] = base64.b64encode(sha1(to_utf8(self.body)).digest())
if 'oauth_consumer_key' not in self:
self['oauth_consumer_key'] = consumer.key
if token and 'oauth_token' not in self:
self['oauth_token'] = token.key
self['oauth_signature_method'] = signature_method.name
self['oauth_signature'] = signature_method.sign(self, consumer, token) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement not_operator attribute identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier string string_start string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list call attribute call identifier argument_list call identifier argument_list attribute identifier identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement boolean_operator identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier identifier identifier | Set the signature parameter to the result of sign. |
def run(self):
with utils.ChangeDir(self.dirname):
sys.path.insert(0, self.dirname)
sys.argv[1:] = self.args
runpy.run_module(self.not_suffixed(self.filename),
run_name='__main__',
alter_sys=True) | module function_definition identifier parameters identifier block with_statement with_clause with_item call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer attribute identifier identifier expression_statement assignment subscript attribute identifier identifier slice integer attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier true | Executes the code of the specified module. |
def _normalize(self, addr):
normalize = None
if isinstance(addr, Address):
normalize = addr.addr
self._is_x10 = addr.is_x10
elif isinstance(addr, bytearray):
normalize = binascii.unhexlify(binascii.hexlify(addr).decode())
elif isinstance(addr, bytes):
normalize = addr
elif isinstance(addr, str):
addr = addr.replace('.', '')
addr = addr[0:6]
if addr[0:3].lower() == 'x10':
x10_addr = Address.x10(addr[3:4], int(addr[4:6]))
normalize = x10_addr.addr
self._is_x10 = True
else:
normalize = binascii.unhexlify(addr.lower())
elif addr is None:
normalize = None
else:
_LOGGER.warning('Address class init with unknown type %s: %r',
type(addr), addr)
return normalize | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute call attribute identifier identifier argument_list identifier identifier argument_list elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier subscript identifier slice integer integer if_statement comparison_operator call attribute subscript identifier slice integer integer identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier slice integer integer call identifier argument_list subscript identifier slice integer integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier true else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list elif_clause comparison_operator identifier none block expression_statement assignment identifier none else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier identifier return_statement identifier | Take any format of address and turn it into a hex string. |
def handle_login_failure(self, provider, reason):
logger.error('Authenication Failure: {0}'.format(reason))
messages.error(self.request, 'Authenication Failed. Please try again')
return redirect(self.get_error_redirect(provider, reason)) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end return_statement call identifier argument_list call attribute identifier identifier argument_list identifier identifier | Message user and redirect on error. |
def var(self):
return self._constructor(self.values.var(axis=0, keepdims=True)) | module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier true | Compute the variance across images. |
def unicodestr(s, encoding='utf-8', fallback='iso-8859-1'):
if isinstance(s, unicode):
return s
try:
return s.decode(encoding)
except UnicodeError:
return s.decode(fallback) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block return_statement identifier try_statement block return_statement call attribute identifier identifier argument_list identifier except_clause identifier block return_statement call attribute identifier identifier argument_list identifier | Convert a string to unicode if it isn't already. |
def process_satellites(self, helper, sess):
good_satellites = helper.get_snmp_value(sess, helper, self.oids['oid_gps_satellites_good'])
helper.add_summary("Good satellites: {}".format(good_satellites))
helper.add_metric(label='satellites', value=good_satellites) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier | check and show the good satellites |
def make_template(name, func, *args, **kwargs):
if args or kwargs:
func = functools.partial(func, *args, **kwargs)
return Template(name, func) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement boolean_operator identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement call identifier argument_list identifier identifier | Given an arbitrary function, wrap it so that it does parameter sharing. |
def _search_tree(self, name):
tpl1 = "{sep}{name}{sep}".format(sep=self._node_separator, name=name)
tpl2 = "{sep}{name}".format(sep=self._node_separator, name=name)
tpl3 = "{name}{sep}".format(sep=self._node_separator, name=name)
return sorted(
[
node
for node in self._db
if (tpl1 in node)
or node.endswith(tpl2)
or node.startswith(tpl3)
or (name == node)
]
) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier return_statement call identifier argument_list list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause boolean_operator boolean_operator boolean_operator parenthesized_expression comparison_operator identifier identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier parenthesized_expression comparison_operator identifier identifier | Search_tree for nodes that contain a specific hierarchy name. |
def position(self, message):
if not message.line_number:
message.line_number = 1
for patched_file in self.patch:
target = patched_file.target_file.lstrip("b/")
if target == message.path:
offset = 1
for hunk in patched_file:
for position, hunk_line in enumerate(hunk):
if hunk_line.target_line_no == message.line_number:
if not hunk_line.is_added:
return
return position + offset
offset += len(hunk) + 1 | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier integer for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier integer for_statement identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block if_statement not_operator attribute identifier identifier block return_statement return_statement binary_operator identifier identifier expression_statement augmented_assignment identifier binary_operator call identifier argument_list identifier integer | Calculate position within the PR, which is not the line number |
async def create_scene_member(self, shade_position, scene_id, shade_id):
data = {
ATTR_SCENE_MEMBER: {
ATTR_POSITION_DATA: shade_position,
ATTR_SCENE_ID: scene_id,
ATTR_SHADE_ID: shade_id,
}
}
return await self.request.post(self._base_path, data=data) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier dictionary pair identifier dictionary pair identifier identifier pair identifier identifier pair identifier identifier return_statement await call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier | Adds a shade to an existing scene |
def split_low_tag(tag):
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun} | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Take a low tag and split it back into the low dict that it came from |
def entry_index(request, limit=0, template='djournal/entry_index.html'):
entries = Entry.public.all()
if limit > 0:
entries = entries[:limit]
context = {
'entries': entries,
}
return render_to_response(
template,
context,
context_instance=RequestContext(request),
) | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier integer block expression_statement assignment identifier subscript identifier slice identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier return_statement call identifier argument_list identifier identifier keyword_argument identifier call identifier argument_list identifier | Returns a reponse of a fixed number of entries; all of them, by default. |
def convert_group(tokens):
tok = tokens.asList()
dic = dict(tok)
if not (len(dic) == len(tok)):
raise ParseFatalException("Names in group must be unique: %s" % tokens)
return ConfGroup(dic) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator parenthesized_expression comparison_operator call identifier argument_list identifier call identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement call identifier argument_list identifier | Converts parseResult from to ConfGroup type. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.