code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _match_value_filter(self, p, value):
return self._VALUE_FILTER_MAP[p[0]](value[p[1]], p[2]) | module function_definition identifier parameters identifier identifier identifier block return_statement call subscript attribute identifier identifier subscript identifier integer argument_list subscript identifier subscript identifier integer subscript identifier integer | Returns True of False if value in the pattern p matches the filter. |
def infos(cls, fqdn):
if isinstance(fqdn, (list, tuple)):
ids = []
for fqd_ in fqdn:
ids.extend(cls.infos(fqd_))
return ids
ids = cls.usable_id(fqdn)
if not ids:
return []
if not isinstance(ids, (list, tuple)):
ids = [ids]
return [cls.info(id_) for id_ in ids] | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block return_statement list if_statement not_operator call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier list identifier return_statement list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier | Display information about hosted certificates for a fqdn. |
def clean():
shutil.rmtree(BUILD_PATH, ignore_errors=True)
shutil.rmtree(os.path.join(SOURCE_PATH, 'reference', 'api'),
ignore_errors=True) | module function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement 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 keyword_argument identifier true | Clean documentation generated files. |
def parse_time_arg(s):
try:
return time.strptime(s, "%Y-%m-%d %H:%M")
except ValueError as e:
raise argparse.ArgumentTypeError(e) | module function_definition identifier parameters identifier block try_statement block return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block raise_statement call attribute identifier identifier argument_list identifier | Parse a time stamp in the "year-month-day hour-minute" format. |
def words_amount_needed(entropybits: Union[int, float],
entropy_w: Union[int, float],
entropy_n: Union[int, float],
amount_n: int) -> int:
if not isinstance(entropybits, (int, float)):
raise TypeError('entropybits can only be int or float')
if not isinstance(entropy_w, (int, float)):
raise TypeError('entropy_w can only be int or float')
if not isinstance(entropy_n, (int, float)):
raise TypeError('entropy_n can only be int or float')
if not isinstance(amount_n, int):
raise TypeError('amount_n can only be int')
if entropybits < 0:
raise ValueError('entropybits should be greater than 0')
if entropy_w <= 0:
raise ValueError('entropy_w should be greater than 0')
if entropy_n < 0:
raise ValueError('entropy_n should be greater than 0')
if amount_n < 0:
raise ValueError('amount_n should be greater than 0')
amount_w = (entropybits - entropy_n * amount_n) / entropy_w
if amount_w > -1.0:
return ceil(fabs(amount_w))
return 0 | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type identifier type identifier block if_statement not_operator call identifier argument_list identifier tuple identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator call identifier argument_list identifier tuple identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator call identifier argument_list identifier tuple identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier binary_operator identifier identifier identifier if_statement comparison_operator identifier unary_operator float block return_statement call identifier argument_list call identifier argument_list identifier return_statement integer | Calculate words needed for a passphrase based on entropy. |
def _colorize_single_line(line, regexp, color_def):
match = regexp.match(line)
groupdict = match.groupdict()
groups = match.groups()
if not groupdict:
color = color_def[0]
dark = color_def[1]
cprint("%s\n" % line, color, fg_dark=dark)
else:
rev_groups = {v: k for k, v in groupdict.items()}
for part in groups:
if part in rev_groups and rev_groups[part] in color_def:
group_name = rev_groups[part]
cprint(
part,
color_def[group_name][0],
fg_dark=color_def[group_name][1],
)
else:
cprint(part)
cprint("\n") | module function_definition identifier parameters identifier identifier 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 call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement call identifier argument_list binary_operator string string_start string_content escape_sequence string_end identifier identifier keyword_argument identifier identifier else_clause block expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list for_statement identifier identifier block if_statement boolean_operator comparison_operator identifier identifier comparison_operator subscript identifier identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement call identifier argument_list identifier subscript subscript identifier identifier integer keyword_argument identifier subscript subscript identifier identifier integer else_clause block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content escape_sequence string_end | Print single line to console with ability to colorize parts of it. |
def retry_after(cls, response, default=5, _now=time.time):
val = response.headers.getRawHeaders(b'retry-after', [default])[0]
try:
return int(val)
except ValueError:
return http.stringToDatetime(val) - _now() | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier attribute identifier identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end list identifier integer try_statement block return_statement call identifier argument_list identifier except_clause identifier block return_statement binary_operator call attribute identifier identifier argument_list identifier call identifier argument_list | Parse the Retry-After value from a response. |
def loads(astring):
try:
return pickle.loads(lzma.decompress(astring))
except lzma.LZMAError as e:
raise SerializerError(
'Cannot decompress object ("{}")'.format(str(e))
)
except pickle.UnpicklingError as e:
raise SerializerError(
'Cannot restore object ("{}")'.format(str(e))
) | module function_definition identifier parameters identifier block try_statement block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier | Decompress and deserialize string into a Python object via pickle. |
def stopping_criteria(self):
"Test whether the stopping criteria has been achieved."
if self.stopping_criteria_tl():
return True
if self.generations < np.inf:
inds = self.popsize * self.generations
flag = inds <= len(self.population.hist)
else:
flag = False
if flag:
return True
est = self.population.estopping
if self._tr_fraction < 1:
if est is not None and est.fitness_vs == 0:
return True
esr = self._early_stopping_rounds
if self._tr_fraction < 1 and esr is not None and est is not None:
position = self.population.estopping.position
if position < self.init_popsize:
position = self.init_popsize
return (len(self.population.hist) +
self._unfeasible_counter -
position) > esr
return flag | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement call attribute identifier identifier argument_list block return_statement true if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier comparison_operator identifier call identifier argument_list attribute attribute identifier identifier identifier else_clause block expression_statement assignment identifier false if_statement identifier block return_statement true expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier integer block if_statement boolean_operator comparison_operator identifier none comparison_operator attribute identifier identifier integer block return_statement true expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator boolean_operator comparison_operator attribute identifier identifier integer comparison_operator identifier none comparison_operator identifier none block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier return_statement comparison_operator parenthesized_expression binary_operator binary_operator call identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier identifier identifier return_statement identifier | Test whether the stopping criteria has been achieved. |
def where_stmt_handle(tokens):
internal_assert(len(tokens) == 2, "invalid where statement tokens", tokens)
base_stmt, assignment_stmts = tokens
stmts = list(assignment_stmts) + [base_stmt]
return "\n".join(stmts) + "\n" | module function_definition identifier parameters identifier block expression_statement call identifier argument_list comparison_operator call identifier argument_list identifier integer string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list identifier list identifier return_statement binary_operator call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier string string_start string_content escape_sequence string_end | Process a where statement. |
def write_config(self, outfile):
utils.write_yaml(self.config, outfile, default_flow_style=False) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier false | Write the configuration dictionary to an output file. |
def main():
while 1:
events = get_key()
if events:
for event in events:
print(event.ev_type, event.code, event.state) | module function_definition identifier parameters block while_statement integer block expression_statement assignment identifier call identifier argument_list if_statement identifier block for_statement identifier identifier block expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier | Just print out some event infomation when keys are pressed. |
def backtracking(a, L, bestsofar):
w, j = max(L.items())
while j != -1:
yield j
w, j = bestsofar[j] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list while_statement comparison_operator identifier unary_operator integer block expression_statement yield identifier expression_statement assignment pattern_list identifier identifier subscript identifier identifier | Start with the heaviest weight and emit index |
def delete(self):
for module in self.compute():
yield from module.instance().project_closing(self)
yield from self._close_and_clean(True)
for module in self.compute():
yield from module.instance().project_closed(self) | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement yield call attribute call attribute identifier identifier argument_list identifier argument_list identifier expression_statement yield call attribute identifier identifier argument_list true for_statement identifier call attribute identifier identifier argument_list block expression_statement yield call attribute call attribute identifier identifier argument_list identifier argument_list identifier | Removes project from disk |
def list_keys(self):
key_dirs = self._check_minions_directories()
ret = {}
for dir_ in key_dirs:
if dir_ is None:
continue
ret[os.path.basename(dir_)] = []
try:
for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(dir_)):
if not fn_.startswith('.'):
if os.path.isfile(os.path.join(dir_, fn_)):
ret[os.path.basename(dir_)].append(
salt.utils.stringutils.to_unicode(fn_)
)
except (OSError, IOError):
continue
return ret | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary for_statement identifier identifier block if_statement comparison_operator identifier none block continue_statement expression_statement assignment subscript identifier call attribute attribute identifier identifier identifier argument_list identifier list try_statement block for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block if_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier block expression_statement call attribute subscript identifier call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list identifier except_clause tuple identifier identifier block continue_statement return_statement identifier | Return a dict of managed keys and what the key status are |
def db(self):
if self._db is None:
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
from .tcex_redis import TcExRedis
self._db = TcExRedis(
self.tcex.default_args.tc_playbook_db_path,
self.tcex.default_args.tc_playbook_db_port,
self.tcex.default_args.tc_playbook_db_context,
)
elif self.tcex.default_args.tc_playbook_db_type == 'TCKeyValueAPI':
from .tcex_key_value import TcExKeyValue
self._db = TcExKeyValue(self.tcex)
else:
err = u'Invalid DB Type: ({})'.format(self.tcex.default_args.tc_playbook_db_type)
raise RuntimeError(err)
return self._db | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator attribute attribute attribute identifier identifier identifier identifier string string_start string_content string_end block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute attribute attribute identifier identifier identifier identifier attribute attribute attribute identifier identifier identifier identifier attribute attribute attribute identifier identifier identifier identifier elif_clause comparison_operator attribute attribute attribute identifier identifier identifier identifier string string_start string_content string_end block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute attribute attribute identifier identifier identifier identifier raise_statement call identifier argument_list identifier return_statement attribute identifier identifier | Return the correct KV store for this execution. |
def rlmf_tictactoe():
hparams = rlmf_original()
hparams.game = "tictactoe"
hparams.rl_env_name = "T2TEnv-TicTacToeEnv-v0"
hparams.eval_max_num_noops = 0
hparams.max_num_noops = 0
hparams.rl_should_derive_observation_space = False
hparams.policy_network = "feed_forward_categorical_policy"
hparams.base_algo_params = "ppo_ttt_params"
hparams.frame_stack_size = 1
return hparams | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier integer return_statement identifier | Base set of hparams for model-free PPO. |
def new_mountpoint(self, name):
url = posixpath.join(self.path, name)
r = self._jfs.post(url, extra_headers={'content-type': 'application/x-www-form-urlencoded'})
return r | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end return_statement identifier | Create a new mountpoint |
def map_over_glob(fn, path, pattern):
return [fn(x) for x in glob.glob(os.path.join(path, pattern))] | module function_definition identifier parameters identifier identifier identifier block return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier | map a function over a glob pattern, relative to a directory |
def _collection_function_inclusion_builder(funcs: Iterable[str]) -> NodePredicate:
funcs = set(funcs)
if not funcs:
raise ValueError('can not build function inclusion filter with empty list of functions')
def functions_inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:
return node.function in funcs
return functions_inclusion_filter | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block return_statement comparison_operator attribute identifier identifier identifier return_statement identifier | Build a function inclusion filter for a collection of functions. |
def wait(self):
"wait for a message, respecting timeout"
data=self.getcon().recv(256)
if not data: raise PubsubDisco
if self.reset:
self.reset=False
raise PubsubDisco
self.buf+=data
msg,self.buf=complete_message(self.buf)
return msg | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list integer if_statement not_operator identifier block raise_statement identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier false raise_statement identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement assignment pattern_list identifier attribute identifier identifier call identifier argument_list attribute identifier identifier return_statement identifier | wait for a message, respecting timeout |
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1')
tower_conv1_1 = slim.conv2d(tower_conv1_0, 160, [1, 7],
scope='Conv2d_0b_1x7')
tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [7, 1],
scope='Conv2d_0c_7x1')
mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2])
up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,
activation_fn=None, scope='Conv2d_1x1')
net += scale * up
if activation_fn:
net = activation_fn(net)
return net | module function_definition identifier parameters identifier default_parameter identifier float default_parameter identifier attribute attribute identifier identifier identifier default_parameter identifier none default_parameter identifier none block with_statement with_clause with_item call attribute identifier identifier argument_list identifier string string_start string_content string_end list identifier keyword_argument identifier identifier block with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer integer keyword_argument identifier string string_start string_content string_end with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer integer keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer list integer integer keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer list integer integer keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript call attribute identifier identifier argument_list integer integer keyword_argument identifier none keyword_argument identifier none keyword_argument identifier string string_start string_content string_end expression_statement augmented_assignment identifier binary_operator identifier identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Builds the 17x17 resnet block. |
def validate_port_or_colon_separated_port_range(port_range):
if port_range.count(':') > 1:
raise ValidationError(_("One colon allowed in port range"))
ports = port_range.split(':')
for port in ports:
validate_port_range(port) | module function_definition identifier parameters identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end integer block raise_statement call identifier argument_list call 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 for_statement identifier identifier block expression_statement call identifier argument_list identifier | Accepts a port number or a single-colon separated range. |
def iexpand(string, keep_escapes=False):
if isinstance(string, bytes):
is_bytes = True
string = string.decode('latin-1')
else:
is_bytes = False
if is_bytes:
return (entry.encode('latin-1') for entry in ExpandBrace(keep_escapes).expand(string))
else:
return (entry for entry in ExpandBrace(keep_escapes).expand(string)) | module function_definition identifier parameters identifier default_parameter identifier false block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier true expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier false if_statement identifier block return_statement generator_expression call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause identifier call attribute call identifier argument_list identifier identifier argument_list identifier else_clause block return_statement generator_expression identifier for_in_clause identifier call attribute call identifier argument_list identifier identifier argument_list identifier | Expand braces and return an iterator. |
def fenceloader(self):
if not self.target_system in self.fenceloader_by_sysid:
self.fenceloader_by_sysid[self.target_system] = mavwp.MAVFenceLoader()
return self.fenceloader_by_sysid[self.target_system] | module function_definition identifier parameters identifier block if_statement not_operator comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list return_statement subscript attribute identifier identifier attribute identifier identifier | fence loader by sysid |
def rle_encode(img:NPArrayMask)->str:
"Return run-length encoding string from `img`."
pixels = np.concatenate([[0], img.flatten() , [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(str(x) for x in runs) | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list list list integer call attribute identifier identifier argument_list list integer expression_statement assignment identifier binary_operator subscript call attribute identifier identifier argument_list comparison_operator subscript identifier slice integer subscript identifier slice unary_operator integer integer integer expression_statement augmented_assignment subscript identifier slice integer integer subscript identifier slice integer return_statement call attribute string string_start string_content string_end identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier | Return run-length encoding string from `img`. |
def print_all_dockerfiles(collector, **kwargs):
for name, image in collector.configuration["images"].items():
print("{0}".format(name))
print("-" * len(name))
kwargs["image"] = image
print_dockerfile(collector, **kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block for_statement pattern_list identifier identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call identifier argument_list identifier dictionary_splat identifier | Print all the dockerfiles |
def lam_at_index(self, lidx):
if self.path_ is None:
return self.lam * self.lam_scale_
return self.lam * self.lam_scale_ * self.path_[lidx] | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block return_statement binary_operator attribute identifier identifier attribute identifier identifier return_statement binary_operator binary_operator attribute identifier identifier attribute identifier identifier subscript attribute identifier identifier identifier | Compute the scaled lambda used at index lidx. |
def allLobbySlots(self):
if self.debug:
p = ["Lobby Configuration detail:"] + \
[" %s:%s%s"%(p, " "*(12-len(p.type)), p.name)]
if self.observers:
p += [" observers: %d"%self.observers]
print(os.linesep.join(p))
return (self.agents, self.computers, self.observers) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier binary_operator list string string_start string_content string_end line_continuation list binary_operator string string_start string_content string_end tuple identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator integer call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement augmented_assignment identifier list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier return_statement tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier | the current configuration of the lobby's players, defined before the match starts |
def check_hamster(self):
try:
todays_facts = self.storage._Storage__get_todays_facts()
self.check_user(todays_facts)
except Exception as e:
logger.error("Error while refreshing: %s" % e)
finally:
return True | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier finally_clause block return_statement true | refresh hamster every x secs - load today, check last activity etc. |
def submit_query_request(end_point, *args, **kwargs):
ev_limit = kwargs.pop('ev_limit', 10)
best_first = kwargs.pop('best_first', True)
tries = kwargs.pop('tries', 2)
query_str = '?' + '&'.join(['%s=%s' % (k, v) for k, v in kwargs.items()
if v is not None]
+ list(args))
return submit_statement_request('get', end_point, query_str,
ev_limit=ev_limit, best_first=best_first,
tries=tries) | 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 string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end true expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list binary_operator list_comprehension binary_operator string string_start string_content string_end tuple identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier none call identifier argument_list identifier return_statement call identifier argument_list string string_start string_content string_end identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Low level function to format the query string. |
def tooltip_query(self, widget, x, y, keyboard_mode, tooltip):
tooltip.set_text(subprocess.getoutput("acpi"))
return True | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end return_statement true | Set tooltip which appears when you hover mouse curson onto icon in system panel. |
def reversed(self):
return Arc(self.end, self.radius, self.rotation, self.large_arc,
not self.sweep, self.start) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier not_operator attribute identifier identifier attribute identifier identifier | returns a copy of the Arc object with its orientation reversed. |
def drive(self):
if self.is_drive:
return self
cleartext = self.luks_cleartext_slave
if cleartext:
return cleartext.drive
if self.is_block:
return self._daemon[self._P.Block.Drive]
return None | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement identifier expression_statement assignment identifier attribute identifier identifier if_statement identifier block return_statement attribute identifier identifier if_statement attribute identifier identifier block return_statement subscript attribute identifier identifier attribute attribute attribute identifier identifier identifier identifier return_statement none | Get wrapper to the drive containing this device. |
def download_and_extract_to_mkdtemp(bucket, key, session=None):
if session:
s3_client = session.client('s3')
else:
s3_client = boto3.client('s3')
transfer = S3Transfer(s3_client)
filedes, temp_file = tempfile.mkstemp()
os.close(filedes)
transfer.download_file(bucket, key, temp_file)
output_dir = tempfile.mkdtemp()
zip_ref = zipfile.ZipFile(temp_file, 'r')
zip_ref.extractall(output_dir)
zip_ref.close()
os.remove(temp_file)
return output_dir | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Download zip archive and extract it to temporary directory. |
def DEFINE_bool(self, name, default, help, constant=False):
self.AddOption(
type_info.Bool(name=name, default=default, description=help),
constant=constant) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier false block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | A helper for defining boolean options. |
def filter_decimal(string, default=None, lower=None, upper=None):
try:
d = decimal.Decimal(string)
if lower is not None and d < lower:
raise InvalidInputError("value too small")
if upper is not None and d >= upper:
raise InvalidInputError("value too large")
return d
except decimal.InvalidOperation:
if not string and default is not None:
return default
else:
raise InvalidInputError("invalid decimal number") | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator identifier none comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement identifier except_clause attribute identifier identifier block if_statement boolean_operator not_operator identifier comparison_operator identifier none block return_statement identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Return the input decimal number, or the default. |
def patch_lustre_path(f_path):
if CHECK_LUSTRE_PATH_LEN and len(f_path) == 60:
if os.path.isabs(f_path):
f_path = '/.' + f_path
else:
f_path = './' + f_path
return f_path | module function_definition identifier parameters identifier block if_statement boolean_operator identifier comparison_operator call identifier argument_list identifier integer block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier return_statement identifier | Patch any 60-character pathnames, to avoid a current Lustre bug. |
def json(self):
if six.PY3:
return json.loads(self.body.decode(self.charset))
else:
return json.loads(self.body) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier else_clause block return_statement call attribute identifier identifier argument_list attribute identifier identifier | Return response body deserialized into JSON object. |
def create_python_worker(self, func, *args, **kwargs):
worker = PythonWorker(func, args, kwargs)
self._create_worker(worker)
return worker | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Create a new python worker instance. |
def to_json(value, **kwargs):
if isinstance(value, HasProperties):
return value.serialize(**kwargs)
return value | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list dictionary_splat identifier return_statement identifier | Return value, serialized if value is a HasProperties instance |
def unexpected(lexer: Lexer, at_token: Token = None) -> GraphQLError:
token = at_token or lexer.token
return GraphQLSyntaxError(lexer.source, token.start, f"Unexpected {token.desc}") | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier none type identifier block expression_statement assignment identifier boolean_operator identifier attribute identifier identifier return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier string string_start string_content interpolation attribute identifier identifier string_end | Create an error when an unexpected lexed token is encountered. |
def use_plenary_gradebook_column_view(self):
self._object_views['gradebook_column'] = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_gradebook_column_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement | Pass through to provider GradebookColumnLookupSession.use_plenary_gradebook_column_view |
def fields(self, value):
if type(value) is list:
self._fields = value
else:
raise TypeError("Input must be a list") | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment attribute identifier identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | sets the fields variable |
def save_setup_command(argv, build_path):
file_name = os.path.join(build_path, 'setup_command')
with open(file_name, 'w') as f:
f.write(' '.join(argv[:]) + '\n') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end 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 call attribute identifier identifier argument_list binary_operator call attribute string string_start string_content string_end identifier argument_list subscript identifier slice string string_start string_content escape_sequence string_end | Save setup command to a file. |
def create_environment(self, name, default=False, zone=None):
from qubell.api.private.environment import Environment
return Environment.new(organization=self, name=name, zone_id=zone, default=default, router=self._router) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier none block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier | Creates environment and returns Environment object. |
def _progress_hook(self, blocknum, blocksize, totalsize):
read = blocknum * blocksize
if totalsize > 0:
percent = read * 1e2 / totalsize
s = "\r%d%% %*d / %d" % (
percent, len(str(totalsize)), read, totalsize)
sys.stdout.write(s)
if read >= totalsize:
sys.stdout.write("\n")
else:
sys.stdout.write("read %d\n" % read) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator binary_operator identifier float identifier expression_statement assignment identifier binary_operator string string_start string_content escape_sequence string_end tuple identifier call identifier argument_list call identifier argument_list identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end identifier | Progress hook for urlretrieve. |
def delete_sp_template_for_vlan(self, vlan_id):
with self.session.begin(subtransactions=True):
try:
self.session.query(
ucsm_model.ServiceProfileTemplate).filter_by(
vlan_id=vlan_id).delete()
except orm.exc.NoResultFound:
return | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true block try_statement block expression_statement call attribute call attribute call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list except_clause attribute attribute identifier identifier identifier block return_statement | Deletes SP Template for a vlan_id if it exists. |
def previous_blocks(self, quantity=-1):
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"-date", "-block_letter").filter(Q(date__lt=self.date) | (Q(date=self.date) & Q(block_letter__lt=self.block_letter))))
if quantity == -1:
return reversed(blocks)
return reversed(blocks[:quantity]) | module function_definition identifier parameters identifier default_parameter identifier unary_operator integer block expression_statement assignment identifier parenthesized_expression call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list binary_operator call identifier argument_list keyword_argument identifier attribute identifier identifier parenthesized_expression binary_operator call identifier argument_list keyword_argument identifier attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier if_statement comparison_operator identifier unary_operator integer block return_statement call identifier argument_list identifier return_statement call identifier argument_list subscript identifier slice identifier | Get the previous blocks in order. |
def ansi_len(string):
return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string)) | module function_definition identifier parameters identifier block return_statement binary_operator call identifier argument_list identifier call identifier argument_list call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_end identifier | Extra length due to any ANSI sequences in the string. |
def monkey_patch():
reset()
time_mod.time = time
time_mod.sleep = sleep
time_mod.gmtime = gmtime
time_mod.localtime = localtime
time_mod.ctime = ctime
time_mod.asctime = asctime
time_mod.strftime = strftime | module function_definition identifier parameters block expression_statement call identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier | monkey patch `time` module to use out versions |
def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns):
mgr = SoftLayer.DedicatedHostManager(env.client)
guests = mgr.list_guests(host_id=identifier,
cpus=cpu,
hostname=hostname,
domain=domain,
memory=memory,
tags=tag,
mask=columns.mask())
table = formatting.Table(columns.columns)
table.sortby = sortby
for guest in guests:
table.add_row([value or formatting.blank()
for value in columns.row(guest)])
env.fout(table) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list list_comprehension boolean_operator identifier call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | List guests which are in a dedicated host server. |
def update_stress_mode(self):
self.stress_conroller.kill_stress_process()
self.view.clock_view.set_text(ZERO_TIME)
self.stress_start_time = timeit.default_timer()
if self.stress_conroller.get_current_mode() == 'Stress':
stress_cmd = self.view.stress_menu.get_stress_cmd()
self.stress_conroller.start_stress(stress_cmd)
elif self.stress_conroller.get_current_mode() == 'FIRESTARTER':
stress_cmd = [self.firestarter]
self.stress_conroller.start_stress(stress_cmd) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier elif_clause comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Updates stress mode according to radio buttons state |
def add_broker(self, broker):
if broker not in self._brokers:
self._brokers.add(broker)
else:
self.log.warning(
'Broker {broker_id} already present in '
'replication-group {rg_id}'.format(
broker_id=broker.id,
rg_id=self._id,
)
) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Add broker to current broker-list. |
def datetime_to_millis(x):
if x is None:
return None
if hasattr(x, 'timestamp'):
secs = x.timestamp()
elif x.tzinfo is None:
secs = (time.mktime((x.year, x.month, x.day,
x.hour, x.minute, x.second,
-1, -1, -1)) + x.microsecond / 1e6)
else:
secs = (x - _EPOCH).total_seconds()
return int(secs * 1000) | module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block return_statement none if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list elif_clause comparison_operator attribute identifier identifier none block expression_statement assignment identifier parenthesized_expression binary_operator call attribute identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier unary_operator integer unary_operator integer unary_operator integer binary_operator attribute identifier identifier float else_clause block expression_statement assignment identifier call attribute parenthesized_expression binary_operator identifier identifier identifier argument_list return_statement call identifier argument_list binary_operator identifier integer | Convert a `datetime.datetime` to milliseconds since the epoch |
def render_in_page(request, template):
from leonardo.module.web.models import Page
page = request.leonardo_page if hasattr(
request, 'leonardo_page') else Page.objects.filter(parent=None).first()
if page:
try:
slug = request.path_info.split("/")[-2:-1][0]
except KeyError:
slug = None
try:
body = render_to_string(template, RequestContext(request, {
'request_path': request.path,
'feincms_page': page,
'slug': slug,
'standalone': True}))
response = http.HttpResponseNotFound(
body, content_type=CONTENT_TYPE)
except TemplateDoesNotExist:
response = False
return response
return False | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier expression_statement assignment identifier conditional_expression attribute identifier identifier call identifier argument_list identifier string string_start string_content string_end call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier none identifier argument_list if_statement identifier block try_statement block expression_statement assignment identifier subscript subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end slice unary_operator integer unary_operator integer integer except_clause identifier block expression_statement assignment identifier none try_statement block expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list identifier dictionary pair string string_start string_content string_end attribute identifier 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 true expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier except_clause identifier block expression_statement assignment identifier false return_statement identifier return_statement false | return rendered template in standalone mode or ``False`` |
def resources(self):
return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())] | module function_definition identifier parameters identifier block return_statement list_comprehension call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list | Retrieve contents of each page of PDF |
def _mds_rpc_post(self, device_id, _wrap_with_consumer=True, async_id=None, **params):
self.ensure_notifications_thread()
api = self._get_api(mds.DeviceRequestsApi)
async_id = async_id or utils.new_async_id()
device_request = mds.DeviceRequest(**params)
api.create_async_request(
device_id,
async_id=async_id,
body=device_request,
)
return AsyncConsumer(async_id, self._db) if _wrap_with_consumer else async_id | module function_definition identifier parameters identifier identifier default_parameter identifier true default_parameter identifier none dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier boolean_operator identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement conditional_expression call identifier argument_list identifier attribute identifier identifier identifier identifier | Helper for using RPC endpoint |
def move_to_next_bit_address(self):
self._current_bit_address = self.next_bit_address()
self.mark_address(self._current_bit_address.split('.')[0], self._size_of_current_register_address) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer attribute identifier identifier | Moves to next available bit address position |
def upload(self, path, engine, description=None):
if description is None:
head, tail = ntpath.split(path)
description = tail or ntpath.basename(head)
url = "http://quickslice.{}/config/raw/".format(self.config.host)
with open(path) as config_file:
content = config_file.read()
payload = {"engine": engine,
"description": description,
"content": content}
post_resp = requests.post(url, json=payload, cookies={"session": self.session})
if not post_resp.ok:
raise errors.ResourceError("config upload to slicing service failed")
self.description = description
self.location = post_resp.headers["Location"] | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier boolean_operator identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier 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 expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end attribute identifier identifier if_statement not_operator attribute identifier identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end | Create a new config resource in the slicing service and upload the path contents to it |
def extract_pdftotext(self, filename, **kwargs):
if 'layout' in kwargs:
args = ['pdftotext', '-layout', filename, '-']
else:
args = ['pdftotext', filename, '-']
stdout, _ = self.run(args)
return stdout | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end else_clause block expression_statement assignment identifier list string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier return_statement identifier | Extract text from pdfs using the pdftotext command line utility. |
def loc_info(text, index):
if index > len(text):
raise ValueError('Invalid index.')
line, last_ln = text.count('\n', 0, index), text.rfind('\n', 0, index)
col = index - (last_ln + 1)
return (line, col) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier expression_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end integer identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end integer identifier expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator identifier integer return_statement tuple identifier identifier | Location of `index` in source code `text`. |
def instruction_ASR_register(self, opcode, register):
a = register.value
r = self.ASR(a)
register.set(r) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Arithmetic shift accumulator right |
def clean_text(text):
if text:
text = html2text.html2text(clean_markdown(text))
return re.sub(r'\s+', ' ', text).strip() | module function_definition identifier parameters identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier return_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier identifier argument_list | Retrieve clean text without markdown sintax or other things. |
def rename_column(self, model, old_name, new_name):
field = model._meta.fields[old_name]
if isinstance(field, pw.ForeignKeyField):
old_name = field.column_name
self.__del_field__(model, field)
field.name = field.column_name = new_name
model._meta.add_field(new_name, field)
if isinstance(field, pw.ForeignKeyField):
field.column_name = new_name = field.column_name + '_id'
self.ops.append(self.migrator.rename_column(model._meta.table_name, old_name, new_name))
return model | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier identifier if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment attribute identifier identifier assignment attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier identifier identifier return_statement identifier | Rename field in model. |
def titleify(self, lang='en', allwords=False, lastword=True):
if lang in LOWERCASE_WORDS:
lc_words = LOWERCASE_WORDS[lang]
else:
lc_words = []
s = str(self).strip()
l = re.split(r"([_\W]+)", s)
for i in range(len(l)):
l[i] = l[i].lower()
if (
allwords == True
or i == 0
or (lastword == True and i == len(l) - 1)
or l[i].lower() not in lc_words
):
w = l[i]
if len(w) > 1:
w = w[0].upper() + w[1:]
else:
w = w.upper()
l[i] = w
s = "".join(l)
return String(s) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier true block if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier else_clause block expression_statement assignment identifier list expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement assignment subscript identifier identifier call attribute subscript identifier identifier identifier argument_list if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator identifier true comparison_operator identifier integer parenthesized_expression boolean_operator comparison_operator identifier true comparison_operator identifier binary_operator call identifier argument_list identifier integer comparison_operator call attribute subscript identifier identifier identifier argument_list identifier block expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier binary_operator call attribute subscript identifier integer identifier argument_list subscript identifier slice integer else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier call attribute string string_start string_end identifier argument_list identifier return_statement call identifier argument_list identifier | takes a string and makes a title from it |
def compile_rich(cls, code, path=None, extra_args=None):
return {
contract_name: {
'code': '0x' + contract.get('bin_hex'),
'info': {
'abiDefinition': contract.get('abi'),
'compilerVersion': cls.compiler_version(),
'developerDoc': contract.get('devdoc'),
'language': 'Solidity',
'languageVersion': '0',
'source': code,
'userDoc': contract.get('userdoc')
},
}
for contract_name, contract
in cls.combined(code, path=path, extra_args=extra_args)
} | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block return_statement dictionary_comprehension pair identifier dictionary pair string string_start string_content string_end binary_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier | full format as returned by jsonrpc |
def _process_locale(self, locale):
if locale.lower().startswith('en'):
return False
return (locale in self.enabled_locales or
self.reverse_locale_map.get(locale.lower(), None)
in self.enabled_locales or
locale in self.lower_locales or
self.reverse_locale_map.get(locale.lower(), None)
in self.lower_locales
) | module function_definition identifier parameters identifier identifier block if_statement call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block return_statement false return_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list none attribute identifier identifier comparison_operator identifier attribute identifier identifier comparison_operator call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list none attribute identifier identifier | Return True if this locale should be processed. |
def get(path):
try:
import cPickle as pickle
except:
import pickle
with open(path, 'rb') as file:
return pickle.load(file) | module function_definition identifier parameters identifier block try_statement block import_statement aliased_import dotted_name identifier identifier except_clause block import_statement dotted_name identifier 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 return_statement call attribute identifier identifier argument_list identifier | Read an object from file |
def _parse_head(heads, head_grads):
if isinstance(heads, NDArray):
heads = [heads]
if isinstance(head_grads, NDArray):
head_grads = [head_grads]
head_handles = c_handle_array(heads)
if head_grads is None:
hgrad_handles = ctypes.c_void_p(0)
else:
assert len(heads) == len(head_grads), \
"heads and head_grads must be lists of the same length"
hgrad_handles = c_array(NDArrayHandle,
[i.handle if i is not None else NDArrayHandle(0)
for i in head_grads])
return head_handles, hgrad_handles | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list integer else_clause block assert_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier list_comprehension conditional_expression attribute identifier identifier comparison_operator identifier none call identifier argument_list integer for_in_clause identifier identifier return_statement expression_list identifier identifier | parse head gradient for backward and grad. |
def convert_to_python(self, xmlrpc=None):
if xmlrpc:
return xmlrpc.get(self.name, self.default)
elif self.default:
return self.default
else:
return None | module function_definition identifier parameters identifier default_parameter identifier none block if_statement identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier elif_clause attribute identifier identifier block return_statement attribute identifier identifier else_clause block return_statement none | Extracts a value for the field from an XML-RPC response. |
def check_is_a_sequence(var, allow_none=False):
if not is_a_sequence(var, allow_none=allow_none):
raise TypeError("var must be a list or tuple, however type(var) is {}"
.format(type(var))) | module function_definition identifier parameters identifier default_parameter identifier false block if_statement not_operator call identifier argument_list identifier keyword_argument identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier | Calls is_a_sequence and raises a type error if the check fails. |
def orphans(dburl, sitedir):
oldcwd = os.getcwd()
os.chdir(sitedir)
db = StrictRedis.from_url(dburl)
job = get_current_job(db)
job.meta.update({'out': '', 'return': None, 'status': None})
job.save()
returncode, out = orphans_single(default_exec=True)
job.meta.update({'out': out, 'return': returncode, 'status':
returncode == 0})
job.save()
os.chdir(oldcwd)
return returncode | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end string string_start string_end pair string string_start string_content string_end none pair string string_start string_content string_end none expression_statement call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call identifier argument_list keyword_argument identifier true expression_statement call attribute attribute identifier identifier 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 comparison_operator identifier integer expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Remove all orphans in the site. |
def compute(self, today, assets, out, *arrays):
raise NotImplementedError(
"{name} must define a compute method".format(
name=type(self).__name__
)
) | module function_definition identifier parameters identifier identifier identifier identifier list_splat_pattern identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute call identifier argument_list identifier identifier | Override this method with a function that writes a value into `out`. |
def _get_template(querystring_key, mapping):
default = None
try:
template_and_keys = mapping.items()
except AttributeError:
template_and_keys = mapping
for template, key in template_and_keys:
if key is None:
key = PAGE_LABEL
default = template
if key == querystring_key:
return template
return default | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block expression_statement assignment identifier identifier for_statement pattern_list identifier identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement assignment identifier identifier if_statement comparison_operator identifier identifier block return_statement identifier return_statement identifier | Return the template corresponding to the given ``querystring_key``. |
def apply_mana_drain(self):
self.r = self.g = self.b = self.y = 0 | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier assignment attribute identifier identifier assignment attribute identifier identifier assignment attribute identifier identifier integer | Clear current mana values. |
def description(self):
if 'metrics' in self.raw:
metrics = self.raw['metrics']
head = metrics[0:-1] or metrics[0:1]
text = ", ".join(head)
if len(metrics) > 1:
tail = metrics[-1]
text = text + " and " + tail
else:
text = 'n/a'
return text | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier boolean_operator subscript identifier slice integer unary_operator integer subscript identifier slice integer integer expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier unary_operator integer expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier else_clause block expression_statement assignment identifier string string_start string_content string_end return_statement identifier | A list of the metrics this query will ask for. |
def cli(env, sortby, datacenter):
block_manager = SoftLayer.BlockStorageManager(env.client)
mask = "mask[serviceResource[datacenter[name]],"\
"replicationPartners[serviceResource[datacenter[name]]]]"
block_volumes = block_manager.list_block_volumes(datacenter=datacenter,
mask=mask)
datacenters = dict()
for volume in block_volumes:
service_resource = volume['serviceResource']
if 'datacenter' in service_resource:
datacenter_name = service_resource['datacenter']['name']
if datacenter_name not in datacenters.keys():
datacenters[datacenter_name] = 1
else:
datacenters[datacenter_name] += 1
table = formatting.KeyValueTable(DEFAULT_COLUMNS)
table.sortby = sortby
for datacenter_name in datacenters:
table.add_row([datacenter_name, datacenters[datacenter_name]])
env.fout(table) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier integer else_clause block expression_statement augmented_assignment subscript identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list list identifier subscript identifier identifier expression_statement call attribute identifier identifier argument_list identifier | List number of block storage volumes per datacenter. |
def blur(self):
self._has_focus = False
try:
self._columns[self._live_col][self._live_widget].blur()
except IndexError:
pass | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false try_statement block expression_statement call attribute subscript subscript attribute identifier identifier attribute identifier identifier attribute identifier identifier identifier argument_list except_clause identifier block pass_statement | Call this to take the input focus from this Layout. |
def provide_with_default(self, name, default=None):
return self.provider.instantiate_by_name_with_default(name, default_value=default) | module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier | Return a dependency-injected instance |
def _get_table_info(self):
self.fields = []
self.field_info = {}
self.cursor.execute('PRAGMA table_info (%s)' %self.name)
for field_info in self.cursor.fetchall():
fname = field_info[1].encode('utf-8')
self.fields.append(fname)
ftype = field_info[2].encode('utf-8')
info = {'type':ftype}
info['NOT NULL'] = field_info[3] != 0
default = field_info[4]
if isinstance(default,unicode):
default = guess_default_fmt(default)
info['DEFAULT'] = default
self.field_info[fname] = info | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier dictionary expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end comparison_operator subscript identifier integer integer expression_statement assignment identifier subscript identifier integer if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript attribute identifier identifier identifier identifier | Inspect the base to get field names |
def _compute_centers(self, X, sparse, rs):
super(GRBFRandomLayer, self)._compute_centers(X, sparse, rs)
centers = self.components_['centers']
sorted_distances = np.sort(squareform(pdist(centers)))
self.dF_vals = sorted_distances[:, -1]
self.dN_vals = sorted_distances[:, 1]/100.0
tauNum = np.log(np.log(self.grbf_lambda) /
np.log(1.0 - self.grbf_lambda))
tauDenom = np.log(self.dF_vals/self.dN_vals)
self.tau_vals = tauNum/tauDenom
self._extra_args['taus'] = self.tau_vals | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list identifier expression_statement assignment attribute identifier identifier subscript identifier slice unary_operator integer expression_statement assignment attribute identifier identifier binary_operator subscript identifier slice integer float expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list binary_operator float attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier | Generate centers, then compute tau, dF and dN vals |
def move(self, new_father, idx=None, prepend=None, name=None):
self.parent.pop(self._own_index)
new_father._insert(self, idx=idx, prepend=prepend, name=name)
new_father._stable = False
return self | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment attribute identifier identifier false return_statement identifier | Moves this element from his father to the given one. |
def parse(self, **kwargs):
try:
output_folder = self.retrieved
except exceptions.NotExistent:
return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER
filename_stdout = self.node.get_attribute('output_filename')
filename_stderr = self.node.get_attribute('error_filename')
try:
with output_folder.open(filename_stderr, 'r') as handle:
exit_code = self.parse_stderr(handle)
except (OSError, IOError):
self.logger.exception('Failed to read the stderr file\n%s', traceback.format_exc())
return self.exit_codes.ERROR_READING_ERROR_FILE
if exit_code:
return exit_code
try:
with output_folder.open(filename_stdout, 'r') as handle:
handle.seek(0)
exit_code = self.parse_stdout(handle)
except (OSError, IOError):
self.logger.exception('Failed to read the stdout file\n%s', traceback.format_exc())
return self.exit_codes.ERROR_READING_OUTPUT_FILE
if exit_code:
return exit_code | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier attribute identifier identifier except_clause attribute identifier identifier block return_statement attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end try_statement block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause tuple identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end call attribute identifier identifier argument_list return_statement attribute attribute identifier identifier identifier if_statement identifier block return_statement identifier try_statement block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause tuple identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end call attribute identifier identifier argument_list return_statement attribute attribute identifier identifier identifier if_statement identifier block return_statement identifier | Parse the contents of the output files retrieved in the `FolderData`. |
def cache_keys(keys):
d = known_keys()
known_names = dict(zip(d.values(), d.keys()))
for k in keys:
i = (ord(k),) if len(k) == 1 else known_names[k]
_key_cache.insert(0, i) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement assignment identifier conditional_expression tuple call identifier argument_list identifier comparison_operator call identifier argument_list identifier integer subscript identifier identifier expression_statement call attribute identifier identifier argument_list integer identifier | Allow debugging via PyCharm |
def load(self, name):
name = ctypes.util.find_library(name)
return ctypes.cdll.LoadLibrary(name) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Loads and returns foreign library. |
def new_text_block(self, **kwargs):
proto = {'content': '', 'type': self.markdown}
proto.update(**kwargs)
return proto | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_end pair string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list dictionary_splat identifier return_statement identifier | Create a new text block. |
def _where(filename, dirs=[], env="PATH"):
if not isinstance(dirs, list):
dirs = [dirs]
if glob(filename):
return filename
paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
for path in paths:
for match in glob(os.path.join(path, filename)):
if match:
return os.path.normpath(match)
raise IOError("File not found: %s" % filename) | module function_definition identifier parameters identifier default_parameter identifier list default_parameter identifier string string_start string_content string_end block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier if_statement call identifier argument_list identifier block return_statement identifier expression_statement assignment identifier binary_operator binary_operator list attribute identifier identifier call attribute subscript attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier identifier for_statement identifier identifier block for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier block if_statement identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Find file in current dir or system path |
def _read_from_buffer(self, size=-1):
size = size if size >= 0 else len(self._buffer)
part = self._buffer.read(size)
self._current_pos += len(part)
return part | module function_definition identifier parameters identifier default_parameter identifier unary_operator integer block expression_statement assignment identifier conditional_expression identifier comparison_operator identifier integer call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier call identifier argument_list identifier return_statement identifier | Remove at most size bytes from our buffer and return them. |
async def send_api(container, targetname, name, params = {}):
handle = object()
apiEvent = ModuleAPICall(handle, targetname, name, params = params)
await container.wait_for_send(apiEvent) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier dictionary block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier identifier keyword_argument identifier identifier expression_statement await call attribute identifier identifier argument_list identifier | Send API and discard the result |
def plot(self, overlay=True, **labels):
pylab = LazyImport.pylab()
colours = list('rgbymc')
colours_len = len(colours)
colours_pos = 0
plots = len(self.groups)
for name, series in self.groups.iteritems():
colour = colours[colours_pos % colours_len]
colours_pos += 1
if not overlay:
pylab.subplot(plots, 1, colours_pos)
kwargs = {}
if name in labels:
name = labels[name]
if name is not None:
kwargs['label'] = name
pylab.plot(series.dates, series.values, '%s-' % colour, **kwargs)
if name is not None:
pylab.legend()
pylab.show() | module function_definition identifier parameters identifier default_parameter identifier true dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier subscript identifier binary_operator identifier identifier expression_statement augmented_assignment identifier integer if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list identifier integer identifier expression_statement assignment identifier dictionary if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier binary_operator string string_start string_content string_end identifier dictionary_splat identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Plot all time series in the group. |
def explained_inertia_(self):
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_] | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end return_statement list_comprehension binary_operator identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier | The percentage of explained inertia per principal component. |
def _set_params(self):
if self.docs['in']['params']:
self.docs['out']['params'] = list(self.docs['in']['params'])
for e in self.element['params']:
if type(e) is tuple:
param = e[0]
else:
param = e
found = False
for i, p in enumerate(self.docs['out']['params']):
if param == p[0]:
found = True
if type(e) is tuple:
self.docs['out']['params'][i] = (p[0], p[1], p[2], e[1])
if not found:
if type(e) is tuple:
p = (param, '', None, e[1])
else:
p = (param, '', None, None)
self.docs['out']['params'].append(p) | module function_definition identifier parameters identifier block if_statement subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end call identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end for_statement identifier subscript attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifier integer else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier false for_statement pattern_list identifier identifier call identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end block if_statement comparison_operator identifier subscript identifier integer block expression_statement assignment identifier true if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment subscript subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end identifier tuple subscript identifier integer subscript identifier integer subscript identifier integer subscript identifier integer if_statement not_operator identifier block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier tuple identifier string string_start string_end none subscript identifier integer else_clause block expression_statement assignment identifier tuple identifier string string_start string_end none none expression_statement call attribute subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier | Sets the parameters with types, descriptions and default value if any |
def SetOperator(self, operator):
self.operator = operator
attribute_type = self.attribute_obj.GetRDFValueType()
operators = attribute_type.operators
self.number_of_args, self.operator_method = operators.get(
operator, (0, None))
if self.operator_method is None:
raise lexer.ParseError("Operator %s not defined on attribute '%s'" %
(operator, self.attribute))
self.operator_method = getattr(attribute_type, self.operator_method) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list identifier tuple integer none if_statement comparison_operator attribute identifier identifier none block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier attribute identifier identifier | Sets the operator for this expression. |
def _validate_master(new_class):
if not new_class.master or not isinstance(new_class.master, ForwardManyToOneDescriptor):
raise ImproperlyConfigured("{0}.master should be a ForeignKey to the shared table.".format(new_class.__name__))
remote_field = new_class.master.field.remote_field
shared_model = remote_field.model
meta = shared_model._parler_meta
if meta is not None:
if meta._has_translations_model(new_class):
raise ImproperlyConfigured("The model '{0}' already has an associated translation table!".format(shared_model.__name__))
if meta._has_translations_field(remote_field.related_name):
raise ImproperlyConfigured("The model '{0}' already has an associated translation field named '{1}'!".format(shared_model.__name__, remote_field.related_name))
return shared_model | module function_definition identifier parameters identifier block if_statement boolean_operator not_operator attribute identifier identifier not_operator call identifier argument_list attribute identifier identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block if_statement call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement call attribute identifier identifier argument_list attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier return_statement identifier | Check whether the 'master' field on a TranslatedFieldsModel is correctly configured. |
def _install_from_path(path):
if not os.path.exists(path):
msg = 'File not found: {0}'.format(path)
raise SaltInvocationError(msg)
cmd = 'installer -pkg "{0}" -target /'.format(path)
return salt.utils.mac_utils.execute_return_success(cmd) | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier raise_statement call identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier | Internal function to install a package from the given path |
def _format_json(self, ans, q):
params = {}
try: params['indent'] = int(q.get('indent')[0])
except: pass
return json.dumps(ans, **params)+'\n' | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary try_statement block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript call attribute identifier identifier argument_list string string_start string_content string_end integer except_clause block pass_statement return_statement binary_operator call attribute identifier identifier argument_list identifier dictionary_splat identifier string string_start string_content escape_sequence string_end | Generate a json response string. |
def file_matches(filename, patterns):
return any(fnmatch.fnmatch(filename, pat)
or fnmatch.fnmatch(os.path.basename(filename), pat)
for pat in patterns) | module function_definition identifier parameters identifier identifier block return_statement call identifier generator_expression boolean_operator call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier for_in_clause identifier identifier | Does this filename match any of the patterns? |
def format_error(err_type, err_value, err_trace=None):
if err_trace is None:
err_parts = "".join(traceback.format_exception_only(err_type, err_value)).strip().split(": ", 1)
if len(err_parts) == 1:
err_name, err_msg = err_parts[0], ""
else:
err_name, err_msg = err_parts
err_name = err_name.split(".")[-1]
return err_name + ": " + err_msg
else:
return "".join(traceback.format_exception(err_type, err_value, err_trace)).strip() | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute call attribute call attribute string string_start string_end identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end integer if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment pattern_list identifier identifier expression_list subscript identifier integer string string_start string_end else_clause block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end unary_operator integer return_statement binary_operator binary_operator identifier string string_start string_content string_end identifier else_clause block return_statement call attribute call attribute string string_start string_end identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier identifier argument_list | Properly formats the specified error. |
def actualize (self):
if self.actualized_:
return
self.actualized_ = True
ps = self.properties ()
properties = self.adjust_properties (ps)
actual_targets = []
for i in self.targets ():
actual_targets.append (i.actualize ())
self.actualize_sources (self.sources (), properties)
self.engine_.add_dependency (actual_targets, self.actual_sources_ + self.dependency_only_sources_)
import toolset
toolset.set_target_variables (self.manager_, self.action_name_, actual_targets, properties)
engine = self.manager_.engine ()
bjam.call("set-target-variable", actual_targets, ".action", repr(self))
self.manager_.engine ().set_update_action (self.action_name_, actual_targets, self.actual_sources_,
properties)
self.manager_.engine ().set_update_action ('common.Clean', 'clean-all',
actual_targets)
return actual_targets | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement expression_statement assignment attribute identifier identifier true expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier binary_operator attribute identifier identifier attribute identifier identifier import_statement dotted_name identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list attribute identifier identifier identifier attribute identifier identifier identifier expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier return_statement identifier | Generates actual build instructions. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.