code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def on_exit(self):
"""
Cleanup after the command finishes.
Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs.
"""
if self.zip_path:
# Only try to remove uploaded zip if we're running a command that has loaded credentials
if s... | def function[on_exit, parameter[self]]:
constant[
Cleanup after the command finishes.
Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs.
]
if name[self].zip_path begin[:]
if name[self].load_credentials begin[:]
... | keyword[def] identifier[on_exit] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[zip_path] :
keyword[if] identifier[self] . identifier[load_credentials] :
identifier[self] . identifier[remove_uploaded_zip] ()
ide... | def on_exit(self):
"""
Cleanup after the command finishes.
Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs.
"""
if self.zip_path:
# Only try to remove uploaded zip if we're running a command that has loaded credentials
if self.load_credent... |
def best_hits(self):
"""
returns a dict with query => best mapped position
"""
self.quality_sort()
best_hits = dict((query, next(blines)) for (query, blines) in \
groupby(self, lambda x: x.query))
self.ref_sort()
return best_hits | def function[best_hits, parameter[self]]:
constant[
returns a dict with query => best mapped position
]
call[name[self].quality_sort, parameter[]]
variable[best_hits] assign[=] call[name[dict], parameter[<ast.GeneratorExp object at 0x7da18f00fb50>]]
call[name[self].ref_so... | keyword[def] identifier[best_hits] ( identifier[self] ):
literal[string]
identifier[self] . identifier[quality_sort] ()
identifier[best_hits] = identifier[dict] (( identifier[query] , identifier[next] ( identifier[blines] )) keyword[for] ( identifier[query] , identifier[blines] ) keyword[... | def best_hits(self):
"""
returns a dict with query => best mapped position
"""
self.quality_sort()
best_hits = dict(((query, next(blines)) for (query, blines) in groupby(self, lambda x: x.query)))
self.ref_sort()
return best_hits |
def findNextSection(self, scope, name):
""" Starts with given par (scope+name) and looks further down the list
of parameters until one of a different non-null scope is found. Upon
success, returns the (scope, name) tuple, otherwise (None, None). """
# first find index of starting point
... | def function[findNextSection, parameter[self, scope, name]]:
constant[ Starts with given par (scope+name) and looks further down the list
of parameters until one of a different non-null scope is found. Upon
success, returns the (scope, name) tuple, otherwise (None, None). ]
variable[pli... | keyword[def] identifier[findNextSection] ( identifier[self] , identifier[scope] , identifier[name] ):
literal[string]
identifier[plist] = identifier[self] . identifier[_taskParsObj] . identifier[getParList] ()
identifier[start] = literal[int]
keyword[for] identifier[i] ... | def findNextSection(self, scope, name):
""" Starts with given par (scope+name) and looks further down the list
of parameters until one of a different non-null scope is found. Upon
success, returns the (scope, name) tuple, otherwise (None, None). """
# first find index of starting point
plis... |
def before_sample(analysis_request):
"""Method triggered before "sample" transition for the Analysis Request
passed in is performed
"""
if not analysis_request.getDateSampled():
analysis_request.setDateSampled(DateTime())
if not analysis_request.getSampler():
analysis_request.setSamp... | def function[before_sample, parameter[analysis_request]]:
constant[Method triggered before "sample" transition for the Analysis Request
passed in is performed
]
if <ast.UnaryOp object at 0x7da1b1d3b340> begin[:]
call[name[analysis_request].setDateSampled, parameter[call[name[Date... | keyword[def] identifier[before_sample] ( identifier[analysis_request] ):
literal[string]
keyword[if] keyword[not] identifier[analysis_request] . identifier[getDateSampled] ():
identifier[analysis_request] . identifier[setDateSampled] ( identifier[DateTime] ())
keyword[if] keyword[not] ide... | def before_sample(analysis_request):
"""Method triggered before "sample" transition for the Analysis Request
passed in is performed
"""
if not analysis_request.getDateSampled():
analysis_request.setDateSampled(DateTime()) # depends on [control=['if'], data=[]]
if not analysis_request.getSam... |
def run(cmd, background=False):
"""
Executes the given command
If background flag is True the command will run in background
and this method will return a :class:`Popen` object
If background is False (default) the command will run in this thread
and this method will return stdout.
A Comma... | def function[run, parameter[cmd, background]]:
constant[
Executes the given command
If background flag is True the command will run in background
and this method will return a :class:`Popen` object
If background is False (default) the command will run in this thread
and this method will re... | keyword[def] identifier[run] ( identifier[cmd] , identifier[background] = keyword[False] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] % identifier[cmd] )
keyword[if] identifier[background] :
keyword[return] identifier[subprocess] . identifier[Popen] ( identif... | def run(cmd, background=False):
"""
Executes the given command
If background flag is True the command will run in background
and this method will return a :class:`Popen` object
If background is False (default) the command will run in this thread
and this method will return stdout.
A Comma... |
def Task(entry): # pylint: disable=invalid-name
"""
Decorator with which classes, who act as tasks in a `Lane`, must be decorated. When a class is
being decorated, it becomes a child of `LaneTask`.
Parameters
----------
entry: The name of the task's "main" method, i.e. the method which is exec... | def function[Task, parameter[entry]]:
constant[
Decorator with which classes, who act as tasks in a `Lane`, must be decorated. When a class is
being decorated, it becomes a child of `LaneTask`.
Parameters
----------
entry: The name of the task's "main" method, i.e. the method which is execu... | keyword[def] identifier[Task] ( identifier[entry] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[entry] , identifier[string_types] ):
keyword[raise] identifier[TypeError] ( literal[string]
literal[string]
literal[string] )... | def Task(entry): # pylint: disable=invalid-name
'\n Decorator with which classes, who act as tasks in a `Lane`, must be decorated. When a class is\n being decorated, it becomes a child of `LaneTask`.\n\n Parameters\n ----------\n entry: The name of the task\'s "main" method, i.e. the method which is... |
def required_unique(objects, key):
"""
A pyrsistent invariant which requires all objects in the given iterable to
have a unique key.
:param objects: The objects to check.
:param key: A one-argument callable to compute the key of an object.
:return: An invariant failure if any two or more objec... | def function[required_unique, parameter[objects, key]]:
constant[
A pyrsistent invariant which requires all objects in the given iterable to
have a unique key.
:param objects: The objects to check.
:param key: A one-argument callable to compute the key of an object.
:return: An invariant f... | keyword[def] identifier[required_unique] ( identifier[objects] , identifier[key] ):
literal[string]
identifier[keys] ={}
identifier[duplicate] = identifier[set] ()
keyword[for] identifier[k] keyword[in] identifier[map] ( identifier[key] , identifier[objects] ):
identifier[keys] [ iden... | def required_unique(objects, key):
"""
A pyrsistent invariant which requires all objects in the given iterable to
have a unique key.
:param objects: The objects to check.
:param key: A one-argument callable to compute the key of an object.
:return: An invariant failure if any two or more objec... |
def _record_score(self, history, current_score):
"""Record the current store and, if applicable, if it's the best score
yet.
"""
history.record(self.name_, current_score)
is_best = self._is_best_score(current_score)
if is_best is None:
return
histor... | def function[_record_score, parameter[self, history, current_score]]:
constant[Record the current store and, if applicable, if it's the best score
yet.
]
call[name[history].record, parameter[name[self].name_, name[current_score]]]
variable[is_best] assign[=] call[name[self]._is_... | keyword[def] identifier[_record_score] ( identifier[self] , identifier[history] , identifier[current_score] ):
literal[string]
identifier[history] . identifier[record] ( identifier[self] . identifier[name_] , identifier[current_score] )
identifier[is_best] = identifier[self] . identifier[... | def _record_score(self, history, current_score):
"""Record the current store and, if applicable, if it's the best score
yet.
"""
history.record(self.name_, current_score)
is_best = self._is_best_score(current_score)
if is_best is None:
return # depends on [control=['if'], data=... |
def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 2:
return self.print_help()
source_url = self.actual_arguments[0]
output_file_path = self.actual_arguments[1]
... | def function[perform_command, parameter[self]]:
constant[
Perform command and return the appropriate exit code.
:rtype: int
]
if compare[call[name[len], parameter[name[self].actual_arguments]] less[<] constant[2]] begin[:]
return[call[name[self].print_help, parameter[]]]... | keyword[def] identifier[perform_command] ( identifier[self] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[actual_arguments] )< literal[int] :
keyword[return] identifier[self] . identifier[print_help] ()
identifier[source_url] = identifier[sel... | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 2:
return self.print_help() # depends on [control=['if'], data=[]]
source_url = self.actual_arguments[0]
output_file_path = self.actual_a... |
def worker(self, fifo):
'''Worker thread continuously filtering and converting data when data becomes available.
'''
logging.debug('Starting worker thread for %s', fifo)
self._fifo_conditions[fifo].acquire()
while True:
try:
data_tuple = self._f... | def function[worker, parameter[self, fifo]]:
constant[Worker thread continuously filtering and converting data when data becomes available.
]
call[name[logging].debug, parameter[constant[Starting worker thread for %s], name[fifo]]]
call[call[name[self]._fifo_conditions][name[fifo]].acqui... | keyword[def] identifier[worker] ( identifier[self] , identifier[fifo] ):
literal[string]
identifier[logging] . identifier[debug] ( literal[string] , identifier[fifo] )
identifier[self] . identifier[_fifo_conditions] [ identifier[fifo] ]. identifier[acquire] ()
keyword[while] ... | def worker(self, fifo):
"""Worker thread continuously filtering and converting data when data becomes available.
"""
logging.debug('Starting worker thread for %s', fifo)
self._fifo_conditions[fifo].acquire()
while True:
try:
data_tuple = self._fifo_data_deque[fifo].popleft() ... |
def from_config(cls, filename):
"""
Create a SlackObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``webhook_url`` and can optionally set
``bot_name``, ``icon``, ``completed_text``,... | def function[from_config, parameter[cls, filename]]:
constant[
Create a SlackObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``webhook_url`` and can optionally set
``bot_name``, ``... | keyword[def] identifier[from_config] ( identifier[cls] , identifier[filename] ):
literal[string]
identifier[d] = identifier[load_config_file] ( identifier[filename] )
identifier[obs] = keyword[None]
keyword[if] literal[string] keyword[in] identifier[d] :
identifie... | def from_config(cls, filename):
"""
Create a SlackObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``webhook_url`` and can optionally set
``bot_name``, ``icon``, ``completed_text``, ``i... |
def receive_data(socket):
"""Receive an answer from the daemon and return the response.
Args:
socket (socket.socket): A socket that is connected to the daemon.
Returns:
dir or string: The unpickled answer.
"""
answer = b""
while True:
packet = socket.recv(4096)
if n... | def function[receive_data, parameter[socket]]:
constant[Receive an answer from the daemon and return the response.
Args:
socket (socket.socket): A socket that is connected to the daemon.
Returns:
dir or string: The unpickled answer.
]
variable[answer] assign[=] constant[b'']
... | keyword[def] identifier[receive_data] ( identifier[socket] ):
literal[string]
identifier[answer] = literal[string]
keyword[while] keyword[True] :
identifier[packet] = identifier[socket] . identifier[recv] ( literal[int] )
keyword[if] keyword[not] identifier[packet] : keyword[brea... | def receive_data(socket):
"""Receive an answer from the daemon and return the response.
Args:
socket (socket.socket): A socket that is connected to the daemon.
Returns:
dir or string: The unpickled answer.
"""
answer = b''
while True:
packet = socket.recv(4096)
if n... |
def _check_success(self):
"""
Returns True if task has been completed.
"""
# remember objects that are on the correct pegs
gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id]
for i in range(len(self.ob_inits)):
obj_str = str(self.item_names[i]) + "0"... | def function[_check_success, parameter[self]]:
constant[
Returns True if task has been completed.
]
variable[gripper_site_pos] assign[=] call[name[self].sim.data.site_xpos][name[self].eef_site_id]
for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter... | keyword[def] identifier[_check_success] ( identifier[self] ):
literal[string]
identifier[gripper_site_pos] = identifier[self] . identifier[sim] . identifier[data] . identifier[site_xpos] [ identifier[self] . identifier[eef_site_id] ]
keyword[for] identifier[i] keyword[in] iden... | def _check_success(self):
"""
Returns True if task has been completed.
"""
# remember objects that are on the correct pegs
gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id]
for i in range(len(self.ob_inits)):
obj_str = str(self.item_names[i]) + '0'
obj_pos = se... |
def _parse (self):
"""Parse the BDF mime structure and record the locations of the binary
blobs. Sets up various data fields in the BDFData object."""
feedparser = FeedParser (Message)
binarychunks = {}
sizeinfo = None
headxml = None
self.fp.seek (0, 0)
... | def function[_parse, parameter[self]]:
constant[Parse the BDF mime structure and record the locations of the binary
blobs. Sets up various data fields in the BDFData object.]
variable[feedparser] assign[=] call[name[FeedParser], parameter[name[Message]]]
variable[binarychunks] assign[=] ... | keyword[def] identifier[_parse] ( identifier[self] ):
literal[string]
identifier[feedparser] = identifier[FeedParser] ( identifier[Message] )
identifier[binarychunks] ={}
identifier[sizeinfo] = keyword[None]
identifier[headxml] = keyword[None]
identifie... | def _parse(self):
"""Parse the BDF mime structure and record the locations of the binary
blobs. Sets up various data fields in the BDFData object."""
feedparser = FeedParser(Message)
binarychunks = {}
sizeinfo = None
headxml = None
self.fp.seek(0, 0)
while True:
data = self.f... |
def settings(self, key=None, section=None):
"""The settings overridden from the wandb/settings file.
Args:
key (str, optional): If provided only this setting is returned
section (str, optional): If provided this section of the setting file is
used, defaults to "defau... | def function[settings, parameter[self, key, section]]:
constant[The settings overridden from the wandb/settings file.
Args:
key (str, optional): If provided only this setting is returned
section (str, optional): If provided this section of the setting file is
used, d... | keyword[def] identifier[settings] ( identifier[self] , identifier[key] = keyword[None] , identifier[section] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_settings] :
identifier[self] . identifier[_settings] = identifier[self] . identifier... | def settings(self, key=None, section=None):
"""The settings overridden from the wandb/settings file.
Args:
key (str, optional): If provided only this setting is returned
section (str, optional): If provided this section of the setting file is
used, defaults to "default"
... |
def calc_distribution_stats(x):
"""Calculate various summary statistics of data.
Parameters
----------
x : numpy.ndarray or pandas.Series
Array to compute summary statistics for.
Returns
-------
pandas.Series
Series containing mean, median, std, as well as 5, 25, 75 and
... | def function[calc_distribution_stats, parameter[x]]:
constant[Calculate various summary statistics of data.
Parameters
----------
x : numpy.ndarray or pandas.Series
Array to compute summary statistics for.
Returns
-------
pandas.Series
Series containing mean, median, st... | keyword[def] identifier[calc_distribution_stats] ( identifier[x] ):
literal[string]
keyword[return] identifier[pd] . identifier[Series] ({ literal[string] : identifier[np] . identifier[mean] ( identifier[x] ),
literal[string] : identifier[np] . identifier[median] ( identifier[x] ),
literal[stri... | def calc_distribution_stats(x):
"""Calculate various summary statistics of data.
Parameters
----------
x : numpy.ndarray or pandas.Series
Array to compute summary statistics for.
Returns
-------
pandas.Series
Series containing mean, median, std, as well as 5, 25, 75 and
... |
def get_error(self, errstr):
'''
Parse out an error and return a targeted error string
'''
for line in errstr.split('\n'):
if line.startswith('ssh:'):
return line
if line.startswith('Pseudo-terminal'):
continue
if 'to th... | def function[get_error, parameter[self, errstr]]:
constant[
Parse out an error and return a targeted error string
]
for taget[name[line]] in starred[call[name[errstr].split, parameter[constant[
]]]] begin[:]
if call[name[line].startswith, parameter[constant[ssh:]]] begin[... | keyword[def] identifier[get_error] ( identifier[self] , identifier[errstr] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[errstr] . identifier[split] ( literal[string] ):
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ):
... | def get_error(self, errstr):
"""
Parse out an error and return a targeted error string
"""
for line in errstr.split('\n'):
if line.startswith('ssh:'):
return line # depends on [control=['if'], data=[]]
if line.startswith('Pseudo-terminal'):
continue # de... |
def _set_interface_dynamic_bypass_name_prefix(self, v, load=False):
"""
Setter method for interface_dynamic_bypass_name_prefix, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/interface_dynamic_bypass_name_prefix ... | def function[_set_interface_dynamic_bypass_name_prefix, parameter[self, v, load]]:
constant[
Setter method for interface_dynamic_bypass_name_prefix, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/interface_dy... | keyword[def] identifier[_set_interface_dynamic_bypass_name_prefix] ( 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] )
... | def _set_interface_dynamic_bypass_name_prefix(self, v, load=False):
"""
Setter method for interface_dynamic_bypass_name_prefix, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/interface_dynamic_bypass/mpls_interface_dynamic_bypass_sub_cmds/interface_dynamic_bypass_name_prefix ... |
def get_version(name, dirs=None, config=None):
"""Retrieve the current version of the given program from cached names.
"""
if dirs:
p = _get_program_file(dirs)
else:
p = tz.get_in(["resources", "program_versions"], config)
if p:
with open(p) as in_handle:
for line... | def function[get_version, parameter[name, dirs, config]]:
constant[Retrieve the current version of the given program from cached names.
]
if name[dirs] begin[:]
variable[p] assign[=] call[name[_get_program_file], parameter[name[dirs]]]
if name[p] begin[:]
with... | keyword[def] identifier[get_version] ( identifier[name] , identifier[dirs] = keyword[None] , identifier[config] = keyword[None] ):
literal[string]
keyword[if] identifier[dirs] :
identifier[p] = identifier[_get_program_file] ( identifier[dirs] )
keyword[else] :
identifier[p] = identi... | def get_version(name, dirs=None, config=None):
"""Retrieve the current version of the given program from cached names.
"""
if dirs:
p = _get_program_file(dirs) # depends on [control=['if'], data=[]]
else:
p = tz.get_in(['resources', 'program_versions'], config)
if p:
with op... |
def cache_cluster_present(name, wait=900, security_groups=None, region=None, key=None,
keyid=None, profile=None, **args):
'''
Ensure a given cache cluster exists.
name
Name of the cache cluster (cache cluster id).
wait
Integer describing how long, in seconds, ... | def function[cache_cluster_present, parameter[name, wait, security_groups, region, key, keyid, profile]]:
constant[
Ensure a given cache cluster exists.
name
Name of the cache cluster (cache cluster id).
wait
Integer describing how long, in seconds, to wait for confirmation from AW... | keyword[def] identifier[cache_cluster_present] ( identifier[name] , identifier[wait] = literal[int] , identifier[security_groups] = keyword[None] , identifier[region] = keyword[None] , identifier[key] = keyword[None] ,
identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ,** identifier[args] ):
... | def cache_cluster_present(name, wait=900, security_groups=None, region=None, key=None, keyid=None, profile=None, **args):
"""
Ensure a given cache cluster exists.
name
Name of the cache cluster (cache cluster id).
wait
Integer describing how long, in seconds, to wait for confirmation f... |
def pad_release(release_to_pad, num_sections=4):
'''
Pad out package and kernel release versions so that
``LooseVersion`` comparisons will be correct.
Release versions with less than num_sections will
be padded in front of the last section with zeros.
For example ::
pad_release("390.e... | def function[pad_release, parameter[release_to_pad, num_sections]]:
constant[
Pad out package and kernel release versions so that
``LooseVersion`` comparisons will be correct.
Release versions with less than num_sections will
be padded in front of the last section with zeros.
For example :... | keyword[def] identifier[pad_release] ( identifier[release_to_pad] , identifier[num_sections] = literal[int] ):
literal[string]
identifier[parts] = identifier[release_to_pad] . identifier[split] ( literal[string] )
keyword[if] identifier[len] ( identifier[parts] )> identifier[num_sections] :
... | def pad_release(release_to_pad, num_sections=4):
"""
Pad out package and kernel release versions so that
``LooseVersion`` comparisons will be correct.
Release versions with less than num_sections will
be padded in front of the last section with zeros.
For example ::
pad_release("390.e... |
def _reg_sighandlers(self):
""" Registers signal handlers to this class.
"""
# SIGCHLD, so we shutdown when any of the child processes exit
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGCHLD, _handler)
signal.signal(signal.SIGTERM, _handler) | def function[_reg_sighandlers, parameter[self]]:
constant[ Registers signal handlers to this class.
]
variable[_handler] assign[=] <ast.Lambda object at 0x7da20e9b1780>
call[name[signal].signal, parameter[name[signal].SIGCHLD, name[_handler]]]
call[name[signal].signal, parame... | keyword[def] identifier[_reg_sighandlers] ( identifier[self] ):
literal[string]
identifier[_handler] = keyword[lambda] identifier[signo] , identifier[frame] : identifier[self] . identifier[shutdown] ()
identifier[signal] . identifier[signal] ( identifier[signal] . identifier[SIG... | def _reg_sighandlers(self):
""" Registers signal handlers to this class.
"""
# SIGCHLD, so we shutdown when any of the child processes exit
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGCHLD, _handler)
signal.signal(signal.SIGTERM, _handler) |
async def update(self, records: Iterable[DataRecord], values: SQLValuesToWrite, returning=False) -> Union[int, Iterable[DataRecord]]:
"""
:param records:
:param values:
:param returning:
:return: return count if returning is False, otherwise records
"""
raise NotI... | <ast.AsyncFunctionDef object at 0x7da1b0012e00> | keyword[async] keyword[def] identifier[update] ( identifier[self] , identifier[records] : identifier[Iterable] [ identifier[DataRecord] ], identifier[values] : identifier[SQLValuesToWrite] , identifier[returning] = keyword[False] )-> identifier[Union] [ identifier[int] , identifier[Iterable] [ identifier[DataRecord]... | async def update(self, records: Iterable[DataRecord], values: SQLValuesToWrite, returning=False) -> Union[int, Iterable[DataRecord]]:
"""
:param records:
:param values:
:param returning:
:return: return count if returning is False, otherwise records
"""
raise NotImplement... |
def minimize_spec(spec_dict, operations=None, resources=None):
"""
Trims down a source spec dict to only the operations or resources indicated.
:param spec_dict: The source spec dict to minimize.
:type spec_dict: dict
:param operations: A list of opertion IDs to retain.
:type operations: list of... | def function[minimize_spec, parameter[spec_dict, operations, resources]]:
constant[
Trims down a source spec dict to only the operations or resources indicated.
:param spec_dict: The source spec dict to minimize.
:type spec_dict: dict
:param operations: A list of opertion IDs to retain.
:typ... | keyword[def] identifier[minimize_spec] ( identifier[spec_dict] , identifier[operations] = keyword[None] , identifier[resources] = keyword[None] ):
literal[string]
identifier[operations] = identifier[operations] keyword[or] []
identifier[resources] = identifier[resources] keyword[or] []
id... | def minimize_spec(spec_dict, operations=None, resources=None):
"""
Trims down a source spec dict to only the operations or resources indicated.
:param spec_dict: The source spec dict to minimize.
:type spec_dict: dict
:param operations: A list of opertion IDs to retain.
:type operations: list of... |
def getVolInfo(*paths):
'''
Retrieve volume usage info for the given path.
'''
path = os.path.join(*paths)
path = os.path.expanduser(path)
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
return {
'free': free,
'used': total ... | def function[getVolInfo, parameter[]]:
constant[
Retrieve volume usage info for the given path.
]
variable[path] assign[=] call[name[os].path.join, parameter[<ast.Starred object at 0x7da18eb54310>]]
variable[path] assign[=] call[name[os].path.expanduser, parameter[name[path]]]
va... | keyword[def] identifier[getVolInfo] (* identifier[paths] ):
literal[string]
identifier[path] = identifier[os] . identifier[path] . identifier[join] (* identifier[paths] )
identifier[path] = identifier[os] . identifier[path] . identifier[expanduser] ( identifier[path] )
identifier[st] = identifie... | def getVolInfo(*paths):
"""
Retrieve volume usage info for the given path.
"""
path = os.path.join(*paths)
path = os.path.expanduser(path)
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
return {'free': free, 'used': total - free, 'total': tot... |
def unite_dict(a, b):
"""
>>> a = {'name': 'Sylvanas'}
>>> b = {'gender': 'Man'}
>>> unite_dict(a, b)
{'name': 'Sylvanas', 'gender': 'Man'}
"""
c = {}
c.update(a)
c.update(b)
return c | def function[unite_dict, parameter[a, b]]:
constant[
>>> a = {'name': 'Sylvanas'}
>>> b = {'gender': 'Man'}
>>> unite_dict(a, b)
{'name': 'Sylvanas', 'gender': 'Man'}
]
variable[c] assign[=] dictionary[[], []]
call[name[c].update, parameter[name[a]]]
call[name[c].upda... | keyword[def] identifier[unite_dict] ( identifier[a] , identifier[b] ):
literal[string]
identifier[c] ={}
identifier[c] . identifier[update] ( identifier[a] )
identifier[c] . identifier[update] ( identifier[b] )
keyword[return] identifier[c] | def unite_dict(a, b):
"""
>>> a = {'name': 'Sylvanas'}
>>> b = {'gender': 'Man'}
>>> unite_dict(a, b)
{'name': 'Sylvanas', 'gender': 'Man'}
"""
c = {}
c.update(a)
c.update(b)
return c |
def displacements(self):
"""Return displacements
Returns
-------
There are two types of displacement dataset. See the docstring
of set_displacement_dataset about types 1 and 2 for displacement
dataset format.
Type-1, List of list
The internal list ha... | def function[displacements, parameter[self]]:
constant[Return displacements
Returns
-------
There are two types of displacement dataset. See the docstring
of set_displacement_dataset about types 1 and 2 for displacement
dataset format.
Type-1, List of list
... | keyword[def] identifier[displacements] ( identifier[self] ):
literal[string]
identifier[disps] =[]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[_displacement_dataset] :
keyword[for] identifier[disp] keyword[in] identifier[self] . identifier[_dis... | def displacements(self):
"""Return displacements
Returns
-------
There are two types of displacement dataset. See the docstring
of set_displacement_dataset about types 1 and 2 for displacement
dataset format.
Type-1, List of list
The internal list has 4 ... |
def comma(value):
"""
FORMAT WITH THOUSANDS COMMA (,) SEPARATOR
"""
try:
if float(value) == _round(float(value), 0):
output = "{:,}".format(int(value))
else:
output = "{:,}".format(float(value))
except Exception:
output = text_type(value)
return o... | def function[comma, parameter[value]]:
constant[
FORMAT WITH THOUSANDS COMMA (,) SEPARATOR
]
<ast.Try object at 0x7da1b1d20bb0>
return[name[output]] | keyword[def] identifier[comma] ( identifier[value] ):
literal[string]
keyword[try] :
keyword[if] identifier[float] ( identifier[value] )== identifier[_round] ( identifier[float] ( identifier[value] ), literal[int] ):
identifier[output] = literal[string] . identifier[format] ( identif... | def comma(value):
"""
FORMAT WITH THOUSANDS COMMA (,) SEPARATOR
"""
try:
if float(value) == _round(float(value), 0):
output = '{:,}'.format(int(value)) # depends on [control=['if'], data=[]]
else:
output = '{:,}'.format(float(value)) # depends on [control=['try'... |
def create_content(self):
"""
Render the template, apply options on it, and save it to the cache.
"""
self.render_node()
if self.options.compress_spaces:
self.content = self.RE_SPACELESS.sub(' ', self.content)
if self.options.compress:
to_cache =... | def function[create_content, parameter[self]]:
constant[
Render the template, apply options on it, and save it to the cache.
]
call[name[self].render_node, parameter[]]
if name[self].options.compress_spaces begin[:]
name[self].content assign[=] call[name[self].RE_... | keyword[def] identifier[create_content] ( identifier[self] ):
literal[string]
identifier[self] . identifier[render_node] ()
keyword[if] identifier[self] . identifier[options] . identifier[compress_spaces] :
identifier[self] . identifier[content] = identifier[self] . identifi... | def create_content(self):
"""
Render the template, apply options on it, and save it to the cache.
"""
self.render_node()
if self.options.compress_spaces:
self.content = self.RE_SPACELESS.sub(' ', self.content) # depends on [control=['if'], data=[]]
if self.options.compress:
... |
def PCA(Y, components):
"""
run PCA, retrieving the first (components) principle components
return [s0, eig, w0]
s0: factors
w0: weights
"""
N,D = Y.shape
sv = linalg.svd(Y, full_matrices=0);
[s0, w0] = [sv[0][:, 0:components], np.dot(np.diag(sv[1]), sv[2]).T[:, 0:components]]
v = s0.std(axis=0)
s0 /= v;
w... | def function[PCA, parameter[Y, components]]:
constant[
run PCA, retrieving the first (components) principle components
return [s0, eig, w0]
s0: factors
w0: weights
]
<ast.Tuple object at 0x7da1b09052a0> assign[=] name[Y].shape
variable[sv] assign[=] call[name[linalg].svd, parameter[name[Y]]... | keyword[def] identifier[PCA] ( identifier[Y] , identifier[components] ):
literal[string]
identifier[N] , identifier[D] = identifier[Y] . identifier[shape]
identifier[sv] = identifier[linalg] . identifier[svd] ( identifier[Y] , identifier[full_matrices] = literal[int] );
[ identifier[s0] , identifier[w0] ]=[... | def PCA(Y, components):
"""
run PCA, retrieving the first (components) principle components
return [s0, eig, w0]
s0: factors
w0: weights
"""
(N, D) = Y.shape
sv = linalg.svd(Y, full_matrices=0)
[s0, w0] = [sv[0][:, 0:components], np.dot(np.diag(sv[1]), sv[2]).T[:, 0:components]]
v = s0.std(axis... |
def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes):
"""
:param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data
"... | def function[dics_to_itunessd, parameter[header_dic, tracks_dics, playlists_dics_and_indexes]]:
constant[
:param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the ... | keyword[def] identifier[dics_to_itunessd] ( identifier[header_dic] , identifier[tracks_dics] , identifier[playlists_dics_and_indexes] ):
literal[string]
identifier[header_dic] [ literal[string] ]= identifier[get_table_size] ( identifier[header_table] )
identifier[header_dic] [ literal[... | def dics_to_itunessd(header_dic, tracks_dics, playlists_dics_and_indexes):
"""
:param header_dic: dic of header_table
:param tracks_dics: list of all track_table's dics
:param playlists_dics_and_indexes: list of all playlists and all their track's indexes
:return: the whole iTunesSD bytes data
"... |
def iterable(obj, strok=False):
"""
Checks if the input implements the iterator interface. An exception is made
for strings, which return False unless `strok` is True
Args:
obj (object): a scalar or iterable input
strok (bool): if True allow strings to be interpreted as iterable
R... | def function[iterable, parameter[obj, strok]]:
constant[
Checks if the input implements the iterator interface. An exception is made
for strings, which return False unless `strok` is True
Args:
obj (object): a scalar or iterable input
strok (bool): if True allow strings to be inter... | keyword[def] identifier[iterable] ( identifier[obj] , identifier[strok] = keyword[False] ):
literal[string]
keyword[try] :
identifier[iter] ( identifier[obj] )
keyword[except] identifier[Exception] :
keyword[return] keyword[False]
keyword[else] :
keyword[return] ide... | def iterable(obj, strok=False):
"""
Checks if the input implements the iterator interface. An exception is made
for strings, which return False unless `strok` is True
Args:
obj (object): a scalar or iterable input
strok (bool): if True allow strings to be interpreted as iterable
R... |
def forward_committor(T, A, B):
r"""Forward committor between given sets.
The forward committor u(x) between sets A and B is the probability
for the chain starting in x to reach B before reaching A.
Parameters
----------
T : (M, M) ndarray
Transition matrix
A : array_like
L... | def function[forward_committor, parameter[T, A, B]]:
constant[Forward committor between given sets.
The forward committor u(x) between sets A and B is the probability
for the chain starting in x to reach B before reaching A.
Parameters
----------
T : (M, M) ndarray
Transition matri... | keyword[def] identifier[forward_committor] ( identifier[T] , identifier[A] , identifier[B] ):
literal[string]
identifier[X] = identifier[set] ( identifier[range] ( identifier[T] . identifier[shape] [ literal[int] ]))
identifier[A] = identifier[set] ( identifier[A] )
identifier[B] = identifier[set... | def forward_committor(T, A, B):
"""Forward committor between given sets.
The forward committor u(x) between sets A and B is the probability
for the chain starting in x to reach B before reaching A.
Parameters
----------
T : (M, M) ndarray
Transition matrix
A : array_like
Li... |
def get(cls, key, default=None, separator='.', global_=False):
""" Retrieve a key value from loaded configuration.
Order of search if global_=False:
1/ environnment variables
2/ local configuration
3/ global configuration
"""
# first check environnment variables
... | def function[get, parameter[cls, key, default, separator, global_]]:
constant[ Retrieve a key value from loaded configuration.
Order of search if global_=False:
1/ environnment variables
2/ local configuration
3/ global configuration
]
if <ast.UnaryOp object at 0... | keyword[def] identifier[get] ( identifier[cls] , identifier[key] , identifier[default] = keyword[None] , identifier[separator] = literal[string] , identifier[global_] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[global_] :
identifier[ret] ... | def get(cls, key, default=None, separator='.', global_=False):
""" Retrieve a key value from loaded configuration.
Order of search if global_=False:
1/ environnment variables
2/ local configuration
3/ global configuration
"""
# first check environnment variables
# if... |
def set_dword_at_offset(self, offset, dword):
"""Set the double word value at the given file offset."""
return self.set_bytes_at_offset(offset, self.get_data_from_dword(dword)) | def function[set_dword_at_offset, parameter[self, offset, dword]]:
constant[Set the double word value at the given file offset.]
return[call[name[self].set_bytes_at_offset, parameter[name[offset], call[name[self].get_data_from_dword, parameter[name[dword]]]]]] | keyword[def] identifier[set_dword_at_offset] ( identifier[self] , identifier[offset] , identifier[dword] ):
literal[string]
keyword[return] identifier[self] . identifier[set_bytes_at_offset] ( identifier[offset] , identifier[self] . identifier[get_data_from_dword] ( identifier[dword] )) | def set_dword_at_offset(self, offset, dword):
"""Set the double word value at the given file offset."""
return self.set_bytes_at_offset(offset, self.get_data_from_dword(dword)) |
def calculate_colorbar(self):
"""
Returns the positions and colors of all intervals inside the colorbar.
"""
self._base._process_values()
self._base._find_range()
X, Y = self._base._mesh()
C = self._base._values[:, np.newaxis]
return X, Y, C | def function[calculate_colorbar, parameter[self]]:
constant[
Returns the positions and colors of all intervals inside the colorbar.
]
call[name[self]._base._process_values, parameter[]]
call[name[self]._base._find_range, parameter[]]
<ast.Tuple object at 0x7da18f58f010> a... | keyword[def] identifier[calculate_colorbar] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_base] . identifier[_process_values] ()
identifier[self] . identifier[_base] . identifier[_find_range] ()
identifier[X] , identifier[Y] = identifier[self] . identifier[_... | def calculate_colorbar(self):
"""
Returns the positions and colors of all intervals inside the colorbar.
"""
self._base._process_values()
self._base._find_range()
(X, Y) = self._base._mesh()
C = self._base._values[:, np.newaxis]
return (X, Y, C) |
def hybrid_threaded_worker(selector, workers):
"""Runs a set of workers, each in a separate thread.
:param selector:
A function that takes a hints-tuple and returns a key
indexing a worker in the `workers` dictionary.
:param workers:
A dictionary of workers.
:returns:
A... | def function[hybrid_threaded_worker, parameter[selector, workers]]:
constant[Runs a set of workers, each in a separate thread.
:param selector:
A function that takes a hints-tuple and returns a key
indexing a worker in the `workers` dictionary.
:param workers:
A dictionary of wo... | keyword[def] identifier[hybrid_threaded_worker] ( identifier[selector] , identifier[workers] ):
literal[string]
identifier[result_queue] = identifier[Queue] ()
identifier[job_sink] ={ identifier[k] : identifier[w] . identifier[sink] () keyword[for] identifier[k] , identifier[w] keyword[in] identif... | def hybrid_threaded_worker(selector, workers):
"""Runs a set of workers, each in a separate thread.
:param selector:
A function that takes a hints-tuple and returns a key
indexing a worker in the `workers` dictionary.
:param workers:
A dictionary of workers.
:returns:
A... |
def express_route_cross_connections(self):
"""Instance depends on the API version:
* 2018-02-01: :class:`ExpressRouteCrossConnectionsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionsOperations>`
* 2018-04-01: :class:`ExpressRouteCrossConnectionsOperations<a... | def function[express_route_cross_connections, parameter[self]]:
constant[Instance depends on the API version:
* 2018-02-01: :class:`ExpressRouteCrossConnectionsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionsOperations>`
* 2018-04-01: :class:`ExpressRouteC... | keyword[def] identifier[express_route_cross_connections] ( identifier[self] ):
literal[string]
identifier[api_version] = identifier[self] . identifier[_get_api_version] ( literal[string] )
keyword[if] identifier[api_version] == literal[string] :
keyword[from] . identifier[v20... | def express_route_cross_connections(self):
"""Instance depends on the API version:
* 2018-02-01: :class:`ExpressRouteCrossConnectionsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionsOperations>`
* 2018-04-01: :class:`ExpressRouteCrossConnectionsOperations<azure... |
def uri_to_iri(uri, charset='utf-8', errors='replace'):
r"""
Converts a URI in a given charset to a IRI.
Examples for URI versus IRI:
>>> uri_to_iri(b'http://xn--n3h.net/')
u'http://\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\xfcser:p\xe4s... | def function[uri_to_iri, parameter[uri, charset, errors]]:
constant[
Converts a URI in a given charset to a IRI.
Examples for URI versus IRI:
>>> uri_to_iri(b'http://xn--n3h.net/')
u'http://\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\x... | keyword[def] identifier[uri_to_iri] ( identifier[uri] , identifier[charset] = literal[string] , identifier[errors] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[uri] , identifier[tuple] ):
identifier[uri] = identifier[url_unparse] ( identifier[uri] )
id... | def uri_to_iri(uri, charset='utf-8', errors='replace'):
"""
Converts a URI in a given charset to a IRI.
Examples for URI versus IRI:
>>> uri_to_iri(b'http://xn--n3h.net/')
u'http://\\u2603.net/'
>>> uri_to_iri(b'http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\\xfcser:p\\xe... |
def find_prekeyed(self, value, key):
"""
Find a value in a node, using a key function. The value is already a
key.
"""
while self is not NULL:
direction = cmp(value, key(self.value))
if direction < 0:
self = self.left
elif dire... | def function[find_prekeyed, parameter[self, value, key]]:
constant[
Find a value in a node, using a key function. The value is already a
key.
]
while compare[name[self] is_not name[NULL]] begin[:]
variable[direction] assign[=] call[name[cmp], parameter[name[value]... | keyword[def] identifier[find_prekeyed] ( identifier[self] , identifier[value] , identifier[key] ):
literal[string]
keyword[while] identifier[self] keyword[is] keyword[not] identifier[NULL] :
identifier[direction] = identifier[cmp] ( identifier[value] , identifier[key] ( identifier... | def find_prekeyed(self, value, key):
"""
Find a value in a node, using a key function. The value is already a
key.
"""
while self is not NULL:
direction = cmp(value, key(self.value))
if direction < 0:
self = self.left # depends on [control=['if'], data=[]]
... |
def dump_json(data, indent=None):
"""
:param list | dict data:
:param Optional[int] indent:
:rtype: unicode
"""
return json.dumps(data,
indent=indent,
ensure_ascii=False,
sort_keys=True,
separators=(',', ': '... | def function[dump_json, parameter[data, indent]]:
constant[
:param list | dict data:
:param Optional[int] indent:
:rtype: unicode
]
return[call[name[json].dumps, parameter[name[data]]]] | keyword[def] identifier[dump_json] ( identifier[data] , identifier[indent] = keyword[None] ):
literal[string]
keyword[return] identifier[json] . identifier[dumps] ( identifier[data] ,
identifier[indent] = identifier[indent] ,
identifier[ensure_ascii] = keyword[False] ,
identifier[sort_keys]... | def dump_json(data, indent=None):
"""
:param list | dict data:
:param Optional[int] indent:
:rtype: unicode
"""
return json.dumps(data, indent=indent, ensure_ascii=False, sort_keys=True, separators=(',', ': ')) |
def _step_to_marker_frame(self, frame_no, dt=None):
'''Update the simulator to a specific frame of marker data.
This method returns a generator of body states for the skeleton! This
generator must be exhausted (e.g., by consuming this call in a for loop)
for the simulator to work proper... | def function[_step_to_marker_frame, parameter[self, frame_no, dt]]:
constant[Update the simulator to a specific frame of marker data.
This method returns a generator of body states for the skeleton! This
generator must be exhausted (e.g., by consuming this call in a for loop)
for the si... | keyword[def] identifier[_step_to_marker_frame] ( identifier[self] , identifier[frame_no] , identifier[dt] = keyword[None] ):
literal[string]
identifier[self] . identifier[markers] . identifier[detach] ()
identifier[self] . identifier[markers] . identifier[reposition] ( identifier[... | def _step_to_marker_frame(self, frame_no, dt=None):
"""Update the simulator to a specific frame of marker data.
This method returns a generator of body states for the skeleton! This
generator must be exhausted (e.g., by consuming this call in a for loop)
for the simulator to work properly.
... |
def require_ajax_logged_in(func):
"""Check if ajax API is logged in and login if not
"""
@functools.wraps(func)
def inner_func(self, *pargs, **kwargs):
if not self._ajax_api.logged_in:
logger.info('Logging into AJAX API for required meta method')
if not self.has_credentia... | def function[require_ajax_logged_in, parameter[func]]:
constant[Check if ajax API is logged in and login if not
]
def function[inner_func, parameter[self]]:
if <ast.UnaryOp object at 0x7da1b0fe5cf0> begin[:]
call[name[logger].info, parameter[constant[Logging i... | keyword[def] identifier[require_ajax_logged_in] ( identifier[func] ):
literal[string]
@ identifier[functools] . identifier[wraps] ( identifier[func] )
keyword[def] identifier[inner_func] ( identifier[self] ,* identifier[pargs] ,** identifier[kwargs] ):
keyword[if] keyword[not] identifier[se... | def require_ajax_logged_in(func):
"""Check if ajax API is logged in and login if not
"""
@functools.wraps(func)
def inner_func(self, *pargs, **kwargs):
if not self._ajax_api.logged_in:
logger.info('Logging into AJAX API for required meta method')
if not self.has_credenti... |
def output(self, stream, value):
"""SPL output port assignment expression.
Arguments:
stream(Stream): Output stream the assignment is for.
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.
Returns:
... | def function[output, parameter[self, stream, value]]:
constant[SPL output port assignment expression.
Arguments:
stream(Stream): Output stream the assignment is for.
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expr... | keyword[def] identifier[output] ( identifier[self] , identifier[stream] , identifier[value] ):
literal[string]
keyword[if] identifier[stream] keyword[not] keyword[in] identifier[self] . identifier[outputs] :
keyword[raise] identifier[ValueError] ( literal[string] )
identi... | def output(self, stream, value):
"""SPL output port assignment expression.
Arguments:
stream(Stream): Output stream the assignment is for.
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.
Returns:
... |
def get_permalink_ids_iter(self):
'''
Method to get permalink ids from content. To be bound to the class last
thing.
'''
permalink_id_key = self.settings['PERMALINK_ID_METADATA_KEY']
permalink_ids = self.metadata.get(permalink_id_key, '')
for permalink_id in permalink_ids.split(','):
... | def function[get_permalink_ids_iter, parameter[self]]:
constant[
Method to get permalink ids from content. To be bound to the class last
thing.
]
variable[permalink_id_key] assign[=] call[name[self].settings][constant[PERMALINK_ID_METADATA_KEY]]
variable[permalink_ids] assign[=] call... | keyword[def] identifier[get_permalink_ids_iter] ( identifier[self] ):
literal[string]
identifier[permalink_id_key] = identifier[self] . identifier[settings] [ literal[string] ]
identifier[permalink_ids] = identifier[self] . identifier[metadata] . identifier[get] ( identifier[permalink_id_key] , litera... | def get_permalink_ids_iter(self):
"""
Method to get permalink ids from content. To be bound to the class last
thing.
"""
permalink_id_key = self.settings['PERMALINK_ID_METADATA_KEY']
permalink_ids = self.metadata.get(permalink_id_key, '')
for permalink_id in permalink_ids.split(','):
... |
def hdrtxt(xmethod, dmethod, opt):
"""Return ``hdrtxt`` argument for ``.IterStatsConfig`` initialiser.
"""
txt = ['Itn', 'Fnc', 'DFid', u('ℓ1'), 'Cnstr']
if xmethod == 'admm':
txt.extend(['r_X', 's_X', u('ρ_X')])
else:
if opt['CBPDN', 'BackTrack', 'Enabled']:
txt.extend(... | def function[hdrtxt, parameter[xmethod, dmethod, opt]]:
constant[Return ``hdrtxt`` argument for ``.IterStatsConfig`` initialiser.
]
variable[txt] assign[=] list[[<ast.Constant object at 0x7da1b069b070>, <ast.Constant object at 0x7da1b0698c40>, <ast.Constant object at 0x7da1b069a590>, <ast.Call objec... | keyword[def] identifier[hdrtxt] ( identifier[xmethod] , identifier[dmethod] , identifier[opt] ):
literal[string]
identifier[txt] =[ literal[string] , literal[string] , literal[string] , identifier[u] ( literal[string] ), literal[string] ]
keyword[if] identifier[xmethod] == literal[string] :
... | def hdrtxt(xmethod, dmethod, opt):
"""Return ``hdrtxt`` argument for ``.IterStatsConfig`` initialiser.
"""
txt = ['Itn', 'Fnc', 'DFid', u('ℓ1'), 'Cnstr']
if xmethod == 'admm':
txt.extend(['r_X', 's_X', u('ρ_X')]) # depends on [control=['if'], data=[]]
elif opt['CBPDN', 'BackTrack', 'Enabled... |
def cidr_notation(ip_address, netmask):
"""
Retrieve the cidr notation given an ip address and netmask.
For example:
cidr_notation('12.34.56.78', '255.255.255.248')
Would return: 12.34.56.72/29
@see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for... | def function[cidr_notation, parameter[ip_address, netmask]]:
constant[
Retrieve the cidr notation given an ip address and netmask.
For example:
cidr_notation('12.34.56.78', '255.255.255.248')
Would return: 12.34.56.72/29
@see http://terminalmage.net/2012/06/10/how-to... | keyword[def] identifier[cidr_notation] ( identifier[ip_address] , identifier[netmask] ):
literal[string]
keyword[try] :
identifier[inet_aton] ( identifier[ip_address] )
keyword[except] :
keyword[raise] identifier[Exception] ( literal[string] % identifier[ip_address] )
keyword[t... | def cidr_notation(ip_address, netmask):
"""
Retrieve the cidr notation given an ip address and netmask.
For example:
cidr_notation('12.34.56.78', '255.255.255.248')
Would return: 12.34.56.72/29
@see http://terminalmage.net/2012/06/10/how-to-find-out-the-cidr-notation-for... |
async def delete(self):
"""Deletes a scene from a shade"""
_val = await self.request.delete(
self._base_path,
params={
ATTR_SCENE_ID: self._raw_data.get(ATTR_SCENE_ID),
ATTR_SHADE_ID: self._raw_data.get(ATTR_SHADE_ID),
},
)
... | <ast.AsyncFunctionDef object at 0x7da1b2345de0> | keyword[async] keyword[def] identifier[delete] ( identifier[self] ):
literal[string]
identifier[_val] = keyword[await] identifier[self] . identifier[request] . identifier[delete] (
identifier[self] . identifier[_base_path] ,
identifier[params] ={
identifier[ATTR_SCENE_I... | async def delete(self):
"""Deletes a scene from a shade"""
_val = await self.request.delete(self._base_path, params={ATTR_SCENE_ID: self._raw_data.get(ATTR_SCENE_ID), ATTR_SHADE_ID: self._raw_data.get(ATTR_SHADE_ID)})
return _val |
def _endProgramsNode(self, name, content):
"""Process the end of a node under xtvd/programs"""
if name == 'series':
self._series = content
elif name == 'title':
self._title = content
elif name == 'subtitle':
self._subtitle = content
elif name ... | def function[_endProgramsNode, parameter[self, name, content]]:
constant[Process the end of a node under xtvd/programs]
if compare[name[name] equal[==] constant[series]] begin[:]
name[self]._series assign[=] name[content] | keyword[def] identifier[_endProgramsNode] ( identifier[self] , identifier[name] , identifier[content] ):
literal[string]
keyword[if] identifier[name] == literal[string] :
identifier[self] . identifier[_series] = identifier[content]
keyword[elif] identifier[name] == literal... | def _endProgramsNode(self, name, content):
"""Process the end of a node under xtvd/programs"""
if name == 'series':
self._series = content # depends on [control=['if'], data=[]]
elif name == 'title':
self._title = content # depends on [control=['if'], data=[]]
elif name == 'subtitle':
... |
def scatter(self, x, y, xerr=[], yerr=[], mark='o', markstyle=None):
"""Plot a series of points.
Plot a series of points (marks) that are not connected by a
line. Shortcut for plot with linestyle=None.
:param x: array containing x-values.
:param y: array containing y-values.
... | def function[scatter, parameter[self, x, y, xerr, yerr, mark, markstyle]]:
constant[Plot a series of points.
Plot a series of points (marks) that are not connected by a
line. Shortcut for plot with linestyle=None.
:param x: array containing x-values.
:param y: array containing ... | keyword[def] identifier[scatter] ( identifier[self] , identifier[x] , identifier[y] , identifier[xerr] =[], identifier[yerr] =[], identifier[mark] = literal[string] , identifier[markstyle] = keyword[None] ):
literal[string]
identifier[self] . identifier[plot] ( identifier[x] , identifier[y] , ident... | def scatter(self, x, y, xerr=[], yerr=[], mark='o', markstyle=None):
"""Plot a series of points.
Plot a series of points (marks) that are not connected by a
line. Shortcut for plot with linestyle=None.
:param x: array containing x-values.
:param y: array containing y-values.
... |
def get_json_object_lines(annotation: ResourceAnnotation,
properties: Dict[str, Any], field: str,
url_params: Dict, request: bool = False,
object_property: bool = False) -> List[str]:
"""Generate documentation for the given object annotat... | def function[get_json_object_lines, parameter[annotation, properties, field, url_params, request, object_property]]:
constant[Generate documentation for the given object annotation.
:param doctor.resource.ResourceAnnotation annotation:
Annotation object for the associated handler method.
:param... | keyword[def] identifier[get_json_object_lines] ( identifier[annotation] : identifier[ResourceAnnotation] ,
identifier[properties] : identifier[Dict] [ identifier[str] , identifier[Any] ], identifier[field] : identifier[str] ,
identifier[url_params] : identifier[Dict] , identifier[request] : identifier[bool] = keywo... | def get_json_object_lines(annotation: ResourceAnnotation, properties: Dict[str, Any], field: str, url_params: Dict, request: bool=False, object_property: bool=False) -> List[str]:
"""Generate documentation for the given object annotation.
:param doctor.resource.ResourceAnnotation annotation:
Annotation... |
def free(self, local_path):
'''
Stop synchronization of local_path
'''
# Process local ~~~
# 1. Syncthing config
config = self.get_config()
# Check whether folders are still connected to this device
folder = st_util.find_folder_with_path(local_path, config)
self.delete_... | def function[free, parameter[self, local_path]]:
constant[
Stop synchronization of local_path
]
variable[config] assign[=] call[name[self].get_config, parameter[]]
variable[folder] assign[=] call[name[st_util].find_folder_with_path, parameter[name[local_path], name[config]]]
ca... | keyword[def] identifier[free] ( identifier[self] , identifier[local_path] ):
literal[string]
identifier[config] = identifier[self] . identifier[get_config] ()
identifier[folder] = identifier[st_util] . identifier[find_folder_with_path] ( identifier[local_path] , identifier[config] )
... | def free(self, local_path):
"""
Stop synchronization of local_path
"""
# Process local ~~~
# 1. Syncthing config
config = self.get_config() # Check whether folders are still connected to this device
folder = st_util.find_folder_with_path(local_path, config)
self.delete_folder(local_p... |
def vrf_add(self, route_dist, import_rts, export_rts, site_of_origins=None,
route_family=RF_VPN_V4, multi_exit_disc=None):
""" This method adds a new vrf used for VPN.
``route_dist`` specifies a route distinguisher value.
``import_rts`` specifies a list of route targets to be i... | def function[vrf_add, parameter[self, route_dist, import_rts, export_rts, site_of_origins, route_family, multi_exit_disc]]:
constant[ This method adds a new vrf used for VPN.
``route_dist`` specifies a route distinguisher value.
``import_rts`` specifies a list of route targets to be imported.
... | keyword[def] identifier[vrf_add] ( identifier[self] , identifier[route_dist] , identifier[import_rts] , identifier[export_rts] , identifier[site_of_origins] = keyword[None] ,
identifier[route_family] = identifier[RF_VPN_V4] , identifier[multi_exit_disc] = keyword[None] ):
literal[string]
keyword[i... | def vrf_add(self, route_dist, import_rts, export_rts, site_of_origins=None, route_family=RF_VPN_V4, multi_exit_disc=None):
""" This method adds a new vrf used for VPN.
``route_dist`` specifies a route distinguisher value.
``import_rts`` specifies a list of route targets to be imported.
``... |
def run(self):
"""Method representing the thread's activity.
You may override this method in a subclass. The standard run() method
invokes the callable object passed to the object's constructor as the
target argument, if any, with sequential and keyword arguments taken
from the ... | def function[run, parameter[self]]:
constant[Method representing the thread's activity.
You may override this method in a subclass. The standard run() method
invokes the callable object passed to the object's constructor as the
target argument, if any, with sequential and keyword argume... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[if] identifier[self] . identifier[__target] :
identifier[self] . identifier[__target] (* identifier[self] . identifier[__args] ,** identifier[self] . identifier[__kwargs] )
... | def run(self):
"""Method representing the thread's activity.
You may override this method in a subclass. The standard run() method
invokes the callable object passed to the object's constructor as the
target argument, if any, with sequential and keyword arguments taken
from the args... |
def get_index_and_columns_order(cls, columns_in_file_expected, columns_dict, file_path):
"""
:param columns_in_file_expected:
:param columns_dict:
:param file_path:
:rtype: tuple[list,list]
"""
use_columns_with_index = []
column_names_in_db = [... | def function[get_index_and_columns_order, parameter[cls, columns_in_file_expected, columns_dict, file_path]]:
constant[
:param columns_in_file_expected:
:param columns_dict:
:param file_path:
:rtype: tuple[list,list]
]
variable[use_columns_with_index] ... | keyword[def] identifier[get_index_and_columns_order] ( identifier[cls] , identifier[columns_in_file_expected] , identifier[columns_dict] , identifier[file_path] ):
literal[string]
identifier[use_columns_with_index] =[]
identifier[column_names_in_db] =[]
identifier[column_names_fr... | def get_index_and_columns_order(cls, columns_in_file_expected, columns_dict, file_path):
"""
:param columns_in_file_expected:
:param columns_dict:
:param file_path:
:rtype: tuple[list,list]
"""
use_columns_with_index = []
column_names_in_db = []
column... |
def debug(self, text):
"""
Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their t... | def function[debug, parameter[self, text]]:
constant[
Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they a... | keyword[def] identifier[debug] ( identifier[self] , identifier[text] ):
literal[string]
identifier[self] . identifier[queue] . identifier[put] ( identifier[dill] . identifier[dumps] ( identifier[LogMessageCommand] ( identifier[text] = identifier[text] , identifier[level] = identifier[logging] . ide... | def debug(self, text):
"""
Posts a debug message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their times... |
def thread_pool(self, thread_pool_patterns=None, params=None):
"""
Get information about thread pools.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-thread-pool.html>`_
:arg thread_pool_patterns: A comma-separated list of regular-expressions
to filter... | def function[thread_pool, parameter[self, thread_pool_patterns, params]]:
constant[
Get information about thread pools.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-thread-pool.html>`_
:arg thread_pool_patterns: A comma-separated list of regular-expressions
... | keyword[def] identifier[thread_pool] ( identifier[self] , identifier[thread_pool_patterns] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[transport] . identifier[perform_request] ( literal[string] , identifier[_make_path] ( lit... | def thread_pool(self, thread_pool_patterns=None, params=None):
"""
Get information about thread pools.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-thread-pool.html>`_
:arg thread_pool_patterns: A comma-separated list of regular-expressions
to filter the... |
def check_for_errors(self):
"""Check connection and channel for errors.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
try... | def function[check_for_errors, parameter[self]]:
constant[Check connection and channel for errors.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:retu... | keyword[def] identifier[check_for_errors] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[_connection] . identifier[check_for_errors] ()
keyword[except] identifier[AMQPConnectionError] :
identifier[self] . identifier[set_state] ... | def check_for_errors(self):
"""Check connection and channel for errors.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
try:
... |
def create(vm_):
'''
Create a single VM from a data dict.
'''
try:
if vm_['profile'] and config.is_profile_configured(
__opts__,
__active_provider_name__ or 'azurearm',
vm_['profile'],
vm_=vm_
) is False:
return False
except... | def function[create, parameter[vm_]]:
constant[
Create a single VM from a data dict.
]
<ast.Try object at 0x7da1b2346b30>
if compare[call[name[vm_].get, parameter[constant[bootstrap_interface]]] is constant[None]] begin[:]
call[name[vm_]][constant[bootstrap_interface]] assign... | keyword[def] identifier[create] ( identifier[vm_] ):
literal[string]
keyword[try] :
keyword[if] identifier[vm_] [ literal[string] ] keyword[and] identifier[config] . identifier[is_profile_configured] (
identifier[__opts__] ,
identifier[__active_provider_name__] keyword[or] li... | def create(vm_):
"""
Create a single VM from a data dict.
"""
try:
if vm_['profile'] and config.is_profile_configured(__opts__, __active_provider_name__ or 'azurearm', vm_['profile'], vm_=vm_) is False:
return False # depends on [control=['if'], data=[]] # depends on [control=['try... |
def _extract_nonce(cls, http_result):
"""
Given an HTTP response from the sessino endpoint, extract the nonce, so we can "sign" requests with it.
We don't really sign the requests in the traditional sense of a nonce, we just incude them in the auth requests.
:param http_result: HTTP res... | def function[_extract_nonce, parameter[cls, http_result]]:
constant[
Given an HTTP response from the sessino endpoint, extract the nonce, so we can "sign" requests with it.
We don't really sign the requests in the traditional sense of a nonce, we just incude them in the auth requests.
:... | keyword[def] identifier[_extract_nonce] ( identifier[cls] , identifier[http_result] ):
literal[string]
identifier[last_redirect_url] = identifier[urlparse] ( identifier[http_result] . identifier[history] [- literal[int] ]. identifier[request] . identifier[url] )
identifier[last_r... | def _extract_nonce(cls, http_result):
"""
Given an HTTP response from the sessino endpoint, extract the nonce, so we can "sign" requests with it.
We don't really sign the requests in the traditional sense of a nonce, we just incude them in the auth requests.
:param http_result: HTTP respons... |
def to_server_timezone(self, timezones, for_year):
"""Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there
may be multiple matches. If so, we return a random timezone ID.
:param timezones: A list of server timezones, as returned by
... | def function[to_server_timezone, parameter[self, timezones, for_year]]:
constant[Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there
may be multiple matches. If so, we return a random timezone ID.
:param timezones: A list of server timezo... | keyword[def] identifier[to_server_timezone] ( identifier[self] , identifier[timezones] , identifier[for_year] ):
literal[string]
identifier[candidates] = identifier[set] ()
keyword[for] identifier[tz_id] , identifier[tz_name] , identifier[tz_periods] , identifier[tz_transitions] , identif... | def to_server_timezone(self, timezones, for_year):
"""Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there
may be multiple matches. If so, we return a random timezone ID.
:param timezones: A list of server timezones, as returned by
... |
def _startXTVDNode(self, name, attrs):
"""Process the start of the top-level xtvd node"""
schemaVersion = attrs.get('schemaVersion')
validFrom = self._parseDateTime(attrs.get('from'))
validTo = self._parseDateTime(attrs.get('to'))
self._progress.printMsg('Parsing version %s data... | def function[_startXTVDNode, parameter[self, name, attrs]]:
constant[Process the start of the top-level xtvd node]
variable[schemaVersion] assign[=] call[name[attrs].get, parameter[constant[schemaVersion]]]
variable[validFrom] assign[=] call[name[self]._parseDateTime, parameter[call[name[attrs].... | keyword[def] identifier[_startXTVDNode] ( identifier[self] , identifier[name] , identifier[attrs] ):
literal[string]
identifier[schemaVersion] = identifier[attrs] . identifier[get] ( literal[string] )
identifier[validFrom] = identifier[self] . identifier[_parseDateTime] ( identifier[attrs... | def _startXTVDNode(self, name, attrs):
"""Process the start of the top-level xtvd node"""
schemaVersion = attrs.get('schemaVersion')
validFrom = self._parseDateTime(attrs.get('from'))
validTo = self._parseDateTime(attrs.get('to'))
self._progress.printMsg('Parsing version %s data from %s to %s' % (sc... |
def _get_friends_count(session, user_id):
"""
https://vk.com/dev/friends.get
"""
response = session.fetch('friends.get', user_id=user_id, count=1)
return response["count"] | def function[_get_friends_count, parameter[session, user_id]]:
constant[
https://vk.com/dev/friends.get
]
variable[response] assign[=] call[name[session].fetch, parameter[constant[friends.get]]]
return[call[name[response]][constant[count]]] | keyword[def] identifier[_get_friends_count] ( identifier[session] , identifier[user_id] ):
literal[string]
identifier[response] = identifier[session] . identifier[fetch] ( literal[string] , identifier[user_id] = identifier[user_id] , identifier[count] = literal[int] )
keyword[return] iden... | def _get_friends_count(session, user_id):
"""
https://vk.com/dev/friends.get
"""
response = session.fetch('friends.get', user_id=user_id, count=1)
return response['count'] |
def get_task(self, name, include_helpers=True):
"""
Get task identified by name or raise TaskNotFound if there
is no such task
:param name: name of helper/task to get
:param include_helpers: if True, also look for helpers
:return: task or helper identified by name
... | def function[get_task, parameter[self, name, include_helpers]]:
constant[
Get task identified by name or raise TaskNotFound if there
is no such task
:param name: name of helper/task to get
:param include_helpers: if True, also look for helpers
:return: task or helper iden... | keyword[def] identifier[get_task] ( identifier[self] , identifier[name] , identifier[include_helpers] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[include_helpers] keyword[and] identifier[name] keyword[in] identifier[self] . identifier[_helper_names] :
... | def get_task(self, name, include_helpers=True):
"""
Get task identified by name or raise TaskNotFound if there
is no such task
:param name: name of helper/task to get
:param include_helpers: if True, also look for helpers
:return: task or helper identified by name
"""... |
def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
"""Plot a GO DAG for the upper portion of a single Group of user GOs."""
# Get GO IDs which are in the hdrgo path
goids_possible = ntpltgo1.gosubdag.go2obj.keys()
# Get upper GO IDs which have the most descendants
retur... | def function[_get_gos_upper, parameter[self, ntpltgo1, max_upper, go2parentids]]:
constant[Plot a GO DAG for the upper portion of a single Group of user GOs.]
variable[goids_possible] assign[=] call[name[ntpltgo1].gosubdag.go2obj.keys, parameter[]]
return[call[name[self]._get_gosrcs_upper, parameter... | keyword[def] identifier[_get_gos_upper] ( identifier[self] , identifier[ntpltgo1] , identifier[max_upper] , identifier[go2parentids] ):
literal[string]
identifier[goids_possible] = identifier[ntpltgo1] . identifier[gosubdag] . identifier[go2obj] . identifier[keys] ()
keyw... | def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
"""Plot a GO DAG for the upper portion of a single Group of user GOs."""
# Get GO IDs which are in the hdrgo path
goids_possible = ntpltgo1.gosubdag.go2obj.keys()
# Get upper GO IDs which have the most descendants
return self._get_gosrcs_u... |
def build_parameters(self, stack, provider_stack=None):
"""Builds the CloudFormation Parameters for our stack.
Args:
stack (:class:`stacker.stack.Stack`): A stacker stack
provider_stack (dict): An optional Stacker provider object
Returns:
dict: The parameter... | def function[build_parameters, parameter[self, stack, provider_stack]]:
constant[Builds the CloudFormation Parameters for our stack.
Args:
stack (:class:`stacker.stack.Stack`): A stacker stack
provider_stack (dict): An optional Stacker provider object
Returns:
... | keyword[def] identifier[build_parameters] ( identifier[self] , identifier[stack] , identifier[provider_stack] = keyword[None] ):
literal[string]
identifier[resolved] = identifier[_resolve_parameters] ( identifier[stack] . identifier[parameter_values] , identifier[stack] . identifier[blueprint] )
... | def build_parameters(self, stack, provider_stack=None):
"""Builds the CloudFormation Parameters for our stack.
Args:
stack (:class:`stacker.stack.Stack`): A stacker stack
provider_stack (dict): An optional Stacker provider object
Returns:
dict: The parameters fo... |
def check_sample_files(fam_filename, raw_dirname):
"""Checks the raw sample files.
:param fam_filename: the name of the FAM file.
:param raw_dirname: the name of the directory containing the raw file.
:type fam_filename: str
:type raw_dirname: str
:returns: the set of all the sample files tha... | def function[check_sample_files, parameter[fam_filename, raw_dirname]]:
constant[Checks the raw sample files.
:param fam_filename: the name of the FAM file.
:param raw_dirname: the name of the directory containing the raw file.
:type fam_filename: str
:type raw_dirname: str
:returns: the ... | keyword[def] identifier[check_sample_files] ( identifier[fam_filename] , identifier[raw_dirname] ):
literal[string]
identifier[fam_samples] = keyword[None]
keyword[with] identifier[open] ( identifier[fam_filename] , literal[string] ) keyword[as] identifier[i_file] :
identifier[fam_sam... | def check_sample_files(fam_filename, raw_dirname):
"""Checks the raw sample files.
:param fam_filename: the name of the FAM file.
:param raw_dirname: the name of the directory containing the raw file.
:type fam_filename: str
:type raw_dirname: str
:returns: the set of all the sample files tha... |
def save(self):
"""Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, then the document is
... | def function[save, parameter[self]]:
constant[Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, th... | keyword[def] identifier[save] ( identifier[self] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[pre_save] ()
identifier[database] , identifier[collection] = identifier[self] . identifier[_collection_key... | def save(self):
"""Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, then the document is
vali... |
def set_aux(self, aux):
"""
Sets the TCP auxiliary port.
:param aux: console auxiliary port (integer)
"""
self.aux = aux
yield from self._hypervisor.send('vm set_aux_tcp_port "{name}" {aux}'.format(name=self._name, aux=aux)) | def function[set_aux, parameter[self, aux]]:
constant[
Sets the TCP auxiliary port.
:param aux: console auxiliary port (integer)
]
name[self].aux assign[=] name[aux]
<ast.YieldFrom object at 0x7da18f8104f0> | keyword[def] identifier[set_aux] ( identifier[self] , identifier[aux] ):
literal[string]
identifier[self] . identifier[aux] = identifier[aux]
keyword[yield] keyword[from] identifier[self] . identifier[_hypervisor] . identifier[send] ( literal[string] . identifier[format] ( identifier[n... | def set_aux(self, aux):
"""
Sets the TCP auxiliary port.
:param aux: console auxiliary port (integer)
"""
self.aux = aux
yield from self._hypervisor.send('vm set_aux_tcp_port "{name}" {aux}'.format(name=self._name, aux=aux)) |
def update_date(self):
"""269 Date normalization."""
dates_269 = record_get_field_instances(self.record, '269')
for idx, field in enumerate(dates_269):
new_subs = []
old_subs = field[0]
for code, value in old_subs:
if code == "c":
... | def function[update_date, parameter[self]]:
constant[269 Date normalization.]
variable[dates_269] assign[=] call[name[record_get_field_instances], parameter[name[self].record, constant[269]]]
for taget[tuple[[<ast.Name object at 0x7da20c6c5810>, <ast.Name object at 0x7da20c6c6680>]]] in starred[... | keyword[def] identifier[update_date] ( identifier[self] ):
literal[string]
identifier[dates_269] = identifier[record_get_field_instances] ( identifier[self] . identifier[record] , literal[string] )
keyword[for] identifier[idx] , identifier[field] keyword[in] identifier[enumerate] ( iden... | def update_date(self):
"""269 Date normalization."""
dates_269 = record_get_field_instances(self.record, '269')
for (idx, field) in enumerate(dates_269):
new_subs = []
old_subs = field[0]
for (code, value) in old_subs:
if code == 'c':
new_subs.append(('c',... |
def handle(self, cycle_delay=0.1):
"""
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
"""
asyncore.loop(cycle_delay, count=1)
self._server.process(int(cycle_delay * 1000)) | def function[handle, parameter[self, cycle_delay]]:
constant[
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
]
call[name[asyncore].loop, parameter[name[cycle_delay]]]
call[name[self]._server.process, parameter[call[na... | keyword[def] identifier[handle] ( identifier[self] , identifier[cycle_delay] = literal[int] ):
literal[string]
identifier[asyncore] . identifier[loop] ( identifier[cycle_delay] , identifier[count] = literal[int] )
identifier[self] . identifier[_server] . identifier[process] ( identifier[in... | def handle(self, cycle_delay=0.1):
"""
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
"""
asyncore.loop(cycle_delay, count=1)
self._server.process(int(cycle_delay * 1000)) |
def databases(self):
"""
list of databases available from eutils (per einfo query)
"""
try:
return self._databases
except AttributeError:
self._databases = self.einfo().databases
return self._databases | def function[databases, parameter[self]]:
constant[
list of databases available from eutils (per einfo query)
]
<ast.Try object at 0x7da18f58eec0> | keyword[def] identifier[databases] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_databases]
keyword[except] identifier[AttributeError] :
identifier[self] . identifier[_databases] = identifier[self] . identif... | def databases(self):
"""
list of databases available from eutils (per einfo query)
"""
try:
return self._databases # depends on [control=['try'], data=[]]
except AttributeError:
self._databases = self.einfo().databases
return self._databases # depends on [control=['... |
def init_parser(cls, parser):
"""Initialize argument parser"""
subparsers = parser.add_subparsers(title='Search domain')
# Compound subcommand
parser_compound = subparsers.add_parser(
'compound', help='Search in compounds')
parser_compound.set_defaults(which='compoun... | def function[init_parser, parameter[cls, parser]]:
constant[Initialize argument parser]
variable[subparsers] assign[=] call[name[parser].add_subparsers, parameter[]]
variable[parser_compound] assign[=] call[name[subparsers].add_parser, parameter[constant[compound]]]
call[name[parser_comp... | keyword[def] identifier[init_parser] ( identifier[cls] , identifier[parser] ):
literal[string]
identifier[subparsers] = identifier[parser] . identifier[add_subparsers] ( identifier[title] = literal[string] )
identifier[parser_compound] = identifier[subparsers] . identifier[add_pa... | def init_parser(cls, parser):
"""Initialize argument parser"""
subparsers = parser.add_subparsers(title='Search domain')
# Compound subcommand
parser_compound = subparsers.add_parser('compound', help='Search in compounds')
parser_compound.set_defaults(which='compound')
parser_compound.add_argume... |
def GetIPAddresses(self):
"""Return a list of IP addresses."""
results = []
for address in self.addresses:
human_readable_address = address.human_readable_address
if human_readable_address is not None:
results.append(human_readable_address)
return results | def function[GetIPAddresses, parameter[self]]:
constant[Return a list of IP addresses.]
variable[results] assign[=] list[[]]
for taget[name[address]] in starred[name[self].addresses] begin[:]
variable[human_readable_address] assign[=] name[address].human_readable_address
... | keyword[def] identifier[GetIPAddresses] ( identifier[self] ):
literal[string]
identifier[results] =[]
keyword[for] identifier[address] keyword[in] identifier[self] . identifier[addresses] :
identifier[human_readable_address] = identifier[address] . identifier[human_readable_address]
... | def GetIPAddresses(self):
"""Return a list of IP addresses."""
results = []
for address in self.addresses:
human_readable_address = address.human_readable_address
if human_readable_address is not None:
results.append(human_readable_address) # depends on [control=['if'], data=['h... |
def unpack_nested_exception(error):
"""
If exception are stacked, return the first one
:param error: A python exception with possible exception embeded within
:return: A python exception with no exception embeded within
"""
i = 0
while True:
if error.args[i:]:
... | def function[unpack_nested_exception, parameter[error]]:
constant[
If exception are stacked, return the first one
:param error: A python exception with possible exception embeded within
:return: A python exception with no exception embeded within
]
variable[i] assign[=] cons... | keyword[def] identifier[unpack_nested_exception] ( identifier[error] ):
literal[string]
identifier[i] = literal[int]
keyword[while] keyword[True] :
keyword[if] identifier[error] . identifier[args] [ identifier[i] :]:
keyword[if] identifier[isinstance] ( identifier[error] . id... | def unpack_nested_exception(error):
"""
If exception are stacked, return the first one
:param error: A python exception with possible exception embeded within
:return: A python exception with no exception embeded within
"""
i = 0
while True:
if error.args[i:]:
... |
def patch(self, url: StrOrURL,
*, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
"""Perform HTTP PATCH request."""
return _RequestContextManager(
self._request(hdrs.METH_PATCH, url,
data=data,
**kwargs)) | def function[patch, parameter[self, url]]:
constant[Perform HTTP PATCH request.]
return[call[name[_RequestContextManager], parameter[call[name[self]._request, parameter[name[hdrs].METH_PATCH, name[url]]]]]] | keyword[def] identifier[patch] ( identifier[self] , identifier[url] : identifier[StrOrURL] ,
*, identifier[data] : identifier[Any] = keyword[None] ,** identifier[kwargs] : identifier[Any] )-> literal[string] :
literal[string]
keyword[return] identifier[_RequestContextManager] (
identifier... | def patch(self, url: StrOrURL, *, data: Any=None, **kwargs: Any) -> '_RequestContextManager':
"""Perform HTTP PATCH request."""
return _RequestContextManager(self._request(hdrs.METH_PATCH, url, data=data, **kwargs)) |
def get_current_user():
"""Get current user."""
if not 'user_id' in session:
return None
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None
return user | def function[get_current_user, parameter[]]:
constant[Get current user.]
if <ast.UnaryOp object at 0x7da20c9939a0> begin[:]
return[constant[None]]
variable[user] assign[=] call[call[name[User].query.filter, parameter[compare[name[User].id equal[==] call[name[session]][constant[user_id]]]... | keyword[def] identifier[get_current_user] ():
literal[string]
keyword[if] keyword[not] literal[string] keyword[in] identifier[session] :
keyword[return] keyword[None]
identifier[user] = identifier[User] . identifier[query] . identifier[filter] ( identifier[User] . identifier[id] == iden... | def get_current_user():
"""Get current user."""
if not 'user_id' in session:
return None # depends on [control=['if'], data=[]]
user = User.query.filter(User.id == session['user_id']).first()
if not user:
signout_user()
return None # depends on [control=['if'], data=[]]
ret... |
def set_subplot_ylabel(self, row, column, text):
"""Set a label for the y-axis of a subplot.
:param row,column: specify the subplot.
:param text: text of the label.
"""
subplot = self.get_subplot_at(row, column)
subplot.set_ylabel(text) | def function[set_subplot_ylabel, parameter[self, row, column, text]]:
constant[Set a label for the y-axis of a subplot.
:param row,column: specify the subplot.
:param text: text of the label.
]
variable[subplot] assign[=] call[name[self].get_subplot_at, parameter[name[row], nam... | keyword[def] identifier[set_subplot_ylabel] ( identifier[self] , identifier[row] , identifier[column] , identifier[text] ):
literal[string]
identifier[subplot] = identifier[self] . identifier[get_subplot_at] ( identifier[row] , identifier[column] )
identifier[subplot] . identifier[set_ylab... | def set_subplot_ylabel(self, row, column, text):
"""Set a label for the y-axis of a subplot.
:param row,column: specify the subplot.
:param text: text of the label.
"""
subplot = self.get_subplot_at(row, column)
subplot.set_ylabel(text) |
def register_file(name, member, path, digest='', conn=None):
'''
Register a file in the package database
'''
close = False
if conn is None:
close = True
conn = init()
conn.execute('INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (
name,
'{0}/{1}'.... | def function[register_file, parameter[name, member, path, digest, conn]]:
constant[
Register a file in the package database
]
variable[close] assign[=] constant[False]
if compare[name[conn] is constant[None]] begin[:]
variable[close] assign[=] constant[True]
... | keyword[def] identifier[register_file] ( identifier[name] , identifier[member] , identifier[path] , identifier[digest] = literal[string] , identifier[conn] = keyword[None] ):
literal[string]
identifier[close] = keyword[False]
keyword[if] identifier[conn] keyword[is] keyword[None] :
identi... | def register_file(name, member, path, digest='', conn=None):
"""
Register a file in the package database
"""
close = False
if conn is None:
close = True
conn = init() # depends on [control=['if'], data=['conn']]
conn.execute('INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ... |
def dec(self, byts):
'''
Decode an envelope dict and decrypt the given bytes.
Args:
byts (bytes): Bytes to decrypt.
Returns:
bytes: Decrypted message.
'''
envl = s_msgpack.un(byts)
iv = envl.get('iv', b'')
asscd = envl.get('asscd'... | def function[dec, parameter[self, byts]]:
constant[
Decode an envelope dict and decrypt the given bytes.
Args:
byts (bytes): Bytes to decrypt.
Returns:
bytes: Decrypted message.
]
variable[envl] assign[=] call[name[s_msgpack].un, parameter[name[b... | keyword[def] identifier[dec] ( identifier[self] , identifier[byts] ):
literal[string]
identifier[envl] = identifier[s_msgpack] . identifier[un] ( identifier[byts] )
identifier[iv] = identifier[envl] . identifier[get] ( literal[string] , literal[string] )
identifier[asscd] = identi... | def dec(self, byts):
"""
Decode an envelope dict and decrypt the given bytes.
Args:
byts (bytes): Bytes to decrypt.
Returns:
bytes: Decrypted message.
"""
envl = s_msgpack.un(byts)
iv = envl.get('iv', b'')
asscd = envl.get('asscd', b'')
data ... |
def _request_check(self, address):
"""Wake one monitor. Hold the lock when calling this."""
server = self._servers.get(address)
# "server" is None if another thread removed it from the topology.
if server:
server.request_check() | def function[_request_check, parameter[self, address]]:
constant[Wake one monitor. Hold the lock when calling this.]
variable[server] assign[=] call[name[self]._servers.get, parameter[name[address]]]
if name[server] begin[:]
call[name[server].request_check, parameter[]] | keyword[def] identifier[_request_check] ( identifier[self] , identifier[address] ):
literal[string]
identifier[server] = identifier[self] . identifier[_servers] . identifier[get] ( identifier[address] )
keyword[if] identifier[server] :
identifier[server] . identifie... | def _request_check(self, address):
"""Wake one monitor. Hold the lock when calling this."""
server = self._servers.get(address)
# "server" is None if another thread removed it from the topology.
if server:
server.request_check() # depends on [control=['if'], data=[]] |
def search_dict(data, key):
"""
Search for a key in a nested dict, or list of nested dicts, and return the values.
:param data: dict/list to search
:param key: key to find
:return: matches for key
"""
if isinstance(data, dict):
for dkey, value in data.items():
if dkey ==... | def function[search_dict, parameter[data, key]]:
constant[
Search for a key in a nested dict, or list of nested dicts, and return the values.
:param data: dict/list to search
:param key: key to find
:return: matches for key
]
if call[name[isinstance], parameter[name[data], name[dict... | keyword[def] identifier[search_dict] ( identifier[data] , identifier[key] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] ):
keyword[for] identifier[dkey] , identifier[value] keyword[in] identifier[data] . identifier[items] ():
keyword[i... | def search_dict(data, key):
"""
Search for a key in a nested dict, or list of nested dicts, and return the values.
:param data: dict/list to search
:param key: key to find
:return: matches for key
"""
if isinstance(data, dict):
for (dkey, value) in data.items():
if dkey ... |
def _check_values(self, value):
"""
Given a list of possible PK values, returns a QuerySet of the
corresponding objects. Raises a ValidationError if a given value is
invalid (not a valid PK, not in the queryset, etc.)
"""
key = self.to_field_name or 'pk'
# dedupli... | def function[_check_values, parameter[self, value]]:
constant[
Given a list of possible PK values, returns a QuerySet of the
corresponding objects. Raises a ValidationError if a given value is
invalid (not a valid PK, not in the queryset, etc.)
]
variable[key] assign[=] <... | keyword[def] identifier[_check_values] ( identifier[self] , identifier[value] ):
literal[string]
identifier[key] = identifier[self] . identifier[to_field_name] keyword[or] literal[string]
keyword[try] :
identifier[value] = identifier[frozenset] ( identifie... | def _check_values(self, value):
"""
Given a list of possible PK values, returns a QuerySet of the
corresponding objects. Raises a ValidationError if a given value is
invalid (not a valid PK, not in the queryset, etc.)
"""
key = self.to_field_name or 'pk'
# deduplicate given v... |
def save(self):
"""
:return: save this OS instance on Ariane server (create or update)
"""
LOGGER.debug("OSInstance.save")
post_payload = {}
consolidated_osi_id = []
consolidated_ipa_id = []
consolidated_nic_id = []
consolidated_app_id = []
... | def function[save, parameter[self]]:
constant[
:return: save this OS instance on Ariane server (create or update)
]
call[name[LOGGER].debug, parameter[constant[OSInstance.save]]]
variable[post_payload] assign[=] dictionary[[], []]
variable[consolidated_osi_id] assign[=] l... | keyword[def] identifier[save] ( identifier[self] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
identifier[post_payload] ={}
identifier[consolidated_osi_id] =[]
identifier[consolidated_ipa_id] =[]
identifier[consolidated_nic_id] =[]... | def save(self):
"""
:return: save this OS instance on Ariane server (create or update)
"""
LOGGER.debug('OSInstance.save')
post_payload = {}
consolidated_osi_id = []
consolidated_ipa_id = []
consolidated_nic_id = []
consolidated_app_id = []
consolidated_env_id = []
co... |
def write_ch (self, ch):
'''This puts a character at the current cursor position. The cursor
position is moved forward with wrap-around, but no scrolling is done if
the cursor hits the lower-right corner of the screen. '''
if isinstance(ch, bytes):
ch = self._decode(ch)
... | def function[write_ch, parameter[self, ch]]:
constant[This puts a character at the current cursor position. The cursor
position is moved forward with wrap-around, but no scrolling is done if
the cursor hits the lower-right corner of the screen. ]
if call[name[isinstance], parameter[name[... | keyword[def] identifier[write_ch] ( identifier[self] , identifier[ch] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[ch] , identifier[bytes] ):
identifier[ch] = identifier[self] . identifier[_decode] ( identifier[ch] )
identifier[ch] = ident... | def write_ch(self, ch):
"""This puts a character at the current cursor position. The cursor
position is moved forward with wrap-around, but no scrolling is done if
the cursor hits the lower-right corner of the screen. """
if isinstance(ch, bytes):
ch = self._decode(ch) # depends on [con... |
def search_metrics(self, *args, **kwargs):
"""
Args:
query (string): elasticsearch string query
order_by (optional[string]): property by which to order results
offset (optional[int]): number of results to skip for pagination
(default=0)
lim... | def function[search_metrics, parameter[self]]:
constant[
Args:
query (string): elasticsearch string query
order_by (optional[string]): property by which to order results
offset (optional[int]): number of results to skip for pagination
(default=0)
... | keyword[def] identifier[search_metrics] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_search_metrics_and_metadata] (
identifier[self] . identifier[_METRIC_ENDPOINT_SUFFIX] ,* identifier[args] ,** identifier[... | def search_metrics(self, *args, **kwargs):
"""
Args:
query (string): elasticsearch string query
order_by (optional[string]): property by which to order results
offset (optional[int]): number of results to skip for pagination
(default=0)
limit (... |
def ephemeral(cls):
"""
Creates a new ephemeral key constructed using a raw 32-byte string from urandom.
Ephemeral keys are used once for each encryption task and are then discarded;
they are not intended for long-term or repeat use.
"""
private_key = nacl.public.PrivateK... | def function[ephemeral, parameter[cls]]:
constant[
Creates a new ephemeral key constructed using a raw 32-byte string from urandom.
Ephemeral keys are used once for each encryption task and are then discarded;
they are not intended for long-term or repeat use.
]
variable[... | keyword[def] identifier[ephemeral] ( identifier[cls] ):
literal[string]
identifier[private_key] = identifier[nacl] . identifier[public] . identifier[PrivateKey] ( identifier[os] . identifier[urandom] ( literal[int] ))
keyword[return] identifier[cls] ( identifier[private_key] . identifier[... | def ephemeral(cls):
"""
Creates a new ephemeral key constructed using a raw 32-byte string from urandom.
Ephemeral keys are used once for each encryption task and are then discarded;
they are not intended for long-term or repeat use.
"""
private_key = nacl.public.PrivateKey(os.ur... |
def make_d2p_id(self):
"""
Make an association id for phenotypic associations with disease
that is defined by:
source of association + disease + relationship + phenotype
+ onset + frequency
:return:
"""
attributes = [self.onset, self.frequency]
... | def function[make_d2p_id, parameter[self]]:
constant[
Make an association id for phenotypic associations with disease
that is defined by:
source of association + disease + relationship + phenotype
+ onset + frequency
:return:
]
variable[attributes] assig... | keyword[def] identifier[make_d2p_id] ( identifier[self] ):
literal[string]
identifier[attributes] =[ identifier[self] . identifier[onset] , identifier[self] . identifier[frequency] ]
identifier[assoc_id] = identifier[self] . identifier[make_association_id] (
identifier[self] . id... | def make_d2p_id(self):
"""
Make an association id for phenotypic associations with disease
that is defined by:
source of association + disease + relationship + phenotype
+ onset + frequency
:return:
"""
attributes = [self.onset, self.frequency]
assoc_id = se... |
def mouse(table, day=None):
"""Handler for showing mouse statistics for specified type and day."""
where = (("day", day),) if day else ()
events = db.fetch(table, where=where, order="day")
for e in events: e["dt"] = datetime.datetime.fromtimestamp(e["stamp"])
stats, positions, events = stats_mo... | def function[mouse, parameter[table, day]]:
constant[Handler for showing mouse statistics for specified type and day.]
variable[where] assign[=] <ast.IfExp object at 0x7da20e956050>
variable[events] assign[=] call[name[db].fetch, parameter[name[table]]]
for taget[name[e]] in starred[name... | keyword[def] identifier[mouse] ( identifier[table] , identifier[day] = keyword[None] ):
literal[string]
identifier[where] =(( literal[string] , identifier[day] ),) keyword[if] identifier[day] keyword[else] ()
identifier[events] = identifier[db] . identifier[fetch] ( identifier[table] , identifier... | def mouse(table, day=None):
"""Handler for showing mouse statistics for specified type and day."""
where = (('day', day),) if day else ()
events = db.fetch(table, where=where, order='day')
for e in events:
e['dt'] = datetime.datetime.fromtimestamp(e['stamp']) # depends on [control=['for'], data... |
def get_cds_ranges_for_transcript(self, transcript_id):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=cds".format(transcript_id)
r = self.ensembl_re... | def function[get_cds_ranges_for_transcript, parameter[self, transcript_id]]:
constant[ obtain the sequence for a transcript from ensembl
]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da1b1a1c220>], [<ast.Constant object at 0x7da1b1a1f730>]]
name[self].attempt assig... | keyword[def] identifier[get_cds_ranges_for_transcript] ( identifier[self] , identifier[transcript_id] ):
literal[string]
identifier[headers] ={ literal[string] : literal[string] }
identifier[self] . identifier[attempt] = literal[int]
identifier[ext] = literal[string] . identifi... | def get_cds_ranges_for_transcript(self, transcript_id):
""" obtain the sequence for a transcript from ensembl
"""
headers = {'content-type': 'application/json'}
self.attempt = 0
ext = '/overlap/id/{}?feature=cds'.format(transcript_id)
r = self.ensembl_request(ext, headers)
cds_ranges = [... |
def get_state_for_transition(self, transition):
"""Calculate the target state of a transition
:param transition: The transition of which the target state is determined
:return: the to-state of the transition
:raises exceptions.TypeError: if the transition parameter is of wrong type
... | def function[get_state_for_transition, parameter[self, transition]]:
constant[Calculate the target state of a transition
:param transition: The transition of which the target state is determined
:return: the to-state of the transition
:raises exceptions.TypeError: if the transition para... | keyword[def] identifier[get_state_for_transition] ( identifier[self] , identifier[transition] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[transition] , identifier[Transition] ):
keyword[raise] identifier[TypeError] ( literal[string] )
... | def get_state_for_transition(self, transition):
"""Calculate the target state of a transition
:param transition: The transition of which the target state is determined
:return: the to-state of the transition
:raises exceptions.TypeError: if the transition parameter is of wrong type
... |
def featured_playlists(self, locale=None, country=None, timestamp=None, limit=20, offset=0):
"""Get a list of Spotify featured playlists.
Parameters
----------
locale : LOCALE_TP
LOCALE
country : COUNTRY_TP
COUNTRY
timestamp : TIMESTAMP_TP
... | def function[featured_playlists, parameter[self, locale, country, timestamp, limit, offset]]:
constant[Get a list of Spotify featured playlists.
Parameters
----------
locale : LOCALE_TP
LOCALE
country : COUNTRY_TP
COUNTRY
timestamp : TIMESTAMP_TP
... | keyword[def] identifier[featured_playlists] ( identifier[self] , identifier[locale] = keyword[None] , identifier[country] = keyword[None] , identifier[timestamp] = keyword[None] , identifier[limit] = literal[int] , identifier[offset] = literal[int] ):
literal[string]
identifier[route] = identifier[... | def featured_playlists(self, locale=None, country=None, timestamp=None, limit=20, offset=0):
"""Get a list of Spotify featured playlists.
Parameters
----------
locale : LOCALE_TP
LOCALE
country : COUNTRY_TP
COUNTRY
timestamp : TIMESTAMP_TP
... |
def get_list(medium, user, credentials):
"""Returns a MediumList (Anime or Manga depends on [medium]) of user.
If user is not given, the username is taken from the initialized auth
credentials.
:param medium Anime or manga (tokens.Medium.Anime or tokens.Medium.Manga)
:param user The user whose lis... | def function[get_list, parameter[medium, user, credentials]]:
constant[Returns a MediumList (Anime or Manga depends on [medium]) of user.
If user is not given, the username is taken from the initialized auth
credentials.
:param medium Anime or manga (tokens.Medium.Anime or tokens.Medium.Manga)
:... | keyword[def] identifier[get_list] ( identifier[medium] , identifier[user] , identifier[credentials] ):
literal[string]
identifier[helpers] . identifier[check_creds] ( identifier[credentials] , identifier[header] )
identifier[list_url] = identifier[helpers] . identifier[get_list_url] ( identifier[mediu... | def get_list(medium, user, credentials):
"""Returns a MediumList (Anime or Manga depends on [medium]) of user.
If user is not given, the username is taken from the initialized auth
credentials.
:param medium Anime or manga (tokens.Medium.Anime or tokens.Medium.Manga)
:param user The user whose lis... |
def add_shared_configs(p, base_dir=''):
"""Add configargparser/argparse configs for shared argument.
Arguments:
p - configargparse.ArgParser object
base_dir - base directory for file/path defaults.
"""
p.add('--host', default='localhost',
help="Service host")
p.add('--port... | def function[add_shared_configs, parameter[p, base_dir]]:
constant[Add configargparser/argparse configs for shared argument.
Arguments:
p - configargparse.ArgParser object
base_dir - base directory for file/path defaults.
]
call[name[p].add, parameter[constant[--host]]]
... | keyword[def] identifier[add_shared_configs] ( identifier[p] , identifier[base_dir] = literal[string] ):
literal[string]
identifier[p] . identifier[add] ( literal[string] , identifier[default] = literal[string] ,
identifier[help] = literal[string] )
identifier[p] . identifier[add] ( literal[string... | def add_shared_configs(p, base_dir=''):
"""Add configargparser/argparse configs for shared argument.
Arguments:
p - configargparse.ArgParser object
base_dir - base directory for file/path defaults.
"""
p.add('--host', default='localhost', help='Service host')
p.add('--port', '-p', t... |
def is_equal(self, other):
"""
Computes whether two Partial Orderings contain the same information
"""
if not (hasattr(other, 'get_domain') or hasattr(other, 'upper') or hasattr(other, 'lower')):
other = self.coerce(other)
if self.is_domain_equal(other) \
... | def function[is_equal, parameter[self, other]]:
constant[
Computes whether two Partial Orderings contain the same information
]
if <ast.UnaryOp object at 0x7da204345cf0> begin[:]
variable[other] assign[=] call[name[self].coerce, parameter[name[other]]]
if <ast.Boo... | keyword[def] identifier[is_equal] ( identifier[self] , identifier[other] ):
literal[string]
keyword[if] keyword[not] ( identifier[hasattr] ( identifier[other] , literal[string] ) keyword[or] identifier[hasattr] ( identifier[other] , literal[string] ) keyword[or] identifier[hasattr] ( identifier[... | def is_equal(self, other):
"""
Computes whether two Partial Orderings contain the same information
"""
if not (hasattr(other, 'get_domain') or hasattr(other, 'upper') or hasattr(other, 'lower')):
other = self.coerce(other) # depends on [control=['if'], data=[]]
if self.is_domain_equ... |
def wait_until_queue_empty(self, channels, report=True, clear_end=True):
"""
Waits until all queues of channels are empty.
"""
state = {'message': ''}
self.logger.debug("wait_until_queue_empty: report=%s %s"
% (str(report), str([channel+':'+str(len(self... | def function[wait_until_queue_empty, parameter[self, channels, report, clear_end]]:
constant[
Waits until all queues of channels are empty.
]
variable[state] assign[=] dictionary[[<ast.Constant object at 0x7da18f58d180>], [<ast.Constant object at 0x7da18f58e500>]]
call[name[self]... | keyword[def] identifier[wait_until_queue_empty] ( identifier[self] , identifier[channels] , identifier[report] = keyword[True] , identifier[clear_end] = keyword[True] ):
literal[string]
identifier[state] ={ literal[string] : literal[string] }
identifier[self] . identifier[logger] . identi... | def wait_until_queue_empty(self, channels, report=True, clear_end=True):
"""
Waits until all queues of channels are empty.
"""
state = {'message': ''}
self.logger.debug('wait_until_queue_empty: report=%s %s' % (str(report), str([channel + ':' + str(len(self.queues[channel])) for channel in c... |
def interpolate2dStructuredIDW(grid, mask, kernel=15, power=2, fx=1, fy=1):
'''
replace all values in [grid] indicated by [mask]
with the inverse distance weighted interpolation of all values within
px+-kernel
[power] -> distance weighting factor: 1/distance**[power]
'''
weights = ... | def function[interpolate2dStructuredIDW, parameter[grid, mask, kernel, power, fx, fy]]:
constant[
replace all values in [grid] indicated by [mask]
with the inverse distance weighted interpolation of all values within
px+-kernel
[power] -> distance weighting factor: 1/distance**[power]
]
... | keyword[def] identifier[interpolate2dStructuredIDW] ( identifier[grid] , identifier[mask] , identifier[kernel] = literal[int] , identifier[power] = literal[int] , identifier[fx] = literal[int] , identifier[fy] = literal[int] ):
literal[string]
identifier[weights] = identifier[np] . identifier[empty] ( id... | def interpolate2dStructuredIDW(grid, mask, kernel=15, power=2, fx=1, fy=1):
"""
replace all values in [grid] indicated by [mask]
with the inverse distance weighted interpolation of all values within
px+-kernel
[power] -> distance weighting factor: 1/distance**[power]
"""
weights = np.empty... |
def _derive_list_path(self):
"""Guess otu list file path produced by Mothur"""
base, ext = path.splitext(self._input_filename)
return '%s.unique.%s.list' % (base, self.__get_method_abbrev()) | def function[_derive_list_path, parameter[self]]:
constant[Guess otu list file path produced by Mothur]
<ast.Tuple object at 0x7da1b0b55420> assign[=] call[name[path].splitext, parameter[name[self]._input_filename]]
return[binary_operation[constant[%s.unique.%s.list] <ast.Mod object at 0x7da2590d692... | keyword[def] identifier[_derive_list_path] ( identifier[self] ):
literal[string]
identifier[base] , identifier[ext] = identifier[path] . identifier[splitext] ( identifier[self] . identifier[_input_filename] )
keyword[return] literal[string] %( identifier[base] , identifier[self] . identif... | def _derive_list_path(self):
"""Guess otu list file path produced by Mothur"""
(base, ext) = path.splitext(self._input_filename)
return '%s.unique.%s.list' % (base, self.__get_method_abbrev()) |
def top_path(sources, sinks, net_flux):
"""
Use the Dijkstra algorithm for finding the shortest path
connecting a set of source states from a set of sink states.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_... | def function[top_path, parameter[sources, sinks, net_flux]]:
constant[
Use the Dijkstra algorithm for finding the shortest path
connecting a set of source states from a set of sink states.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the so... | keyword[def] identifier[top_path] ( identifier[sources] , identifier[sinks] , identifier[net_flux] ):
literal[string]
identifier[sources] = identifier[np] . identifier[array] ( identifier[sources] , identifier[dtype] = identifier[np] . identifier[int] ). identifier[reshape] ((- literal[int] ,))
identi... | def top_path(sources, sinks, net_flux):
"""
Use the Dijkstra algorithm for finding the shortest path
connecting a set of source states from a set of sink states.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_... |
def combine_action_handlers(*handlers):
"""
This function combines the given action handlers into a single function
which will call all of them.
"""
# make sure each of the given handlers is callable
for handler in handlers:
# if the handler is not a function
if not (isco... | def function[combine_action_handlers, parameter[]]:
constant[
This function combines the given action handlers into a single function
which will call all of them.
]
for taget[name[handler]] in starred[name[handlers]] begin[:]
if <ast.UnaryOp object at 0x7da18f00f340> ... | keyword[def] identifier[combine_action_handlers] (* identifier[handlers] ):
literal[string]
keyword[for] identifier[handler] keyword[in] identifier[handlers] :
keyword[if] keyword[not] ( identifier[iscoroutinefunction] ( identifier[handler] ) keyword[or] identifier[iscoroutine] ( id... | def combine_action_handlers(*handlers):
"""
This function combines the given action handlers into a single function
which will call all of them.
"""
# make sure each of the given handlers is callable
for handler in handlers:
# if the handler is not a function
if not (isco... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.