code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def aliased(aliased_class):
"""
Decorator function that *must* be used in combination with @alias
decorator. This class will make the magic happen!
@aliased classes will have their aliased method (via @alias) actually
aliased.
This method simply iterates over the member attributes of 'aliased_cl... | def function[aliased, parameter[aliased_class]]:
constant[
Decorator function that *must* be used in combination with @alias
decorator. This class will make the magic happen!
@aliased classes will have their aliased method (via @alias) actually
aliased.
This method simply iterates over the m... | keyword[def] identifier[aliased] ( identifier[aliased_class] ):
literal[string]
identifier[original_methods] = identifier[aliased_class] . identifier[__dict__] . identifier[copy] ()
identifier[original_methods_set] = identifier[set] ( identifier[original_methods] )
keyword[for] identifier[name] ... | def aliased(aliased_class):
"""
Decorator function that *must* be used in combination with @alias
decorator. This class will make the magic happen!
@aliased classes will have their aliased method (via @alias) actually
aliased.
This method simply iterates over the member attributes of 'aliased_cl... |
def prepare(self, data_source):
"""
Called with the training data.
@param data_source: Either a pandas.DataFrame or a file-like object.
"""
dataframe = self.__get_dataframe(data_source, use_target=True)
self.__config.get_data_model().set_features_types_from_dataframe(data... | def function[prepare, parameter[self, data_source]]:
constant[
Called with the training data.
@param data_source: Either a pandas.DataFrame or a file-like object.
]
variable[dataframe] assign[=] call[name[self].__get_dataframe, parameter[name[data_source]]]
call[call[name... | keyword[def] identifier[prepare] ( identifier[self] , identifier[data_source] ):
literal[string]
identifier[dataframe] = identifier[self] . identifier[__get_dataframe] ( identifier[data_source] , identifier[use_target] = keyword[True] )
identifier[self] . identifier[__config] . identifier[... | def prepare(self, data_source):
"""
Called with the training data.
@param data_source: Either a pandas.DataFrame or a file-like object.
"""
dataframe = self.__get_dataframe(data_source, use_target=True)
self.__config.get_data_model().set_features_types_from_dataframe(dataframe)
d... |
def r_dts_collection(self, objectId=None):
""" DTS Collection Metadata reply for given objectId
:param objectId: Collection Identifier
:return: JSON Format of DTS Collection
"""
try:
j = self.resolver.getMetadata(objectId=objectId).export(Mimetypes.JSON.DTS.Std)
... | def function[r_dts_collection, parameter[self, objectId]]:
constant[ DTS Collection Metadata reply for given objectId
:param objectId: Collection Identifier
:return: JSON Format of DTS Collection
]
<ast.Try object at 0x7da204621060>
return[name[j]] | keyword[def] identifier[r_dts_collection] ( identifier[self] , identifier[objectId] = keyword[None] ):
literal[string]
keyword[try] :
identifier[j] = identifier[self] . identifier[resolver] . identifier[getMetadata] ( identifier[objectId] = identifier[objectId] ). identifier[export] ( ... | def r_dts_collection(self, objectId=None):
""" DTS Collection Metadata reply for given objectId
:param objectId: Collection Identifier
:return: JSON Format of DTS Collection
"""
try:
j = self.resolver.getMetadata(objectId=objectId).export(Mimetypes.JSON.DTS.Std)
j = json... |
def on_message(self, handler, msg):
""" In remote debugging mode this simply acts as a forwarding
proxy for the two clients.
"""
if self.remote_debugging:
#: Forward to other clients
for h in self.handlers:
if h != handler:
h.wr... | def function[on_message, parameter[self, handler, msg]]:
constant[ In remote debugging mode this simply acts as a forwarding
proxy for the two clients.
]
if name[self].remote_debugging begin[:]
for taget[name[h]] in starred[name[self].handlers] begin[:]
... | keyword[def] identifier[on_message] ( identifier[self] , identifier[handler] , identifier[msg] ):
literal[string]
keyword[if] identifier[self] . identifier[remote_debugging] :
keyword[for] identifier[h] keyword[in] identifier[self] . identifier[handlers] :
... | def on_message(self, handler, msg):
""" In remote debugging mode this simply acts as a forwarding
proxy for the two clients.
"""
if self.remote_debugging:
#: Forward to other clients
for h in self.handlers:
if h != handler:
h.write_message(msg, True) ... |
def gen_file_lines(path, mode='rUb', strip_eol=True, ascii=True, eol='\n'):
"""Generate a sequence of "documents" from the lines in a file
Arguments:
path (file or str): path to a file or an open file_obj ready to be read
mode (str): file mode to open a file in
strip_eol (bool): whether to st... | def function[gen_file_lines, parameter[path, mode, strip_eol, ascii, eol]]:
constant[Generate a sequence of "documents" from the lines in a file
Arguments:
path (file or str): path to a file or an open file_obj ready to be read
mode (str): file mode to open a file in
strip_eol (bool): whe... | keyword[def] identifier[gen_file_lines] ( identifier[path] , identifier[mode] = literal[string] , identifier[strip_eol] = keyword[True] , identifier[ascii] = keyword[True] , identifier[eol] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[path] , identifier[str] ):
... | def gen_file_lines(path, mode='rUb', strip_eol=True, ascii=True, eol='\n'):
"""Generate a sequence of "documents" from the lines in a file
Arguments:
path (file or str): path to a file or an open file_obj ready to be read
mode (str): file mode to open a file in
strip_eol (bool): whether to st... |
def main(testfiles=None, action=printer):
"""testfiles can be None, in which case the command line arguments are used as filenames.
testfiles can be a string, in which case that file is parsed.
testfiles can be a list.
In all cases, the filenames will be globbed.
If more than one file is parsed... | def function[main, parameter[testfiles, action]]:
constant[testfiles can be None, in which case the command line arguments are used as filenames.
testfiles can be a string, in which case that file is parsed.
testfiles can be a list.
In all cases, the filenames will be globbed.
If more than one f... | keyword[def] identifier[main] ( identifier[testfiles] = keyword[None] , identifier[action] = identifier[printer] ):
literal[string]
identifier[testfiles] = identifier[get_filename_list] ( identifier[testfiles] )
identifier[print] ( identifier[testfiles] )
keyword[if] identifier[action] :
... | def main(testfiles=None, action=printer):
"""testfiles can be None, in which case the command line arguments are used as filenames.
testfiles can be a string, in which case that file is parsed.
testfiles can be a list.
In all cases, the filenames will be globbed.
If more than one file is parsed succ... |
def persist(self, name, project=None, drop_model=False, **kwargs):
"""
Persist the execution into a new model.
:param name: model name
:param project: name of the project
:param drop_model: drop model before creation
"""
return super(ODPSModelExpr, self).persist(... | def function[persist, parameter[self, name, project, drop_model]]:
constant[
Persist the execution into a new model.
:param name: model name
:param project: name of the project
:param drop_model: drop model before creation
]
return[call[call[name[super], parameter[na... | keyword[def] identifier[persist] ( identifier[self] , identifier[name] , identifier[project] = keyword[None] , identifier[drop_model] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[super] ( identifier[ODPSModelExpr] , identifier[self] ). identifier[persist] (... | def persist(self, name, project=None, drop_model=False, **kwargs):
"""
Persist the execution into a new model.
:param name: model name
:param project: name of the project
:param drop_model: drop model before creation
"""
return super(ODPSModelExpr, self).persist(name, pr... |
def enablePackrat():
"""Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code... | def function[enablePackrat, parameter[]]:
constant[Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-execut... | keyword[def] identifier[enablePackrat] ():
literal[string]
keyword[if] keyword[not] identifier[ParserElement] . identifier[_packratEnabled] :
identifier[ParserElement] . identifier[_packratEnabled] = keyword[True]
identifier[ParserElement] . identifier[_parse] = identif... | def enablePackrat():
"""Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. M... |
def get_counter(data, base):
"""
See setCounters() / getCounters() methods in IJ source, ij/gui/PointRoi.java.
"""
b0 = data[base]
b1 = data[base + 1]
b2 = data[base + 2]
b3 = data[base + 3]
counter = b3
position = (b1 << 8) + b2
return counter, position | def function[get_counter, parameter[data, base]]:
constant[
See setCounters() / getCounters() methods in IJ source, ij/gui/PointRoi.java.
]
variable[b0] assign[=] call[name[data]][name[base]]
variable[b1] assign[=] call[name[data]][binary_operation[name[base] + constant[1]]]
vari... | keyword[def] identifier[get_counter] ( identifier[data] , identifier[base] ):
literal[string]
identifier[b0] = identifier[data] [ identifier[base] ]
identifier[b1] = identifier[data] [ identifier[base] + literal[int] ]
identifier[b2] = identifier[data] [ identifier[base] + literal[int] ]
id... | def get_counter(data, base):
"""
See setCounters() / getCounters() methods in IJ source, ij/gui/PointRoi.java.
"""
b0 = data[base]
b1 = data[base + 1]
b2 = data[base + 2]
b3 = data[base + 3]
counter = b3
position = (b1 << 8) + b2
return (counter, position) |
def _savepath(self, filename):
"""
Returns the full path for saving the file, adding an extension
and making the filename unique as necessary.
"""
(basename, ext) = os.path.splitext(filename)
basename = basename if (ext in self.extensions) else filename
ext = ext ... | def function[_savepath, parameter[self, filename]]:
constant[
Returns the full path for saving the file, adding an extension
and making the filename unique as necessary.
]
<ast.Tuple object at 0x7da1afe0dea0> assign[=] call[name[os].path.splitext, parameter[name[filename]]]
... | keyword[def] identifier[_savepath] ( identifier[self] , identifier[filename] ):
literal[string]
( identifier[basename] , identifier[ext] )= identifier[os] . identifier[path] . identifier[splitext] ( identifier[filename] )
identifier[basename] = identifier[basename] keyword[if] ( identifier... | def _savepath(self, filename):
"""
Returns the full path for saving the file, adding an extension
and making the filename unique as necessary.
"""
(basename, ext) = os.path.splitext(filename)
basename = basename if ext in self.extensions else filename
ext = ext if ext in self.ext... |
def _run_init(
argv,
flags_parser,
):
"""Does one-time initialization and re-parses flags on rerun."""
if _run_init.done:
return flags_parser(argv)
command_name.make_process_name_useful()
# Set up absl logging handler.
logging.use_absl_handler()
args = _register_and_parse_flags_with_usage(
... | def function[_run_init, parameter[argv, flags_parser]]:
constant[Does one-time initialization and re-parses flags on rerun.]
if name[_run_init].done begin[:]
return[call[name[flags_parser], parameter[name[argv]]]]
call[name[command_name].make_process_name_useful, parameter[]]
cal... | keyword[def] identifier[_run_init] (
identifier[argv] ,
identifier[flags_parser] ,
):
literal[string]
keyword[if] identifier[_run_init] . identifier[done] :
keyword[return] identifier[flags_parser] ( identifier[argv] )
identifier[command_name] . identifier[make_process_name_useful] ()
identif... | def _run_init(argv, flags_parser):
"""Does one-time initialization and re-parses flags on rerun."""
if _run_init.done:
return flags_parser(argv) # depends on [control=['if'], data=[]]
command_name.make_process_name_useful()
# Set up absl logging handler.
logging.use_absl_handler()
args ... |
def _update_api_client(self, api_parent_class=None):
"""Updates the ApiClient object of specified parent api (or all of them)"""
clients = ([self.api_clients[api_parent_class]]
if api_parent_class else self.api_clients.values())
for api_client in clients:
api_clie... | def function[_update_api_client, parameter[self, api_parent_class]]:
constant[Updates the ApiClient object of specified parent api (or all of them)]
variable[clients] assign[=] <ast.IfExp object at 0x7da1b040ffa0>
for taget[name[api_client]] in starred[name[clients]] begin[:]
nam... | keyword[def] identifier[_update_api_client] ( identifier[self] , identifier[api_parent_class] = keyword[None] ):
literal[string]
identifier[clients] =([ identifier[self] . identifier[api_clients] [ identifier[api_parent_class] ]]
keyword[if] identifier[api_parent_class] keyword[else] id... | def _update_api_client(self, api_parent_class=None):
"""Updates the ApiClient object of specified parent api (or all of them)"""
clients = [self.api_clients[api_parent_class]] if api_parent_class else self.api_clients.values()
for api_client in clients:
api_client.configuration.host = self.config.ge... |
def in_bulk(self, id_list):
"""
Returns a dictionary mapping each of the given IDs to the object with
that ID.
"""
if not id_list:
return {}
qs = self._clone()
qs.add_filter(('pk__in', id_list))
qs._clear_ordering(force_empty=True)
retu... | def function[in_bulk, parameter[self, id_list]]:
constant[
Returns a dictionary mapping each of the given IDs to the object with
that ID.
]
if <ast.UnaryOp object at 0x7da1b0e6c0a0> begin[:]
return[dictionary[[], []]]
variable[qs] assign[=] call[name[self]._clone,... | keyword[def] identifier[in_bulk] ( identifier[self] , identifier[id_list] ):
literal[string]
keyword[if] keyword[not] identifier[id_list] :
keyword[return] {}
identifier[qs] = identifier[self] . identifier[_clone] ()
identifier[qs] . identifier[add_filter] (( litera... | def in_bulk(self, id_list):
"""
Returns a dictionary mapping each of the given IDs to the object with
that ID.
"""
if not id_list:
return {} # depends on [control=['if'], data=[]]
qs = self._clone()
qs.add_filter(('pk__in', id_list))
qs._clear_ordering(force_empty=Tr... |
def should_break_here(self, frame):
"""Check wether there is a breakpoint at this frame."""
# Next line commented out for performance
#_logger.b_debug("should_break_here(filename=%s, lineno=%s) with breaks=%s",
# frame.f_code.co_filename,
# frame.f_l... | def function[should_break_here, parameter[self, frame]]:
constant[Check wether there is a breakpoint at this frame.]
variable[c_file_name] assign[=] call[name[self].canonic, parameter[name[frame].f_code.co_filename]]
if <ast.UnaryOp object at 0x7da1b23466b0> begin[:]
return[constant[Fals... | keyword[def] identifier[should_break_here] ( identifier[self] , identifier[frame] ):
literal[string]
identifier[c_file_name] = identifier[self] . identifier[canonic] ( identifier[frame] . identifier[f_code] . identifier[co_filename] )
keyword[i... | def should_break_here(self, frame):
"""Check wether there is a breakpoint at this frame."""
# Next line commented out for performance
#_logger.b_debug("should_break_here(filename=%s, lineno=%s) with breaks=%s",
# frame.f_code.co_filename,
# frame.f_lineno,
# ... |
def generate_folder_names(self):
"""Set appropriate folder names."""
self.project_dir = os.path.join(prms.Paths.outdatadir, self.project)
self.batch_dir = os.path.join(self.project_dir, self.name)
self.raw_dir = os.path.join(self.batch_dir, "raw_data") | def function[generate_folder_names, parameter[self]]:
constant[Set appropriate folder names.]
name[self].project_dir assign[=] call[name[os].path.join, parameter[name[prms].Paths.outdatadir, name[self].project]]
name[self].batch_dir assign[=] call[name[os].path.join, parameter[name[self].project... | keyword[def] identifier[generate_folder_names] ( identifier[self] ):
literal[string]
identifier[self] . identifier[project_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[prms] . identifier[Paths] . identifier[outdatadir] , identifier[self] . identifier[project] )
... | def generate_folder_names(self):
"""Set appropriate folder names."""
self.project_dir = os.path.join(prms.Paths.outdatadir, self.project)
self.batch_dir = os.path.join(self.project_dir, self.name)
self.raw_dir = os.path.join(self.batch_dir, 'raw_data') |
def drop_table(self, model, cascade=True):
"""Drop model and table from database.
>> migrator.drop_table(model, cascade=True)
"""
del self.orm[model._meta.table_name]
self.ops.append(self.migrator.drop_table(model, cascade)) | def function[drop_table, parameter[self, model, cascade]]:
constant[Drop model and table from database.
>> migrator.drop_table(model, cascade=True)
]
<ast.Delete object at 0x7da2054a4040>
call[name[self].ops.append, parameter[call[name[self].migrator.drop_table, parameter[name[model... | keyword[def] identifier[drop_table] ( identifier[self] , identifier[model] , identifier[cascade] = keyword[True] ):
literal[string]
keyword[del] identifier[self] . identifier[orm] [ identifier[model] . identifier[_meta] . identifier[table_name] ]
identifier[self] . identifier[ops] . ident... | def drop_table(self, model, cascade=True):
"""Drop model and table from database.
>> migrator.drop_table(model, cascade=True)
"""
del self.orm[model._meta.table_name]
self.ops.append(self.migrator.drop_table(model, cascade)) |
def hash_full_tree(self, leaves):
"""Hash a set of leaves representing a valid full tree."""
root_hash, hashes = self._hash_full(leaves, 0, len(leaves))
assert len(hashes) == count_bits_set(len(leaves))
assert (self._hash_fold(hashes) == root_hash if hashes else
root_hash... | def function[hash_full_tree, parameter[self, leaves]]:
constant[Hash a set of leaves representing a valid full tree.]
<ast.Tuple object at 0x7da1b2586500> assign[=] call[name[self]._hash_full, parameter[name[leaves], constant[0], call[name[len], parameter[name[leaves]]]]]
assert[compare[call[name[le... | keyword[def] identifier[hash_full_tree] ( identifier[self] , identifier[leaves] ):
literal[string]
identifier[root_hash] , identifier[hashes] = identifier[self] . identifier[_hash_full] ( identifier[leaves] , literal[int] , identifier[len] ( identifier[leaves] ))
keyword[assert] identifie... | def hash_full_tree(self, leaves):
"""Hash a set of leaves representing a valid full tree."""
(root_hash, hashes) = self._hash_full(leaves, 0, len(leaves))
assert len(hashes) == count_bits_set(len(leaves))
assert self._hash_fold(hashes) == root_hash if hashes else root_hash == self.hash_empty()
retur... |
def p_pointer(self, p):
'pointer : identifier LBRACKET expression RBRACKET'
p[0] = Pointer(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | def function[p_pointer, parameter[self, p]]:
constant[pointer : identifier LBRACKET expression RBRACKET]
call[name[p]][constant[0]] assign[=] call[name[Pointer], parameter[call[name[p]][constant[1]], call[name[p]][constant[3]]]]
call[name[p].set_lineno, parameter[constant[0], call[name[p].lineno... | keyword[def] identifier[p_pointer] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[Pointer] ( identifier[p] [ literal[int] ], identifier[p] [ literal[int] ], identifier[lineno] = identifier[p] . identifier[lineno] ( literal[int] ))
identifie... | def p_pointer(self, p):
"""pointer : identifier LBRACKET expression RBRACKET"""
p[0] = Pointer(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
async def googlecast(dev: Device, target, value):
"""Return Googlecast settings."""
if target and value:
click.echo("Setting %s = %s" % (target, value))
await dev.set_googlecast_settings(target, value)
print_settings(await dev.get_googlecast_settings()) | <ast.AsyncFunctionDef object at 0x7da20cabebf0> | keyword[async] keyword[def] identifier[googlecast] ( identifier[dev] : identifier[Device] , identifier[target] , identifier[value] ):
literal[string]
keyword[if] identifier[target] keyword[and] identifier[value] :
identifier[click] . identifier[echo] ( literal[string] %( identifier[target] , i... | async def googlecast(dev: Device, target, value):
"""Return Googlecast settings."""
if target and value:
click.echo('Setting %s = %s' % (target, value))
await dev.set_googlecast_settings(target, value) # depends on [control=['if'], data=[]]
print_settings(await dev.get_googlecast_settings()... |
def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['ds'] = self._ds
return json.dumps(json_dict) | def function[to_json, parameter[self]]:
constant[
:return: str
]
variable[json_dict] assign[=] call[name[self].to_json_basic, parameter[]]
call[name[json_dict]][constant[ds]] assign[=] name[self]._ds
return[call[name[json].dumps, parameter[name[json_dict]]]] | keyword[def] identifier[to_json] ( identifier[self] ):
literal[string]
identifier[json_dict] = identifier[self] . identifier[to_json_basic] ()
identifier[json_dict] [ literal[string] ]= identifier[self] . identifier[_ds]
keyword[return] identifier[json] . identifier[dumps] ( ide... | def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['ds'] = self._ds
return json.dumps(json_dict) |
def prepare_backend_environ(self, host, method, relative_url, headers, body,
source_ip, port):
"""Build an environ object for the backend to consume.
Args:
host: A string containing the host serving the request.
method: A string containing the HTTP method of the reques... | def function[prepare_backend_environ, parameter[self, host, method, relative_url, headers, body, source_ip, port]]:
constant[Build an environ object for the backend to consume.
Args:
host: A string containing the host serving the request.
method: A string containing the HTTP method of the reque... | keyword[def] identifier[prepare_backend_environ] ( identifier[self] , identifier[host] , identifier[method] , identifier[relative_url] , identifier[headers] , identifier[body] ,
identifier[source_ip] , identifier[port] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[body] , identifier[... | def prepare_backend_environ(self, host, method, relative_url, headers, body, source_ip, port):
"""Build an environ object for the backend to consume.
Args:
host: A string containing the host serving the request.
method: A string containing the HTTP method of the request.
relative_url: A strin... |
def get_if_raw_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in network format. If no global address is found, None
is returned.
"""
#r = filter(lambda x: x[2] == iff and x[1] == IPV6_ADDR_GLOBAL, in6_getifaddr())
r = [ x for x in in6_getifadd... | def function[get_if_raw_addr6, parameter[iff]]:
constant[
Returns the main global unicast address associated with provided
interface, in network format. If no global address is found, None
is returned.
]
variable[r] assign[=] <ast.ListComp object at 0x7da1b1206c50>
if compare[... | keyword[def] identifier[get_if_raw_addr6] ( identifier[iff] ):
literal[string]
identifier[r] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[in6_getifaddr] () keyword[if] identifier[x] [ literal[int] ]== identifier[iff] keyword[and] identifier[x] [ literal[int] ]== identifier... | def get_if_raw_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in network format. If no global address is found, None
is returned.
"""
#r = filter(lambda x: x[2] == iff and x[1] == IPV6_ADDR_GLOBAL, in6_getifaddr())
r = [x for x in in6_getifaddr... |
def push_stack(stack, substack, op_id):
"""Proxy of push, where we know we're pushing a stack onto a stack.
Used when differentiating call trees,where sub-functions get their own stack.
See push() for more.
Args:
stack: The stack object, which must support appending values.
substack: The stack to appe... | def function[push_stack, parameter[stack, substack, op_id]]:
constant[Proxy of push, where we know we're pushing a stack onto a stack.
Used when differentiating call trees,where sub-functions get their own stack.
See push() for more.
Args:
stack: The stack object, which must support appending values... | keyword[def] identifier[push_stack] ( identifier[stack] , identifier[substack] , identifier[op_id] ):
literal[string]
keyword[if] identifier[substack] keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[isinstance] ( identifier[substack] , identifier[Stack] ):
keyword[raise]... | def push_stack(stack, substack, op_id):
"""Proxy of push, where we know we're pushing a stack onto a stack.
Used when differentiating call trees,where sub-functions get their own stack.
See push() for more.
Args:
stack: The stack object, which must support appending values.
substack: The stack to ap... |
def phi(self, Xpred, degrees=None):
"""
Compute the design matrix for this model
using the degrees given by the index array
in degrees
:param array-like Xpred: inputs to compute the design matrix for
:param array-like degrees: array of degrees to use [default=range(self.... | def function[phi, parameter[self, Xpred, degrees]]:
constant[
Compute the design matrix for this model
using the degrees given by the index array
in degrees
:param array-like Xpred: inputs to compute the design matrix for
:param array-like degrees: array of degrees to us... | keyword[def] identifier[phi] ( identifier[self] , identifier[Xpred] , identifier[degrees] = keyword[None] ):
literal[string]
keyword[assert] identifier[Xpred] . identifier[shape] [ literal[int] ]== identifier[self] . identifier[X] . identifier[shape] [ literal[int] ], literal[string]
key... | def phi(self, Xpred, degrees=None):
"""
Compute the design matrix for this model
using the degrees given by the index array
in degrees
:param array-like Xpred: inputs to compute the design matrix for
:param array-like degrees: array of degrees to use [default=range(self.degr... |
def dump_migration_session_state(raw):
"""
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. Fo... | def function[dump_migration_session_state, parameter[raw]]:
constant[
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output... | keyword[def] identifier[dump_migration_session_state] ( identifier[raw] ):
literal[string]
keyword[class] identifier[BlockStyle] ( identifier[str] ): keyword[pass]
keyword[class] identifier[SessionDumper] ( identifier[yaml] . identifier[SafeDumper] ): keyword[pass]
keyword[def] identifier[st... | def dump_migration_session_state(raw):
"""
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. Fo... |
def list_files(self, prefix, flat=False):
"""
List the files in the layer with the given prefix.
flat means only generate one level of a directory,
while non-flat means generate all file paths with that
prefix.
"""
layer_path = self.get_path_to_file("")
path = os.path.join(la... | def function[list_files, parameter[self, prefix, flat]]:
constant[
List the files in the layer with the given prefix.
flat means only generate one level of a directory,
while non-flat means generate all file paths with that
prefix.
]
variable[layer_path] assign[=] call[name[self].... | keyword[def] identifier[list_files] ( identifier[self] , identifier[prefix] , identifier[flat] = keyword[False] ):
literal[string]
identifier[layer_path] = identifier[self] . identifier[get_path_to_file] ( literal[string] )
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( ide... | def list_files(self, prefix, flat=False):
"""
List the files in the layer with the given prefix.
flat means only generate one level of a directory,
while non-flat means generate all file paths with that
prefix.
"""
layer_path = self.get_path_to_file('')
path = os.path.join(layer_path,... |
def _check_file_exists(self, cfg_file):
"""
Check that the file exists on remote device using full path.
cfg_file is full path i.e. flash:/file_name
For example
# dir flash:/candidate_config.txt
Directory of flash:/candidate_config.txt
33 -rw- 5592 Dec... | def function[_check_file_exists, parameter[self, cfg_file]]:
constant[
Check that the file exists on remote device using full path.
cfg_file is full path i.e. flash:/file_name
For example
# dir flash:/candidate_config.txt
Directory of flash:/candidate_config.txt
... | keyword[def] identifier[_check_file_exists] ( identifier[self] , identifier[cfg_file] ):
literal[string]
identifier[cmd] = literal[string] . identifier[format] ( identifier[cfg_file] )
identifier[success_pattern] = literal[string] . identifier[format] ( identifier[cfg_file] )
iden... | def _check_file_exists(self, cfg_file):
"""
Check that the file exists on remote device using full path.
cfg_file is full path i.e. flash:/file_name
For example
# dir flash:/candidate_config.txt
Directory of flash:/candidate_config.txt
33 -rw- 5592 Dec 18 ... |
def open_file_for_write(filepath, mode=None):
"""Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to /tmp, and reads of these ... | def function[open_file_for_write, parameter[filepath, mode]]:
constant[Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to... | keyword[def] identifier[open_file_for_write] ( identifier[filepath] , identifier[mode] = keyword[None] ):
literal[string]
identifier[stream] = identifier[StringIO] ()
keyword[yield] identifier[stream]
identifier[content] = identifier[stream] . identifier[getvalue] ()
identifier[filepath] ... | def open_file_for_write(filepath, mode=None):
"""Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to /tmp, and reads of these ... |
def recursive_parse_kwargs(root_func, path_=None, verbose=None):
"""
recursive kwargs parser
TODO: rectify with others
FIXME: if docstr indentation is off, this fails
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_f... | def function[recursive_parse_kwargs, parameter[root_func, path_, verbose]]:
constant[
recursive kwargs parser
TODO: rectify with others
FIXME: if docstr indentation is off, this fails
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwa... | keyword[def] identifier[recursive_parse_kwargs] ( identifier[root_func] , identifier[path_] = keyword[None] , identifier[verbose] = keyword[None] ):
literal[string]
keyword[if] identifier[verbose] keyword[is] keyword[None] :
identifier[verbose] = identifier[VERBOSE_INSPECT]
keyword[if] i... | def recursive_parse_kwargs(root_func, path_=None, verbose=None):
"""
recursive kwargs parser
TODO: rectify with others
FIXME: if docstr indentation is off, this fails
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_f... |
def _solve_pkg(main_globals):
'''
Find parent python path of __main__. From there solve the package
containing __main__, import it and set __package__ variable.
:param main_globals: globals dictionary in __main__
'''
# find __main__'s file directory and search path
main_dir, search_path = _... | def function[_solve_pkg, parameter[main_globals]]:
constant[
Find parent python path of __main__. From there solve the package
containing __main__, import it and set __package__ variable.
:param main_globals: globals dictionary in __main__
]
<ast.Tuple object at 0x7da1b004b610> assign[=... | keyword[def] identifier[_solve_pkg] ( identifier[main_globals] ):
literal[string]
identifier[main_dir] , identifier[search_path] = identifier[_try_search_paths] ( identifier[main_globals] )
keyword[if] keyword[not] identifier[search_path] :
identifier[_log_debug] ( literal[string] % id... | def _solve_pkg(main_globals):
"""
Find parent python path of __main__. From there solve the package
containing __main__, import it and set __package__ variable.
:param main_globals: globals dictionary in __main__
"""
# find __main__'s file directory and search path
(main_dir, search_path) =... |
def storm_relative_helicity(u, v, heights, depth, bottom=0 * units.m,
storm_u=0 * units('m/s'), storm_v=0 * units('m/s')):
# Partially adapted from similar SharpPy code
r"""Calculate storm relative helicity.
Calculates storm relatively helicity following [Markowski2010] 230-231.... | def function[storm_relative_helicity, parameter[u, v, heights, depth, bottom, storm_u, storm_v]]:
constant[Calculate storm relative helicity.
Calculates storm relatively helicity following [Markowski2010] 230-231.
.. math:: \int\limits_0^d (\bar v - c) \cdot \bar\omega_{h} \,dz
This is applied to... | keyword[def] identifier[storm_relative_helicity] ( identifier[u] , identifier[v] , identifier[heights] , identifier[depth] , identifier[bottom] = literal[int] * identifier[units] . identifier[m] ,
identifier[storm_u] = literal[int] * identifier[units] ( literal[string] ), identifier[storm_v] = literal[int] * identif... | def storm_relative_helicity(u, v, heights, depth, bottom=0 * units.m, storm_u=0 * units('m/s'), storm_v=0 * units('m/s')):
# Partially adapted from similar SharpPy code
'Calculate storm relative helicity.\n\n Calculates storm relatively helicity following [Markowski2010] 230-231.\n\n .. math:: \\int\\limi... |
def _show_final_overflow_message(self, row_overflow, col_overflow):
"""Displays overflow message after import in statusbar"""
if row_overflow and col_overflow:
overflow_cause = _("rows and columns")
elif row_overflow:
overflow_cause = _("rows")
elif col_overflow:... | def function[_show_final_overflow_message, parameter[self, row_overflow, col_overflow]]:
constant[Displays overflow message after import in statusbar]
if <ast.BoolOp object at 0x7da1b16a55a0> begin[:]
variable[overflow_cause] assign[=] call[name[_], parameter[constant[rows and columns]]]... | keyword[def] identifier[_show_final_overflow_message] ( identifier[self] , identifier[row_overflow] , identifier[col_overflow] ):
literal[string]
keyword[if] identifier[row_overflow] keyword[and] identifier[col_overflow] :
identifier[overflow_cause] = identifier[_] ( literal[string... | def _show_final_overflow_message(self, row_overflow, col_overflow):
"""Displays overflow message after import in statusbar"""
if row_overflow and col_overflow:
overflow_cause = _('rows and columns') # depends on [control=['if'], data=[]]
elif row_overflow:
overflow_cause = _('rows') # depe... |
def convolve(image, pixel_filter, channels=3, name=None):
"""Perform a 2D pixel convolution on the given image.
Arguments:
image: A 3D `float32` `Tensor` of shape `[height, width, channels]`,
where `channels` is the third argument to this function and the
first two dimensions are arbitrary.
pix... | def function[convolve, parameter[image, pixel_filter, channels, name]]:
constant[Perform a 2D pixel convolution on the given image.
Arguments:
image: A 3D `float32` `Tensor` of shape `[height, width, channels]`,
where `channels` is the third argument to this function and the
first two dimensi... | keyword[def] identifier[convolve] ( identifier[image] , identifier[pixel_filter] , identifier[channels] = literal[int] , identifier[name] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( identifier[name] , literal[string] ):
identifier[tf] . identifier[compat] . ... | def convolve(image, pixel_filter, channels=3, name=None):
"""Perform a 2D pixel convolution on the given image.
Arguments:
image: A 3D `float32` `Tensor` of shape `[height, width, channels]`,
where `channels` is the third argument to this function and the
first two dimensions are arbitrary.
p... |
def same_values(l1,l2):
'''
from elist.elist import *
l1 = [1,2,3,5]
l2 = [0,2,3,4]
same_values(l1,l2)
'''
rslt = []
for i in range(0,l1.__len__()):
if(l1[i]==l2[i]):
rslt.append(l1[i])
return(rslt) | def function[same_values, parameter[l1, l2]]:
constant[
from elist.elist import *
l1 = [1,2,3,5]
l2 = [0,2,3,4]
same_values(l1,l2)
]
variable[rslt] assign[=] list[[]]
for taget[name[i]] in starred[call[name[range], parameter[constant[0], call[name[l1].__len__,... | keyword[def] identifier[same_values] ( identifier[l1] , identifier[l2] ):
literal[string]
identifier[rslt] =[]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[l1] . identifier[__len__] ()):
keyword[if] ( identifier[l1] [ identifier[i] ]== identifier[l2]... | def same_values(l1, l2):
"""
from elist.elist import *
l1 = [1,2,3,5]
l2 = [0,2,3,4]
same_values(l1,l2)
"""
rslt = []
for i in range(0, l1.__len__()):
if l1[i] == l2[i]:
rslt.append(l1[i]) # depends on [control=['if'], data=[]] # depends on [control=... |
def _forward(self):
"""Advance to the next token.
Internal methods, updates:
- self.current_token
- self.current_pos
Raises:
MissingTokensError: when trying to advance beyond the end of the
token flow.
"""
try:
self.curren... | def function[_forward, parameter[self]]:
constant[Advance to the next token.
Internal methods, updates:
- self.current_token
- self.current_pos
Raises:
MissingTokensError: when trying to advance beyond the end of the
token flow.
]
<ast.Tr... | keyword[def] identifier[_forward] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[current_token] = identifier[next] ( identifier[self] . identifier[tokens] )
keyword[except] identifier[StopIteration] :
keyword[raise] identifier... | def _forward(self):
"""Advance to the next token.
Internal methods, updates:
- self.current_token
- self.current_pos
Raises:
MissingTokensError: when trying to advance beyond the end of the
token flow.
"""
try:
self.current_token = ne... |
def population_chart_extractor(impact_report, component_metadata):
"""Creating population donut chart.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata:... | def function[population_chart_extractor, parameter[impact_report, component_metadata]]:
constant[Creating population donut chart.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
... | keyword[def] identifier[population_chart_extractor] ( identifier[impact_report] , identifier[component_metadata] ):
literal[string]
identifier[context] ={}
identifier[extra_args] = identifier[component_metadata] . identifier[extra_args]
identifier[analysis_layer] = identifier[impact_report] . i... | def population_chart_extractor(impact_report, component_metadata):
"""Creating population donut chart.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata:... |
def get_el_sp(obj):
"""
Utility method to get an Element or Specie from an input obj.
If obj is in itself an element or a specie, it is returned automatically.
If obj is an int or a string representing an integer, the Element
with the atomic number obj is returned.
If obj is a string, Specie par... | def function[get_el_sp, parameter[obj]]:
constant[
Utility method to get an Element or Specie from an input obj.
If obj is in itself an element or a specie, it is returned automatically.
If obj is an int or a string representing an integer, the Element
with the atomic number obj is returned.
... | keyword[def] identifier[get_el_sp] ( identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] ,( identifier[Element] , identifier[Specie] , identifier[DummySpecie] )):
keyword[return] identifier[obj]
keyword[if] identifier[isinstance] ( identifier[obj] ,( i... | def get_el_sp(obj):
"""
Utility method to get an Element or Specie from an input obj.
If obj is in itself an element or a specie, it is returned automatically.
If obj is an int or a string representing an integer, the Element
with the atomic number obj is returned.
If obj is a string, Specie par... |
def bond_sample_states(
perc_graph, num_nodes, num_edges, seed, spanning_cluster=True,
auxiliary_node_attributes=None, auxiliary_edge_attributes=None,
spanning_sides=None,
**kwargs
):
'''
Generate successive sample states of the bond percolation model
This is a :ref:`generator function <pyt... | def function[bond_sample_states, parameter[perc_graph, num_nodes, num_edges, seed, spanning_cluster, auxiliary_node_attributes, auxiliary_edge_attributes, spanning_sides]]:
constant[
Generate successive sample states of the bond percolation model
This is a :ref:`generator function <python:tut-generator... | keyword[def] identifier[bond_sample_states] (
identifier[perc_graph] , identifier[num_nodes] , identifier[num_edges] , identifier[seed] , identifier[spanning_cluster] = keyword[True] ,
identifier[auxiliary_node_attributes] = keyword[None] , identifier[auxiliary_edge_attributes] = keyword[None] ,
identifier[spannin... | def bond_sample_states(perc_graph, num_nodes, num_edges, seed, spanning_cluster=True, auxiliary_node_attributes=None, auxiliary_edge_attributes=None, spanning_sides=None, **kwargs):
"""
Generate successive sample states of the bond percolation model
This is a :ref:`generator function <python:tut-generators... |
def complain(distribution_name):
"""Issue a warning if `distribution_name` is installed.
In a future release, this method will be updated to raise ImportError
rather than just send a warning.
Args:
distribution_name (str): The name of the obsolete distribution.
"""
try:
pkg_res... | def function[complain, parameter[distribution_name]]:
constant[Issue a warning if `distribution_name` is installed.
In a future release, this method will be updated to raise ImportError
rather than just send a warning.
Args:
distribution_name (str): The name of the obsolete distribution.
... | keyword[def] identifier[complain] ( identifier[distribution_name] ):
literal[string]
keyword[try] :
identifier[pkg_resources] . identifier[get_distribution] ( identifier[distribution_name] )
identifier[warnings] . identifier[warn] (
literal[string]
literal[string]
... | def complain(distribution_name):
"""Issue a warning if `distribution_name` is installed.
In a future release, this method will be updated to raise ImportError
rather than just send a warning.
Args:
distribution_name (str): The name of the obsolete distribution.
"""
try:
pkg_res... |
def get_abilities():
"""Visit Bulbapedia and pull names and descriptions from the table, 'list of Abilities.' Save as JSON."""
page = requests.get('http://bulbapedia.bulbagarden.net/wiki/Ability')
soup = bs4.BeautifulSoup(page.text)
table = soup.find("table", {"class": "sortable"})
tablerows = [tr f... | def function[get_abilities, parameter[]]:
constant[Visit Bulbapedia and pull names and descriptions from the table, 'list of Abilities.' Save as JSON.]
variable[page] assign[=] call[name[requests].get, parameter[constant[http://bulbapedia.bulbagarden.net/wiki/Ability]]]
variable[soup] assign[=] ... | keyword[def] identifier[get_abilities] ():
literal[string]
identifier[page] = identifier[requests] . identifier[get] ( literal[string] )
identifier[soup] = identifier[bs4] . identifier[BeautifulSoup] ( identifier[page] . identifier[text] )
identifier[table] = identifier[soup] . identifier[find] (... | def get_abilities():
"""Visit Bulbapedia and pull names and descriptions from the table, 'list of Abilities.' Save as JSON."""
page = requests.get('http://bulbapedia.bulbagarden.net/wiki/Ability')
soup = bs4.BeautifulSoup(page.text)
table = soup.find('table', {'class': 'sortable'})
tablerows = [tr f... |
def add_wic(self, old_wic, wic):
"""
Convert the old style WIC slot to a new style WIC slot and add the WIC
to the node properties
:param str old_wic: Old WIC slot
:param str wic: WIC name
"""
new_wic = 'wic' + old_wic[-1]
self.node['properties'][new_wic]... | def function[add_wic, parameter[self, old_wic, wic]]:
constant[
Convert the old style WIC slot to a new style WIC slot and add the WIC
to the node properties
:param str old_wic: Old WIC slot
:param str wic: WIC name
]
variable[new_wic] assign[=] binary_operation[... | keyword[def] identifier[add_wic] ( identifier[self] , identifier[old_wic] , identifier[wic] ):
literal[string]
identifier[new_wic] = literal[string] + identifier[old_wic] [- literal[int] ]
identifier[self] . identifier[node] [ literal[string] ][ identifier[new_wic] ]= identifier[wic] | def add_wic(self, old_wic, wic):
"""
Convert the old style WIC slot to a new style WIC slot and add the WIC
to the node properties
:param str old_wic: Old WIC slot
:param str wic: WIC name
"""
new_wic = 'wic' + old_wic[-1]
self.node['properties'][new_wic] = wic |
def _refit(self):
"""Update the map :math:`\pi` keeping the output :math:`g` fixed
Use Eq. (7) and below in [GR04]_
"""
# temporary variables for manipulation
mu_diff = np.empty_like(self.f.components[0].mu)
sigma = np.empty_like(self.f.components[0].sigma)
me... | def function[_refit, parameter[self]]:
constant[Update the map :math:`\pi` keeping the output :math:`g` fixed
Use Eq. (7) and below in [GR04]_
]
variable[mu_diff] assign[=] call[name[np].empty_like, parameter[call[name[self].f.components][constant[0]].mu]]
variable[sigma] assig... | keyword[def] identifier[_refit] ( identifier[self] ):
literal[string]
identifier[mu_diff] = identifier[np] . identifier[empty_like] ( identifier[self] . identifier[f] . identifier[components] [ literal[int] ]. identifier[mu] )
identifier[sigma] = identifier[np] . identifier[empty_... | def _refit(self):
"""Update the map :math:`\\pi` keeping the output :math:`g` fixed
Use Eq. (7) and below in [GR04]_
"""
# temporary variables for manipulation
mu_diff = np.empty_like(self.f.components[0].mu)
sigma = np.empty_like(self.f.components[0].sigma)
mean = np.empty_like(mu... |
def deletescript(self, name):
"""Delete a script from the server
See MANAGESIEVE specifications, section 2.10
:param name: script's name
:rtype: boolean
"""
code, data = self.__send_command(
"DELETESCRIPT", [name.encode("utf-8")])
if code == "OK":
... | def function[deletescript, parameter[self, name]]:
constant[Delete a script from the server
See MANAGESIEVE specifications, section 2.10
:param name: script's name
:rtype: boolean
]
<ast.Tuple object at 0x7da20c9928f0> assign[=] call[name[self].__send_command, parameter... | keyword[def] identifier[deletescript] ( identifier[self] , identifier[name] ):
literal[string]
identifier[code] , identifier[data] = identifier[self] . identifier[__send_command] (
literal[string] ,[ identifier[name] . identifier[encode] ( literal[string] )])
keyword[if] identifi... | def deletescript(self, name):
"""Delete a script from the server
See MANAGESIEVE specifications, section 2.10
:param name: script's name
:rtype: boolean
"""
(code, data) = self.__send_command('DELETESCRIPT', [name.encode('utf-8')])
if code == 'OK':
return True # de... |
def connect(self):
"""
Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters
"""
if (self.__ser is not None):
serial = importlib.import_module("serial")
if self.__stopbits == 0:
self.__ser.stopbits = serial.STOPBITS_ON... | def function[connect, parameter[self]]:
constant[
Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters
]
if compare[name[self].__ser is_not constant[None]] begin[:]
variable[serial] assign[=] call[name[importlib].import_module, parameter[constan... | keyword[def] identifier[connect] ( identifier[self] ):
literal[string]
keyword[if] ( identifier[self] . identifier[__ser] keyword[is] keyword[not] keyword[None] ):
identifier[serial] = identifier[importlib] . identifier[import_module] ( literal[string] )
keyword[if] id... | def connect(self):
"""
Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters
"""
if self.__ser is not None:
serial = importlib.import_module('serial')
if self.__stopbits == 0:
self.__ser.stopbits = serial.STOPBITS_ONE # depends on [control=[... |
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI did not contain a fragment component.
"""
fragment = self.fragment
if fragment is not None:
return uridecode(fragment, ... | def function[getfragment, parameter[self, default, encoding, errors]]:
constant[Return the decoded fragment identifier, or `default` if the
original URI did not contain a fragment component.
]
variable[fragment] assign[=] name[self].fragment
if compare[name[fragment] is_not cons... | keyword[def] identifier[getfragment] ( identifier[self] , identifier[default] = keyword[None] , identifier[encoding] = literal[string] , identifier[errors] = literal[string] ):
literal[string]
identifier[fragment] = identifier[self] . identifier[fragment]
keyword[if] identifier[fragment]... | def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI did not contain a fragment component.
"""
fragment = self.fragment
if fragment is not None:
return uridecode(fragment, encoding, errors... |
def _makeplot(self, ax, fig, data, ymin=None, ymax=None, height=6,
width=6, dos=None, color=None):
"""Utility method to tidy phonon band structure diagrams. """
# Define colours
if color is None:
color = 'C0' # Default to first colour in matplotlib series
... | def function[_makeplot, parameter[self, ax, fig, data, ymin, ymax, height, width, dos, color]]:
constant[Utility method to tidy phonon band structure diagrams. ]
if compare[name[color] is constant[None]] begin[:]
variable[color] assign[=] constant[C0]
variable[tymax] assign[=] <a... | keyword[def] identifier[_makeplot] ( identifier[self] , identifier[ax] , identifier[fig] , identifier[data] , identifier[ymin] = keyword[None] , identifier[ymax] = keyword[None] , identifier[height] = literal[int] ,
identifier[width] = literal[int] , identifier[dos] = keyword[None] , identifier[color] = keyword[None... | def _makeplot(self, ax, fig, data, ymin=None, ymax=None, height=6, width=6, dos=None, color=None):
"""Utility method to tidy phonon band structure diagrams. """
# Define colours
if color is None:
color = 'C0' # Default to first colour in matplotlib series # depends on [control=['if'], data=['color... |
def clearLocalServices(self):
'send Bye messages for the services and remove them'
for service in list(self._localServices.values()):
self._sendBye(service)
self._localServices.clear() | def function[clearLocalServices, parameter[self]]:
constant[send Bye messages for the services and remove them]
for taget[name[service]] in starred[call[name[list], parameter[call[name[self]._localServices.values, parameter[]]]]] begin[:]
call[name[self]._sendBye, parameter[name[service]... | keyword[def] identifier[clearLocalServices] ( identifier[self] ):
literal[string]
keyword[for] identifier[service] keyword[in] identifier[list] ( identifier[self] . identifier[_localServices] . identifier[values] ()):
identifier[self] . identifier[_sendBye] ( identifier[service] )
... | def clearLocalServices(self):
"""send Bye messages for the services and remove them"""
for service in list(self._localServices.values()):
self._sendBye(service) # depends on [control=['for'], data=['service']]
self._localServices.clear() |
def to_agraph(
self,
indicators: bool = False,
indicator_values: bool = False,
nodes_to_highlight=None,
*args,
**kwargs,
):
""" Exports the CAG as a pygraphviz AGraph for visualization.
Args:
indicators: Whether to display indicators in th... | def function[to_agraph, parameter[self, indicators, indicator_values, nodes_to_highlight]]:
constant[ Exports the CAG as a pygraphviz AGraph for visualization.
Args:
indicators: Whether to display indicators in the AGraph
indicator_values: Whether to display indicator values in ... | keyword[def] identifier[to_agraph] (
identifier[self] ,
identifier[indicators] : identifier[bool] = keyword[False] ,
identifier[indicator_values] : identifier[bool] = keyword[False] ,
identifier[nodes_to_highlight] = keyword[None] ,
* identifier[args] ,
** identifier[kwargs] ,
):
literal[string]
... | def to_agraph(self, indicators: bool=False, indicator_values: bool=False, nodes_to_highlight=None, *args, **kwargs):
""" Exports the CAG as a pygraphviz AGraph for visualization.
Args:
indicators: Whether to display indicators in the AGraph
indicator_values: Whether to display indic... |
def get_subnets(context, limit=None, page_reverse=False, sorts=['id'],
marker=None, filters=None, fields=None):
"""Retrieve a list of subnets.
The contents of the list depends on the identity of the user
making the request (as indicated by the context) as well as any
filters.
: para... | def function[get_subnets, parameter[context, limit, page_reverse, sorts, marker, filters, fields]]:
constant[Retrieve a list of subnets.
The contents of the list depends on the identity of the user
making the request (as indicated by the context) as well as any
filters.
: param context: neutron... | keyword[def] identifier[get_subnets] ( identifier[context] , identifier[limit] = keyword[None] , identifier[page_reverse] = keyword[False] , identifier[sorts] =[ literal[string] ],
identifier[marker] = keyword[None] , identifier[filters] = keyword[None] , identifier[fields] = keyword[None] ):
literal[string]
... | def get_subnets(context, limit=None, page_reverse=False, sorts=['id'], marker=None, filters=None, fields=None):
"""Retrieve a list of subnets.
The contents of the list depends on the identity of the user
making the request (as indicated by the context) as well as any
filters.
: param context: neutr... |
def update_my_account(self, body, **kwargs): # noqa: E501
"""Updates attributes of the account. # noqa: E501
An endpoint for updating the account. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/accounts/me -d '{\"phone_number\": \"12345678\"}' -H 'content-type: application/j... | def function[update_my_account, parameter[self, body]]:
constant[Updates attributes of the account. # noqa: E501
An endpoint for updating the account. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/accounts/me -d '{"phone_number": "12345678"}' -H 'content-type: application/js... | keyword[def] identifier[update_my_account] ( identifier[self] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[... | def update_my_account(self, body, **kwargs): # noqa: E501
'Updates attributes of the account. # noqa: E501\n\n An endpoint for updating the account. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/accounts/me -d \'{"phone_number": "12345678"}\' -H \'content-type: application/json\'... |
def Enable(self, value):
"enable or disable all menu items"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
it.Enable(value) | def function[Enable, parameter[self, value]]:
constant[enable or disable all menu items]
for taget[name[i]] in starred[call[name[range], parameter[call[name[self].GetMenuItemCount, parameter[]]]]] begin[:]
variable[it] assign[=] call[name[self].FindItemByPosition, parameter[name[i]]]
... | keyword[def] identifier[Enable] ( identifier[self] , identifier[value] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[GetMenuItemCount] ()):
identifier[it] = identifier[self] . identifier[FindItemByPosition] ( identifie... | def Enable(self, value):
"""enable or disable all menu items"""
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
it.Enable(value) # depends on [control=['for'], data=['i']] |
def fatigue_eval_med_freq(data, sample_rate, time_units=True, raw_to_mv=True,
device="biosignalsplux", resolution=16, show_plot=False):
"""
-----
Brief
-----
Returns the evolution time series of EMG median frequency along the acquisition, based on a sliding window
mecha... | def function[fatigue_eval_med_freq, parameter[data, sample_rate, time_units, raw_to_mv, device, resolution, show_plot]]:
constant[
-----
Brief
-----
Returns the evolution time series of EMG median frequency along the acquisition, based on a sliding window
mechanism.
-----------
Desc... | keyword[def] identifier[fatigue_eval_med_freq] ( identifier[data] , identifier[sample_rate] , identifier[time_units] = keyword[True] , identifier[raw_to_mv] = keyword[True] ,
identifier[device] = literal[string] , identifier[resolution] = literal[int] , identifier[show_plot] = keyword[False] ):
literal[string] ... | def fatigue_eval_med_freq(data, sample_rate, time_units=True, raw_to_mv=True, device='biosignalsplux', resolution=16, show_plot=False):
"""
-----
Brief
-----
Returns the evolution time series of EMG median frequency along the acquisition, based on a sliding window
mechanism.
-----------
... |
def fixed_point_uniform(points, cells, *args, **kwargs):
"""Idea:
Move interior mesh points into the weighted averages of the circumcenters
of their adjacent cells. If a triangle cell switches orientation in the
process, don't move quite so far.
"""
def get_new_points(mesh):
# Get circu... | def function[fixed_point_uniform, parameter[points, cells]]:
constant[Idea:
Move interior mesh points into the weighted averages of the circumcenters
of their adjacent cells. If a triangle cell switches orientation in the
process, don't move quite so far.
]
def function[get_new_points, p... | keyword[def] identifier[fixed_point_uniform] ( identifier[points] , identifier[cells] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[get_new_points] ( identifier[mesh] ):
identifier[cc] = identifier[mesh] . identifier[cell_circumcenters]
... | def fixed_point_uniform(points, cells, *args, **kwargs):
"""Idea:
Move interior mesh points into the weighted averages of the circumcenters
of their adjacent cells. If a triangle cell switches orientation in the
process, don't move quite so far.
"""
def get_new_points(mesh):
# Get circu... |
def cmServiceAccept():
"""CM SERVICE ACCEPT Section 9.2.5"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x21) # 00100001
packet = a / b
return packet | def function[cmServiceAccept, parameter[]]:
constant[CM SERVICE ACCEPT Section 9.2.5]
variable[a] assign[=] call[name[TpPd], parameter[]]
variable[b] assign[=] call[name[MessageType], parameter[]]
variable[packet] assign[=] binary_operation[name[a] / name[b]]
return[name[packet]] | keyword[def] identifier[cmServiceAccept] ():
literal[string]
identifier[a] = identifier[TpPd] ( identifier[pd] = literal[int] )
identifier[b] = identifier[MessageType] ( identifier[mesType] = literal[int] )
identifier[packet] = identifier[a] / identifier[b]
keyword[return] identifier[packe... | def cmServiceAccept():
"""CM SERVICE ACCEPT Section 9.2.5"""
a = TpPd(pd=5)
b = MessageType(mesType=33) # 00100001
packet = a / b
return packet |
def status(self):
"""Return current readings, as a dictionary with:
duration -- the duration of the measurements, in seconds;
cpm -- the radiation count by minute;
uSvh -- the radiation dose, exprimed in Sievert per house (uSv/h);
uSvhError -- the incertitude for ... | def function[status, parameter[self]]:
constant[Return current readings, as a dictionary with:
duration -- the duration of the measurements, in seconds;
cpm -- the radiation count by minute;
uSvh -- the radiation dose, exprimed in Sievert per house (uSv/h);
uSvhEr... | keyword[def] identifier[status] ( identifier[self] ):
literal[string]
identifier[minutes] = identifier[min] ( identifier[self] . identifier[duration] , identifier[MAX_CPM_TIME] )/ literal[int] / literal[int]
identifier[cpm] = identifier[self] . identifier[count] / identifier[minutes] key... | def status(self):
"""Return current readings, as a dictionary with:
duration -- the duration of the measurements, in seconds;
cpm -- the radiation count by minute;
uSvh -- the radiation dose, exprimed in Sievert per house (uSv/h);
uSvhError -- the incertitude for the ... |
def fit(self, X, y=None):
"""Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self
"""
return self.parti... | def function[fit, parameter[self, X, y]]:
constant[Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self
]
r... | keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[y] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[partial_fit] ( identifier[np] . identifier[concatenate] ( identifier[X] , identifier[axis] = literal[int] )) | def fit(self, X, y=None):
"""Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self
"""
return self.partial_fit(n... |
def _connect_setns(spec, kind=None):
"""
Return ContextService arguments for a mitogen_setns connection.
"""
return {
'method': 'setns',
'kwargs': {
'container': spec.remote_addr(),
'username': spec.remote_user(),
'python_path': spec.python_path(),
... | def function[_connect_setns, parameter[spec, kind]]:
constant[
Return ContextService arguments for a mitogen_setns connection.
]
return[dictionary[[<ast.Constant object at 0x7da1b1d52830>, <ast.Constant object at 0x7da1b1d53820>], [<ast.Constant object at 0x7da1b1d52620>, <ast.Dict object at 0x7da1b... | keyword[def] identifier[_connect_setns] ( identifier[spec] , identifier[kind] = keyword[None] ):
literal[string]
keyword[return] {
literal[string] : literal[string] ,
literal[string] :{
literal[string] : identifier[spec] . identifier[remote_addr] (),
literal[string] : identifier[spec] .... | def _connect_setns(spec, kind=None):
"""
Return ContextService arguments for a mitogen_setns connection.
"""
return {'method': 'setns', 'kwargs': {'container': spec.remote_addr(), 'username': spec.remote_user(), 'python_path': spec.python_path(), 'kind': kind or spec.mitogen_kind(), 'docker_path': spec.... |
def vnc_raspi_osmc():
'''Install and configure dispmanx_vnc server on osmc (raspberry pi).
More Infos:
* https://github.com/patrikolausson/dispmanx_vnc
* https://discourse.osmc.tv/t/howto-install-a-vnc-server-on-the-raspberry-pi/1517
* tightvnc:
* http://raspberry.tips/raspberrypi-einstei... | def function[vnc_raspi_osmc, parameter[]]:
constant[Install and configure dispmanx_vnc server on osmc (raspberry pi).
More Infos:
* https://github.com/patrikolausson/dispmanx_vnc
* https://discourse.osmc.tv/t/howto-install-a-vnc-server-on-the-raspberry-pi/1517
* tightvnc:
* http://ras... | keyword[def] identifier[vnc_raspi_osmc] ():
literal[string]
identifier[print] ( identifier[blue] ( literal[string] ))
identifier[install_packages] ([
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
])
identifier[print] ( iden... | def vnc_raspi_osmc():
"""Install and configure dispmanx_vnc server on osmc (raspberry pi).
More Infos:
* https://github.com/patrikolausson/dispmanx_vnc
* https://discourse.osmc.tv/t/howto-install-a-vnc-server-on-the-raspberry-pi/1517
* tightvnc:
* http://raspberry.tips/raspberrypi-einstei... |
def search_memories(self):
"""
Search and return list of 1-wire memories.
"""
if not self.connected:
raise NotConnected()
return self._cf.mem.get_mems(MemoryElement.TYPE_1W) | def function[search_memories, parameter[self]]:
constant[
Search and return list of 1-wire memories.
]
if <ast.UnaryOp object at 0x7da1b1634250> begin[:]
<ast.Raise object at 0x7da1b16355d0>
return[call[name[self]._cf.mem.get_mems, parameter[name[MemoryElement].TYPE_1W]]] | keyword[def] identifier[search_memories] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[connected] :
keyword[raise] identifier[NotConnected] ()
keyword[return] identifier[self] . identifier[_cf] . identifier[mem] . identifier[g... | def search_memories(self):
"""
Search and return list of 1-wire memories.
"""
if not self.connected:
raise NotConnected() # depends on [control=['if'], data=[]]
return self._cf.mem.get_mems(MemoryElement.TYPE_1W) |
def sflow_source_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow")
source_ip = ET.SubElement(sflow, "source-ip")
source_ip.text = kwargs.pop('source_ip')
... | def function[sflow_source_ip, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[sflow] assign[=] call[name[ET].SubElement, parameter[name[config], constant[sflow]]]
variable[source_ip] assign[=... | keyword[def] identifier[sflow_source_ip] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[sflow] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , identifie... | def sflow_source_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
sflow = ET.SubElement(config, 'sflow', xmlns='urn:brocade.com:mgmt:brocade-sflow')
source_ip = ET.SubElement(sflow, 'source-ip')
source_ip.text = kwargs.pop('source_ip')
callback = kwargs.pop('c... |
def histogram(data, **kwargs):
"""
Function to create histogram, e.g. for voltages or currents.
Parameters
----------
data : :pandas:`pandas.DataFrame<dataframe>`
Data to be plotted, e.g. voltage or current (`v_res` or `i_res` from
:class:`edisgo.grid.network.Results`). Index of the... | def function[histogram, parameter[data]]:
constant[
Function to create histogram, e.g. for voltages or currents.
Parameters
----------
data : :pandas:`pandas.DataFrame<dataframe>`
Data to be plotted, e.g. voltage or current (`v_res` or `i_res` from
:class:`edisgo.grid.network.Re... | keyword[def] identifier[histogram] ( identifier[data] ,** identifier[kwargs] ):
literal[string]
identifier[timeindex] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] )
identifier[directory] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] )
identif... | def histogram(data, **kwargs):
"""
Function to create histogram, e.g. for voltages or currents.
Parameters
----------
data : :pandas:`pandas.DataFrame<dataframe>`
Data to be plotted, e.g. voltage or current (`v_res` or `i_res` from
:class:`edisgo.grid.network.Results`). Index of the... |
def t_ID(self, t):
r"[a-zA-Z_][0-9a-zA-Z_]*|[a-zA-Z][0-9a-zA-Z_]*[0-9a-zA-Z_]+"
t.endlexpos = t.lexpos + len(t.value)
value = t.value.upper()
if value in self.keywords:
t.type = value
return t | def function[t_ID, parameter[self, t]]:
constant[[a-zA-Z_][0-9a-zA-Z_]*|[a-zA-Z][0-9a-zA-Z_]*[0-9a-zA-Z_]+]
name[t].endlexpos assign[=] binary_operation[name[t].lexpos + call[name[len], parameter[name[t].value]]]
variable[value] assign[=] call[name[t].value.upper, parameter[]]
if compare... | keyword[def] identifier[t_ID] ( identifier[self] , identifier[t] ):
literal[string]
identifier[t] . identifier[endlexpos] = identifier[t] . identifier[lexpos] + identifier[len] ( identifier[t] . identifier[value] )
identifier[value] = identifier[t] . identifier[value] . identifier[upper] ... | def t_ID(self, t):
"""[a-zA-Z_][0-9a-zA-Z_]*|[a-zA-Z][0-9a-zA-Z_]*[0-9a-zA-Z_]+"""
t.endlexpos = t.lexpos + len(t.value)
value = t.value.upper()
if value in self.keywords:
t.type = value # depends on [control=['if'], data=['value']]
return t |
def set_client_key(self, zmq_socket, client_secret_key_path, server_public_key_path):
'''must call before bind'''
load_and_set_key(zmq_socket, client_secret_key_path)
server_public, _ = zmq.auth.load_certificate(server_public_key_path)
zmq_socket.curve_serverkey = server_public | def function[set_client_key, parameter[self, zmq_socket, client_secret_key_path, server_public_key_path]]:
constant[must call before bind]
call[name[load_and_set_key], parameter[name[zmq_socket], name[client_secret_key_path]]]
<ast.Tuple object at 0x7da1b0a1dde0> assign[=] call[name[zmq].auth.lo... | keyword[def] identifier[set_client_key] ( identifier[self] , identifier[zmq_socket] , identifier[client_secret_key_path] , identifier[server_public_key_path] ):
literal[string]
identifier[load_and_set_key] ( identifier[zmq_socket] , identifier[client_secret_key_path] )
identifier[server_pu... | def set_client_key(self, zmq_socket, client_secret_key_path, server_public_key_path):
"""must call before bind"""
load_and_set_key(zmq_socket, client_secret_key_path)
(server_public, _) = zmq.auth.load_certificate(server_public_key_path)
zmq_socket.curve_serverkey = server_public |
def update_scalar_bar_range(self, clim, name=None):
"""Update the value range of the active or named scalar bar.
Parameters
----------
2 item list
The new range of scalar bar. Example: ``[-1, 2]``.
name : str, optional
The title of the scalar bar to upda... | def function[update_scalar_bar_range, parameter[self, clim, name]]:
constant[Update the value range of the active or named scalar bar.
Parameters
----------
2 item list
The new range of scalar bar. Example: ``[-1, 2]``.
name : str, optional
The title of ... | keyword[def] identifier[update_scalar_bar_range] ( identifier[self] , identifier[clim] , identifier[name] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[clim] , identifier[float] ) keyword[or] identifier[isinstance] ( identifier[clim] , identifier[int] ):
... | def update_scalar_bar_range(self, clim, name=None):
"""Update the value range of the active or named scalar bar.
Parameters
----------
2 item list
The new range of scalar bar. Example: ``[-1, 2]``.
name : str, optional
The title of the scalar bar to update
... |
def remove_species(self, species):
"""
Remove all occurrences of several species from a structure.
Args:
species: Sequence of species to remove, e.g., ["Li", "Na"].
"""
new_sites = []
species = [get_el_sp(s) for s in species]
for site in self._sites:... | def function[remove_species, parameter[self, species]]:
constant[
Remove all occurrences of several species from a structure.
Args:
species: Sequence of species to remove, e.g., ["Li", "Na"].
]
variable[new_sites] assign[=] list[[]]
variable[species] assign[=... | keyword[def] identifier[remove_species] ( identifier[self] , identifier[species] ):
literal[string]
identifier[new_sites] =[]
identifier[species] =[ identifier[get_el_sp] ( identifier[s] ) keyword[for] identifier[s] keyword[in] identifier[species] ]
keyword[for] identifier[si... | def remove_species(self, species):
"""
Remove all occurrences of several species from a structure.
Args:
species: Sequence of species to remove, e.g., ["Li", "Na"].
"""
new_sites = []
species = [get_el_sp(s) for s in species]
for site in self._sites:
new_sp_o... |
def dispatch(self, opcode, context):
"""Dispatches a context on a given opcode. Returns True if the context
is done matching, False if it must be resumed when next encountered."""
if id(context) in self.executing_contexts:
generator = self.executing_contexts[id(context)]
... | def function[dispatch, parameter[self, opcode, context]]:
constant[Dispatches a context on a given opcode. Returns True if the context
is done matching, False if it must be resumed when next encountered.]
if compare[call[name[id], parameter[name[context]]] in name[self].executing_contexts] begin... | keyword[def] identifier[dispatch] ( identifier[self] , identifier[opcode] , identifier[context] ):
literal[string]
keyword[if] identifier[id] ( identifier[context] ) keyword[in] identifier[self] . identifier[executing_contexts] :
identifier[generator] = identifier[self] . identifier[... | def dispatch(self, opcode, context):
"""Dispatches a context on a given opcode. Returns True if the context
is done matching, False if it must be resumed when next encountered."""
if id(context) in self.executing_contexts:
generator = self.executing_contexts[id(context)]
del self.executi... |
def digit(decimal, digit, input_base=10):
"""
Find the value of an integer at a specific digit when represented in a
particular base.
Args:
decimal(int): A number represented in base 10 (positive integer).
digit(int): The digit to find where zero is the first, lowest, digit.
... | def function[digit, parameter[decimal, digit, input_base]]:
constant[
Find the value of an integer at a specific digit when represented in a
particular base.
Args:
decimal(int): A number represented in base 10 (positive integer).
digit(int): The digit to find where zero is the first... | keyword[def] identifier[digit] ( identifier[decimal] , identifier[digit] , identifier[input_base] = literal[int] ):
literal[string]
keyword[if] identifier[decimal] == literal[int] :
keyword[return] literal[int]
keyword[if] identifier[digit] != literal[int] :
keyword[return] ... | def digit(decimal, digit, input_base=10):
"""
Find the value of an integer at a specific digit when represented in a
particular base.
Args:
decimal(int): A number represented in base 10 (positive integer).
digit(int): The digit to find where zero is the first, lowest, digit.
bas... |
def user_name_attributes(user, service):
"""Return all available user name related fields and methods."""
attributes = {}
attributes['username'] = user.get_username()
attributes['full_name'] = user.get_full_name()
attributes['short_name'] = user.get_short_name()
return attributes | def function[user_name_attributes, parameter[user, service]]:
constant[Return all available user name related fields and methods.]
variable[attributes] assign[=] dictionary[[], []]
call[name[attributes]][constant[username]] assign[=] call[name[user].get_username, parameter[]]
call[name[a... | keyword[def] identifier[user_name_attributes] ( identifier[user] , identifier[service] ):
literal[string]
identifier[attributes] ={}
identifier[attributes] [ literal[string] ]= identifier[user] . identifier[get_username] ()
identifier[attributes] [ literal[string] ]= identifier[user] . identifier... | def user_name_attributes(user, service):
"""Return all available user name related fields and methods."""
attributes = {}
attributes['username'] = user.get_username()
attributes['full_name'] = user.get_full_name()
attributes['short_name'] = user.get_short_name()
return attributes |
def bipartite_as_graph(self) -> Graph: # pragma: no cover
"""Returns a :class:`graphviz.Graph` representation of this bipartite graph."""
if Graph is None:
raise ImportError('The graphviz package is required to draw the graph.')
graph = Graph()
nodes_left = {} # type: Dict[... | def function[bipartite_as_graph, parameter[self]]:
constant[Returns a :class:`graphviz.Graph` representation of this bipartite graph.]
if compare[name[Graph] is constant[None]] begin[:]
<ast.Raise object at 0x7da1b23450f0>
variable[graph] assign[=] call[name[Graph], parameter[]]
... | keyword[def] identifier[bipartite_as_graph] ( identifier[self] )-> identifier[Graph] :
literal[string]
keyword[if] identifier[Graph] keyword[is] keyword[None] :
keyword[raise] identifier[ImportError] ( literal[string] )
identifier[graph] = identifier[Graph] ()
ide... | def bipartite_as_graph(self) -> Graph: # pragma: no cover
'Returns a :class:`graphviz.Graph` representation of this bipartite graph.'
if Graph is None:
raise ImportError('The graphviz package is required to draw the graph.') # depends on [control=['if'], data=[]]
graph = Graph()
nodes_left = {... |
def _gather_group_members(group, groups, users):
'''
Gather group members
'''
_group = __salt__['group.info'](group)
if not _group:
log.warning('Group %s does not exist, ignoring.', group)
return
for member in _group['members']:
if member not in users:
users... | def function[_gather_group_members, parameter[group, groups, users]]:
constant[
Gather group members
]
variable[_group] assign[=] call[call[name[__salt__]][constant[group.info]], parameter[name[group]]]
if <ast.UnaryOp object at 0x7da1b211c220> begin[:]
call[name[log].war... | keyword[def] identifier[_gather_group_members] ( identifier[group] , identifier[groups] , identifier[users] ):
literal[string]
identifier[_group] = identifier[__salt__] [ literal[string] ]( identifier[group] )
keyword[if] keyword[not] identifier[_group] :
identifier[log] . identifier[warni... | def _gather_group_members(group, groups, users):
"""
Gather group members
"""
_group = __salt__['group.info'](group)
if not _group:
log.warning('Group %s does not exist, ignoring.', group)
return # depends on [control=['if'], data=[]]
for member in _group['members']:
if ... |
def set_timestamp(self,timestamp=None):
"""
Set the timestamp of the linguistic processor, set to None for the current time
@type timestamp:string
@param timestamp: version of the linguistic processor
"""
if timestamp is None:
import time
timestamp... | def function[set_timestamp, parameter[self, timestamp]]:
constant[
Set the timestamp of the linguistic processor, set to None for the current time
@type timestamp:string
@param timestamp: version of the linguistic processor
]
if compare[name[timestamp] is constant[None]] ... | keyword[def] identifier[set_timestamp] ( identifier[self] , identifier[timestamp] = keyword[None] ):
literal[string]
keyword[if] identifier[timestamp] keyword[is] keyword[None] :
keyword[import] identifier[time]
identifier[timestamp] = identifier[time] . identifier[st... | def set_timestamp(self, timestamp=None):
"""
Set the timestamp of the linguistic processor, set to None for the current time
@type timestamp:string
@param timestamp: version of the linguistic processor
"""
if timestamp is None:
import time
timestamp = time.strftim... |
def set(self, key, value, lease=None, return_previous=None, timeout=None):
"""
Set the value for the key in the key-value store.
Setting a value on a key increments the revision
of the key-value store and generates one event in
the event history.
:param key: key is the ... | def function[set, parameter[self, key, value, lease, return_previous, timeout]]:
constant[
Set the value for the key in the key-value store.
Setting a value on a key increments the revision
of the key-value store and generates one event in
the event history.
:param key:... | keyword[def] identifier[set] ( identifier[self] , identifier[key] , identifier[value] , identifier[lease] = keyword[None] , identifier[return_previous] = keyword[None] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[assembler] = identifier[commons] . identifier[PutRequestAssembl... | def set(self, key, value, lease=None, return_previous=None, timeout=None):
"""
Set the value for the key in the key-value store.
Setting a value on a key increments the revision
of the key-value store and generates one event in
the event history.
:param key: key is the key,... |
def getDuration(self):
"""Returns the time in minutes taken for this analysis.
If the analysis is not yet 'ready to process', returns 0
If the analysis is still in progress (not yet verified),
duration = date_verified - date_start_process
Otherwise:
duration = cur... | def function[getDuration, parameter[self]]:
constant[Returns the time in minutes taken for this analysis.
If the analysis is not yet 'ready to process', returns 0
If the analysis is still in progress (not yet verified),
duration = date_verified - date_start_process
Otherwise:... | keyword[def] identifier[getDuration] ( identifier[self] ):
literal[string]
identifier[starttime] = identifier[self] . identifier[getStartProcessDate] ()
keyword[if] keyword[not] identifier[starttime] :
keyword[return] literal[int]
identifier[endtime] = id... | def getDuration(self):
"""Returns the time in minutes taken for this analysis.
If the analysis is not yet 'ready to process', returns 0
If the analysis is still in progress (not yet verified),
duration = date_verified - date_start_process
Otherwise:
duration = current... |
def setlist(self, key, values):
"""
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't... | def function[setlist, parameter[self, key, values]]:
constant[
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new valu... | keyword[def] identifier[setlist] ( identifier[self] , identifier[key] , identifier[values] ):
literal[string]
keyword[if] keyword[not] identifier[values] keyword[and] identifier[key] keyword[in] identifier[self] :
identifier[self] . identifier[pop] ( identifier[key] )
ke... | def setlist(self, key, values):
"""
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't hav... |
def data_source_and_uncertainty_flags(self, value=None):
"""Corresponds to IDD Field `data_source_and_uncertainty_flags` Initial
day of weather file is checked by EnergyPlus for validity (as shown
below) Each field is checked for "missing" as shown below. Reasonable
values, calculated va... | def function[data_source_and_uncertainty_flags, parameter[self, value]]:
constant[Corresponds to IDD Field `data_source_and_uncertainty_flags` Initial
day of weather file is checked by EnergyPlus for validity (as shown
below) Each field is checked for "missing" as shown below. Reasonable
... | keyword[def] identifier[data_source_and_uncertainty_flags] ( identifier[self] , identifier[value] = keyword[None] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[try] :
identifier[value] = identifier[str] ( identifi... | def data_source_and_uncertainty_flags(self, value=None):
"""Corresponds to IDD Field `data_source_and_uncertainty_flags` Initial
day of weather file is checked by EnergyPlus for validity (as shown
below) Each field is checked for "missing" as shown below. Reasonable
values, calculated values... |
def plot_curves_z(data, name, title=None):
"""Generates a simple plot of the quasiparticle weight decay curves given
data object with doping setup"""
plt.figure()
for zet, c in zip(data['zeta'], data['doping']):
plt.plot(data['u_int'], zet[:, 0], label='$n={}$'.format(str(c)))
if title !... | def function[plot_curves_z, parameter[data, name, title]]:
constant[Generates a simple plot of the quasiparticle weight decay curves given
data object with doping setup]
call[name[plt].figure, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da2054a40a0>, <ast.Name object at 0x7da2054... | keyword[def] identifier[plot_curves_z] ( identifier[data] , identifier[name] , identifier[title] = keyword[None] ):
literal[string]
identifier[plt] . identifier[figure] ()
keyword[for] identifier[zet] , identifier[c] keyword[in] identifier[zip] ( identifier[data] [ literal[string] ], identifier[da... | def plot_curves_z(data, name, title=None):
"""Generates a simple plot of the quasiparticle weight decay curves given
data object with doping setup"""
plt.figure()
for (zet, c) in zip(data['zeta'], data['doping']):
plt.plot(data['u_int'], zet[:, 0], label='$n={}$'.format(str(c))) # depends on... |
def provider_for_url(self, url):
"""
Find the right provider for a URL
"""
for provider, regex in self.get_registry().items():
if re.match(regex, url) is not None:
return provider
raise OEmbedMissingEndpoint('No endpoint matches URL: %s' % url... | def function[provider_for_url, parameter[self, url]]:
constant[
Find the right provider for a URL
]
for taget[tuple[[<ast.Name object at 0x7da18ede4490>, <ast.Name object at 0x7da18ede46a0>]]] in starred[call[call[name[self].get_registry, parameter[]].items, parameter[]]] begin[:]
... | keyword[def] identifier[provider_for_url] ( identifier[self] , identifier[url] ):
literal[string]
keyword[for] identifier[provider] , identifier[regex] keyword[in] identifier[self] . identifier[get_registry] (). identifier[items] ():
keyword[if] identifier[re] . identifier[match] (... | def provider_for_url(self, url):
"""
Find the right provider for a URL
"""
for (provider, regex) in self.get_registry().items():
if re.match(regex, url) is not None:
return provider # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
raise OEm... |
def output_of(*cmd: Optional[str], **kwargs) -> str:
"""Invokes a subprocess and returns its output as a string.
Args:
cmd: Components of the command to execute, e.g. ["echo", "dog"].
**kwargs: Extra arguments for asyncio.create_subprocess_shell, such as
a cwd (current working direc... | def function[output_of, parameter[]]:
constant[Invokes a subprocess and returns its output as a string.
Args:
cmd: Components of the command to execute, e.g. ["echo", "dog"].
**kwargs: Extra arguments for asyncio.create_subprocess_shell, such as
a cwd (current working directory)... | keyword[def] identifier[output_of] (* identifier[cmd] : identifier[Optional] [ identifier[str] ],** identifier[kwargs] )-> identifier[str] :
literal[string]
identifier[result] = identifier[cast] ( identifier[str] , identifier[run_cmd] (* identifier[cmd] ,
identifier[log_run_to_stderr] = keyword[False]... | def output_of(*cmd: Optional[str], **kwargs) -> str:
"""Invokes a subprocess and returns its output as a string.
Args:
cmd: Components of the command to execute, e.g. ["echo", "dog"].
**kwargs: Extra arguments for asyncio.create_subprocess_shell, such as
a cwd (current working direc... |
def retry_after(cls, response, default=5, _now=time.time):
"""
Parse the Retry-After value from a response.
"""
val = response.headers.getRawHeaders(b'retry-after', [default])[0]
try:
return int(val)
except ValueError:
return http.stringToDatetime(... | def function[retry_after, parameter[cls, response, default, _now]]:
constant[
Parse the Retry-After value from a response.
]
variable[val] assign[=] call[call[name[response].headers.getRawHeaders, parameter[constant[b'retry-after'], list[[<ast.Name object at 0x7da18f58f040>]]]]][constant... | keyword[def] identifier[retry_after] ( identifier[cls] , identifier[response] , identifier[default] = literal[int] , identifier[_now] = identifier[time] . identifier[time] ):
literal[string]
identifier[val] = identifier[response] . identifier[headers] . identifier[getRawHeaders] ( literal[string] ,... | def retry_after(cls, response, default=5, _now=time.time):
"""
Parse the Retry-After value from a response.
"""
val = response.headers.getRawHeaders(b'retry-after', [default])[0]
try:
return int(val) # depends on [control=['try'], data=[]]
except ValueError:
return http.... |
def _set_traffic_eng(self, v, load=False):
"""
Setter method for traffic_eng, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/traffic_eng (container)
If this variable is read-only (config: false) in the
so... | def function[_set_traffic_eng, parameter[self, v, load]]:
constant[
Setter method for traffic_eng, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/traffic_eng (container)
If this variable is read-only (con... | keyword[def] identifier[_set_traffic_eng] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
id... | def _set_traffic_eng(self, v, load=False):
"""
Setter method for traffic_eng, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/traffic_eng (container)
If this variable is read-only (config: false) in the
so... |
def getv(self, r):
""" Like the above, but returns the <int> value.
"""
v = self.get(r)
if not is_unknown(v):
try:
v = int(v)
except ValueError:
v = None
else:
v = None
return v | def function[getv, parameter[self, r]]:
constant[ Like the above, but returns the <int> value.
]
variable[v] assign[=] call[name[self].get, parameter[name[r]]]
if <ast.UnaryOp object at 0x7da20c6c4cd0> begin[:]
<ast.Try object at 0x7da20c6c4dc0>
return[name[v]] | keyword[def] identifier[getv] ( identifier[self] , identifier[r] ):
literal[string]
identifier[v] = identifier[self] . identifier[get] ( identifier[r] )
keyword[if] keyword[not] identifier[is_unknown] ( identifier[v] ):
keyword[try] :
identifier[v] = identif... | def getv(self, r):
""" Like the above, but returns the <int> value.
"""
v = self.get(r)
if not is_unknown(v):
try:
v = int(v) # depends on [control=['try'], data=[]]
except ValueError:
v = None # depends on [control=['except'], data=[]] # depends on [contro... |
def trim(self, lower=None, upper=None):
"""Trim upper values in accordance with :math:`IC \\leq ICMAX`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(5)
>>> icmax(2.0)
>>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0)
>>> states.ic
ic(0.... | def function[trim, parameter[self, lower, upper]]:
constant[Trim upper values in accordance with :math:`IC \leq ICMAX`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(5)
>>> icmax(2.0)
>>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0)
>>> states.... | keyword[def] identifier[trim] ( identifier[self] , identifier[lower] = keyword[None] , identifier[upper] = keyword[None] ):
literal[string]
keyword[if] identifier[upper] keyword[is] keyword[None] :
identifier[control] = identifier[self] . identifier[subseqs] . identifier[seqs] . ide... | def trim(self, lower=None, upper=None):
"""Trim upper values in accordance with :math:`IC \\leq ICMAX`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(5)
>>> icmax(2.0)
>>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0)
>>> states.ic
ic(0.0, 0... |
def proccesser_markdown(lowstate_item, config, **kwargs):
'''
Takes low state data and returns a dict of proccessed data
that is by default used in a jinja template when rendering a markdown highstate_doc.
This `lowstate_item_markdown` given a lowstate item, returns a dict like:
.. code-block:: ya... | def function[proccesser_markdown, parameter[lowstate_item, config]]:
constant[
Takes low state data and returns a dict of proccessed data
that is by default used in a jinja template when rendering a markdown highstate_doc.
This `lowstate_item_markdown` given a lowstate item, returns a dict like:
... | keyword[def] identifier[proccesser_markdown] ( identifier[lowstate_item] , identifier[config] ,** identifier[kwargs] ):
literal[string]
identifier[s] = identifier[lowstate_item]
identifier[state_function] = literal[string] . identifier[format] ( identifier[s] [ literal[string] ], identifier[s] [... | def proccesser_markdown(lowstate_item, config, **kwargs):
"""
Takes low state data and returns a dict of proccessed data
that is by default used in a jinja template when rendering a markdown highstate_doc.
This `lowstate_item_markdown` given a lowstate item, returns a dict like:
.. code-block:: ya... |
def clear_imgs(self) -> None:
"Clear the widget's images preview pane."
self._preview_header.value = self._heading
self._img_pane.children = tuple() | def function[clear_imgs, parameter[self]]:
constant[Clear the widget's images preview pane.]
name[self]._preview_header.value assign[=] name[self]._heading
name[self]._img_pane.children assign[=] call[name[tuple], parameter[]] | keyword[def] identifier[clear_imgs] ( identifier[self] )-> keyword[None] :
literal[string]
identifier[self] . identifier[_preview_header] . identifier[value] = identifier[self] . identifier[_heading]
identifier[self] . identifier[_img_pane] . identifier[children] = identifier[tuple] () | def clear_imgs(self) -> None:
"""Clear the widget's images preview pane."""
self._preview_header.value = self._heading
self._img_pane.children = tuple() |
def get_value(self, sid, dt, field):
"""
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
colname : string
The price field. e.g. ('open', 'high', 'low', 'close'... | def function[get_value, parameter[self, sid, dt, field]]:
constant[
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
colname : string
The price field. e.g. ('op... | keyword[def] identifier[get_value] ( identifier[self] , identifier[sid] , identifier[dt] , identifier[field] ):
literal[string]
identifier[ix] = identifier[self] . identifier[sid_day_index] ( identifier[sid] , identifier[dt] )
identifier[price] = identifier[self] . identifier[_spot_col] ( ... | def get_value(self, sid, dt, field):
"""
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
colname : string
The price field. e.g. ('open', 'high', 'low', 'close', 'v... |
def coord(self, offset=(0,0)):
'''return lat,lon within a tile given (offsetx,offsety)'''
(tilex, tiley) = self.tile
(offsetx, offsety) = offset
world_tiles = 1<<self.zoom
x = ( tilex + 1.0*offsetx/TILES_WIDTH ) / (world_tiles/2.) - 1
y = ( tiley + 1.0*offsety/TILES_HEIGHT) / (world_tiles/2.) - 1
lon = x ... | def function[coord, parameter[self, offset]]:
constant[return lat,lon within a tile given (offsetx,offsety)]
<ast.Tuple object at 0x7da1b1790310> assign[=] name[self].tile
<ast.Tuple object at 0x7da1b17912a0> assign[=] name[offset]
variable[world_tiles] assign[=] binary_operation[constan... | keyword[def] identifier[coord] ( identifier[self] , identifier[offset] =( literal[int] , literal[int] )):
literal[string]
( identifier[tilex] , identifier[tiley] )= identifier[self] . identifier[tile]
( identifier[offsetx] , identifier[offsety] )= identifier[offset]
identifier[world_tiles] = literal[int]... | def coord(self, offset=(0, 0)):
"""return lat,lon within a tile given (offsetx,offsety)"""
(tilex, tiley) = self.tile
(offsetx, offsety) = offset
world_tiles = 1 << self.zoom
x = (tilex + 1.0 * offsetx / TILES_WIDTH) / (world_tiles / 2.0) - 1
y = (tiley + 1.0 * offsety / TILES_HEIGHT) / (world_t... |
def get_proc_outputs(self):
"""
If stored procedure has result sets and OUTPUT parameters use this method
after you processed all result sets to get values of OUTPUT parameters.
:return: A list of output parameter values.
"""
self._session.complete_rpc()
results ... | def function[get_proc_outputs, parameter[self]]:
constant[
If stored procedure has result sets and OUTPUT parameters use this method
after you processed all result sets to get values of OUTPUT parameters.
:return: A list of output parameter values.
]
call[name[self]._sess... | keyword[def] identifier[get_proc_outputs] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_session] . identifier[complete_rpc] ()
identifier[results] =[ keyword[None] ]* identifier[len] ( identifier[self] . identifier[_session] . identifier[output_params] . identifier[... | def get_proc_outputs(self):
"""
If stored procedure has result sets and OUTPUT parameters use this method
after you processed all result sets to get values of OUTPUT parameters.
:return: A list of output parameter values.
"""
self._session.complete_rpc()
results = [None] * le... |
def getscript(self, name):
"""Download a script from the server
See MANAGESIEVE specifications, section 2.9
:param name: script's name
:rtype: string
:returns: the script's content on succes, None otherwise
"""
code, data, content = self.__send_command(
... | def function[getscript, parameter[self, name]]:
constant[Download a script from the server
See MANAGESIEVE specifications, section 2.9
:param name: script's name
:rtype: string
:returns: the script's content on succes, None otherwise
]
<ast.Tuple object at 0x7da... | keyword[def] identifier[getscript] ( identifier[self] , identifier[name] ):
literal[string]
identifier[code] , identifier[data] , identifier[content] = identifier[self] . identifier[__send_command] (
literal[string] ,[ identifier[name] . identifier[encode] ( literal[string] )], identifier[... | def getscript(self, name):
"""Download a script from the server
See MANAGESIEVE specifications, section 2.9
:param name: script's name
:rtype: string
:returns: the script's content on succes, None otherwise
"""
(code, data, content) = self.__send_command('GETSCRIPT', [n... |
def dump_cookie(
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=False,
httponly=False,
charset="utf-8",
sync_expires=True,
max_size=4093,
samesite=None,
):
"""Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
The parameter... | def function[dump_cookie, parameter[key, value, max_age, expires, path, domain, secure, httponly, charset, sync_expires, max_size, samesite]]:
constant[Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
The parameters are the same as in the cookie Morsel object in the
Python standard libr... | keyword[def] identifier[dump_cookie] (
identifier[key] ,
identifier[value] = literal[string] ,
identifier[max_age] = keyword[None] ,
identifier[expires] = keyword[None] ,
identifier[path] = literal[string] ,
identifier[domain] = keyword[None] ,
identifier[secure] = keyword[False] ,
identifier[httponly] = keyw... | def dump_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, charset='utf-8', sync_expires=True, max_size=4093, samesite=None):
"""Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
The parameters are the same as in the cookie Morsel object in th... |
def _set_up_reference_fields(new_class):
"""Walk through relation fields and setup shadow attributes"""
if new_class.meta_.declared_fields:
for _, field in new_class.meta_.declared_fields.items():
if isinstance(field, Reference):
shadow_field_name, shadow_... | def function[_set_up_reference_fields, parameter[new_class]]:
constant[Walk through relation fields and setup shadow attributes]
if name[new_class].meta_.declared_fields begin[:]
for taget[tuple[[<ast.Name object at 0x7da20c76d570>, <ast.Name object at 0x7da20c76d2a0>]]] in starred[call[... | keyword[def] identifier[_set_up_reference_fields] ( identifier[new_class] ):
literal[string]
keyword[if] identifier[new_class] . identifier[meta_] . identifier[declared_fields] :
keyword[for] identifier[_] , identifier[field] keyword[in] identifier[new_class] . identifier[meta_] . ... | def _set_up_reference_fields(new_class):
"""Walk through relation fields and setup shadow attributes"""
if new_class.meta_.declared_fields:
for (_, field) in new_class.meta_.declared_fields.items():
if isinstance(field, Reference):
(shadow_field_name, shadow_field) = field.ge... |
def _read_mode_route(self, size, kind):
"""Read options with route data.
Positional arguments:
* size - int, length of option
* kind - int, 7/131/137 (RR/LSR/SSR)
Returns:
* dict -- extracted option with route data
Structure of these options:
... | def function[_read_mode_route, parameter[self, size, kind]]:
constant[Read options with route data.
Positional arguments:
* size - int, length of option
* kind - int, 7/131/137 (RR/LSR/SSR)
Returns:
* dict -- extracted option with route data
Structu... | keyword[def] identifier[_read_mode_route] ( identifier[self] , identifier[size] , identifier[kind] ):
literal[string]
keyword[if] identifier[size] < literal[int] keyword[or] ( identifier[size] - literal[int] )% literal[int] != literal[int] :
keyword[raise] identifier[ProtocolError] ... | def _read_mode_route(self, size, kind):
"""Read options with route data.
Positional arguments:
* size - int, length of option
* kind - int, 7/131/137 (RR/LSR/SSR)
Returns:
* dict -- extracted option with route data
Structure of these options:
... |
def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None):
"""
Fit an autoregressive model with additional exogenous variables. The model predicts a value
at time t of a dependent variable, Y, as a function of previous values of Y, and a combination
of previous values of ... | def function[fit_model, parameter[y, x, yMaxLag, xMaxLag, includesOriginalX, noIntercept, sc]]:
constant[
Fit an autoregressive model with additional exogenous variables. The model predicts a value
at time t of a dependent variable, Y, as a function of previous values of Y, and a combination
of prev... | keyword[def] identifier[fit_model] ( identifier[y] , identifier[x] , identifier[yMaxLag] , identifier[xMaxLag] , identifier[includesOriginalX] = keyword[True] , identifier[noIntercept] = keyword[False] , identifier[sc] = keyword[None] ):
literal[string]
keyword[assert] identifier[sc] != keyword[None] , li... | def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None):
"""
Fit an autoregressive model with additional exogenous variables. The model predicts a value
at time t of a dependent variable, Y, as a function of previous values of Y, and a combination
of previous values of ... |
def pg2df(res):
'''
takes a getlog requests result
returns a table as df
'''
# parse res
soup = BeautifulSoup(res.text)
if u'Pas de r\xe9ponse pour cette recherche.' in soup.text:
pass # <-- don't pass !
else:
params = urlparse.parse_qs(urlparse.urlsplit... | def function[pg2df, parameter[res]]:
constant[
takes a getlog requests result
returns a table as df
]
variable[soup] assign[=] call[name[BeautifulSoup], parameter[name[res].text]]
if compare[constant[Pas de réponse pour cette recherche.] in name[soup].text] begin[:]
p... | keyword[def] identifier[pg2df] ( identifier[res] ):
literal[string]
identifier[soup] = identifier[BeautifulSoup] ( identifier[res] . identifier[text] )
keyword[if] literal[string] keyword[in] identifier[soup] . identifier[text] :
keyword[pass]
keyword[else] :
identifi... | def pg2df(res):
"""
takes a getlog requests result
returns a table as df
"""
# parse res
soup = BeautifulSoup(res.text)
if u'Pas de réponse pour cette recherche.' in soup.text:
pass # <-- don't pass ! # depends on [control=['if'], data=[]]
else:
params = urlpars... |
def method_already_there(object_type, method_name, this_class_only=False):
"""
Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs from
the one in `object`.
:param object_type:
:param method_name:
:param this_class_only:
:return:
... | def function[method_already_there, parameter[object_type, method_name, this_class_only]]:
constant[
Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs from
the one in `object`.
:param object_type:
:param method_name:
:param this_c... | keyword[def] identifier[method_already_there] ( identifier[object_type] , identifier[method_name] , identifier[this_class_only] = keyword[False] ):
literal[string]
keyword[if] identifier[this_class_only] :
keyword[return] identifier[method_name] keyword[in] identifier[vars] ( identifier[object... | def method_already_there(object_type, method_name, this_class_only=False):
"""
Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs from
the one in `object`.
:param object_type:
:param method_name:
:param this_class_only:
:return:
... |
def _check_parameter_range(s_min, s_max):
r"""Performs a final check on a clipped parameter range.
.. note::
This is a helper for :func:`clip_range`.
If both values are unchanged from the "unset" default, this returns
the whole interval :math:`\left[0.0, 1.0\right]`.
If only one of the va... | def function[_check_parameter_range, parameter[s_min, s_max]]:
constant[Performs a final check on a clipped parameter range.
.. note::
This is a helper for :func:`clip_range`.
If both values are unchanged from the "unset" default, this returns
the whole interval :math:`\left[0.0, 1.0\right... | keyword[def] identifier[_check_parameter_range] ( identifier[s_min] , identifier[s_max] ):
literal[string]
keyword[if] identifier[s_min] == identifier[DEFAULT_S_MIN] :
keyword[return] literal[int] , literal[int]
keyword[if] identifier[s_max] == identifier[DEFAULT_S_MAX] :
... | def _check_parameter_range(s_min, s_max):
"""Performs a final check on a clipped parameter range.
.. note::
This is a helper for :func:`clip_range`.
If both values are unchanged from the "unset" default, this returns
the whole interval :math:`\\left[0.0, 1.0\\right]`.
If only one of the v... |
def _remove_overlaps(in_file, out_dir, data):
"""Remove regions that overlap with next region, these result in issues with PureCN.
"""
out_file = os.path.join(out_dir, "%s-nooverlaps%s" % utils.splitext_plus(os.path.basename(in_file)))
if not utils.file_uptodate(out_file, in_file):
with file_tra... | def function[_remove_overlaps, parameter[in_file, out_dir, data]]:
constant[Remove regions that overlap with next region, these result in issues with PureCN.
]
variable[out_file] assign[=] call[name[os].path.join, parameter[name[out_dir], binary_operation[constant[%s-nooverlaps%s] <ast.Mod object at... | keyword[def] identifier[_remove_overlaps] ( identifier[in_file] , identifier[out_dir] , identifier[data] ):
literal[string]
identifier[out_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[out_dir] , literal[string] % identifier[utils] . identifier[splitext_plus] ( identifier[os] . ... | def _remove_overlaps(in_file, out_dir, data):
"""Remove regions that overlap with next region, these result in issues with PureCN.
"""
out_file = os.path.join(out_dir, '%s-nooverlaps%s' % utils.splitext_plus(os.path.basename(in_file)))
if not utils.file_uptodate(out_file, in_file):
with file_tra... |
def new(conf):
"""Factory to create hash functions from configuration section. If an
algorithm takes custom parameters, you can separate them by a colon like
this: pbkdf2:arg1:arg2:arg3."""
algorithm = conf.get("algorithm")
salt = conf.get("salt").encode("utf-8")
if algorithm == "none":
... | def function[new, parameter[conf]]:
constant[Factory to create hash functions from configuration section. If an
algorithm takes custom parameters, you can separate them by a colon like
this: pbkdf2:arg1:arg2:arg3.]
variable[algorithm] assign[=] call[name[conf].get, parameter[constant[algorithm]]... | keyword[def] identifier[new] ( identifier[conf] ):
literal[string]
identifier[algorithm] = identifier[conf] . identifier[get] ( literal[string] )
identifier[salt] = identifier[conf] . identifier[get] ( literal[string] ). identifier[encode] ( literal[string] )
keyword[if] identifier[algorithm] ... | def new(conf):
"""Factory to create hash functions from configuration section. If an
algorithm takes custom parameters, you can separate them by a colon like
this: pbkdf2:arg1:arg2:arg3."""
algorithm = conf.get('algorithm')
salt = conf.get('salt').encode('utf-8')
if algorithm == 'none':
... |
async def handle_action(self, action: str, request_id: str, **kwargs):
"""
run the action.
"""
try:
await self.check_permissions(action, **kwargs)
if action not in self.actions:
raise MethodNotAllowed(method=action)
content, status = ... | <ast.AsyncFunctionDef object at 0x7da204623cd0> | keyword[async] keyword[def] identifier[handle_action] ( identifier[self] , identifier[action] : identifier[str] , identifier[request_id] : identifier[str] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
keyword[await] identifier[self] . identifier[check_permissions] ( identi... | async def handle_action(self, action: str, request_id: str, **kwargs):
"""
run the action.
"""
try:
await self.check_permissions(action, **kwargs)
if action not in self.actions:
raise MethodNotAllowed(method=action) # depends on [control=['if'], data=['action']]
... |
def margin(self):
"""
[float] 总保证金
"""
return sum(position.margin for position in six.itervalues(self._positions)) | def function[margin, parameter[self]]:
constant[
[float] 总保证金
]
return[call[name[sum], parameter[<ast.GeneratorExp object at 0x7da1b21782b0>]]] | keyword[def] identifier[margin] ( identifier[self] ):
literal[string]
keyword[return] identifier[sum] ( identifier[position] . identifier[margin] keyword[for] identifier[position] keyword[in] identifier[six] . identifier[itervalues] ( identifier[self] . identifier[_positions] )) | def margin(self):
"""
[float] 总保证金
"""
return sum((position.margin for position in six.itervalues(self._positions))) |
def restore_layout(self, name, *args):
"""
Restores given layout.
:param name: Layout name.
:type name: unicode
:param \*args: Arguments.
:type \*args: \*
:return: Method success.
:rtype: bool
"""
layout = self.__layouts.get(name)
... | def function[restore_layout, parameter[self, name]]:
constant[
Restores given layout.
:param name: Layout name.
:type name: unicode
:param \*args: Arguments.
:type \*args: \*
:return: Method success.
:rtype: bool
]
variable[layout] assign[... | keyword[def] identifier[restore_layout] ( identifier[self] , identifier[name] ,* identifier[args] ):
literal[string]
identifier[layout] = identifier[self] . identifier[__layouts] . identifier[get] ( identifier[name] )
keyword[if] keyword[not] identifier[layout] :
keyword[ra... | def restore_layout(self, name, *args):
"""
Restores given layout.
:param name: Layout name.
:type name: unicode
:param \\*args: Arguments.
:type \\*args: \\*
:return: Method success.
:rtype: bool
"""
layout = self.__layouts.get(name)
if not la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.