code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _expected_condition_value_in_element_attribute(self, element_attribute_value):
"""Tries to find the element and checks that it contains the requested attribute with the expected value,
but does not thrown an exception if the element is not found
:param element_attribute_value: Tuple with... | def function[_expected_condition_value_in_element_attribute, parameter[self, element_attribute_value]]:
constant[Tries to find the element and checks that it contains the requested attribute with the expected value,
but does not thrown an exception if the element is not found
:param element_... | keyword[def] identifier[_expected_condition_value_in_element_attribute] ( identifier[self] , identifier[element_attribute_value] ):
literal[string]
identifier[element] , identifier[attribute] , identifier[value] = identifier[element_attribute_value]
identifier[web_element] = identifier[se... | def _expected_condition_value_in_element_attribute(self, element_attribute_value):
"""Tries to find the element and checks that it contains the requested attribute with the expected value,
but does not thrown an exception if the element is not found
:param element_attribute_value: Tuple with 3 i... |
def refresh_persistent_maps(self):
"""
Get information about persistent maps of the robots.
:return:
"""
for robot in self._robots:
resp2 = (requests.get(urljoin(
self.ENDPOINT,
'users/me/robots/{}/persistent_maps'.format(robot.serial)... | def function[refresh_persistent_maps, parameter[self]]:
constant[
Get information about persistent maps of the robots.
:return:
]
for taget[name[robot]] in starred[name[self]._robots] begin[:]
variable[resp2] assign[=] call[name[requests].get, parameter[call[name... | keyword[def] identifier[refresh_persistent_maps] ( identifier[self] ):
literal[string]
keyword[for] identifier[robot] keyword[in] identifier[self] . identifier[_robots] :
identifier[resp2] =( identifier[requests] . identifier[get] ( identifier[urljoin] (
identifier[self... | def refresh_persistent_maps(self):
"""
Get information about persistent maps of the robots.
:return:
"""
for robot in self._robots:
resp2 = requests.get(urljoin(self.ENDPOINT, 'users/me/robots/{}/persistent_maps'.format(robot.serial)), headers=self._headers)
resp2.raise_... |
def _validate_logical_id(cls, logical_id):
"""Validates that the provided logical id is an alphanumeric string.
:param str logical_id: the logical id to validate
:returns: True if the logical id is valid
:rtype: bool
:raises TypeError: if the logical id is invalid
"""
... | def function[_validate_logical_id, parameter[cls, logical_id]]:
constant[Validates that the provided logical id is an alphanumeric string.
:param str logical_id: the logical id to validate
:returns: True if the logical id is valid
:rtype: bool
:raises TypeError: if the logical i... | keyword[def] identifier[_validate_logical_id] ( identifier[cls] , identifier[logical_id] ):
literal[string]
identifier[pattern] = identifier[re] . identifier[compile] ( literal[string] )
keyword[if] identifier[logical_id] keyword[is] keyword[not] keyword[None] keyword[and] identifier... | def _validate_logical_id(cls, logical_id):
"""Validates that the provided logical id is an alphanumeric string.
:param str logical_id: the logical id to validate
:returns: True if the logical id is valid
:rtype: bool
:raises TypeError: if the logical id is invalid
"""
pa... |
def restore_edge(self, edge):
"""
Restores a previously hidden edge back into the graph.
"""
try:
head_id, tail_id, data = self.hidden_edges[edge]
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
self.edges[edge] = he... | def function[restore_edge, parameter[self, edge]]:
constant[
Restores a previously hidden edge back into the graph.
]
<ast.Try object at 0x7da1b0e271f0> | keyword[def] identifier[restore_edge] ( identifier[self] , identifier[edge] ):
literal[string]
keyword[try] :
identifier[head_id] , identifier[tail_id] , identifier[data] = identifier[self] . identifier[hidden_edges] [ identifier[edge] ]
identifier[self] . identifier[nodes... | def restore_edge(self, edge):
"""
Restores a previously hidden edge back into the graph.
"""
try:
(head_id, tail_id, data) = self.hidden_edges[edge]
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
self.edges[edge] = (head_id, tail_id, data)... |
def copy(self):
'''Generate a Primer copy.
:returns: A safely-editable copy of the current primer.
:rtype: coral.DNA
'''
return type(self)(self.anneal, self.tm, overhang=self.overhang,
name=self.name, note=self.note) | def function[copy, parameter[self]]:
constant[Generate a Primer copy.
:returns: A safely-editable copy of the current primer.
:rtype: coral.DNA
]
return[call[call[name[type], parameter[name[self]]], parameter[name[self].anneal, name[self].tm]]] | keyword[def] identifier[copy] ( identifier[self] ):
literal[string]
keyword[return] identifier[type] ( identifier[self] )( identifier[self] . identifier[anneal] , identifier[self] . identifier[tm] , identifier[overhang] = identifier[self] . identifier[overhang] ,
identifier[name] = identi... | def copy(self):
"""Generate a Primer copy.
:returns: A safely-editable copy of the current primer.
:rtype: coral.DNA
"""
return type(self)(self.anneal, self.tm, overhang=self.overhang, name=self.name, note=self.note) |
def on_tblFunctions1_itemSelectionChanged(self):
"""Choose selected hazard x exposure combination.
.. note:: This is an automatic Qt slot
executed when the category selection changes.
"""
# Clear the selection on the 2nd matrix
self.parent.step_fc_functions2.tblFuncti... | def function[on_tblFunctions1_itemSelectionChanged, parameter[self]]:
constant[Choose selected hazard x exposure combination.
.. note:: This is an automatic Qt slot
executed when the category selection changes.
]
call[name[self].parent.step_fc_functions2.tblFunctions2.clearCo... | keyword[def] identifier[on_tblFunctions1_itemSelectionChanged] ( identifier[self] ):
literal[string]
identifier[self] . identifier[parent] . identifier[step_fc_functions2] . identifier[tblFunctions2] . identifier[clearContents] ()
identifier[self] . identifier[parent] . identifier... | def on_tblFunctions1_itemSelectionChanged(self):
"""Choose selected hazard x exposure combination.
.. note:: This is an automatic Qt slot
executed when the category selection changes.
"""
# Clear the selection on the 2nd matrix
self.parent.step_fc_functions2.tblFunctions2.clearCo... |
def get_polling_override(self):
"""Get the current polling override value in milliseconds.
See :meth:`set_polling_override` for more information.
Returns:
None on error, otherwise the current override period in milliseconds
(0 = disabled).
"""
pollin... | def function[get_polling_override, parameter[self]]:
constant[Get the current polling override value in milliseconds.
See :meth:`set_polling_override` for more information.
Returns:
None on error, otherwise the current override period in milliseconds
(0 = disabled). ... | keyword[def] identifier[get_polling_override] ( identifier[self] ):
literal[string]
identifier[polling_override] = identifier[self] . identifier[get_characteristic_handle_from_uuid] ( identifier[UUID_POLLING_OVERRIDE] )
keyword[if] identifier[polling_override] keyword[is] keyword[None] ... | def get_polling_override(self):
"""Get the current polling override value in milliseconds.
See :meth:`set_polling_override` for more information.
Returns:
None on error, otherwise the current override period in milliseconds
(0 = disabled).
"""
polling_overri... |
def check_hash_key(query_on, key):
"""Only allows == against query_on.hash_key"""
return (
isinstance(key, BaseCondition) and
(key.operation == "==") and
(key.column is query_on.hash_key)
) | def function[check_hash_key, parameter[query_on, key]]:
constant[Only allows == against query_on.hash_key]
return[<ast.BoolOp object at 0x7da1b0f2e7d0>] | keyword[def] identifier[check_hash_key] ( identifier[query_on] , identifier[key] ):
literal[string]
keyword[return] (
identifier[isinstance] ( identifier[key] , identifier[BaseCondition] ) keyword[and]
( identifier[key] . identifier[operation] == literal[string] ) keyword[and]
( identifier[k... | def check_hash_key(query_on, key):
"""Only allows == against query_on.hash_key"""
return isinstance(key, BaseCondition) and key.operation == '==' and (key.column is query_on.hash_key) |
def lookup_init_systems(self):
"""Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed.
"""
if utils.IS_... | def function[lookup_init_systems, parameter[self]]:
constant[Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed.
... | keyword[def] identifier[lookup_init_systems] ( identifier[self] ):
literal[string]
keyword[if] identifier[utils] . identifier[IS_WIN] :
identifier[logger] . identifier[debug] (
literal[string] )
keyword[return] [ literal[string] ]
keyword[if] identi... | def lookup_init_systems(self):
"""Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed.
"""
if utils.IS_WIN:
... |
def to_glyphs(ufos_or_designspace, glyphs_module=classes, minimize_ufo_diffs=False):
"""
Take a list of UFOs or a single DesignspaceDocument with attached UFOs
and converts it into a GSFont object.
The GSFont object is in-memory, it's up to the user to write it to the disk
if needed.
This shou... | def function[to_glyphs, parameter[ufos_or_designspace, glyphs_module, minimize_ufo_diffs]]:
constant[
Take a list of UFOs or a single DesignspaceDocument with attached UFOs
and converts it into a GSFont object.
The GSFont object is in-memory, it's up to the user to write it to the disk
if neede... | keyword[def] identifier[to_glyphs] ( identifier[ufos_or_designspace] , identifier[glyphs_module] = identifier[classes] , identifier[minimize_ufo_diffs] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[ufos_or_designspace] , literal[string] ):
identifier[builder] = ... | def to_glyphs(ufos_or_designspace, glyphs_module=classes, minimize_ufo_diffs=False):
"""
Take a list of UFOs or a single DesignspaceDocument with attached UFOs
and converts it into a GSFont object.
The GSFont object is in-memory, it's up to the user to write it to the disk
if needed.
This shou... |
async def blob(self, elem=None, elem_type=None, params=None):
"""
Loads/dumps blob
:return:
"""
elem_type = elem_type if elem_type else elem.__class__
if hasattr(elem_type, 'blob_serialize'):
elem = elem_type() if elem is None else elem
return awai... | <ast.AsyncFunctionDef object at 0x7da1b2457910> | keyword[async] keyword[def] identifier[blob] ( identifier[self] , identifier[elem] = keyword[None] , identifier[elem_type] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
identifier[elem_type] = identifier[elem_type] keyword[if] identifier[elem_type] keyword[else] ident... | async def blob(self, elem=None, elem_type=None, params=None):
"""
Loads/dumps blob
:return:
"""
elem_type = elem_type if elem_type else elem.__class__
if hasattr(elem_type, 'blob_serialize'):
elem = elem_type() if elem is None else elem
return await elem.blob_serializ... |
def validate(self, model, checks=[]):
"""Use a defined schema to validate the medium table format."""
custom = [
check_partial(gene_id_check, frozenset(g.id for g in model.genes))
]
super(EssentialityExperiment, self).validate(
model=model, checks=checks + custom) | def function[validate, parameter[self, model, checks]]:
constant[Use a defined schema to validate the medium table format.]
variable[custom] assign[=] list[[<ast.Call object at 0x7da1b23448b0>]]
call[call[name[super], parameter[name[EssentialityExperiment], name[self]]].validate, parameter[]] | keyword[def] identifier[validate] ( identifier[self] , identifier[model] , identifier[checks] =[]):
literal[string]
identifier[custom] =[
identifier[check_partial] ( identifier[gene_id_check] , identifier[frozenset] ( identifier[g] . identifier[id] keyword[for] identifier[g] keyword[in]... | def validate(self, model, checks=[]):
"""Use a defined schema to validate the medium table format."""
custom = [check_partial(gene_id_check, frozenset((g.id for g in model.genes)))]
super(EssentialityExperiment, self).validate(model=model, checks=checks + custom) |
def restore_from_archive(self, parent=None):
"""Function to restore a DP from archived copy
Asks for confirmation along the way if parent is not None
(in which case it will be the parent widget for confirmation dialogs)
"""
from PyQt4.Qt import QMessageBox
exists = os.pat... | def function[restore_from_archive, parameter[self, parent]]:
constant[Function to restore a DP from archived copy
Asks for confirmation along the way if parent is not None
(in which case it will be the parent widget for confirmation dialogs)
]
from relative_module[PyQt4.Qt] import mo... | keyword[def] identifier[restore_from_archive] ( identifier[self] , identifier[parent] = keyword[None] ):
literal[string]
keyword[from] identifier[PyQt4] . identifier[Qt] keyword[import] identifier[QMessageBox]
identifier[exists] = identifier[os] . identifier[path] . identifier[exists] ... | def restore_from_archive(self, parent=None):
"""Function to restore a DP from archived copy
Asks for confirmation along the way if parent is not None
(in which case it will be the parent widget for confirmation dialogs)
"""
from PyQt4.Qt import QMessageBox
exists = os.path.exists(sel... |
def get_profile(name=None, **kwargs):
"""Get the profile by name; if no name is given, return the
default profile.
"""
if isinstance(name, Profile):
return name
clazz = get_profile_class(name or 'default')
return clazz(**kwargs) | def function[get_profile, parameter[name]]:
constant[Get the profile by name; if no name is given, return the
default profile.
]
if call[name[isinstance], parameter[name[name], name[Profile]]] begin[:]
return[name[name]]
variable[clazz] assign[=] call[name[get_profile_class], par... | keyword[def] identifier[get_profile] ( identifier[name] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[name] , identifier[Profile] ):
keyword[return] identifier[name]
identifier[clazz] = identifier[get_profile_class] ( identifier[... | def get_profile(name=None, **kwargs):
"""Get the profile by name; if no name is given, return the
default profile.
"""
if isinstance(name, Profile):
return name # depends on [control=['if'], data=[]]
clazz = get_profile_class(name or 'default')
return clazz(**kwargs) |
def get_fallback_resolution(self):
"""Returns the previous fallback resolution
set by :meth:`set_fallback_resolution`,
or default fallback resolution if never set.
:returns: ``(x_pixels_per_inch, y_pixels_per_inch)``
"""
ppi = ffi.new('double[2]')
cairo.cairo_su... | def function[get_fallback_resolution, parameter[self]]:
constant[Returns the previous fallback resolution
set by :meth:`set_fallback_resolution`,
or default fallback resolution if never set.
:returns: ``(x_pixels_per_inch, y_pixels_per_inch)``
]
variable[ppi] assign[=] ... | keyword[def] identifier[get_fallback_resolution] ( identifier[self] ):
literal[string]
identifier[ppi] = identifier[ffi] . identifier[new] ( literal[string] )
identifier[cairo] . identifier[cairo_surface_get_fallback_resolution] (
identifier[self] . identifier[_pointer] , identifi... | def get_fallback_resolution(self):
"""Returns the previous fallback resolution
set by :meth:`set_fallback_resolution`,
or default fallback resolution if never set.
:returns: ``(x_pixels_per_inch, y_pixels_per_inch)``
"""
ppi = ffi.new('double[2]')
cairo.cairo_surface_get_fa... |
def name(self, value):
"""
Setter for **self.__name** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("name", value)
self._... | def function[name, parameter[self, value]]:
constant[
Setter for **self.__name** attribute.
:param value: Attribute value.
:type value: unicode
]
if compare[name[value] is_not constant[None]] begin[:]
assert[compare[call[name[type], parameter[name[value]]] is nam... | keyword[def] identifier[name] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[assert] identifier[type] ( identifier[value] ) keyword[is] identifier[unicode] , literal[string] . identifier[fo... | def name(self, value):
"""
Setter for **self.__name** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format('name', value) # depends on [control=['if... |
def thub(data, n):
"""
Tee or "T" hub auto-copier to help working with Stream instances as well as
with numbers.
Parameters
----------
data :
Input to be copied. Can be anything.
n :
Number of copies.
Returns
-------
A StreamTeeHub instance, if input data is iterable.
The data itself, ot... | def function[thub, parameter[data, n]]:
constant[
Tee or "T" hub auto-copier to help working with Stream instances as well as
with numbers.
Parameters
----------
data :
Input to be copied. Can be anything.
n :
Number of copies.
Returns
-------
A StreamTeeHub instance, if input data i... | keyword[def] identifier[thub] ( identifier[data] , identifier[n] ):
literal[string]
keyword[return] identifier[StreamTeeHub] ( identifier[data] , identifier[n] ) keyword[if] identifier[isinstance] ( identifier[data] , identifier[Iterable] ) keyword[else] identifier[data] | def thub(data, n):
"""
Tee or "T" hub auto-copier to help working with Stream instances as well as
with numbers.
Parameters
----------
data :
Input to be copied. Can be anything.
n :
Number of copies.
Returns
-------
A StreamTeeHub instance, if input data is iterable.
The data itself, ... |
def lock_access(repository_path, callback):
""" Synchronise access to the user file between processes, this specifies
which user is allowed write access at the current time """
with open(cpjoin(repository_path, 'lock_file'), 'w') as fd:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB... | def function[lock_access, parameter[repository_path, callback]]:
constant[ Synchronise access to the user file between processes, this specifies
which user is allowed write access at the current time ]
with call[name[open], parameter[call[name[cpjoin], parameter[name[repository_path], constant[lock_... | keyword[def] identifier[lock_access] ( identifier[repository_path] , identifier[callback] ):
literal[string]
keyword[with] identifier[open] ( identifier[cpjoin] ( identifier[repository_path] , literal[string] ), literal[string] ) keyword[as] identifier[fd] :
keyword[try] :
identifi... | def lock_access(repository_path, callback):
""" Synchronise access to the user file between processes, this specifies
which user is allowed write access at the current time """
with open(cpjoin(repository_path, 'lock_file'), 'w') as fd:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)... |
def load_font(self, font_path, font_size):
"""Load the specified font from a file."""
self.__font_path = font_path
self.__font_size = font_size
if font_path != "":
self.__font = pygame.font.Font(font_path, font_size)
self.__set_text(self.__text) | def function[load_font, parameter[self, font_path, font_size]]:
constant[Load the specified font from a file.]
name[self].__font_path assign[=] name[font_path]
name[self].__font_size assign[=] name[font_size]
if compare[name[font_path] not_equal[!=] constant[]] begin[:]
n... | keyword[def] identifier[load_font] ( identifier[self] , identifier[font_path] , identifier[font_size] ):
literal[string]
identifier[self] . identifier[__font_path] = identifier[font_path]
identifier[self] . identifier[__font_size] = identifier[font_size]
keyword[if] identifier[... | def load_font(self, font_path, font_size):
"""Load the specified font from a file."""
self.__font_path = font_path
self.__font_size = font_size
if font_path != '':
self.__font = pygame.font.Font(font_path, font_size)
self.__set_text(self.__text) # depends on [control=['if'], data=['font... |
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_interface(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
... | def function[show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_interface, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[show_fabric_trunk_info] assign... | keyword[def] identifier[show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_interface] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[show_fab... | def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_src_interface(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
show_fabric_trunk_info = ET.Element('show_fabric_trunk_info')
config = show_fabric_trunk_info
output = ET.S... |
def _loadDeclarations(self):
"""
load declaratoins from _declr method
This function is called first for parent and then for children
"""
if not hasattr(self, "_interfaces"):
self._interfaces = []
self._setAttrListener = self._declrCollector
self._declr... | def function[_loadDeclarations, parameter[self]]:
constant[
load declaratoins from _declr method
This function is called first for parent and then for children
]
if <ast.UnaryOp object at 0x7da1b0381000> begin[:]
name[self]._interfaces assign[=] list[[]]
n... | keyword[def] identifier[_loadDeclarations] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[_interfaces] =[]
identifier[self] . identifier[_setAttrListener] = identifier[s... | def _loadDeclarations(self):
"""
load declaratoins from _declr method
This function is called first for parent and then for children
"""
if not hasattr(self, '_interfaces'):
self._interfaces = [] # depends on [control=['if'], data=[]]
self._setAttrListener = self._declrColle... |
def make_blastcmd_builder(
mode, outdir, format_exe=None, blast_exe=None, prefix="ANIBLAST"
):
"""Returns BLASTcmds object for construction of BLAST commands."""
if mode == "ANIb": # BLAST/formatting executable depends on mode
blastcmds = BLASTcmds(
BLASTfunctions(construct_makeblastdb_... | def function[make_blastcmd_builder, parameter[mode, outdir, format_exe, blast_exe, prefix]]:
constant[Returns BLASTcmds object for construction of BLAST commands.]
if compare[name[mode] equal[==] constant[ANIb]] begin[:]
variable[blastcmds] assign[=] call[name[BLASTcmds], parameter[call[... | keyword[def] identifier[make_blastcmd_builder] (
identifier[mode] , identifier[outdir] , identifier[format_exe] = keyword[None] , identifier[blast_exe] = keyword[None] , identifier[prefix] = literal[string]
):
literal[string]
keyword[if] identifier[mode] == literal[string] :
identifier[blastcmd... | def make_blastcmd_builder(mode, outdir, format_exe=None, blast_exe=None, prefix='ANIBLAST'):
"""Returns BLASTcmds object for construction of BLAST commands."""
if mode == 'ANIb': # BLAST/formatting executable depends on mode
blastcmds = BLASTcmds(BLASTfunctions(construct_makeblastdb_cmd, construct_blas... |
def context(self, async_context):
"""\
Opens the given asynchronous contest manager on the event loop.
For a context manager that would be called like this::
async with ctx as value:
body
This method allows a call like this::
with event_loop_thr... | def function[context, parameter[self, async_context]]:
constant[ Opens the given asynchronous contest manager on the event loop.
For a context manager that would be called like this::
async with ctx as value:
body
This method allows a call like this::
... | keyword[def] identifier[context] ( identifier[self] , identifier[async_context] ):
literal[string]
identifier[exit] = identifier[type] ( identifier[async_context] ). identifier[__aexit__]
identifier[value] = identifier[self] . identifier[run_coroutine] ( identifier[type] ( identifier[asy... | def context(self, async_context):
""" Opens the given asynchronous contest manager on the event loop.
For a context manager that would be called like this::
async with ctx as value:
body
This method allows a call like this::
with event_loop_thread.co... |
def create(cls, package, inputs=None, settings=None, resume_from=None,
name=None, secret_settings=None, api=None):
"""
Create and start a new run.
:param package: Automation package id
:param inputs: Input dictionary
:param settings: Settings override dictionary
... | def function[create, parameter[cls, package, inputs, settings, resume_from, name, secret_settings, api]]:
constant[
Create and start a new run.
:param package: Automation package id
:param inputs: Input dictionary
:param settings: Settings override dictionary
:param resum... | keyword[def] identifier[create] ( identifier[cls] , identifier[package] , identifier[inputs] = keyword[None] , identifier[settings] = keyword[None] , identifier[resume_from] = keyword[None] ,
identifier[name] = keyword[None] , identifier[secret_settings] = keyword[None] , identifier[api] = keyword[None] ):
... | def create(cls, package, inputs=None, settings=None, resume_from=None, name=None, secret_settings=None, api=None):
"""
Create and start a new run.
:param package: Automation package id
:param inputs: Input dictionary
:param settings: Settings override dictionary
:param resume... |
def assign_default_log_values(self, fpath, line, formatter):
'''
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> from pprint import pprint
>>> formatter = 'logagg.formatters.mongodb'
>>> fpath = '/var/log/mongodb/mongodb.log'
... | def function[assign_default_log_values, parameter[self, fpath, line, formatter]]:
constant[
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> from pprint import pprint
>>> formatter = 'logagg.formatters.mongodb'
>>> fpath = '/var/... | keyword[def] identifier[assign_default_log_values] ( identifier[self] , identifier[fpath] , identifier[line] , identifier[formatter] ):
literal[string]
keyword[return] identifier[dict] (
identifier[id] = keyword[None] ,
identifier[file] = identifier[fpath] ,
identifier[h... | def assign_default_log_values(self, fpath, line, formatter):
"""
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> from pprint import pprint
>>> formatter = 'logagg.formatters.mongodb'
>>> fpath = '/var/log/mongodb/mongodb.log'
... |
def get(self, sid):
"""
Constructs a ExecutionStepContext
:param sid: Step Sid.
:returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext
"""
return Executi... | def function[get, parameter[self, sid]]:
constant[
Constructs a ExecutionStepContext
:param sid: Step Sid.
:returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext
... | keyword[def] identifier[get] ( identifier[self] , identifier[sid] ):
literal[string]
keyword[return] identifier[ExecutionStepContext] (
identifier[self] . identifier[_version] ,
identifier[flow_sid] = identifier[self] . identifier[_solution] [ literal[string] ],
identifi... | def get(self, sid):
"""
Constructs a ExecutionStepContext
:param sid: Step Sid.
:returns: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepContext
"""
return ExecutionStepCo... |
def write_configs(self, project_root):
"""Wrapper method that writes all configuration files to the pipeline
directory
"""
# Write resources config
with open(join(project_root, "resources.config"), "w") as fh:
fh.write(self.resources)
# Write containers conf... | def function[write_configs, parameter[self, project_root]]:
constant[Wrapper method that writes all configuration files to the pipeline
directory
]
with call[name[open], parameter[call[name[join], parameter[name[project_root], constant[resources.config]]], constant[w]]] begin[:]
... | keyword[def] identifier[write_configs] ( identifier[self] , identifier[project_root] ):
literal[string]
keyword[with] identifier[open] ( identifier[join] ( identifier[project_root] , literal[string] ), literal[string] ) keyword[as] identifier[fh] :
identifier[fh] . identifi... | def write_configs(self, project_root):
"""Wrapper method that writes all configuration files to the pipeline
directory
"""
# Write resources config
with open(join(project_root, 'resources.config'), 'w') as fh:
fh.write(self.resources) # depends on [control=['with'], data=['fh']]
... |
def count_dict_values(dict_of_counters: Mapping[X, Sized]) -> typing.Counter[X]:
"""Count the number of elements in each value (can be list, Counter, etc).
:param dict_of_counters: A dictionary of things whose lengths can be measured (lists, Counters, dicts)
:return: A Counter with the same keys as the inp... | def function[count_dict_values, parameter[dict_of_counters]]:
constant[Count the number of elements in each value (can be list, Counter, etc).
:param dict_of_counters: A dictionary of things whose lengths can be measured (lists, Counters, dicts)
:return: A Counter with the same keys as the input but th... | keyword[def] identifier[count_dict_values] ( identifier[dict_of_counters] : identifier[Mapping] [ identifier[X] , identifier[Sized] ])-> identifier[typing] . identifier[Counter] [ identifier[X] ]:
literal[string]
keyword[return] identifier[Counter] ({
identifier[k] : identifier[len] ( identifier[v] )... | def count_dict_values(dict_of_counters: Mapping[X, Sized]) -> typing.Counter[X]:
"""Count the number of elements in each value (can be list, Counter, etc).
:param dict_of_counters: A dictionary of things whose lengths can be measured (lists, Counters, dicts)
:return: A Counter with the same keys as the inp... |
def _create_centerline(self):
"""
Calculate the centerline of a polygon.
Densifies the border of a polygon which is then represented by a Numpy
array of points necessary for creating the Voronoi diagram. Once the
diagram is created, the ridges located within the polygon are
... | def function[_create_centerline, parameter[self]]:
constant[
Calculate the centerline of a polygon.
Densifies the border of a polygon which is then represented by a Numpy
array of points necessary for creating the Voronoi diagram. Once the
diagram is created, the ridges located ... | keyword[def] identifier[_create_centerline] ( identifier[self] ):
literal[string]
identifier[border] = identifier[array] ( identifier[self] . identifier[__densify_border] ())
identifier[vor] = identifier[Voronoi] ( identifier[border] )
identifier[vertex] = identifier[vor] . ident... | def _create_centerline(self):
"""
Calculate the centerline of a polygon.
Densifies the border of a polygon which is then represented by a Numpy
array of points necessary for creating the Voronoi diagram. Once the
diagram is created, the ridges located within the polygon are
... |
def np2str(value):
"""Convert an `numpy.string_` to str.
Args:
value (ndarray): scalar or 1-element numpy array to convert
Raises:
ValueError: if value is array larger than 1-element or it is not of
type `numpy.string_` or it is not a numpy array
"""
if hasattr... | def function[np2str, parameter[value]]:
constant[Convert an `numpy.string_` to str.
Args:
value (ndarray): scalar or 1-element numpy array to convert
Raises:
ValueError: if value is array larger than 1-element or it is not of
type `numpy.string_` or it is not a nump... | keyword[def] identifier[np2str] ( identifier[value] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[value] , literal[string] ) keyword[and] identifier[issubclass] ( identifier[value] . identifier[dtype] . identifier[type] ,( identifier[np] . identifier[string_] , identifier[np] . identifi... | def np2str(value):
"""Convert an `numpy.string_` to str.
Args:
value (ndarray): scalar or 1-element numpy array to convert
Raises:
ValueError: if value is array larger than 1-element or it is not of
type `numpy.string_` or it is not a numpy array
"""
if hasattr... |
def is_rpc_error_exempt(self, error_text):
"""
Check whether an RPC error message is excempt, thus NOT causing an exception.
On some devices the RPC operations may indicate an error response, even though
the operation actually succeeded. This may be in cases where a warning would be
... | def function[is_rpc_error_exempt, parameter[self, error_text]]:
constant[
Check whether an RPC error message is excempt, thus NOT causing an exception.
On some devices the RPC operations may indicate an error response, even though
the operation actually succeeded. This may be in cases w... | keyword[def] identifier[is_rpc_error_exempt] ( identifier[self] , identifier[error_text] ):
literal[string]
keyword[if] identifier[error_text] keyword[is] keyword[not] keyword[None] :
identifier[error_text] = identifier[error_text] . identifier[lower] (). identifier[strip] ()
... | def is_rpc_error_exempt(self, error_text):
"""
Check whether an RPC error message is excempt, thus NOT causing an exception.
On some devices the RPC operations may indicate an error response, even though
the operation actually succeeded. This may be in cases where a warning would be
... |
def set_gene_name(self,name):
"""assign a gene name
:param name: name
:type name: string
"""
self._options = self._options._replace(gene_name = name) | def function[set_gene_name, parameter[self, name]]:
constant[assign a gene name
:param name: name
:type name: string
]
name[self]._options assign[=] call[name[self]._options._replace, parameter[]] | keyword[def] identifier[set_gene_name] ( identifier[self] , identifier[name] ):
literal[string]
identifier[self] . identifier[_options] = identifier[self] . identifier[_options] . identifier[_replace] ( identifier[gene_name] = identifier[name] ) | def set_gene_name(self, name):
"""assign a gene name
:param name: name
:type name: string
"""
self._options = self._options._replace(gene_name=name) |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Raster Map File Read from File Method
"""
# Assign file extension attribute to file object
self.fileExtension = extension
self.filename = filename
... | def function[_read, parameter[self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile]]:
constant[
Raster Map File Read from File Method
]
name[self].fileExtension assign[=] name[extension]
name[self].filename assign[=] name[filena... | keyword[def] identifier[_read] ( identifier[self] , identifier[directory] , identifier[filename] , identifier[session] , identifier[path] , identifier[name] , identifier[extension] , identifier[spatial] , identifier[spatialReferenceID] , identifier[replaceParamFile] ):
literal[string]
iden... | def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Raster Map File Read from File Method
"""
# Assign file extension attribute to file object
self.fileExtension = extension
self.filename = filename
self._load_raste... |
def parse_param(param, include_desc=False):
"""Parse a single typed parameter statement."""
param_def, _colon, desc = param.partition(':')
if not include_desc:
desc = None
else:
desc = desc.lstrip()
if _colon == "":
raise ValidationError("Invalid parameter declaration in do... | def function[parse_param, parameter[param, include_desc]]:
constant[Parse a single typed parameter statement.]
<ast.Tuple object at 0x7da1b026e2f0> assign[=] call[name[param].partition, parameter[constant[:]]]
if <ast.UnaryOp object at 0x7da1b026c820> begin[:]
variable[desc] assi... | keyword[def] identifier[parse_param] ( identifier[param] , identifier[include_desc] = keyword[False] ):
literal[string]
identifier[param_def] , identifier[_colon] , identifier[desc] = identifier[param] . identifier[partition] ( literal[string] )
keyword[if] keyword[not] identifier[include_desc] :
... | def parse_param(param, include_desc=False):
"""Parse a single typed parameter statement."""
(param_def, _colon, desc) = param.partition(':')
if not include_desc:
desc = None # depends on [control=['if'], data=[]]
else:
desc = desc.lstrip()
if _colon == '':
raise ValidationEr... |
def Sh(L: float, h: float, D: float) -> float:
"""
Calculate the Sherwood number.
:param L: [m] mass transfer surface characteristic length.
:param h: [m/s] mass transfer coefficient.
:param D: [m2/s] fluid mass diffusivity.
:returns: float
"""
return h * L / D | def function[Sh, parameter[L, h, D]]:
constant[
Calculate the Sherwood number.
:param L: [m] mass transfer surface characteristic length.
:param h: [m/s] mass transfer coefficient.
:param D: [m2/s] fluid mass diffusivity.
:returns: float
]
return[binary_operation[binary_operation[n... | keyword[def] identifier[Sh] ( identifier[L] : identifier[float] , identifier[h] : identifier[float] , identifier[D] : identifier[float] )-> identifier[float] :
literal[string]
keyword[return] identifier[h] * identifier[L] / identifier[D] | def Sh(L: float, h: float, D: float) -> float:
"""
Calculate the Sherwood number.
:param L: [m] mass transfer surface characteristic length.
:param h: [m/s] mass transfer coefficient.
:param D: [m2/s] fluid mass diffusivity.
:returns: float
"""
return h * L / D |
def user_get(self, domain, userid):
"""
Retrieve a user from the server
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID.
:raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist.
:return: :class:`~.HttpResult`.... | def function[user_get, parameter[self, domain, userid]]:
constant[
Retrieve a user from the server
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID.
:raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist.
:ret... | keyword[def] identifier[user_get] ( identifier[self] , identifier[domain] , identifier[userid] ):
literal[string]
identifier[path] = identifier[self] . identifier[_get_management_path] ( identifier[domain] , identifier[userid] )
keyword[return] identifier[self] . identifier[http_request] ... | def user_get(self, domain, userid):
"""
Retrieve a user from the server
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID.
:raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist.
:return: :class:`~.HttpResult`. The... |
def get_gradebooks(self):
"""Pass through to provider GradebookLookupSession.get_gradebooks"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('gradebook_lookup_session').get_gradebooks()
cat_list ... | def function[get_gradebooks, parameter[self]]:
constant[Pass through to provider GradebookLookupSession.get_gradebooks]
variable[catalogs] assign[=] call[call[name[self]._get_provider_session, parameter[constant[gradebook_lookup_session]]].get_gradebooks, parameter[]]
variable[cat_list] assign[=... | keyword[def] identifier[get_gradebooks] ( identifier[self] ):
literal[string]
identifier[catalogs] = identifier[self] . identifier[_get_provider_session] ( literal[string] ). identifier[get_gradebooks] ()
identifier[cat_list] =[]
keyword[for] identifier[cat] ke... | def get_gradebooks(self):
"""Pass through to provider GradebookLookupSession.get_gradebooks"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bins_template
catalogs = self._get_provider_session('gradebook_lookup_session').get_gradebooks()
cat_list = []
for cat in ... |
def assignIPAddresses(self, prefix=None):
'''
Assign IP addresses to all interfaces on hosts and routers in the
network.
NB: this method assumes that all interfaces are assigned
addresses on the same subnet. If you don't want that behavior,
the setInterfaceAdd... | def function[assignIPAddresses, parameter[self, prefix]]:
constant[
Assign IP addresses to all interfaces on hosts and routers in the
network.
NB: this method assumes that all interfaces are assigned
addresses on the same subnet. If you don't want that behavior,
... | keyword[def] identifier[assignIPAddresses] ( identifier[self] , identifier[prefix] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[prefix] :
identifier[subnet] = identifier[ipaddress] . identifier[IPv4Network] ( literal[string] )
keyword[else] :
... | def assignIPAddresses(self, prefix=None):
"""
Assign IP addresses to all interfaces on hosts and routers in the
network.
NB: this method assumes that all interfaces are assigned
addresses on the same subnet. If you don't want that behavior,
the setInterfaceAddress... |
def from_ini(cls, folder, ini_file='fpp.ini', ichrone='mist', recalc=False,
refit_trap=False, **kwargs):
"""
To enable simple usage, initializes a FPPCalculation from a .ini file
By default, a file called ``fpp.ini`` will be looked for in the
current folder. Also presen... | def function[from_ini, parameter[cls, folder, ini_file, ichrone, recalc, refit_trap]]:
constant[
To enable simple usage, initializes a FPPCalculation from a .ini file
By default, a file called ``fpp.ini`` will be looked for in the
current folder. Also present must be a ``star.ini`` fil... | keyword[def] identifier[from_ini] ( identifier[cls] , identifier[folder] , identifier[ini_file] = literal[string] , identifier[ichrone] = literal[string] , identifier[recalc] = keyword[False] ,
identifier[refit_trap] = keyword[False] ,** identifier[kwargs] ):
literal[string]
ide... | def from_ini(cls, folder, ini_file='fpp.ini', ichrone='mist', recalc=False, refit_trap=False, **kwargs):
"""
To enable simple usage, initializes a FPPCalculation from a .ini file
By default, a file called ``fpp.ini`` will be looked for in the
current folder. Also present must be a ``star.i... |
def worker_activated(name, workers=None, profile='default'):
'''
Activate all the workers in the modjk load balancer
Example:
.. code-block:: yaml
loadbalancer:
modjk.worker_activated:
- workers:
- app1
- app2
'''
if workers is None:
... | def function[worker_activated, parameter[name, workers, profile]]:
constant[
Activate all the workers in the modjk load balancer
Example:
.. code-block:: yaml
loadbalancer:
modjk.worker_activated:
- workers:
- app1
- app2
]
if ... | keyword[def] identifier[worker_activated] ( identifier[name] , identifier[workers] = keyword[None] , identifier[profile] = literal[string] ):
literal[string]
keyword[if] identifier[workers] keyword[is] keyword[None] :
identifier[workers] =[]
keyword[return] identifier[_bulk_state] (
... | def worker_activated(name, workers=None, profile='default'):
"""
Activate all the workers in the modjk load balancer
Example:
.. code-block:: yaml
loadbalancer:
modjk.worker_activated:
- workers:
- app1
- app2
"""
if workers is None:
... |
def transform_non_affine(self, s):
"""
Apply transformation to a Nx1 numpy array.
Parameters
----------
s : array
Data to be transformed in display scale units.
Return
------
array or masked array
Transformed data, in data value u... | def function[transform_non_affine, parameter[self, s]]:
constant[
Apply transformation to a Nx1 numpy array.
Parameters
----------
s : array
Data to be transformed in display scale units.
Return
------
array or masked array
Transf... | keyword[def] identifier[transform_non_affine] ( identifier[self] , identifier[s] ):
literal[string]
identifier[T] = identifier[self] . identifier[_T]
identifier[M] = identifier[self] . identifier[_M]
identifier[W] = identifier[self] . identifier[_W]
identifier[p] = ide... | def transform_non_affine(self, s):
"""
Apply transformation to a Nx1 numpy array.
Parameters
----------
s : array
Data to be transformed in display scale units.
Return
------
array or masked array
Transformed data, in data value units... |
def check_input(self, token):
"""
Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token
"""
if token is None:
raise Exception(self.full_name + ": No token provided!")
if isinstance(... | def function[check_input, parameter[self, token]]:
constant[
Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token
]
if compare[name[token] is constant[None]] begin[:]
<ast.Raise object at 0x7d... | keyword[def] identifier[check_input] ( identifier[self] , identifier[token] ):
literal[string]
keyword[if] identifier[token] keyword[is] keyword[None] :
keyword[raise] identifier[Exception] ( identifier[self] . identifier[full_name] + literal[string] )
keyword[if] identif... | def check_input(self, token):
"""
Performs checks on the input token. Raises an exception if unsupported.
:param token: the token to check
:type token: Token
"""
if token is None:
raise Exception(self.full_name + ': No token provided!') # depends on [control=['if'], dat... |
def filter_human_only(stmts_in, **kwargs):
"""Filter out statements that are grounded, but not to a human gene.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
save : Optional[str]
The name of a pickle file to save the results (stmts... | def function[filter_human_only, parameter[stmts_in]]:
constant[Filter out statements that are grounded, but not to a human gene.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
save : Optional[str]
The name of a pickle file to sa... | keyword[def] identifier[filter_human_only] ( identifier[stmts_in] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[indra] . identifier[databases] keyword[import] identifier[uniprot_client]
keyword[if] literal[string] keyword[in] identifier[kwargs] keyword[and] identifier[kwa... | def filter_human_only(stmts_in, **kwargs):
"""Filter out statements that are grounded, but not to a human gene.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
save : Optional[str]
The name of a pickle file to save the results (stmts... |
def _drop_membership_multicast_socket(self):
"""
Drop membership to multicast
:rtype: None
"""
# Leave group
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_DROP_MEMBERSHIP,
self._membership_request
)
se... | def function[_drop_membership_multicast_socket, parameter[self]]:
constant[
Drop membership to multicast
:rtype: None
]
call[name[self]._multicast_socket.setsockopt, parameter[name[socket].IPPROTO_IP, name[socket].IP_DROP_MEMBERSHIP, name[self]._membership_request]]
name... | keyword[def] identifier[_drop_membership_multicast_socket] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_multicast_socket] . identifier[setsockopt] (
identifier[socket] . identifier[IPPROTO_IP] ,
identifier[socket] . identifier[IP_DROP_MEMBERSHIP] ,... | def _drop_membership_multicast_socket(self):
"""
Drop membership to multicast
:rtype: None
"""
# Leave group
self._multicast_socket.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, self._membership_request)
self._membership_request = None |
def _sync_to_disk(self):
"""Write any changes made on Refpkg to disk.
Other methods of Refpkg that alter the contents of the package
will call this method themselves. Generally you should never
have to call it by hand. The only exception would be if
another program has changed... | def function[_sync_to_disk, parameter[self]]:
constant[Write any changes made on Refpkg to disk.
Other methods of Refpkg that alter the contents of the package
will call this method themselves. Generally you should never
have to call it by hand. The only exception would be if
... | keyword[def] identifier[_sync_to_disk] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[open_manifest] ( literal[string] ) keyword[as] identifier[h] :
identifier[json] . identifier[dump] ( identifier[self] . identifier[contents] , identifier[h] , iden... | def _sync_to_disk(self):
"""Write any changes made on Refpkg to disk.
Other methods of Refpkg that alter the contents of the package
will call this method themselves. Generally you should never
have to call it by hand. The only exception would be if
another program has changed the... |
def getKwConfig(self, kw):
""" return the configuration of kw, dict
USAGE: rdict = getKwConfig(kw)
"""
confd = self.getKwAsDict(kw).values()[0].values()[0]
return {k.lower(): v for k, v in confd.items()} | def function[getKwConfig, parameter[self, kw]]:
constant[ return the configuration of kw, dict
USAGE: rdict = getKwConfig(kw)
]
variable[confd] assign[=] call[call[call[call[call[name[self].getKwAsDict, parameter[name[kw]]].values, parameter[]]][constant[0]].values, parameter[]]][consta... | keyword[def] identifier[getKwConfig] ( identifier[self] , identifier[kw] ):
literal[string]
identifier[confd] = identifier[self] . identifier[getKwAsDict] ( identifier[kw] ). identifier[values] ()[ literal[int] ]. identifier[values] ()[ literal[int] ]
keyword[return] { identifier[k] . iden... | def getKwConfig(self, kw):
""" return the configuration of kw, dict
USAGE: rdict = getKwConfig(kw)
"""
confd = self.getKwAsDict(kw).values()[0].values()[0]
return {k.lower(): v for (k, v) in confd.items()} |
def namedb_get_record_states_at(cur, history_id, block_number):
"""
Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
However, if the record changed a... | def function[namedb_get_record_states_at, parameter[cur, history_id, block_number]]:
constant[
Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
H... | keyword[def] identifier[namedb_get_record_states_at] ( identifier[cur] , identifier[history_id] , identifier[block_number] ):
literal[string]
identifier[query] = literal[string]
identifier[args] =( identifier[history_id] , identifier[block_number] )
identifier[history_rows] = identifier[namedb_q... | def namedb_get_record_states_at(cur, history_id, block_number):
"""
Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
However, if the record changed a... |
def setup_data_stream(
self,
connection_factory: Callable[[tuple], Connection],
data_stream_factory: Callable[[Connection], DataStream]=DataStream) -> \
DataStream:
'''Create and setup a data stream.
This function will set up passive and binary mode and h... | def function[setup_data_stream, parameter[self, connection_factory, data_stream_factory]]:
constant[Create and setup a data stream.
This function will set up passive and binary mode and handle
connecting to the data connection.
Args:
connection_factory: A coroutine callback... | keyword[def] identifier[setup_data_stream] (
identifier[self] ,
identifier[connection_factory] : identifier[Callable] [[ identifier[tuple] ], identifier[Connection] ],
identifier[data_stream_factory] : identifier[Callable] [[ identifier[Connection] ], identifier[DataStream] ]= identifier[DataStream] )-> identifier... | def setup_data_stream(self, connection_factory: Callable[[tuple], Connection], data_stream_factory: Callable[[Connection], DataStream]=DataStream) -> DataStream:
"""Create and setup a data stream.
This function will set up passive and binary mode and handle
connecting to the data connection.
... |
def open_tablebase_native(directory: PathLike, *, libgtb: Any = None, LibraryLoader: Any = ctypes.cdll) -> NativeTablebase:
"""
Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downg... | def function[open_tablebase_native, parameter[directory]]:
constant[
Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade to pure Python
tablebase probing.
:raises... | keyword[def] identifier[open_tablebase_native] ( identifier[directory] : identifier[PathLike] ,*, identifier[libgtb] : identifier[Any] = keyword[None] , identifier[LibraryLoader] : identifier[Any] = identifier[ctypes] . identifier[cdll] )-> identifier[NativeTablebase] :
literal[string]
identifier[libgtb] =... | def open_tablebase_native(directory: PathLike, *, libgtb: Any=None, LibraryLoader: Any=ctypes.cdll) -> NativeTablebase:
"""
Opens a collection of tables for probing using libgtb.
In most cases :func:`~chess.gaviota.open_tablebase()` should be used.
Use this function only if you do not want to downgrade... |
def _get_order_by(order, orderby, order_by_fields):
"""
Return the order by syntax for a model.
Checks whether use ascending or descending order, and maps the fieldnames.
"""
try:
# Find the actual database fieldnames for the keyword.
db_fieldnames = order_by_fields[orderby]
exce... | def function[_get_order_by, parameter[order, orderby, order_by_fields]]:
constant[
Return the order by syntax for a model.
Checks whether use ascending or descending order, and maps the fieldnames.
]
<ast.Try object at 0x7da18c4cdae0>
variable[is_desc] assign[=] <ast.BoolOp object at 0x7... | keyword[def] identifier[_get_order_by] ( identifier[order] , identifier[orderby] , identifier[order_by_fields] ):
literal[string]
keyword[try] :
identifier[db_fieldnames] = identifier[order_by_fields] [ identifier[orderby] ]
keyword[except] identifier[KeyError] :
keyword[raise]... | def _get_order_by(order, orderby, order_by_fields):
"""
Return the order by syntax for a model.
Checks whether use ascending or descending order, and maps the fieldnames.
"""
try:
# Find the actual database fieldnames for the keyword.
db_fieldnames = order_by_fields[orderby] # depen... |
def parse_roadmap_gwas(fn):
"""
Read Roadmap GWAS file and filter for unique, significant (p < 1e-5)
SNPs.
Parameters
----------
fn : str
Path to (subset of) GRASP database.
Returns
-------
df : pandas.DataFrame
Pandas dataframe with de-duplicated, significa... | def function[parse_roadmap_gwas, parameter[fn]]:
constant[
Read Roadmap GWAS file and filter for unique, significant (p < 1e-5)
SNPs.
Parameters
----------
fn : str
Path to (subset of) GRASP database.
Returns
-------
df : pandas.DataFrame
Pandas datafram... | keyword[def] identifier[parse_roadmap_gwas] ( identifier[fn] ):
literal[string]
identifier[df] = identifier[pd] . identifier[read_table] ( identifier[fn] , identifier[low_memory] = keyword[False] ,
identifier[names] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[str... | def parse_roadmap_gwas(fn):
"""
Read Roadmap GWAS file and filter for unique, significant (p < 1e-5)
SNPs.
Parameters
----------
fn : str
Path to (subset of) GRASP database.
Returns
-------
df : pandas.DataFrame
Pandas dataframe with de-duplicated, significa... |
def get_tokens_list(self, registry_address: PaymentNetworkID):
"""Returns a list of tokens the node knows about"""
tokens_list = views.get_token_identifiers(
chain_state=views.state_from_raiden(self.raiden),
payment_network_id=registry_address,
)
return tokens_lis... | def function[get_tokens_list, parameter[self, registry_address]]:
constant[Returns a list of tokens the node knows about]
variable[tokens_list] assign[=] call[name[views].get_token_identifiers, parameter[]]
return[name[tokens_list]] | keyword[def] identifier[get_tokens_list] ( identifier[self] , identifier[registry_address] : identifier[PaymentNetworkID] ):
literal[string]
identifier[tokens_list] = identifier[views] . identifier[get_token_identifiers] (
identifier[chain_state] = identifier[views] . identifier[state_from... | def get_tokens_list(self, registry_address: PaymentNetworkID):
"""Returns a list of tokens the node knows about"""
tokens_list = views.get_token_identifiers(chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address)
return tokens_list |
def get_dir(self, scope, class_):
"""
Return the callable function from appdirs, but with the
result wrapped in self.path_class
"""
prop_name = '{scope}_{class_}_dir'.format(**locals())
value = getattr(self.wrapper, prop_name)
MultiPath = Multi.for_class(self.path... | def function[get_dir, parameter[self, scope, class_]]:
constant[
Return the callable function from appdirs, but with the
result wrapped in self.path_class
]
variable[prop_name] assign[=] call[constant[{scope}_{class_}_dir].format, parameter[]]
variable[value] assign[=] ca... | keyword[def] identifier[get_dir] ( identifier[self] , identifier[scope] , identifier[class_] ):
literal[string]
identifier[prop_name] = literal[string] . identifier[format] (** identifier[locals] ())
identifier[value] = identifier[getattr] ( identifier[self] . identifier[wrapper] , identif... | def get_dir(self, scope, class_):
"""
Return the callable function from appdirs, but with the
result wrapped in self.path_class
"""
prop_name = '{scope}_{class_}_dir'.format(**locals())
value = getattr(self.wrapper, prop_name)
MultiPath = Multi.for_class(self.path_class)
retu... |
def runDia(diagram):
"""Generate the diagrams using Dia."""
ifname = '{}.dia'.format(diagram)
ofname = '{}.png'.format(diagram)
cmd = 'dia -t png-libart -e {} {}'.format(ofname, ifname)
print(' {}'.format(cmd))
subprocess.call(cmd, shell=True)
return True | def function[runDia, parameter[diagram]]:
constant[Generate the diagrams using Dia.]
variable[ifname] assign[=] call[constant[{}.dia].format, parameter[name[diagram]]]
variable[ofname] assign[=] call[constant[{}.png].format, parameter[name[diagram]]]
variable[cmd] assign[=] call[constant... | keyword[def] identifier[runDia] ( identifier[diagram] ):
literal[string]
identifier[ifname] = literal[string] . identifier[format] ( identifier[diagram] )
identifier[ofname] = literal[string] . identifier[format] ( identifier[diagram] )
identifier[cmd] = literal[string] . identifier[format] ( ide... | def runDia(diagram):
"""Generate the diagrams using Dia."""
ifname = '{}.dia'.format(diagram)
ofname = '{}.png'.format(diagram)
cmd = 'dia -t png-libart -e {} {}'.format(ofname, ifname)
print(' {}'.format(cmd))
subprocess.call(cmd, shell=True)
return True |
def asdict(self, name, _type=None, _set=False):
"""
Turn this 'a:2,b:blabla,c:True,a:'d' to
{a:[2, 'd'], b:'blabla', c:True}
"""
if _type is None:
_type = lambda t: t
dict_str = self.pop(name, None)
if not dict_str:
return {}
_d... | def function[asdict, parameter[self, name, _type, _set]]:
constant[
Turn this 'a:2,b:blabla,c:True,a:'d' to
{a:[2, 'd'], b:'blabla', c:True}
]
if compare[name[_type] is constant[None]] begin[:]
variable[_type] assign[=] <ast.Lambda object at 0x7da18f58f430>
... | keyword[def] identifier[asdict] ( identifier[self] , identifier[name] , identifier[_type] = keyword[None] , identifier[_set] = keyword[False] ):
literal[string]
keyword[if] identifier[_type] keyword[is] keyword[None] :
identifier[_type] = keyword[lambda] identifier[t] : identifier... | def asdict(self, name, _type=None, _set=False):
"""
Turn this 'a:2,b:blabla,c:True,a:'d' to
{a:[2, 'd'], b:'blabla', c:True}
"""
if _type is None:
_type = lambda t: t # depends on [control=['if'], data=['_type']]
dict_str = self.pop(name, None)
if not dict_str:
... |
def nr_genes(self):
"""Return the number of genes"""
if self['genes']:
nr_genes = len(self['genes'])
else:
nr_genes = len(self['gene_symbols'])
return nr_genes | def function[nr_genes, parameter[self]]:
constant[Return the number of genes]
if call[name[self]][constant[genes]] begin[:]
variable[nr_genes] assign[=] call[name[len], parameter[call[name[self]][constant[genes]]]]
return[name[nr_genes]] | keyword[def] identifier[nr_genes] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] [ literal[string] ]:
identifier[nr_genes] = identifier[len] ( identifier[self] [ literal[string] ])
keyword[else] :
identifier[nr_genes] = identifier[len] ( ident... | def nr_genes(self):
"""Return the number of genes"""
if self['genes']:
nr_genes = len(self['genes']) # depends on [control=['if'], data=[]]
else:
nr_genes = len(self['gene_symbols'])
return nr_genes |
def assert_valid_name(name: str) -> str:
"""Uphold the spec rules about naming."""
error = is_valid_name_error(name)
if error:
raise error
return name | def function[assert_valid_name, parameter[name]]:
constant[Uphold the spec rules about naming.]
variable[error] assign[=] call[name[is_valid_name_error], parameter[name[name]]]
if name[error] begin[:]
<ast.Raise object at 0x7da1b1de0250>
return[name[name]] | keyword[def] identifier[assert_valid_name] ( identifier[name] : identifier[str] )-> identifier[str] :
literal[string]
identifier[error] = identifier[is_valid_name_error] ( identifier[name] )
keyword[if] identifier[error] :
keyword[raise] identifier[error]
keyword[return] identifier[n... | def assert_valid_name(name: str) -> str:
"""Uphold the spec rules about naming."""
error = is_valid_name_error(name)
if error:
raise error # depends on [control=['if'], data=[]]
return name |
def ScanForStorageMediaImage(self, source_path_spec):
"""Scans the path specification for a supported storage media image format.
Args:
source_path_spec (PathSpec): source path specification.
Returns:
PathSpec: storage media image path specification or None if no supported
storage me... | def function[ScanForStorageMediaImage, parameter[self, source_path_spec]]:
constant[Scans the path specification for a supported storage media image format.
Args:
source_path_spec (PathSpec): source path specification.
Returns:
PathSpec: storage media image path specification or None if no... | keyword[def] identifier[ScanForStorageMediaImage] ( identifier[self] , identifier[source_path_spec] ):
literal[string]
keyword[try] :
identifier[type_indicators] = identifier[analyzer] . identifier[Analyzer] . identifier[GetStorageMediaImageTypeIndicators] (
identifier[source_path_spec] , ide... | def ScanForStorageMediaImage(self, source_path_spec):
"""Scans the path specification for a supported storage media image format.
Args:
source_path_spec (PathSpec): source path specification.
Returns:
PathSpec: storage media image path specification or None if no supported
storage me... |
def sdb_get_or_set_hash(uri,
opts,
length=8,
chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)',
utils=None):
'''
Check if value exists in sdb. If it does, return, otherwise generate a
random string and ... | def function[sdb_get_or_set_hash, parameter[uri, opts, length, chars, utils]]:
constant[
Check if value exists in sdb. If it does, return, otherwise generate a
random string and store it. This can be used for storing secrets in a
centralized place.
]
if <ast.BoolOp object at 0x7da20e9b... | keyword[def] identifier[sdb_get_or_set_hash] ( identifier[uri] ,
identifier[opts] ,
identifier[length] = literal[int] ,
identifier[chars] = literal[string] ,
identifier[utils] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[uri] , identifier[string_type... | def sdb_get_or_set_hash(uri, opts, length=8, chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)', utils=None):
"""
Check if value exists in sdb. If it does, return, otherwise generate a
random string and store it. This can be used for storing secrets in a
centralized place.
"""
if not i... |
def groupby_transform(iterable, keyfunc=None, valuefunc=None):
"""An extension of :func:`itertools.groupby` that transforms the values of
*iterable* after grouping them.
*keyfunc* is a function used to compute a grouping key for each item.
*valuefunc* is a function for transforming the items after group... | def function[groupby_transform, parameter[iterable, keyfunc, valuefunc]]:
constant[An extension of :func:`itertools.groupby` that transforms the values of
*iterable* after grouping them.
*keyfunc* is a function used to compute a grouping key for each item.
*valuefunc* is a function for transforming ... | keyword[def] identifier[groupby_transform] ( identifier[iterable] , identifier[keyfunc] = keyword[None] , identifier[valuefunc] = keyword[None] ):
literal[string]
identifier[valuefunc] =( keyword[lambda] identifier[x] : identifier[x] ) keyword[if] identifier[valuefunc] keyword[is] keyword[None] keywor... | def groupby_transform(iterable, keyfunc=None, valuefunc=None):
"""An extension of :func:`itertools.groupby` that transforms the values of
*iterable* after grouping them.
*keyfunc* is a function used to compute a grouping key for each item.
*valuefunc* is a function for transforming the items after group... |
def new_tmp(self):
""" Create a new temp file allocation """
self.tmp_idx += 1
return p.join(self.tmp_dir, 'tmp_' + str(self.tmp_idx)) | def function[new_tmp, parameter[self]]:
constant[ Create a new temp file allocation ]
<ast.AugAssign object at 0x7da18f58f5b0>
return[call[name[p].join, parameter[name[self].tmp_dir, binary_operation[constant[tmp_] + call[name[str], parameter[name[self].tmp_idx]]]]]] | keyword[def] identifier[new_tmp] ( identifier[self] ):
literal[string]
identifier[self] . identifier[tmp_idx] += literal[int]
keyword[return] identifier[p] . identifier[join] ( identifier[self] . identifier[tmp_dir] , literal[string] + identifier[str] ( identifier[self] . identifier[tmp... | def new_tmp(self):
""" Create a new temp file allocation """
self.tmp_idx += 1
return p.join(self.tmp_dir, 'tmp_' + str(self.tmp_idx)) |
def open(self, value, nt=None, wrap=None, unwrap=None):
"""Mark the PV as opened an provide its initial value.
This initial value is later updated with post().
:param value: A Value, or appropriate object (see nt= and wrap= of the constructor).
Any clients which have begun connecting ... | def function[open, parameter[self, value, nt, wrap, unwrap]]:
constant[Mark the PV as opened an provide its initial value.
This initial value is later updated with post().
:param value: A Value, or appropriate object (see nt= and wrap= of the constructor).
Any clients which have begun... | keyword[def] identifier[open] ( identifier[self] , identifier[value] , identifier[nt] = keyword[None] , identifier[wrap] = keyword[None] , identifier[unwrap] = keyword[None] ):
literal[string]
identifier[self] . identifier[_wrap] = identifier[wrap] keyword[or] ( identifier[nt] keyword[and] iden... | def open(self, value, nt=None, wrap=None, unwrap=None):
"""Mark the PV as opened an provide its initial value.
This initial value is later updated with post().
:param value: A Value, or appropriate object (see nt= and wrap= of the constructor).
Any clients which have begun connecting whic... |
def _set_axis(self, axis, labels, fastpath=False):
"""
Override generic, we want to set the _typ here.
"""
if not fastpath:
labels = ensure_index(labels)
is_all_dates = labels.is_all_dates
if is_all_dates:
if not isinstance(labels,
... | def function[_set_axis, parameter[self, axis, labels, fastpath]]:
constant[
Override generic, we want to set the _typ here.
]
if <ast.UnaryOp object at 0x7da18ede6b00> begin[:]
variable[labels] assign[=] call[name[ensure_index], parameter[name[labels]]]
variable[i... | keyword[def] identifier[_set_axis] ( identifier[self] , identifier[axis] , identifier[labels] , identifier[fastpath] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[fastpath] :
identifier[labels] = identifier[ensure_index] ( identifier[labels] )
ide... | def _set_axis(self, axis, labels, fastpath=False):
"""
Override generic, we want to set the _typ here.
"""
if not fastpath:
labels = ensure_index(labels) # depends on [control=['if'], data=[]]
is_all_dates = labels.is_all_dates
if is_all_dates:
if not isinstance(labels, ... |
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
... | def function[_matplotlib_circuit_drawer, parameter[circuit, scale, filename, style, plot_barriers, reverse_bits, justify]]:
constant[Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.f... | keyword[def] identifier[_matplotlib_circuit_drawer] ( identifier[circuit] ,
identifier[scale] = literal[int] ,
identifier[filename] = keyword[None] ,
identifier[style] = keyword[None] ,
identifier[plot_barriers] = keyword[True] ,
identifier[reverse_bits] = keyword[False] ,
identifier[justify] = keyword[None] ):... | def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.fi... |
def get_var(self, name):
"""
Retrieve a variable assigned to this user
:param name: The name of the variable to retrieve
:type name: str
:rtype: str
:raises VarNotDefinedError: The requested variable has not been defined
"""
if name not in self._vars:
... | def function[get_var, parameter[self, name]]:
constant[
Retrieve a variable assigned to this user
:param name: The name of the variable to retrieve
:type name: str
:rtype: str
:raises VarNotDefinedError: The requested variable has not been defined
]
if ... | keyword[def] identifier[get_var] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_vars] :
keyword[raise] identifier[VarNotDefinedError]
keyword[return] identifier[self] . ident... | def get_var(self, name):
"""
Retrieve a variable assigned to this user
:param name: The name of the variable to retrieve
:type name: str
:rtype: str
:raises VarNotDefinedError: The requested variable has not been defined
"""
if name not in self._vars:
r... |
def run_mnist_DistilledSGLD(num_training=50000, gpu_id=None):
"""Run DistilledSGLD on mnist dataset"""
X, Y, X_test, Y_test = load_mnist(num_training)
minibatch_size = 100
if num_training >= 10000:
num_hidden = 800
total_iter_num = 1000000
teacher_learning_rate = 1E-6
stu... | def function[run_mnist_DistilledSGLD, parameter[num_training, gpu_id]]:
constant[Run DistilledSGLD on mnist dataset]
<ast.Tuple object at 0x7da1b200bdc0> assign[=] call[name[load_mnist], parameter[name[num_training]]]
variable[minibatch_size] assign[=] constant[100]
if compare[name[num_t... | keyword[def] identifier[run_mnist_DistilledSGLD] ( identifier[num_training] = literal[int] , identifier[gpu_id] = keyword[None] ):
literal[string]
identifier[X] , identifier[Y] , identifier[X_test] , identifier[Y_test] = identifier[load_mnist] ( identifier[num_training] )
identifier[minibatch_size] = ... | def run_mnist_DistilledSGLD(num_training=50000, gpu_id=None):
"""Run DistilledSGLD on mnist dataset"""
(X, Y, X_test, Y_test) = load_mnist(num_training)
minibatch_size = 100
if num_training >= 10000:
num_hidden = 800
total_iter_num = 1000000
teacher_learning_rate = 1e-06
... |
async def govt(self, root):
"""Nation's government expenditure, as percentages.
Returns
-------
an :class:`ApiQuery` of :class:`collections.OrderedDict` with \
keys of str and values of float
Keys being, in order: ``Administration``, ``Defense``,
``Educat... | <ast.AsyncFunctionDef object at 0x7da1b2776a10> | keyword[async] keyword[def] identifier[govt] ( identifier[self] , identifier[root] ):
literal[string]
identifier[elem] = identifier[root] . identifier[find] ( literal[string] )
identifier[result] = identifier[OrderedDict] ()
identifier[result] [ literal[string] ]= identifier[flo... | async def govt(self, root):
"""Nation's government expenditure, as percentages.
Returns
-------
an :class:`ApiQuery` of :class:`collections.OrderedDict` with keys of str and values of float
Keys being, in order: ``Administration``, ``Defense``,
``Education``,... |
def email(self, subject, text_body, html_body=None, sender=None, **kwargs):
# type: (str, str, Optional[str], Optional[str], Any) -> None
"""Emails a user.
Args:
subject (str): Email subject
text_body (str): Plain text email body
html_body (str): HTML email b... | def function[email, parameter[self, subject, text_body, html_body, sender]]:
constant[Emails a user.
Args:
subject (str): Email subject
text_body (str): Plain text email body
html_body (str): HTML email body
sender (Optional[str]): Email sender. Defaults ... | keyword[def] identifier[email] ( identifier[self] , identifier[subject] , identifier[text_body] , identifier[html_body] = keyword[None] , identifier[sender] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[configuration] . identifier[emailer] (). identifier[s... | def email(self, subject, text_body, html_body=None, sender=None, **kwargs):
# type: (str, str, Optional[str], Optional[str], Any) -> None
'Emails a user.\n\n Args:\n subject (str): Email subject\n text_body (str): Plain text email body\n html_body (str): HTML email body\n... |
def unbroadcast(a, b):
'''
unbroadcast(a, b) yields a tuple (aa, bb) that is equivalent to (a, b) except that aa and bb
have been reshaped such that arithmetic numpy operations such as aa * bb will result in
row-wise operation instead of column-wise broadcasting.
'''
# they could be sparse:
... | def function[unbroadcast, parameter[a, b]]:
constant[
unbroadcast(a, b) yields a tuple (aa, bb) that is equivalent to (a, b) except that aa and bb
have been reshaped such that arithmetic numpy operations such as aa * bb will result in
row-wise operation instead of column-wise broadcasting.
]... | keyword[def] identifier[unbroadcast] ( identifier[a] , identifier[b] ):
literal[string]
identifier[spa] = identifier[sps] . identifier[issparse] ( identifier[a] )
identifier[spb] = identifier[sps] . identifier[issparse] ( identifier[b] )
keyword[if] identifier[spa] keyword[and] identifier... | def unbroadcast(a, b):
"""
unbroadcast(a, b) yields a tuple (aa, bb) that is equivalent to (a, b) except that aa and bb
have been reshaped such that arithmetic numpy operations such as aa * bb will result in
row-wise operation instead of column-wise broadcasting.
"""
# they could be sparse:
... |
def cached_node_creator(self, target_to_vts):
"""Strategy restores dependency graph node from the build cache.
"""
def creator(target):
vt = target_to_vts[target]
if vt.valid and os.path.exists(self.nodes_json(vt.results_dir)):
try:
with open(self.nodes_json(vt.results_dir), 'r... | def function[cached_node_creator, parameter[self, target_to_vts]]:
constant[Strategy restores dependency graph node from the build cache.
]
def function[creator, parameter[target]]:
variable[vt] assign[=] call[name[target_to_vts]][name[target]]
if <ast.BoolOp object a... | keyword[def] identifier[cached_node_creator] ( identifier[self] , identifier[target_to_vts] ):
literal[string]
keyword[def] identifier[creator] ( identifier[target] ):
identifier[vt] = identifier[target_to_vts] [ identifier[target] ]
keyword[if] identifier[vt] . identifier[valid] keyword[a... | def cached_node_creator(self, target_to_vts):
"""Strategy restores dependency graph node from the build cache.
"""
def creator(target):
vt = target_to_vts[target]
if vt.valid and os.path.exists(self.nodes_json(vt.results_dir)):
try:
with open(self.nodes_json(vt.r... |
def download_pisa_multimers_xml(pdb_ids, save_single_xml_files=True, outdir=None, force_rerun=False):
"""Download the PISA XML file for multimers.
See: http://www.ebi.ac.uk/pdbe/pisa/pi_download.html for more info
XML description of macromolecular assemblies:
http://www.ebi.ac.uk/pdbe/pisa/cgi-bin... | def function[download_pisa_multimers_xml, parameter[pdb_ids, save_single_xml_files, outdir, force_rerun]]:
constant[Download the PISA XML file for multimers.
See: http://www.ebi.ac.uk/pdbe/pisa/pi_download.html for more info
XML description of macromolecular assemblies:
http://www.ebi.ac.uk/pd... | keyword[def] identifier[download_pisa_multimers_xml] ( identifier[pdb_ids] , identifier[save_single_xml_files] = keyword[True] , identifier[outdir] = keyword[None] , identifier[force_rerun] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[outdir] :
identifier[outdir] = ide... | def download_pisa_multimers_xml(pdb_ids, save_single_xml_files=True, outdir=None, force_rerun=False):
"""Download the PISA XML file for multimers.
See: http://www.ebi.ac.uk/pdbe/pisa/pi_download.html for more info
XML description of macromolecular assemblies:
http://www.ebi.ac.uk/pdbe/pisa/cgi-bin... |
def _parse_seq_header(line):
"""Unique ID, head/tail lengths and taxonomy info from a sequence header.
The description is the part of the FASTA/CMA sequence header starting after
the first space (i.e. excluding ID), to the end of the line.
This function looks inside the first '{...}' pair to extract i... | def function[_parse_seq_header, parameter[line]]:
constant[Unique ID, head/tail lengths and taxonomy info from a sequence header.
The description is the part of the FASTA/CMA sequence header starting after
the first space (i.e. excluding ID), to the end of the line.
This function looks inside the ... | keyword[def] identifier[_parse_seq_header] ( identifier[line] ):
literal[string]
identifier[_parts] = identifier[line] [ literal[int] :]. identifier[split] ( keyword[None] , literal[int] )
identifier[rec_id] = identifier[_parts] [ literal[int] ]
identifier[descr] = identifier[_parts] [ ... | def _parse_seq_header(line):
"""Unique ID, head/tail lengths and taxonomy info from a sequence header.
The description is the part of the FASTA/CMA sequence header starting after
the first space (i.e. excluding ID), to the end of the line.
This function looks inside the first '{...}' pair to extract i... |
def jr6_jr6(mag_file, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
specnum=1, samp_con='1', location='unknown', lat='', lon='',
noave=False, meth_code="L... | def function[jr6_jr6, parameter[mag_file, dir_path, input_dir_path, meas_file, spec_file, samp_file, site_file, loc_file, specnum, samp_con, location, lat, lon, noave, meth_code, volume, JR, user]]:
constant[
Convert JR6 .jr6 files to MagIC file(s)
Parameters
----------
mag_file : str
i... | keyword[def] identifier[jr6_jr6] ( identifier[mag_file] , identifier[dir_path] = literal[string] , identifier[input_dir_path] = literal[string] ,
identifier[meas_file] = literal[string] , identifier[spec_file] = literal[string] ,
identifier[samp_file] = literal[string] , identifier[site_file] = literal[string] , id... | def jr6_jr6(mag_file, dir_path='.', input_dir_path='', meas_file='measurements.txt', spec_file='specimens.txt', samp_file='samples.txt', site_file='sites.txt', loc_file='locations.txt', specnum=1, samp_con='1', location='unknown', lat='', lon='', noave=False, meth_code='LP-NO', volume=12, JR=False, user=''):
"""
... |
def get_user_events(self, id, **data):
"""
GET /users/:id/events/
Returns a :ref:`paginated <pagination>` response of :format:`events <event>`, under the key ``events``, of all events the user has access to
"""
return self.get("/users/{0}/events/".format(id), data=data) | def function[get_user_events, parameter[self, id]]:
constant[
GET /users/:id/events/
Returns a :ref:`paginated <pagination>` response of :format:`events <event>`, under the key ``events``, of all events the user has access to
]
return[call[name[self].get, parameter[call[constant[/use... | keyword[def] identifier[get_user_events] ( identifier[self] , identifier[id] ,** identifier[data] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( literal[string] . identifier[format] ( identifier[id] ), identifier[data] = identifier[data] ) | def get_user_events(self, id, **data):
"""
GET /users/:id/events/
Returns a :ref:`paginated <pagination>` response of :format:`events <event>`, under the key ``events``, of all events the user has access to
"""
return self.get('/users/{0}/events/'.format(id), data=data) |
def reindex(self, new_index=None, index_conf=None):
'''Rebuilt the current index
This function could be useful in the case you want to change some index settings/mappings
and you don't want to loose all the entries belonging to that index.
This function is built in such a way ... | def function[reindex, parameter[self, new_index, index_conf]]:
constant[Rebuilt the current index
This function could be useful in the case you want to change some index settings/mappings
and you don't want to loose all the entries belonging to that index.
This function is bui... | keyword[def] identifier[reindex] ( identifier[self] , identifier[new_index] = keyword[None] , identifier[index_conf] = keyword[None] ):
literal[string]
identifier[alias] = identifier[self] . identifier[index_name] keyword[if] identifier[self] . identifier[es] . identifier[indices] . identifier[e... | def reindex(self, new_index=None, index_conf=None):
"""Rebuilt the current index
This function could be useful in the case you want to change some index settings/mappings
and you don't want to loose all the entries belonging to that index.
This function is built in such a way that... |
def floor_nearest(x, dx=1):
"""
floor a number to within a given rounding accuracy
"""
precision = get_sig_digits(dx)
return round(math.floor(float(x) / dx) * dx, precision) | def function[floor_nearest, parameter[x, dx]]:
constant[
floor a number to within a given rounding accuracy
]
variable[precision] assign[=] call[name[get_sig_digits], parameter[name[dx]]]
return[call[name[round], parameter[binary_operation[call[name[math].floor, parameter[binary_operation[ca... | keyword[def] identifier[floor_nearest] ( identifier[x] , identifier[dx] = literal[int] ):
literal[string]
identifier[precision] = identifier[get_sig_digits] ( identifier[dx] )
keyword[return] identifier[round] ( identifier[math] . identifier[floor] ( identifier[float] ( identifier[x] )/ identifier[dx... | def floor_nearest(x, dx=1):
"""
floor a number to within a given rounding accuracy
"""
precision = get_sig_digits(dx)
return round(math.floor(float(x) / dx) * dx, precision) |
def request_write(self, request: TBWriteRequest)->None:
"Queues up an asynchronous write request to Tensorboard."
if self.stop_request.isSet(): return
self.queue.put(request) | def function[request_write, parameter[self, request]]:
constant[Queues up an asynchronous write request to Tensorboard.]
if call[name[self].stop_request.isSet, parameter[]] begin[:]
return[None]
call[name[self].queue.put, parameter[name[request]]] | keyword[def] identifier[request_write] ( identifier[self] , identifier[request] : identifier[TBWriteRequest] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[stop_request] . identifier[isSet] (): keyword[return]
identifier[self] . identifier[queue] . identifi... | def request_write(self, request: TBWriteRequest) -> None:
"""Queues up an asynchronous write request to Tensorboard."""
if self.stop_request.isSet():
return # depends on [control=['if'], data=[]]
self.queue.put(request) |
def __base_state(self, containers):
'''
Convert blockade ID and container information into
a state dictionary object.
'''
return dict(blockade_id=self._blockade_id,
containers=containers,
version=self._state_version) | def function[__base_state, parameter[self, containers]]:
constant[
Convert blockade ID and container information into
a state dictionary object.
]
return[call[name[dict], parameter[]]] | keyword[def] identifier[__base_state] ( identifier[self] , identifier[containers] ):
literal[string]
keyword[return] identifier[dict] ( identifier[blockade_id] = identifier[self] . identifier[_blockade_id] ,
identifier[containers] = identifier[containers] ,
identifier[version] = ... | def __base_state(self, containers):
"""
Convert blockade ID and container information into
a state dictionary object.
"""
return dict(blockade_id=self._blockade_id, containers=containers, version=self._state_version) |
def step(self, actions, step_mul=None):
"""Apply actions, step the world forward, and return observations.
Args:
actions: A list of actions meeting the action spec, one per agent.
step_mul: If specified, use this rather than the environment's default.
Returns:
A tuple of TimeStep namedtu... | def function[step, parameter[self, actions, step_mul]]:
constant[Apply actions, step the world forward, and return observations.
Args:
actions: A list of actions meeting the action spec, one per agent.
step_mul: If specified, use this rather than the environment's default.
Returns:
A... | keyword[def] identifier[step] ( identifier[self] , identifier[actions] , identifier[step_mul] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_state] == identifier[environment] . identifier[StepType] . identifier[LAST] :
keyword[return] identifier[self] . identifier[re... | def step(self, actions, step_mul=None):
"""Apply actions, step the world forward, and return observations.
Args:
actions: A list of actions meeting the action spec, one per agent.
step_mul: If specified, use this rather than the environment's default.
Returns:
A tuple of TimeStep namedtu... |
def _create_plugin(self, config):
"""
Creates a plugin from its config.
Params:
config: plugin configuration as read by ait.config
Returns:
plugin: a Plugin
Raises:
ValueError: if any of the required config values are missing
... | def function[_create_plugin, parameter[self, config]]:
constant[
Creates a plugin from its config.
Params:
config: plugin configuration as read by ait.config
Returns:
plugin: a Plugin
Raises:
ValueError: if any of the required co... | keyword[def] identifier[_create_plugin] ( identifier[self] , identifier[config] ):
literal[string]
keyword[if] identifier[config] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[name] = identifier[config] . identifier[pop] ... | def _create_plugin(self, config):
"""
Creates a plugin from its config.
Params:
config: plugin configuration as read by ait.config
Returns:
plugin: a Plugin
Raises:
ValueError: if any of the required config values are missing
... |
def set_tunnel(self, host, port):
''' Sets up the host and the port for the HTTP CONNECT Tunnelling.'''
url = host
if port:
url = url + u':' + port
var_host = VARIANT.create_bstr_from_str(url)
var_empty = VARIANT.create_empty()
_WinHttpRequest._SetProxy(
... | def function[set_tunnel, parameter[self, host, port]]:
constant[ Sets up the host and the port for the HTTP CONNECT Tunnelling.]
variable[url] assign[=] name[host]
if name[port] begin[:]
variable[url] assign[=] binary_operation[binary_operation[name[url] + constant[:]] + name[por... | keyword[def] identifier[set_tunnel] ( identifier[self] , identifier[host] , identifier[port] ):
literal[string]
identifier[url] = identifier[host]
keyword[if] identifier[port] :
identifier[url] = identifier[url] + literal[string] + identifier[port]
identifier[var_... | def set_tunnel(self, host, port):
""" Sets up the host and the port for the HTTP CONNECT Tunnelling."""
url = host
if port:
url = url + u':' + port # depends on [control=['if'], data=[]]
var_host = VARIANT.create_bstr_from_str(url)
var_empty = VARIANT.create_empty()
_WinHttpRequest._Set... |
def get_src_address_from_data(self, decoded=True):
"""
Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message
Return None otherwise
:param decoded:
:return:
"""
src_address_label = next((lbl for lbl in self.message_type... | def function[get_src_address_from_data, parameter[self, decoded]]:
constant[
Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message
Return None otherwise
:param decoded:
:return:
]
variable[src_address_label] assign[=] ... | keyword[def] identifier[get_src_address_from_data] ( identifier[self] , identifier[decoded] = keyword[True] ):
literal[string]
identifier[src_address_label] = identifier[next] (( identifier[lbl] keyword[for] identifier[lbl] keyword[in] identifier[self] . identifier[message_type] keyword[if] i... | def get_src_address_from_data(self, decoded=True):
"""
Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message
Return None otherwise
:param decoded:
:return:
"""
src_address_label = next((lbl for lbl in self.message_type if lbl.... |
def get_gene_substitution_language() -> ParserElement:
"""Build a gene substitution parser."""
parser_element = gsub_tag + nest(
dna_nucleotide(GSUB_REFERENCE),
ppc.integer(GSUB_POSITION),
dna_nucleotide(GSUB_VARIANT),
)
parser_element.setParseAction(_handle_gsub)
return pars... | def function[get_gene_substitution_language, parameter[]]:
constant[Build a gene substitution parser.]
variable[parser_element] assign[=] binary_operation[name[gsub_tag] + call[name[nest], parameter[call[name[dna_nucleotide], parameter[name[GSUB_REFERENCE]]], call[name[ppc].integer, parameter[name[GSUB_... | keyword[def] identifier[get_gene_substitution_language] ()-> identifier[ParserElement] :
literal[string]
identifier[parser_element] = identifier[gsub_tag] + identifier[nest] (
identifier[dna_nucleotide] ( identifier[GSUB_REFERENCE] ),
identifier[ppc] . identifier[integer] ( identifier[GSUB_POSITI... | def get_gene_substitution_language() -> ParserElement:
"""Build a gene substitution parser."""
parser_element = gsub_tag + nest(dna_nucleotide(GSUB_REFERENCE), ppc.integer(GSUB_POSITION), dna_nucleotide(GSUB_VARIANT))
parser_element.setParseAction(_handle_gsub)
return parser_element |
def std(self) -> Optional[float]: #, ddof=0):
"""Standard deviation of all values entered into histogram.
This number is precise, because we keep the necessary data
separate from bin contents.
Returns
-------
float
"""
# TODO: Add DOF
if self._s... | def function[std, parameter[self]]:
constant[Standard deviation of all values entered into histogram.
This number is precise, because we keep the necessary data
separate from bin contents.
Returns
-------
float
]
if name[self]._stats begin[:]
ret... | keyword[def] identifier[std] ( identifier[self] )-> identifier[Optional] [ identifier[float] ]:
literal[string]
keyword[if] identifier[self] . identifier[_stats] :
keyword[return] identifier[np] . identifier[sqrt] ( identifier[self] . identifier[variance] ())
keywor... | def std(self) -> Optional[float]: #, ddof=0):
'Standard deviation of all values entered into histogram.\n\n This number is precise, because we keep the necessary data\n separate from bin contents.\n\n Returns\n -------\n float\n '
# TODO: Add DOF
if self._stats:
... |
def load_exif(album):
"""Loads the exif data of all images in an album from cache"""
if not hasattr(album.gallery, "exifCache"):
_restore_cache(album.gallery)
cache = album.gallery.exifCache
for media in album.medias:
if media.type == "image":
key = os.path.join(media.path, ... | def function[load_exif, parameter[album]]:
constant[Loads the exif data of all images in an album from cache]
if <ast.UnaryOp object at 0x7da18f09e500> begin[:]
call[name[_restore_cache], parameter[name[album].gallery]]
variable[cache] assign[=] name[album].gallery.exifCache
... | keyword[def] identifier[load_exif] ( identifier[album] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[album] . identifier[gallery] , literal[string] ):
identifier[_restore_cache] ( identifier[album] . identifier[gallery] )
identifier[cache] = identifier[album] ... | def load_exif(album):
"""Loads the exif data of all images in an album from cache"""
if not hasattr(album.gallery, 'exifCache'):
_restore_cache(album.gallery) # depends on [control=['if'], data=[]]
cache = album.gallery.exifCache
for media in album.medias:
if media.type == 'image':
... |
def load_entry_point(self, group, name):
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group, name),))
return ep.load() | def function[load_entry_point, parameter[self, group, name]]:
constant[Return the `name` entry point of `group` or raise ImportError]
variable[ep] assign[=] call[name[self].get_entry_info, parameter[name[group], name[name]]]
if compare[name[ep] is constant[None]] begin[:]
<ast.Raise obje... | keyword[def] identifier[load_entry_point] ( identifier[self] , identifier[group] , identifier[name] ):
literal[string]
identifier[ep] = identifier[self] . identifier[get_entry_info] ( identifier[group] , identifier[name] )
keyword[if] identifier[ep] keyword[is] keyword[None] :
... | def load_entry_point(self, group, name):
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError('Entry point %r not found' % ((group, name),)) # depends on [control=['if'], data=[]]
return ep.load() |
def write(self, data):
"""
write data on the OUT endpoint associated to the HID interface
"""
report_size = self.packet_size
if self.ep_out:
report_size = self.ep_out.wMaxPacketSize
for _ in range(report_size - len(data)):
data.append(0)
... | def function[write, parameter[self, data]]:
constant[
write data on the OUT endpoint associated to the HID interface
]
variable[report_size] assign[=] name[self].packet_size
if name[self].ep_out begin[:]
variable[report_size] assign[=] name[self].ep_out.wMaxPacket... | keyword[def] identifier[write] ( identifier[self] , identifier[data] ):
literal[string]
identifier[report_size] = identifier[self] . identifier[packet_size]
keyword[if] identifier[self] . identifier[ep_out] :
identifier[report_size] = identifier[self] . identifier[ep_out] .... | def write(self, data):
"""
write data on the OUT endpoint associated to the HID interface
"""
report_size = self.packet_size
if self.ep_out:
report_size = self.ep_out.wMaxPacketSize # depends on [control=['if'], data=[]]
for _ in range(report_size - len(data)):
data.appe... |
def printImportedNames(self):
"""Produce a report of imported names."""
for module in self.listModules():
print("%s:" % module.modname)
print(" %s" % "\n ".join(imp.name for imp in module.imported_names)) | def function[printImportedNames, parameter[self]]:
constant[Produce a report of imported names.]
for taget[name[module]] in starred[call[name[self].listModules, parameter[]]] begin[:]
call[name[print], parameter[binary_operation[constant[%s:] <ast.Mod object at 0x7da2590d6920> name[modul... | keyword[def] identifier[printImportedNames] ( identifier[self] ):
literal[string]
keyword[for] identifier[module] keyword[in] identifier[self] . identifier[listModules] ():
identifier[print] ( literal[string] % identifier[module] . identifier[modname] )
identifier[print... | def printImportedNames(self):
"""Produce a report of imported names."""
for module in self.listModules():
print('%s:' % module.modname)
print(' %s' % '\n '.join((imp.name for imp in module.imported_names))) # depends on [control=['for'], data=['module']] |
def stats(self, symbol):
"""
curl https://api.bitfinex.com/v1/stats/btcusd
[
{"period":1,"volume":"7410.27250155"},
{"period":7,"volume":"52251.37118006"},
{"period":30,"volume":"464505.07753251"}
]
"""
data = self._get(self.url_for(PAT... | def function[stats, parameter[self, symbol]]:
constant[
curl https://api.bitfinex.com/v1/stats/btcusd
[
{"period":1,"volume":"7410.27250155"},
{"period":7,"volume":"52251.37118006"},
{"period":30,"volume":"464505.07753251"}
]
]
variable... | keyword[def] identifier[stats] ( identifier[self] , identifier[symbol] ):
literal[string]
identifier[data] = identifier[self] . identifier[_get] ( identifier[self] . identifier[url_for] ( identifier[PATH_STATS] ,( identifier[symbol] )))
keyword[for] identifier[period] keyword[in] ident... | def stats(self, symbol):
"""
curl https://api.bitfinex.com/v1/stats/btcusd
[
{"period":1,"volume":"7410.27250155"},
{"period":7,"volume":"52251.37118006"},
{"period":30,"volume":"464505.07753251"}
]
"""
data = self._get(self.url_for(PATH_STATS,... |
def pull_request(ctx, base_branch, open_pr, stop_timer):
"""Create a new pull request for this issue."""
lancet = ctx.obj
review_status = lancet.config.get("tracker", "review_status")
remote_name = lancet.config.get("repository", "remote_name")
if not base_branch:
base_branch = lancet.conf... | def function[pull_request, parameter[ctx, base_branch, open_pr, stop_timer]]:
constant[Create a new pull request for this issue.]
variable[lancet] assign[=] name[ctx].obj
variable[review_status] assign[=] call[name[lancet].config.get, parameter[constant[tracker], constant[review_status]]]
... | keyword[def] identifier[pull_request] ( identifier[ctx] , identifier[base_branch] , identifier[open_pr] , identifier[stop_timer] ):
literal[string]
identifier[lancet] = identifier[ctx] . identifier[obj]
identifier[review_status] = identifier[lancet] . identifier[config] . identifier[get] ( literal[s... | def pull_request(ctx, base_branch, open_pr, stop_timer):
"""Create a new pull request for this issue."""
lancet = ctx.obj
review_status = lancet.config.get('tracker', 'review_status')
remote_name = lancet.config.get('repository', 'remote_name')
if not base_branch:
base_branch = lancet.config... |
def to_dict(self):
"""
Return the stats as a dictionary.
"""
return {
'mean': self.mean,
'var': self.var,
'min': self.min,
'max': self.max,
'num': self.num
} | def function[to_dict, parameter[self]]:
constant[
Return the stats as a dictionary.
]
return[dictionary[[<ast.Constant object at 0x7da1b0ba72b0>, <ast.Constant object at 0x7da1b0ba6e30>, <ast.Constant object at 0x7da1b0c53520>, <ast.Constant object at 0x7da1b0c50520>, <ast.Constant object at... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
keyword[return] {
literal[string] : identifier[self] . identifier[mean] ,
literal[string] : identifier[self] . identifier[var] ,
literal[string] : identifier[self] . identifier[min] ,
literal[... | def to_dict(self):
"""
Return the stats as a dictionary.
"""
return {'mean': self.mean, 'var': self.var, 'min': self.min, 'max': self.max, 'num': self.num} |
def include(self, *fields, **kwargs):
"""
Return a new QuerySet instance that will include related objects.
If fields are specified, they must be non-hidden relationships.
If select_related(None) is called, clear the list.
"""
clone = self._clone()
# Preserve t... | def function[include, parameter[self]]:
constant[
Return a new QuerySet instance that will include related objects.
If fields are specified, they must be non-hidden relationships.
If select_related(None) is called, clear the list.
]
variable[clone] assign[=] call[name[s... | keyword[def] identifier[include] ( identifier[self] ,* identifier[fields] ,** identifier[kwargs] ):
literal[string]
identifier[clone] = identifier[self] . identifier[_clone] ()
keyword[if] identifier[self] . identifier[query] . identifier[filter_is_sti... | def include(self, *fields, **kwargs):
"""
Return a new QuerySet instance that will include related objects.
If fields are specified, they must be non-hidden relationships.
If select_related(None) is called, clear the list.
"""
clone = self._clone()
# Preserve the stickiness... |
def clean(self, initial_epoch):
""" Remove entries from database that would get overwritten """
self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}}) | def function[clean, parameter[self, initial_epoch]]:
constant[ Remove entries from database that would get overwritten ]
call[name[self].db.metrics.delete_many, parameter[dictionary[[<ast.Constant object at 0x7da1b15f09a0>, <ast.Constant object at 0x7da1b15f1ae0>], [<ast.Attribute object at 0x7da1b15f07... | keyword[def] identifier[clean] ( identifier[self] , identifier[initial_epoch] ):
literal[string]
identifier[self] . identifier[db] . identifier[metrics] . identifier[delete_many] ({ literal[string] : identifier[self] . identifier[model_config] . identifier[run_name] , literal[string] :{ literal[str... | def clean(self, initial_epoch):
""" Remove entries from database that would get overwritten """
self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}}) |
def parse_record( self, lines ):
"""
Parse a TRANSFAC record out of `lines` and return a motif.
"""
# Break lines up
temp_lines = []
for line in lines:
fields = line.rstrip( "\r\n" ).split( None, 1 )
if len( fields ) == 1:
fields.ap... | def function[parse_record, parameter[self, lines]]:
constant[
Parse a TRANSFAC record out of `lines` and return a motif.
]
variable[temp_lines] assign[=] list[[]]
for taget[name[line]] in starred[name[lines]] begin[:]
variable[fields] assign[=] call[call[name[line... | keyword[def] identifier[parse_record] ( identifier[self] , identifier[lines] ):
literal[string]
identifier[temp_lines] =[]
keyword[for] identifier[line] keyword[in] identifier[lines] :
identifier[fields] = identifier[line] . identifier[rstrip] ( literal[string] ). ... | def parse_record(self, lines):
"""
Parse a TRANSFAC record out of `lines` and return a motif.
"""
# Break lines up
temp_lines = []
for line in lines:
fields = line.rstrip('\r\n').split(None, 1)
if len(fields) == 1:
fields.append('') # depends on [control=['if... |
def colorful_print(raw):
'''print colorful text in terminal.'''
lines = raw.split('\n')
colorful = True
detail = False
for line in lines:
if line:
if colorful:
colorful = False
print(colored(line, 'white', 'on_green') + '\n')
conti... | def function[colorful_print, parameter[raw]]:
constant[print colorful text in terminal.]
variable[lines] assign[=] call[name[raw].split, parameter[constant[
]]]
variable[colorful] assign[=] constant[True]
variable[detail] assign[=] constant[False]
for taget[name[line]] in starred... | keyword[def] identifier[colorful_print] ( identifier[raw] ):
literal[string]
identifier[lines] = identifier[raw] . identifier[split] ( literal[string] )
identifier[colorful] = keyword[True]
identifier[detail] = keyword[False]
keyword[for] identifier[line] keyword[in] identifier[lines] ... | def colorful_print(raw):
"""print colorful text in terminal."""
lines = raw.split('\n')
colorful = True
detail = False
for line in lines:
if line:
if colorful:
colorful = False
print(colored(line, 'white', 'on_green') + '\n')
contin... |
def _create_invokeScript(self, network_file_path, commands,
files_map):
"""invokeScript: Configure zLinux os network
invokeScript is included in the network.doscript, it is used to put
the network configuration file to the directory where it belongs and
call... | def function[_create_invokeScript, parameter[self, network_file_path, commands, files_map]]:
constant[invokeScript: Configure zLinux os network
invokeScript is included in the network.doscript, it is used to put
the network configuration file to the directory where it belongs and
call z... | keyword[def] identifier[_create_invokeScript] ( identifier[self] , identifier[network_file_path] , identifier[commands] ,
identifier[files_map] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string]
% identifier[network_file_path] )
identifier[invokeScript] = li... | def _create_invokeScript(self, network_file_path, commands, files_map):
"""invokeScript: Configure zLinux os network
invokeScript is included in the network.doscript, it is used to put
the network configuration file to the directory where it belongs and
call znetconfig to configure the netw... |
def make_optimize_action(self, model, session=None, var_list=None, **kwargs):
"""
Build Optimization action task with Tensorflow optimizer.
:param model: GPflow model.
:param session: Tensorflow session.
:param var_list: List of Tensorflow variables to train.
... | def function[make_optimize_action, parameter[self, model, session, var_list]]:
constant[
Build Optimization action task with Tensorflow optimizer.
:param model: GPflow model.
:param session: Tensorflow session.
:param var_list: List of Tensorflow variables to train.
... | keyword[def] identifier[make_optimize_action] ( identifier[self] , identifier[model] , identifier[session] = keyword[None] , identifier[var_list] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[model] keyword[is] keyword[None] keyword[or] keyword[not] identifi... | def make_optimize_action(self, model, session=None, var_list=None, **kwargs):
"""
Build Optimization action task with Tensorflow optimizer.
:param model: GPflow model.
:param session: Tensorflow session.
:param var_list: List of Tensorflow variables to train.
... |
def metasay(ctx, inputfile, item):
"""Moo some dataset metadata to stdout.
Python module: rio-metasay
(https://github.com/sgillies/rio-plugin-example).
"""
with rasterio.open(inputfile) as src:
meta = src.profile
click.echo(moothedata(meta, key=item)) | def function[metasay, parameter[ctx, inputfile, item]]:
constant[Moo some dataset metadata to stdout.
Python module: rio-metasay
(https://github.com/sgillies/rio-plugin-example).
]
with call[name[rasterio].open, parameter[name[inputfile]]] begin[:]
variable[meta] assign[=] n... | keyword[def] identifier[metasay] ( identifier[ctx] , identifier[inputfile] , identifier[item] ):
literal[string]
keyword[with] identifier[rasterio] . identifier[open] ( identifier[inputfile] ) keyword[as] identifier[src] :
identifier[meta] = identifier[src] . identifier[profile]
identifier... | def metasay(ctx, inputfile, item):
"""Moo some dataset metadata to stdout.
Python module: rio-metasay
(https://github.com/sgillies/rio-plugin-example).
"""
with rasterio.open(inputfile) as src:
meta = src.profile # depends on [control=['with'], data=['src']]
click.echo(moothedata(meta,... |
def get_default_reference(self, method):
"""
Returns the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
:return: reference
:rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str`
"""
if method no... | def function[get_default_reference, parameter[self, method]]:
constant[
Returns the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
:return: reference
:rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str`
... | keyword[def] identifier[get_default_reference] ( identifier[self] , identifier[method] ):
literal[string]
keyword[if] identifier[method] keyword[not] keyword[in] identifier[self] . identifier[_available_methods] :
keyword[raise] identifier[ValueError] ( literal[string] . identifie... | def get_default_reference(self, method):
"""
Returns the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
:return: reference
:rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str`
"""
if method not in sel... |
def root (path, root):
""" If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged.
"""
if os.path.isabs (path):
return path
else:
return os.path.join (root, path) | def function[root, parameter[path, root]]:
constant[ If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged.
]
if call[name[os].path.isabs, parameter[name[path]]] begin[:]
return[name[path]] | keyword[def] identifier[root] ( identifier[path] , identifier[root] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[isabs] ( identifier[path] ):
keyword[return] identifier[path]
keyword[else] :
keyword[return] identifier[os] . identifier[path] . iden... | def root(path, root):
""" If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged.
"""
if os.path.isabs(path):
return path # depends on [control=['if'], data=[]]
else:
return os.path.join(root, path) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.