code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def ignore_logger(name_or_logger, allow_level=None):
def handler(logger, level, msg, args, kwargs):
if allow_level is not None and \
level >= allow_level:
return False
return True
register_special_log_handler(name_or_logger, handler) | module function_definition identifier parameters identifier default_parameter identifier none block function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement boolean_operator comparison_operator identifier none line_continuation comparison_operator identifier identifier block return_statement false return_statement true expression_statement call identifier argument_list identifier identifier | Ignores a logger during breadcrumb recording. |
def _rm_gos_edges_rel(self, rm_goids, edges_rel):
edges_ret = {}
for rname, edges_cur in edges_rel.items():
edges_new = self._rm_gos_edges(rm_goids, edges_cur)
if edges_new:
edges_ret[rname] = edges_new
return edges_ret | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement identifier block expression_statement assignment subscript identifier identifier identifier return_statement identifier | Remove any relationship that contain user-specified edges. |
def _recursive_cleanup(foo):
if isinstance(foo, dict):
for (key, val) in list(foo.items()):
if isinstance(val, dict):
_recursive_cleanup(val)
if val == "" or val == [] or val == {}:
del foo[key] | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block for_statement tuple_pattern identifier identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier if_statement boolean_operator boolean_operator comparison_operator identifier string string_start string_end comparison_operator identifier list comparison_operator identifier dictionary block delete_statement subscript identifier identifier | Aggressively cleans up things that look empty. |
def drange(v0, v1, d):
assert v0 < v1
return xrange(int(v0)//d, int(v1+d)//d) | module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator identifier identifier return_statement call identifier argument_list binary_operator call identifier argument_list identifier identifier binary_operator call identifier argument_list binary_operator identifier identifier identifier | Returns a discrete range. |
def _check_valid_basic(self, get_params):
try:
if get_params(self.variable):
return self.default
except:
pass
return not self.default | module function_definition identifier parameters identifier identifier block try_statement block if_statement call identifier argument_list attribute identifier identifier block return_statement attribute identifier identifier except_clause block pass_statement return_statement not_operator attribute identifier identifier | Simple check that the variable is set |
def cmd_terrain_check(self, args):
if len(args) >= 2:
latlon = (float(args[0]), float(args[1]))
else:
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
if latlon is None:
print("No map click position available")
return
self.check_lat = int(latlon[0]*1e7)
self.check_lon = int(latlon[1]*1e7)
self.master.mav.terrain_check_send(self.check_lat, self.check_lon) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier tuple call identifier argument_list subscript identifier integer call identifier argument_list subscript identifier integer else_clause block try_statement block expression_statement assignment identifier attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier except_clause identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement if_statement comparison_operator identifier none block expression_statement call identifier argument_list string string_start string_content string_end return_statement expression_statement assignment attribute identifier identifier call identifier argument_list binary_operator subscript identifier integer float expression_statement assignment attribute identifier identifier call identifier argument_list binary_operator subscript identifier integer float expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier | check a piece of terrain data |
def merge_dict(dict_1, *other, **kw):
tmp = dict_1.copy()
for x in other:
tmp.update(x)
tmp.update(kw)
return tmp | 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 for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Merge two or more dict including kw into result dict. |
def create_app():
global QT_APP
QT_APP = QApplication.instance()
if QT_APP is None:
QT_APP = QApplication(sys.argv)
return QT_APP | module function_definition identifier parameters block global_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list attribute identifier identifier return_statement identifier | Create a Qt application. |
def reverse(self):
clone = self._clone()
assert self._ordering, "You need to set an ordering for reverse"
ordering = []
for order in self._ordering:
for k,v in order.items():
if v=="asc":
ordering.append({k: "desc"})
else:
ordering.append({k: "asc"})
clone._ordering=ordering
return clone | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list assert_statement attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier list for_statement identifier attribute identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list dictionary pair identifier string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list dictionary pair identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier return_statement identifier | Reverses the ordering of the QuerySet. |
def str_append_hash(*args):
ret_hash = ""
for i in args:
ret_hash += str(i).lower()
return hash(ret_hash) | module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier string string_start string_end for_statement identifier identifier block expression_statement augmented_assignment identifier call attribute call identifier argument_list identifier identifier argument_list return_statement call identifier argument_list identifier | Convert each argument to a lower case string, appended, then hash |
def divide_url(self, url):
if 'https://' in url:
host = url[8:].split('/')[0]
path = url[8 + len(host):]
elif 'http://' in url:
host = url[7:].split('/')[0]
path = url[7 + len(host):]
else:
host = url.split('/')[0]
path = url[len(host):]
return host, path | module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript call attribute subscript identifier slice integer identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier subscript identifier slice binary_operator integer call identifier argument_list identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript call attribute subscript identifier slice integer identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier subscript identifier slice binary_operator integer call identifier argument_list identifier else_clause block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier subscript identifier slice call identifier argument_list identifier return_statement expression_list identifier identifier | divide url into host and path two parts |
def _pnorm_default(x, p):
return np.linalg.norm(x.data.ravel(), ord=p) | module function_definition identifier parameters identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier | Default p-norm implementation. |
def remove(self):
print 'remove'
if self.exists():
print 'cleaning', self.venv
run('rm -rf {}'.format(self.venv)) | module function_definition identifier parameters identifier block print_statement string string_start string_content string_end if_statement call attribute identifier identifier argument_list block print_statement string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | Remove the virtual environment completely |
def inherit_doc(cls):
for name, func in vars(cls).items():
if name.startswith("_"):
continue
if not func.__doc__:
for parent in cls.__bases__:
parent_func = getattr(parent, name, None)
if parent_func and getattr(parent_func, "__doc__", None):
func.__doc__ = parent_func.__doc__
break
return cls | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute call identifier argument_list identifier identifier argument_list block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block continue_statement if_statement not_operator attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier none if_statement boolean_operator identifier call identifier argument_list identifier string string_start string_content string_end none block expression_statement assignment attribute identifier identifier attribute identifier identifier break_statement return_statement identifier | A decorator that makes a class inherit documentation from its parents. |
def execd_run(command, execd_dir=None, die_on_error=True, stderr=subprocess.STDOUT):
for submodule_path in execd_submodule_paths(command, execd_dir):
try:
subprocess.check_output(submodule_path, stderr=stderr,
universal_newlines=True)
except subprocess.CalledProcessError as e:
hookenv.log("Error ({}) running {}. Output: {}".format(
e.returncode, e.cmd, e.output))
if die_on_error:
sys.exit(e.returncode) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier true default_parameter identifier attribute identifier identifier block for_statement identifier call identifier argument_list identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier true except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Run command for each module within execd_dir which defines it. |
def create_inquirer_layout(
ic: InquirerControl,
get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]],
**kwargs) -> Layout:
ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs)
_fix_unecessary_blank_lines(ps)
return Layout(HSplit([
ps.layout.container,
ConditionalContainer(
Window(ic),
filter=~IsDone()
)
])) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type list type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type identifier dictionary_splat_pattern identifier type identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier integer dictionary_splat identifier expression_statement call identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list list attribute attribute identifier identifier identifier call identifier argument_list call identifier argument_list identifier keyword_argument identifier unary_operator call identifier argument_list | Create a layout combining question and inquirer selection. |
def pol2cart(theta, rho):
x = rho * np.cos(theta)
y = rho * np.sin(theta)
return x, y | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier | Polar to Cartesian coordinates conversion. |
def next(self):
line = self.filehandle.readline()
line = line.decode('utf-8', 'replace')
if line == '':
raise StopIteration
line = line.rstrip('\n')
le = LogEvent(line)
if self._datetime_format and self._datetime_nextpos is not None:
ret = le.set_datetime_hint(self._datetime_format,
self._datetime_nextpos,
self.year_rollover)
if not ret:
self._datetime_format = None
self._datetime_nextpos = None
elif le.datetime:
self._datetime_format = le.datetime_format
self._datetime_nextpos = le._datetime_nextpos
return le | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier string string_start string_end block raise_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier if_statement not_operator identifier block expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none elif_clause attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement identifier | Get next line, adjust for year rollover and hint datetime format. |
def onClose(self, was_clean, code, reason):
logger.debug("Connection closed ({peer})".format(peer=self.peer))
self.factory.mease.publisher.publish(
message_type=ON_CLOSE, client_id=self._client_id, client_storage=self.storage)
self.factory.remove_client(self) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Called when a client closes a websocket connection |
def generic_html(self, result, errors):
h1 = htmlize(type(result))
out = []
result = pre_process_json(result)
if not hasattr(result, 'items'):
header = "<tr><th>Value</th></tr>"
if type(result) is list:
result = htmlize_list(result)
else:
result = htmlize(result)
out = ["<tr><td>" + result + "</td></tr>"]
elif hasattr(result, 'lower'):
out = ["<tr><td>" + result + "</td></tr>"]
else:
header = "<tr><th>Key</th><th>Value</th></tr>"
for key, value in result.items():
v = htmlize(value)
row = "<tr><td>{0}</td><td>{1}</td></tr>".format(key, v)
out.append(row)
env = Environment(loader=PackageLoader('giotto'))
template = env.get_template('generic.html')
rendered = template.render({'header': h1, 'table_header': header, 'table_body': out})
return {'body': rendered, 'mimetype': 'text/html'} | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end elif_clause call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier list binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier 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 expression_statement assignment identifier call attribute 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 identifier return_statement dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start string_content string_end | Try to display any object in sensible HTML. |
def _add_cpu_percent(self, cur_read):
for executor_id, cur_data in cur_read.items():
stats = cur_data['statistics']
cpus_limit = stats.get('cpus_limit')
cpus_utilisation = stats.get('cpus_utilisation')
if cpus_utilisation and cpus_limit != 0:
stats['cpus_percent'] = cpus_utilisation / cpus_limit | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator identifier comparison_operator identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end binary_operator identifier identifier | Compute cpu percent basing on the provided utilisation |
def build_archive(cls, **kwargs):
if cls._archive is None:
cls._archive = cls(**kwargs)
return cls._archive | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list dictionary_splat identifier return_statement attribute identifier identifier | Return the singleton `JobArchive` instance, building it if needed |
def version_from_frame(frame):
module = getmodule(frame)
if module is None:
s = "<unknown from {0}:{1}>"
return s.format(frame.f_code.co_filename, frame.f_lineno)
module_name = module.__name__
variable = "AUTOVERSION_{}".format(module_name.upper())
override = os.environ.get(variable, None)
if override is not None:
return override
while True:
try:
get_distribution(module_name)
except DistributionNotFound:
module_name, dot, _ = module_name.partition(".")
if dot == "":
break
else:
return getversion(module_name)
return None | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none if_statement comparison_operator identifier none block return_statement identifier while_statement true block try_statement block expression_statement call identifier argument_list identifier except_clause identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier string string_start string_end block break_statement else_clause block return_statement call identifier argument_list identifier return_statement none | Given a ``frame``, obtain the version number of the module running there. |
def strip_spaces(value, sep=None, join=True):
value = value.strip()
value = [v.strip() for v in value.split(sep)]
join_sep = sep or ' '
return join_sep.join(value) if join else value | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier boolean_operator identifier string string_start string_content string_end return_statement conditional_expression call attribute identifier identifier argument_list identifier identifier identifier | Cleans trailing whitespaces and replaces also multiple whitespaces with a single space. |
def from_dbus_fact(fact):
return Fact(fact[4],
start_time = dt.datetime.utcfromtimestamp(fact[1]),
end_time = dt.datetime.utcfromtimestamp(fact[2]) if fact[2] else None,
description = fact[3],
activity_id = fact[5],
category = fact[6],
tags = fact[7],
date = dt.datetime.utcfromtimestamp(fact[8]).date(),
id = fact[0]
) | module function_definition identifier parameters identifier block return_statement call identifier argument_list subscript identifier integer keyword_argument identifier call attribute attribute identifier identifier identifier argument_list subscript identifier integer keyword_argument identifier conditional_expression call attribute attribute identifier identifier identifier argument_list subscript identifier integer subscript identifier integer none keyword_argument identifier subscript identifier integer keyword_argument identifier subscript identifier integer keyword_argument identifier subscript identifier integer keyword_argument identifier subscript identifier integer keyword_argument identifier call attribute call attribute attribute identifier identifier identifier argument_list subscript identifier integer identifier argument_list keyword_argument identifier subscript identifier integer | unpack the struct into a proper dict |
def _linux_memdata():
grains = {'mem_total': 0, 'swap_total': 0}
meminfo = '/proc/meminfo'
if os.path.isfile(meminfo):
with salt.utils.files.fopen(meminfo, 'r') as ifile:
for line in ifile:
comps = line.rstrip('\n').split(':')
if not len(comps) > 1:
continue
if comps[0].strip() == 'MemTotal':
grains['mem_total'] = int(comps[1].split()[0]) // 1024
if comps[0].strip() == 'SwapTotal':
grains['swap_total'] = int(comps[1].split()[0]) // 1024
return grains | module function_definition identifier parameters block expression_statement assignment identifier dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end integer expression_statement assignment identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end identifier argument_list string string_start string_content string_end if_statement not_operator comparison_operator call identifier argument_list identifier integer block continue_statement if_statement comparison_operator call attribute subscript identifier integer identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end binary_operator call identifier argument_list subscript call attribute subscript identifier integer identifier argument_list integer integer if_statement comparison_operator call attribute subscript identifier integer identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end binary_operator call identifier argument_list subscript call attribute subscript identifier integer identifier argument_list integer integer return_statement identifier | Return the memory information for Linux-like systems |
def transform_dot(self, node, results):
module_dot = results.get("bare_with_attr")
member = results.get("member")
new_name = None
if isinstance(member, list):
member = member[0]
for change in MAPPING[module_dot.value]:
if member.value in change[1]:
new_name = change[0]
break
if new_name:
module_dot.replace(Name(new_name,
prefix=module_dot.prefix))
else:
self.cannot_convert(node, "This is an invalid module element") | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier none if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifier integer for_statement identifier subscript identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier subscript identifier integer block expression_statement assignment identifier subscript identifier integer break_statement if_statement identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier keyword_argument identifier attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end | Transform for calls to module members in code. |
def allow_unregister(self, plugin_override=True):
vals = self._hook_manager.call_hook('course_allow_unregister', course=self, default=self._allow_unregister)
return vals[0] if len(vals) and plugin_override else self._allow_unregister | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier return_statement conditional_expression subscript identifier integer boolean_operator call identifier argument_list identifier identifier attribute identifier identifier | Returns True if students can unregister from course |
def make_json_formatter(graph):
return {
"()": graph.config.logging.json_formatter.formatter,
"fmt": graph.config.logging.json_required_keys,
} | module function_definition identifier parameters identifier block return_statement dictionary pair string string_start string_content string_end attribute attribute attribute attribute identifier identifier identifier identifier identifier pair string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier | Create the default json formatter. |
def whitelist(ctx, whitelist_account, account):
account = Account(account, blockchain_instance=ctx.blockchain)
print_tx(account.whitelist(whitelist_account)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier attribute identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier | Add an account to a whitelist |
def hyperparameters(self):
hyperparameters = super(Chainer, self).hyperparameters()
additional_hyperparameters = {Chainer._use_mpi: self.use_mpi,
Chainer._num_processes: self.num_processes,
Chainer._process_slots_per_host: self.process_slots_per_host,
Chainer._additional_mpi_options: self.additional_mpi_options}
additional_hyperparameters = {k: v for k, v in additional_hyperparameters.items() if v}
hyperparameters.update(Framework._json_encode_hyperparameters(additional_hyperparameters))
return hyperparameters | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment identifier dictionary pair attribute identifier identifier attribute identifier identifier pair attribute identifier identifier attribute identifier identifier pair attribute identifier identifier attribute identifier identifier pair attribute identifier identifier attribute identifier identifier expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier | Return hyperparameters used by your custom Chainer code during training. |
def teardown(self):
if self.controller:
self.controller.teardown()
for monitor in self.monitors:
monitor.teardown() | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Clean up the target once all tests are completed |
def _is_tp(pkt):
tp = [SOMEIP.TYPE_TP_REQUEST, SOMEIP.TYPE_TP_REQUEST_NO_RET,
SOMEIP.TYPE_TP_NOTIFICATION, SOMEIP.TYPE_TP_RESPONSE,
SOMEIP.TYPE_TP_ERROR]
if isinstance(pkt, Packet):
return pkt.msg_type in tp
else:
return pkt[15] in tp | module function_definition identifier parameters identifier block expression_statement assignment identifier list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier if_statement call identifier argument_list identifier identifier block return_statement comparison_operator attribute identifier identifier identifier else_clause block return_statement comparison_operator subscript identifier integer identifier | Returns true if pkt is using SOMEIP-TP, else returns false. |
def _prepare_uimodules(self):
for key, value in self._config.get(config.UI_MODULES, {}).iteritems():
self._config[config.UI_MODULES][key] = self._import_class(value)
self._config[config.UI_MODULES] = dict(self._config[config.UI_MODULES] or {}) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute call attribute attribute identifier identifier identifier argument_list attribute identifier identifier dictionary identifier argument_list block expression_statement assignment subscript subscript attribute identifier identifier attribute identifier identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier attribute identifier identifier call identifier argument_list boolean_operator subscript attribute identifier identifier attribute identifier identifier dictionary | Prepare the UI Modules from a list of namespaced paths. |
def _get_firewall_rules(firewall_rules):
ret = []
for key, value in six.iteritems(firewall_rules):
if 'protocol' not in firewall_rules[key].keys():
raise SaltCloudConfigError(
'The firewall rule \'{0}\' is missing \'protocol\''.format(key)
)
ret.append(FirewallRule(
name=key,
protocol=firewall_rules[key].get('protocol', None),
source_mac=firewall_rules[key].get('source_mac', None),
source_ip=firewall_rules[key].get('source_ip', None),
target_ip=firewall_rules[key].get('target_ip', None),
port_range_start=firewall_rules[key].get('port_range_start', None),
port_range_end=firewall_rules[key].get('port_range_end', None),
icmp_type=firewall_rules[key].get('icmp_type', None),
icmp_code=firewall_rules[key].get('icmp_code', None)
))
return ret | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator string string_start string_content string_end call attribute subscript identifier identifier identifier argument_list block raise_statement call identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier keyword_argument identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end none return_statement identifier | Construct a list of optional firewall rules from the cloud profile. |
def _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None):
fields = get_field_list(fields, schema)
return {'cols': _get_cols(fields, schema), 'rows': []}, 0 | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer default_parameter identifier unary_operator integer default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier return_statement expression_list dictionary pair string string_start string_content string_end call identifier argument_list identifier identifier pair string string_start string_content string_end list integer | Helper function for _get_data that handles empty lists. |
def log_error(self, callback, error=None):
print("Uncaught error during callback: {}".format(callback))
print("Error: {}".format(error)) | module function_definition identifier parameters identifier identifier default_parameter identifier none 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 call attribute string string_start string_content string_end identifier argument_list identifier | Log the error that occurred when running the given callback. |
def state(anon, obj, field, val):
return anon.faker.state(field=field) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier | Returns a randomly selected US state code |
async def save(self, request, response):
if isinstance(response, Response) and SESSION_KEY in request and not response.prepared:
session = request[SESSION_KEY]
if session.save(response.set_cookie):
self.app.logger.debug('Session saved: %s', session) | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator boolean_operator call identifier argument_list identifier identifier comparison_operator identifier identifier not_operator attribute identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end identifier | Save session to response cookies. |
def changelist_view(self, request, extra_context=None):
return super(TrackedLiveAdmin, self).changelist_view(
request, dict(extra_context or {},
url_name='admin:%s_%s_tracking_report' % (self.model._meta.app_label, self.model._meta.model_name),
period_options=self.get_period_options(),
report_options=self.get_report_options())
) | module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier call identifier argument_list boolean_operator identifier dictionary keyword_argument identifier binary_operator string string_start string_content string_end tuple attribute attribute attribute identifier identifier identifier identifier attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list | Updates the changelist view to include settings from this admin. |
def _symmetrize_correlograms(correlograms):
n_clusters, _, n_bins = correlograms.shape
assert n_clusters == _
correlograms[..., 0] = np.maximum(correlograms[..., 0],
correlograms[..., 0].T)
sym = correlograms[..., 1:][..., ::-1]
sym = np.transpose(sym, (1, 0, 2))
return np.dstack((sym, correlograms)) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier attribute identifier identifier assert_statement comparison_operator identifier identifier expression_statement assignment subscript identifier ellipsis integer call attribute identifier identifier argument_list subscript identifier ellipsis integer attribute subscript identifier ellipsis integer identifier expression_statement assignment identifier subscript subscript identifier ellipsis slice integer ellipsis slice unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier tuple integer integer integer return_statement call attribute identifier identifier argument_list tuple identifier identifier | Return the symmetrized version of the CCG arrays. |
def track_download_request(download_url, download_title):
from indico_piwik.plugin import PiwikPlugin
if not download_url:
raise ValueError("download_url can't be empty")
if not download_title:
raise ValueError("download_title can't be empty")
request = PiwikRequest(server_url=PiwikPlugin.settings.get('server_api_url'),
site_id=PiwikPlugin.settings.get('site_id_events'),
api_token=PiwikPlugin.settings.get('server_token'),
query_script=PiwikPlugin.track_script)
action_url = quote(download_url)
dt = datetime.now()
request.call(idsite=request.site_id,
rec=1,
action_name=quote(download_title.encode('utf-8')),
url=action_url,
download=action_url,
h=dt.hour, m=dt.minute, s=dt.second) | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier integer keyword_argument identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Track a download in Piwik |
def scenario(ctx, dependency_name, driver_name, lint_name, provisioner_name,
role_name, scenario_name, verifier_name):
command_args = {
'dependency_name': dependency_name,
'driver_name': driver_name,
'lint_name': lint_name,
'provisioner_name': provisioner_name,
'role_name': role_name,
'scenario_name': scenario_name,
'subcommand': __name__,
'verifier_name': verifier_name,
}
if verifier_name == 'inspec':
command_args['verifier_lint_name'] = 'rubocop'
if verifier_name == 'goss':
command_args['verifier_lint_name'] = 'yamllint'
if verifier_name == 'ansible':
command_args['verifier_lint_name'] = 'ansible-lint'
s = Scenario(command_args)
s.execute() | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block 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 pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Initialize a new scenario for use with Molecule. |
def cache_items(values):
import os
config_path = os.path.expanduser('~/.config/blockade')
file_path = os.path.join(config_path, 'cache.txt')
if not os.path.isfile(file_path):
file(file_path, 'w').close()
written = [x.strip() for x in open(file_path, 'r').readlines()]
handle = open(file_path, 'a')
for item in values:
if is_hashed(item):
hashed = item
else:
hashed = hash_values(item)
if hashed in written:
continue
handle.write(hashed + "\n")
handle.close()
return True | module function_definition identifier parameters identifier block import_statement dotted_name 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 identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end for_statement identifier identifier block if_statement call identifier argument_list identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list binary_operator identifier string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list return_statement true | Cache indicators that were successfully sent to avoid dups. |
def check_exclamations_ppm(text):
err = "leonard.exclamation.30ppm"
msg = u"More than 30 ppm of exclamations. Keep them under control."
regex = r"\w!"
count = len(re.findall(regex, text))
num_words = len(text.split(" "))
ppm = (count*1.0 / num_words) * 1e6
if ppm > 30 and count > 1:
loc = re.search(regex, text).start() + 1
return [(loc, loc+1, err, msg, ".")]
else:
return [] | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator parenthesized_expression binary_operator binary_operator identifier float identifier float if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block expression_statement assignment identifier binary_operator call attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list integer return_statement list tuple identifier binary_operator identifier integer identifier identifier string string_start string_content string_end else_clause block return_statement list | Make sure that the exclamation ppm is under 30. |
def addEdgeToGraph(parentNodeName, childNodeName, graphFileHandle, colour="black", length="10", weight="1", dir="none", label="", style=""):
graphFileHandle.write('edge[color=%s,len=%s,weight=%s,dir=%s,label="%s",style=%s];\n' % (colour, length, weight, dir, label, style))
graphFileHandle.write("%s -- %s;\n" % (parentNodeName, childNodeName)) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier | Links two nodes in the graph together. |
def register_job_from_link(self, link, key, **kwargs):
job_config = kwargs.get('job_config', None)
if job_config is None:
job_config = link.args
status = kwargs.get('status', JobStatus.unknown)
job_details = JobDetails(jobname=link.linkname,
jobkey=key,
appname=link.appname,
logfile=kwargs.get('logfile'),
jobconfig=job_config,
timestamp=get_timestamp(),
file_dict=copy.deepcopy(link.files),
sub_file_dict=copy.deepcopy(link.sub_files),
status=status)
self.register_job(job_details)
return job_details | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Register a job in the `JobArchive` from a `Link` object |
def cwms_process_text():
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
text = body.get('text')
cp = cwms.process_text(text)
return _stmts_from_proc(cp) | module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement dictionary expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier | Process text with CWMS and return INDRA Statements. |
def dateJDN(year, month, day, calendar):
a = (14 - month) // 12
y = year + 4800 - a
m = month + 12*a - 3
if calendar == GREGORIAN:
return day + (153*m + 2)//5 + 365*y + y//4 - y//100 + y//400 - 32045
else:
return day + (153*m + 2)//5 + 365*y + y//4 - 32083 | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator integer identifier integer expression_statement assignment identifier binary_operator binary_operator identifier integer identifier expression_statement assignment identifier binary_operator binary_operator identifier binary_operator integer identifier integer if_statement comparison_operator identifier identifier block return_statement binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator identifier binary_operator parenthesized_expression binary_operator binary_operator integer identifier integer integer binary_operator integer identifier binary_operator identifier integer binary_operator identifier integer binary_operator identifier integer integer else_clause block return_statement binary_operator binary_operator binary_operator binary_operator identifier binary_operator parenthesized_expression binary_operator binary_operator integer identifier integer integer binary_operator integer identifier binary_operator identifier integer integer | Converts date to Julian Day Number. |
def _get_source_sum(source_hash, file_path, saltenv):
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
"the format <hash type>=<hash>").format(source_hash)
source_hash = six.text_type(source_hash)
source_hash_scheme = _urlparse(source_hash).scheme
if source_hash_scheme in schemes:
cached_hash_file = __salt__['cp.cache_file'](source_hash, saltenv)
if not cached_hash_file:
raise CommandExecutionError(('Source hash file {0} not'
' found').format(source_hash))
ret = __salt__['file.extract_hash'](cached_hash_file, '', file_path)
if ret is None:
raise SaltInvocationError(invalid_hash_msg)
else:
items = source_hash.split('=', 1)
if len(items) != 2:
invalid_hash_msg = ('{0}, or it must be a supported protocol'
': {1}').format(invalid_hash_msg,
', '.join(schemes))
raise SaltInvocationError(invalid_hash_msg)
ret['hash_type'], ret['hsum'] = [item.strip().lower() for item in items]
return ret | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute call identifier argument_list identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier call subscript identifier string string_start string_content string_end argument_list identifier identifier if_statement not_operator identifier block raise_statement call identifier argument_list call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call subscript identifier string string_start string_content string_end argument_list identifier string string_start string_end identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier 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 identifier call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier raise_statement call identifier argument_list identifier expression_statement assignment pattern_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end list_comprehension call attribute call attribute identifier identifier argument_list identifier argument_list for_in_clause identifier identifier return_statement identifier | Extract the hash sum, whether it is in a remote hash file, or just a string. |
def read_input_data(filename):
logging.info('Opening file %s for reading input', filename)
input_file = open(filename, 'r')
data = []
labels = []
for line in input_file:
tokens = line.split(',', 1)
labels.append(tokens[0].strip())
data.append(tokens[1].strip())
return labels, data | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list call attribute subscript identifier integer identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute subscript identifier integer identifier argument_list return_statement expression_list identifier identifier | Helper function to get training data |
def task_class(self):
from scenario_player.tasks.base import get_task_class_for_type
root_task_type, _ = self.task
task_class = get_task_class_for_type(root_task_type)
return task_class | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Return the Task class type configured for the scenario. |
def __generate_key(self, config):
cwd = config.get('ssh_path', self._install_directory())
if config.is_affirmative('create', default="yes"):
if not os.path.exists(cwd):
os.makedirs(cwd)
if not os.path.exists(os.path.join(cwd, config.get('keyname'))):
command = "ssh-keygen -t %(type)s -f %(keyname)s -N " % config.to_dict()
lib.call(command, cwd=cwd, output_log_level=logging.DEBUG)
if not config.has('ssh_path'):
config.set('ssh_path', cwd)
config.set('ssh_key_path', os.path.join(config.get('ssh_path'), config.get('keyname'))) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end | Generate the ssh key, and return the ssh config location |
def remove_accounts_from_project(accounts_query, project):
query = accounts_query.filter(date_deleted__isnull=True)
for account in query:
remove_account_from_project(account, project) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier true for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier | Remove accounts from project. |
def _checkblk(name):
blk = __salt__['cmd.run']('blkid -o value -s TYPE {0}'.format(name),
ignore_retcode=True)
return '' if not blk else blk | module function_definition identifier parameters identifier block expression_statement assignment identifier call subscript identifier string string_start string_content string_end argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier true return_statement conditional_expression string string_start string_end not_operator identifier identifier | Check if the blk exists and return its fstype if ok |
def build_lines_data(self, code_obj):
if self.version > 1.4:
linestarts = list(self.opc.findlinestarts(code_obj))
else:
linestarts = [[0, 1]]
self.linestarts = dict(linestarts)
lines = []
LineTuple = namedtuple('LineTuple', ['l_no', 'next'])
_, prev_line_no = linestarts[0]
offset = 0
for start_offset, line_no in linestarts[1:]:
while offset < start_offset:
lines.append(LineTuple(prev_line_no, start_offset))
offset += 1
prev_line_no = line_no
codelen = len(self.code)
while offset < codelen:
lines.append(LineTuple(prev_line_no, codelen))
offset += 1
return lines | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier float block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment identifier list list integer integer expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end expression_statement assignment pattern_list identifier identifier subscript identifier integer expression_statement assignment identifier integer for_statement pattern_list identifier identifier subscript identifier slice integer block while_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier expression_statement augmented_assignment identifier integer expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier while_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier expression_statement augmented_assignment identifier integer return_statement identifier | Generate various line-related helper data. |
def request_reset(self, event):
self.log('Password reset request received:', event.__dict__, lvl=hilight)
user_object = objectmodels['user']
email = event.data.get('email', None)
email_user = None
if email is not None and user_object.count({'mail': email}) > 0:
email_user = user_object.find_one({'mail': email})
if email_user is None:
self._fail(event, msg="Mail address unknown")
return | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier subscript identifier 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 none expression_statement assignment identifier none if_statement boolean_operator comparison_operator identifier none comparison_operator call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end return_statement | An anonymous client requests a password reset |
def clear(self):
self.title = None
self.numbers = np.zeros(0, int)
self.atom_types = []
self.charges = []
self.names = []
self.molecules = np.zeros(0, int)
self.bonds = np.zeros((0, 2), int)
self.bends = np.zeros((0, 3), int)
self.dihedrals = np.zeros((0, 4), int)
self.impropers = np.zeros((0, 4), int)
self.name_cache = {} | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer identifier expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list tuple integer integer identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list tuple integer integer identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list tuple integer integer identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list tuple integer integer identifier expression_statement assignment attribute identifier identifier dictionary | Clear the contents of the data structure |
def getInput():
input = ''
if sys.platform == 'win32':
import msvcrt
if msvcrt.kbhit():
input += msvcrt.getch()
print_(input)
else:
time.sleep(.1)
else:
sock = sys.stdin.fileno()
while len(select.select([sock], [], [], 0.1)[0]) > 0:
input += decode(os.read(sock, 4096))
return input | module function_definition identifier parameters block expression_statement assignment identifier string string_start string_end if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block import_statement dotted_name identifier if_statement call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list float else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list while_statement comparison_operator call identifier argument_list subscript call attribute identifier identifier argument_list list identifier list list float integer integer block expression_statement augmented_assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier integer return_statement identifier | Read the input buffer without blocking the system. |
def concat_generator(filename, up_threshold, low_threshold=10):
txt = ""
for line in tf.gfile.Open(filename):
line = line.strip()
if len(txt) + len(line) + 1 >= up_threshold:
ret = txt
txt = ""
if len(ret) > low_threshold and len(ret) < up_threshold:
yield {"targets": ret}
if not txt:
txt = line
else:
txt = " ".join([txt, line]) | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier string string_start string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator binary_operator binary_operator call identifier argument_list identifier call identifier argument_list identifier integer identifier block expression_statement assignment identifier identifier expression_statement assignment identifier string string_start string_end if_statement boolean_operator comparison_operator call identifier argument_list identifier identifier comparison_operator call identifier argument_list identifier identifier block expression_statement yield dictionary pair string string_start string_content string_end identifier if_statement not_operator identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list identifier identifier | Generate concatenated lines from file upto up_threshold characters. |
def grad(self):
from . import _ndarray_cls
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetGrad(self.handle, ctypes.byref(hdl)))
if hdl.value is None:
return None
return _ndarray_cls(hdl) | module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block return_statement none return_statement call identifier argument_list identifier | Returns gradient buffer attached to this NDArray. |
def find_module(self, fullname, path=None):
basepaths = [""] + list(sys.path)
if fullname.startswith("."):
if path is None:
return None
fullname = fullname[1:]
basepaths.insert(0, path)
fullpath = os.path.join(*fullname.split("."))
for head in basepaths:
path = os.path.join(head, fullpath)
filepath = path + self.ext
dirpath = os.path.join(path, "__init__" + self.ext)
if os.path.exists(filepath):
self.run_compiler(filepath)
return None
if os.path.exists(dirpath):
self.run_compiler(path)
return None
return None | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier binary_operator list string string_start string_end call identifier argument_list attribute identifier identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block if_statement comparison_operator identifier none block return_statement none expression_statement assignment identifier subscript identifier slice integer expression_statement call attribute identifier identifier argument_list integer identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list_splat call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier binary_operator identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier binary_operator string string_start string_content string_end attribute identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement none if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement none return_statement none | Searches for a Coconut file of the given name and compiles it. |
def read_property(f, endianness="<"):
prop_name = types.String.read(f, endianness)
prop_data_type = types.tds_data_types[types.Uint32.read(f, endianness)]
value = prop_data_type.read(f, endianness)
log.debug("Property %s: %r", prop_name, value)
return prop_name, value | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier subscript attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier return_statement expression_list identifier identifier | Read a property from a segment's metadata |
def append_payload(self, payload: Payload) -> Payload:
encoding = payload.headers.get(CONTENT_ENCODING, '').lower()
if encoding and encoding not in ('deflate', 'gzip', 'identity'):
raise RuntimeError('unknown content encoding: {}'.format(encoding))
if encoding == 'identity':
encoding = None
te_encoding = payload.headers.get(
CONTENT_TRANSFER_ENCODING, '').lower()
if te_encoding not in ('', 'base64', 'quoted-printable', 'binary'):
raise RuntimeError('unknown content transfer encoding: {}'
''.format(te_encoding))
if te_encoding == 'binary':
te_encoding = None
size = payload.size
if size is not None and not (encoding or te_encoding):
payload.headers[CONTENT_LENGTH] = str(size)
self._parts.append((payload, encoding, te_encoding))
return payload | module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier string string_start string_end identifier argument_list if_statement boolean_operator identifier comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier none expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier string string_start string_end identifier argument_list if_statement comparison_operator identifier tuple string string_start string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_end identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier none expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator comparison_operator identifier none not_operator parenthesized_expression boolean_operator identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier identifier return_statement identifier | Adds a new body part to multipart writer. |
def drop_streams(streams, kdims, keys):
stream_params = stream_parameters(streams)
inds, dims = zip(*[(ind, kdim) for ind, kdim in enumerate(kdims)
if kdim not in stream_params])
get = operator.itemgetter(*inds)
keys = (get(k) for k in keys)
return dims, ([wrap_tuple(k) for k in keys] if len(inds) == 1 else list(keys)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list list_splat list_comprehension tuple identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier if_clause comparison_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier expression_statement assignment identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier return_statement expression_list identifier parenthesized_expression conditional_expression list_comprehension call identifier argument_list identifier for_in_clause identifier identifier comparison_operator call identifier argument_list identifier integer call identifier argument_list identifier | Drop any dimensioned streams from the keys and kdims. |
def _move_centroids(self):
for k in range(self.n_clusters):
if k in self.clusters:
centroid = np.mean(self._X[self.clusters == k, :], axis=0)
self.centroids[k] = centroid
else:
self.n_clusters-=1
self.centroids = self.centroids[:self.n_clusters]
self.clusters-=1
k-=1 | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier comparison_operator attribute identifier identifier identifier slice keyword_argument identifier integer expression_statement assignment subscript attribute identifier identifier identifier identifier else_clause block expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer expression_statement augmented_assignment identifier integer | Calculate new centroids as the means of the samples in each cluster |
def suppressConsoleOut(meth):
@wraps(meth)
def decorate(*args, **kwargs):
_stdout = sys.stdout
fptr = open(os.devnull, 'w')
sys.stdout = fptr
try:
return meth(*args, **kwargs)
except Exception as e:
raise e
finally:
sys.stdout = _stdout
return decorate | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier try_statement block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement identifier finally_clause block expression_statement assignment attribute identifier identifier identifier return_statement identifier | Disable console output during the method is run. |
def _lookup_style(element, names):
return _STYLES.get('_'+element, '') + \
''.join([_STYLES.get(name, '') for name in names]) | module function_definition identifier parameters identifier identifier block return_statement binary_operator call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier string string_start string_end call attribute string string_start string_end identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier string string_start string_end for_in_clause identifier identifier | Lookup style by either element name or the list of classes |
async def release_name_async(self, bus_name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
"releases a registered bus name."
assert self.loop != None, "no event loop to attach coroutine to"
return \
await self.connection.bus_release_name_async(bus_name, error = error, timeout = timeout) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier attribute identifier identifier block expression_statement string string_start string_content string_end assert_statement comparison_operator attribute identifier identifier none string string_start string_content string_end return_statement line_continuation await call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier | releases a registered bus name. |
def open(self):
self._connection = \
amqp.Connection(host='%s:%s' % (self.hostname, self.port),
userid=self.username, password=self.password,
virtual_host=self.virtual_host, insist=False)
self.channel = self._connection.channel() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier line_continuation call attribute identifier identifier argument_list keyword_argument identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier false expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list | Open a connection to the AMQP compliant broker. |
def uninstall(self, bug: Bug) -> bool:
r = self.__api.post('bugs/{}/uninstall'.format(bug.name))
raise NotImplementedError | module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier raise_statement identifier | Uninstalls the Docker image associated with a given bug. |
def create_response(version, status, headers):
message = []
message.append('HTTP/{} {}\r\n'.format(version, status))
for name, value in headers:
message.append(name)
message.append(': ')
message.append(value)
message.append('\r\n')
message.append('\r\n')
return s2b(''.join(message)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier identifier for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end return_statement call identifier argument_list call attribute string string_start string_end identifier argument_list identifier | Create a HTTP response header. |
def _merge_nbval_coverage_data(cov):
if not cov:
return
suffix = _make_suffix(cov)
if suffix is True:
return
filename = cov.data_files.filename + '.' + suffix
nbval_data = coverage.CoverageData(debug=cov.debug)
try:
nbval_data.read_file(os.path.abspath(filename))
except coverage.CoverageException:
return
aliases = None
if cov.config.paths:
aliases = coverage.files.PathAliases()
for paths in cov.config.paths.values():
result = paths[0]
for pattern in paths[1:]:
aliases.add(pattern, result)
cov.data.update(nbval_data, aliases=aliases)
coverage.misc.file_be_gone(filename) | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier true block return_statement expression_statement assignment identifier binary_operator binary_operator attribute attribute identifier identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier except_clause attribute identifier identifier block return_statement expression_statement assignment identifier none if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement assignment identifier subscript identifier integer for_statement identifier subscript identifier slice integer block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Merge nbval coverage data into pytest-cov data. |
def extern_store_tuple(self, context_handle, vals_ptr, vals_len):
c = self._ffi.from_handle(context_handle)
return c.to_value(tuple(c.from_value(val[0]) for val in self._ffi.unpack(vals_ptr, vals_len))) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list call identifier generator_expression call attribute identifier identifier argument_list subscript identifier integer for_in_clause identifier call attribute attribute identifier identifier identifier argument_list identifier identifier | Given storage and an array of Handles, return a new Handle to represent the list. |
def visit(self, node):
for child in node:
yield child
for subchild in self.visit(child):
yield subchild | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement yield identifier for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement yield identifier | Returns a generator that walks all children recursively. |
def league_scores(self, total_data, time):
data = []
for league, score in self.supported_leagues(total_data):
item = {'league': league, 'homeTeamName': score['homeTeamName'],
'goalsHomeTeam': score['result']['goalsHomeTeam'],
'goalsAwayTeam': score['result']['goalsAwayTeam'],
'awayTeamName': score['awayTeamName']}
data.append(item)
self.generate_output({'league_scores': data, 'time': time}) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end subscript 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 dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Store output of fixtures based on league and time to a JSON file |
def raw_tag(name, value):
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value | module function_definition identifier parameters identifier identifier block return_statement binary_operator binary_operator call attribute identifier identifier argument_list string string_start string_content string_end line_continuation call attribute call identifier argument_list identifier identifier argument_list integer keyword_argument identifier string string_start string_content string_end line_continuation identifier | Create a DMAP tag with raw data. |
def _generate_grid(self):
grid_axes = []
for _, param in self.tunables:
grid_axes.append(param.get_grid_axis(self.grid_width))
return grid_axes | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Get the all possible values for each of the tunables. |
def from_stream(cls, f, **kwargs):
lines = lines_from_stream(f)
if 'meta' not in kwargs:
kwargs['meta'] = {'from': 'stream'}
kwargs['meta']['filepath'] = f.name if hasattr(f, 'name') else None
return cls(lines, **kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end conditional_expression attribute identifier identifier call identifier argument_list identifier string string_start string_content string_end none return_statement call identifier argument_list identifier dictionary_splat identifier | Create an editor instance from a file stream. |
def _where(self, filter_fn):
assert callable(filter_fn), 'filter_fn needs to be callable'
return VList(i for i in self if filter_fn(i())) | module function_definition identifier parameters identifier identifier block assert_statement call identifier argument_list identifier string string_start string_content string_end return_statement call identifier generator_expression identifier for_in_clause identifier identifier if_clause call identifier argument_list call identifier argument_list | use this to filter VLists, simply provide a filter function to filter the current found objects |
def next(self):
self._parse_block()
if self._remaining > 0:
self._remaining -= 1
return six.next(self._iter_rows) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier integer block expression_statement augmented_assignment attribute identifier identifier integer return_statement call attribute identifier identifier argument_list attribute identifier identifier | Get the next row in the page. |
def enqueue(self, item_type, item):
with self.enlock:
self.queue[item_type].append(item) | module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier | Queue a new data item, make item iterable |
def UndoTransaction(self):
from Ucs import ConfigMap
self._transactionInProgress = False
self._configMap = ConfigMap() | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier call identifier argument_list | Cancels any running transaction. |
def project_drawn(cb, msg):
stream = cb.streams[0]
old_data = stream.data
stream.update(data=msg['data'])
element = stream.element
stream.update(data=old_data)
proj = cb.plot.projection
if not isinstance(element, _Element) or element.crs == proj:
return None
crs = element.crs
element.crs = proj
return project(element, projection=crs) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement boolean_operator not_operator call identifier argument_list identifier identifier comparison_operator attribute identifier identifier identifier block return_statement none expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement call identifier argument_list identifier keyword_argument identifier identifier | Projects a drawn element to the declared coordinate system |
def load_handler(self):
handler_path = self.handler_name.split(".")
handler_module = __import__(".".join(handler_path[:-1]), {}, {}, str(handler_path[-1]))
self.handler = getattr(handler_module, handler_path[-1])() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier slice unary_operator integer dictionary dictionary call identifier argument_list subscript identifier unary_operator integer expression_statement assignment attribute identifier identifier call call identifier argument_list identifier subscript identifier unary_operator integer argument_list | Load the detected handler. |
def recv_rpc(self, context, payload):
logger.debug("Adding RPC payload to ControlBuffer queue: %s", payload)
self.buf.put(('rpc', (context, payload)))
with self.cv:
self.cv.notifyAll() | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple string string_start string_content string_end tuple identifier identifier with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list | Call from any thread |
def _maybe_connect(self, node_id):
with self._lock:
conn = self._conns.get(node_id)
if conn is None:
broker = self.cluster.broker_metadata(node_id)
assert broker, 'Broker id %s not in current metadata' % (node_id,)
log.debug("Initiating connection to node %s at %s:%s",
node_id, broker.host, broker.port)
host, port, afi = get_ip_port_afi(broker.host)
cb = WeakMethod(self._conn_state_change)
conn = BrokerConnection(host, broker.port, afi,
state_change_callback=cb,
node_id=node_id,
**self.config)
self._conns[node_id] = conn
elif self._should_recycle_connection(conn):
self._conns.pop(node_id)
return False
elif conn.connected():
return True
conn.connect()
return conn.connected() | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier assert_statement identifier binary_operator string string_start string_content string_end tuple identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier elif_clause call attribute identifier identifier argument_list identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement false elif_clause call attribute identifier identifier argument_list block return_statement true expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list | Idempotent non-blocking connection attempt to the given node id. |
def uniquenessRatio(self, value):
if value >= 5 and value <= 15:
self._uniqueness = value
else:
raise InvalidUniquenessRatioError("Uniqueness ratio must be "
"between 5 and 15.")
self._replace_bm() | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block expression_statement assignment attribute identifier identifier identifier else_clause block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list | Set private ``_uniqueness`` and reset ``_block_matcher``. |
def _run_workflow(items, paired, workflow_file, work_dir):
utils.remove_safe(os.path.join(work_dir, "workspace"))
data = paired.tumor_data if paired else items[0]
cmd = [utils.get_program_python("configManta.py"), workflow_file, "-m", "local", "-j", dd.get_num_cores(data)]
do.run(cmd, "Run manta SV analysis")
utils.remove_safe(os.path.join(work_dir, "workspace")) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier conditional_expression attribute identifier identifier identifier subscript identifier integer expression_statement assignment identifier list call attribute identifier identifier argument_list string string_start string_content string_end identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end | Run manta analysis inside prepared workflow directory. |
def _get_cibpath():
cibpath = os.path.join(__opts__['cachedir'], 'pcs', __env__)
log.trace('cibpath: %s', cibpath)
return cibpath | module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier | Get the path to the directory on the minion where CIB's are saved |
def _format_object(obj, format_type=None):
if json_api_settings.FORMAT_KEYS is not None:
return format_keys(obj, format_type)
return format_field_names(obj, format_type) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator attribute identifier identifier none block return_statement call identifier argument_list identifier identifier return_statement call identifier argument_list identifier identifier | Depending on settings calls either `format_keys` or `format_field_names` |
def to_bigquery_field(self, name_case=DdlParseBase.NAME_CASE.original):
col_name = self.get_name(name_case)
mode = self.bigquery_mode
if self.array_dimensional <= 1:
type = self.bigquery_legacy_data_type
else:
type = "RECORD"
fields = OrderedDict()
fields_cur = fields
for i in range(1, self.array_dimensional):
is_last = True if i == self.array_dimensional - 1 else False
fields_cur['fields'] = [OrderedDict()]
fields_cur = fields_cur['fields'][0]
fields_cur['name'] = "dimension_{}".format(i)
fields_cur['type'] = self.bigquery_legacy_data_type if is_last else "RECORD"
fields_cur['mode'] = self.bigquery_mode if is_last else "REPEATED"
col = OrderedDict()
col['name'] = col_name
col['type'] = type
col['mode'] = mode
if self.array_dimensional > 1:
col['fields'] = fields['fields']
return json.dumps(col) | module function_definition identifier parameters identifier default_parameter identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier identifier for_statement identifier call identifier argument_list integer attribute identifier identifier block expression_statement assignment identifier conditional_expression true comparison_operator identifier binary_operator attribute identifier identifier integer false expression_statement assignment subscript identifier string string_start string_content string_end list call identifier argument_list expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end conditional_expression attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end conditional_expression attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier | Generate BigQuery JSON field define |
def _distarray_missing(self, xc, xd, cdiffs):
cindices = []
dindices = []
for i in range(self._datalen):
cindices.append(np.where(np.isnan(xc[i]))[0])
dindices.append(np.where(np.isnan(xd[i]))[0])
if self.n_jobs != 1:
dist_array = Parallel(n_jobs=self.n_jobs)(delayed(get_row_missing)(
xc, xd, cdiffs, index, cindices, dindices) for index in range(self._datalen))
else:
dist_array = [get_row_missing(xc, xd, cdiffs, index, cindices, dindices)
for index in range(self._datalen)]
return np.array(dist_array) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list subscript call attribute identifier identifier argument_list call attribute identifier identifier argument_list subscript identifier identifier integer expression_statement call attribute identifier identifier argument_list subscript call attribute identifier identifier argument_list call attribute identifier identifier argument_list subscript identifier identifier integer if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call call identifier argument_list keyword_argument identifier attribute identifier identifier generator_expression call call identifier argument_list identifier argument_list identifier identifier identifier identifier identifier identifier for_in_clause identifier call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier list_comprehension call identifier argument_list identifier identifier identifier identifier identifier identifier for_in_clause identifier call identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier | Distance array calculation for data with missing values |
def to_ufo_background_image(self, ufo_glyph, layer):
image = layer.backgroundImage
if image is None:
return
ufo_image = ufo_glyph.image
ufo_image.fileName = image.path
ufo_image.transformation = image.transform
ufo_glyph.lib[CROP_KEY] = list(image.crop)
ufo_glyph.lib[LOCKED_KEY] = image.locked
ufo_glyph.lib[ALPHA_KEY] = image.alpha | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier attribute identifier identifier | Copy the backgound image from the GSLayer to the UFO Glyph. |
def list(gandi, domain, limit):
options = {'items_per_page': limit}
mailboxes = gandi.mail.list(domain, options)
output_list(gandi, [mbox['login'] for mbox in mailboxes])
return mailboxes | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call identifier argument_list identifier list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier identifier return_statement identifier | List mailboxes created on a domain. |
def make_html_page(self, valumap):
logger.info('Making an html report using template %r.', self.html_template)
fh = open(self.html_template)
template = fh.read()
fh.close()
parts = []
for sr in self.subreports:
report_data = [item.html for item in sr.report_data if item.html]
if report_data:
parts.append('\n<h2>{1}</h2>\n'.format(sr.title, sr.reptext))
parts.extend(report_data)
parts.append('\n<hr/>')
valumap['subreports'] = '\n'.join(parts)
html_page = Template(template).safe_substitute(valumap)
return TextPart(fmt='html', text=html_page, ext='html') | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier if_clause attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list identifier return_statement call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end | Builds the report as html page, using the template page from file. |
def CheckRequestsForCompletion(self, requests):
subjects = [r.session_id.Add("state") for r in requests]
statuses_found = {}
for subject, result in self.MultiResolvePrefix(subjects,
self.FLOW_STATUS_PREFIX):
for predicate, _, _ in result:
request_nr = int(predicate.split(":")[-1], 16)
statuses_found.setdefault(subject, set()).add(request_nr)
status_available = set()
for r in requests:
if r.request_id in statuses_found.get(r.session_id.Add("state"), set()):
status_available.add(r)
return status_available | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_in_clause identifier identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier attribute identifier identifier block for_statement pattern_list identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list subscript call attribute identifier identifier argument_list string string_start string_content string_end unary_operator integer integer expression_statement call attribute call attribute identifier identifier argument_list identifier call identifier argument_list identifier argument_list identifier expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Checks if there is a status message queued for a number of requests. |
def app(environ, start_response):
r = HttpRequestHandler(environ, start_response, Router).dispatch()
return r | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier identifier argument_list return_statement identifier | Function called by the WSGI server. |
def __notify(self):
if self.__callback is not None:
try:
self.__callback(
self._done_event.data,
self._done_event.exception,
self.__extra,
)
except Exception as ex:
self._logger.exception("Error calling back method: %s", ex) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block try_statement block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier | Notify the given callback about the result of the execution |
def insert_tracking_record(self):
if self._insert_tracking_record is None:
self._insert_tracking_record = self._prepare_insert(
tmpl=self._insert_values_tmpl,
placeholder_for_id=True,
record_class=self.tracking_record_class,
field_names=self.tracking_record_field_names,
)
return self._insert_tracking_record | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier true keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier return_statement attribute identifier identifier | SQL statement that inserts tracking records. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.