code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def basis_function_ders_one(degree, knot_vector, span, knot, order):
""" Computes the derivative of one basis functions for a single parameter.
Implementation of Algorithm A2.5 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot_vector... | def function[basis_function_ders_one, parameter[degree, knot_vector, span, knot, order]]:
constant[ Computes the derivative of one basis functions for a single parameter.
Implementation of Algorithm A2.5 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree: int
... | keyword[def] identifier[basis_function_ders_one] ( identifier[degree] , identifier[knot_vector] , identifier[span] , identifier[knot] , identifier[order] ):
literal[string]
identifier[ders] =[ literal[int] keyword[for] identifier[_] keyword[in] identifier[range] ( literal[int] , identifier[order] + lit... | def basis_function_ders_one(degree, knot_vector, span, knot, order):
""" Computes the derivative of one basis functions for a single parameter.
Implementation of Algorithm A2.5 from The NURBS Book by Piegl & Tiller.
:param degree: degree, :math:`p`
:type degree: int
:param knot_vector: knot_vector... |
def delall(self, key):
"""Delete all tags of a given kind; see getall."""
if key in self:
del(self[key])
else:
key = key + ":"
for k in self.keys():
if k.startswith(key):
del(self[k]) | def function[delall, parameter[self, key]]:
constant[Delete all tags of a given kind; see getall.]
if compare[name[key] in name[self]] begin[:]
<ast.Delete object at 0x7da1b26af0d0> | keyword[def] identifier[delall] ( identifier[self] , identifier[key] ):
literal[string]
keyword[if] identifier[key] keyword[in] identifier[self] :
keyword[del] ( identifier[self] [ identifier[key] ])
keyword[else] :
identifier[key] = identifier[key] + literal[s... | def delall(self, key):
"""Delete all tags of a given kind; see getall."""
if key in self:
del self[key] # depends on [control=['if'], data=['key', 'self']]
else:
key = key + ':'
for k in self.keys():
if k.startswith(key):
del self[k] # depends on [contro... |
def _find_stars(data, kernel, threshold_eff, min_separation=None,
mask=None, exclude_border=False):
"""
Find stars in an image.
Parameters
----------
data : 2D array_like
The 2D array of the image.
kernel : `_StarFinderKernel`
The convolution kernel.
thresh... | def function[_find_stars, parameter[data, kernel, threshold_eff, min_separation, mask, exclude_border]]:
constant[
Find stars in an image.
Parameters
----------
data : 2D array_like
The 2D array of the image.
kernel : `_StarFinderKernel`
The convolution kernel.
thresho... | keyword[def] identifier[_find_stars] ( identifier[data] , identifier[kernel] , identifier[threshold_eff] , identifier[min_separation] = keyword[None] ,
identifier[mask] = keyword[None] , identifier[exclude_border] = keyword[False] ):
literal[string]
identifier[convolved_data] = identifier[filter_data] ( ... | def _find_stars(data, kernel, threshold_eff, min_separation=None, mask=None, exclude_border=False):
"""
Find stars in an image.
Parameters
----------
data : 2D array_like
The 2D array of the image.
kernel : `_StarFinderKernel`
The convolution kernel.
threshold_eff : float
... |
def _get_heading_level(self, element):
"""
Returns the level of heading.
:param element: The heading.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: The level of heading.
:rtype: int
"""
# pylint: disable=no-self-use
tag... | def function[_get_heading_level, parameter[self, element]]:
constant[
Returns the level of heading.
:param element: The heading.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: The level of heading.
:rtype: int
]
variable[tag] ass... | keyword[def] identifier[_get_heading_level] ( identifier[self] , identifier[element] ):
literal[string]
identifier[tag] = identifier[element] . identifier[get_tag_name] ()
keyword[if] identifier[tag] == literal[string] :
keyword[return] literal[int]
keywo... | def _get_heading_level(self, element):
"""
Returns the level of heading.
:param element: The heading.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: The level of heading.
:rtype: int
"""
# pylint: disable=no-self-use
tag = element.ge... |
def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = np.arange(num_labels) * num_classes
labels_one_hot = np.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset... | def function[dense_to_one_hot, parameter[labels_dense, num_classes]]:
constant[Convert class labels from scalars to one-hot vectors.]
variable[num_labels] assign[=] call[name[labels_dense].shape][constant[0]]
variable[index_offset] assign[=] binary_operation[call[name[np].arange, parameter[name[... | keyword[def] identifier[dense_to_one_hot] ( identifier[labels_dense] , identifier[num_classes] ):
literal[string]
identifier[num_labels] = identifier[labels_dense] . identifier[shape] [ literal[int] ]
identifier[index_offset] = identifier[np] . identifier[arange] ( identifier[num_labels] )... | def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = np.arange(num_labels) * num_classes
labels_one_hot = np.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.rave... |
def debit(self, amount, credit_account, description, debit_memo="", credit_memo="", datetime=None):
""" Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively.
note amount must be non-negative.
"""
assert amount >= 0
return self.po... | def function[debit, parameter[self, amount, credit_account, description, debit_memo, credit_memo, datetime]]:
constant[ Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively.
note amount must be non-negative.
]
assert[compare[name[amount] grea... | keyword[def] identifier[debit] ( identifier[self] , identifier[amount] , identifier[credit_account] , identifier[description] , identifier[debit_memo] = literal[string] , identifier[credit_memo] = literal[string] , identifier[datetime] = keyword[None] ):
literal[string]
keyword[assert] identifier... | def debit(self, amount, credit_account, description, debit_memo='', credit_memo='', datetime=None):
""" Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively.
note amount must be non-negative.
"""
assert amount >= 0
return self.post(amount, cr... |
async def open_pipe_connection(
path=None,
*,
loop=None,
limit=DEFAULT_LIMIT,
**kwargs
):
"""
Connect to a server using a Windows named pipe.
"""
path = path.replace('/', '\\')
loop = loop or asyncio.get_event_loop()
reader = asyncio.StreamReader(limit=limit, loop=loop)
... | <ast.AsyncFunctionDef object at 0x7da1b0a3df60> | keyword[async] keyword[def] identifier[open_pipe_connection] (
identifier[path] = keyword[None] ,
*,
identifier[loop] = keyword[None] ,
identifier[limit] = identifier[DEFAULT_LIMIT] ,
** identifier[kwargs]
):
literal[string]
identifier[path] = identifier[path] . identifier[replace] ( literal[string] ,... | async def open_pipe_connection(path=None, *, loop=None, limit=DEFAULT_LIMIT, **kwargs):
"""
Connect to a server using a Windows named pipe.
"""
path = path.replace('/', '\\')
loop = loop or asyncio.get_event_loop()
reader = asyncio.StreamReader(limit=limit, loop=loop)
protocol = asyncio.Stre... |
def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
... | def function[_evolve, parameter[self, state, qargs]]:
constant[Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator o... | keyword[def] identifier[_evolve] ( identifier[self] , identifier[state] , identifier[qargs] = keyword[None] ):
literal[string]
identifier[state] = identifier[self] . identifier[_format_state] ( identifier[state] )
keyword[if] identifier[qargs] keyword[is] keyword[None] :
ke... | def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the operator.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
... |
def hparams(self, defaults, unused_model_hparams):
"""Returns problem_hparams.
Args:
defaults: default hyperparameters
unused_model_hparams: model hyperparameters
"""
(super(BabiQa, self).hparams(defaults, unused_model_hparams))
p = defaults
num_classes = self._encoders["targets"].... | def function[hparams, parameter[self, defaults, unused_model_hparams]]:
constant[Returns problem_hparams.
Args:
defaults: default hyperparameters
unused_model_hparams: model hyperparameters
]
call[call[name[super], parameter[name[BabiQa], name[self]]].hparams, parameter[name[defaul... | keyword[def] identifier[hparams] ( identifier[self] , identifier[defaults] , identifier[unused_model_hparams] ):
literal[string]
( identifier[super] ( identifier[BabiQa] , identifier[self] ). identifier[hparams] ( identifier[defaults] , identifier[unused_model_hparams] ))
identifier[p] = identifier[def... | def hparams(self, defaults, unused_model_hparams):
"""Returns problem_hparams.
Args:
defaults: default hyperparameters
unused_model_hparams: model hyperparameters
"""
super(BabiQa, self).hparams(defaults, unused_model_hparams)
p = defaults
num_classes = self._encoders['targets'].vo... |
def extract_concepts(self, sentences=None, ids=None, filename=None,
restrict_to_sts=None, restrict_to_sources=None):
""" extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMapLite.
Su... | def function[extract_concepts, parameter[self, sentences, ids, filename, restrict_to_sts, restrict_to_sources]]:
constant[ extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMapLite.
Supported Options:
... | keyword[def] identifier[extract_concepts] ( identifier[self] , identifier[sentences] = keyword[None] , identifier[ids] = keyword[None] , identifier[filename] = keyword[None] ,
identifier[restrict_to_sts] = keyword[None] , identifier[restrict_to_sources] = keyword[None] ):
literal[string]
keyword[i... | def extract_concepts(self, sentences=None, ids=None, filename=None, restrict_to_sts=None, restrict_to_sources=None):
""" extract_concepts takes a list of sentences and ids(optional)
then returns a list of Concept objects extracted via
MetaMapLite.
Supported Options:
... |
def _images(self, sys_output):
''' a helper method for parsing docker image output '''
import re
gap_pattern = re.compile('\t|\s{2,}')
image_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
for i in... | def function[_images, parameter[self, sys_output]]:
constant[ a helper method for parsing docker image output ]
import module[re]
variable[gap_pattern] assign[=] call[name[re].compile, parameter[constant[ |\s{2,}]]]
variable[image_list] assign[=] list[[]]
variable[output_lines] assig... | keyword[def] identifier[_images] ( identifier[self] , identifier[sys_output] ):
literal[string]
keyword[import] identifier[re]
identifier[gap_pattern] = identifier[re] . identifier[compile] ( literal[string] )
identifier[image_list] =[]
identifier[output_lines]... | def _images(self, sys_output):
""" a helper method for parsing docker image output """
import re
gap_pattern = re.compile('\t|\\s{2,}')
image_list = []
output_lines = sys_output.split('\n')
column_headers = gap_pattern.split(output_lines[0])
for i in range(1, len(output_lines)):
colu... |
def display(self, cutout, use_pixel_coords=False):
"""
:param cutout: source cutout object to be display
:type cutout: source.SourceCutout
"""
logging.debug("Current display list contains: {}".format(self._displayables_by_cutout.keys()))
logging.debug("Looking for {}".for... | def function[display, parameter[self, cutout, use_pixel_coords]]:
constant[
:param cutout: source cutout object to be display
:type cutout: source.SourceCutout
]
call[name[logging].debug, parameter[call[constant[Current display list contains: {}].format, parameter[call[name[self]... | keyword[def] identifier[display] ( identifier[self] , identifier[cutout] , identifier[use_pixel_coords] = keyword[False] ):
literal[string]
identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[self] . identifier[_displayables_by_cutout] . identifier[keys] ()))... | def display(self, cutout, use_pixel_coords=False):
"""
:param cutout: source cutout object to be display
:type cutout: source.SourceCutout
"""
logging.debug('Current display list contains: {}'.format(self._displayables_by_cutout.keys()))
logging.debug('Looking for {}'.format(cutout))... |
def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs):
"""Draws the graph.
Uses matplotlib, specifically
:class:`~matplotlib.collections.LineCollection` and
:meth:`~matplotlib.axes.Axes.scatter`. Gets the default
keyword arguments for both methods by calling
... | def function[draw_graph, parameter[self, line_kwargs, scatter_kwargs]]:
constant[Draws the graph.
Uses matplotlib, specifically
:class:`~matplotlib.collections.LineCollection` and
:meth:`~matplotlib.axes.Axes.scatter`. Gets the default
keyword arguments for both methods by calli... | keyword[def] identifier[draw_graph] ( identifier[self] , identifier[line_kwargs] = keyword[None] , identifier[scatter_kwargs] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[HAS_MATPLOTLIB] :
keyword[raise] identifier[ImportError] ( lite... | def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs):
"""Draws the graph.
Uses matplotlib, specifically
:class:`~matplotlib.collections.LineCollection` and
:meth:`~matplotlib.axes.Axes.scatter`. Gets the default
keyword arguments for both methods by calling
... |
def writeNumber(self, n):
"""
Writes a float to the stream.
@type n: C{float}
"""
self.stream.write(TYPE_NUMBER)
self.stream.write_double(n) | def function[writeNumber, parameter[self, n]]:
constant[
Writes a float to the stream.
@type n: C{float}
]
call[name[self].stream.write, parameter[name[TYPE_NUMBER]]]
call[name[self].stream.write_double, parameter[name[n]]] | keyword[def] identifier[writeNumber] ( identifier[self] , identifier[n] ):
literal[string]
identifier[self] . identifier[stream] . identifier[write] ( identifier[TYPE_NUMBER] )
identifier[self] . identifier[stream] . identifier[write_double] ( identifier[n] ) | def writeNumber(self, n):
"""
Writes a float to the stream.
@type n: C{float}
"""
self.stream.write(TYPE_NUMBER)
self.stream.write_double(n) |
def add_web_servers(self, listen_addrs, debug=False, **ssl_args):
"""Add WebSocketServer for each (host, port) in listen_addrs."""
self.servers.extend(
self.get_web_server(listen_addr, debug=debug, **ssl_args)
for listen_addr in listen_addrs
) | def function[add_web_servers, parameter[self, listen_addrs, debug]]:
constant[Add WebSocketServer for each (host, port) in listen_addrs.]
call[name[self].servers.extend, parameter[<ast.GeneratorExp object at 0x7da18f8102b0>]] | keyword[def] identifier[add_web_servers] ( identifier[self] , identifier[listen_addrs] , identifier[debug] = keyword[False] ,** identifier[ssl_args] ):
literal[string]
identifier[self] . identifier[servers] . identifier[extend] (
identifier[self] . identifier[get_web_server] ( identifier[l... | def add_web_servers(self, listen_addrs, debug=False, **ssl_args):
"""Add WebSocketServer for each (host, port) in listen_addrs."""
self.servers.extend((self.get_web_server(listen_addr, debug=debug, **ssl_args) for listen_addr in listen_addrs)) |
def sanitize_index(data, index, copy=False):
"""
Sanitize an index type to return an ndarray of the underlying, pass
through a non-Index.
"""
if index is None:
return data
if len(data) != len(index):
raise ValueError('Length of values does not match length of index')
if is... | def function[sanitize_index, parameter[data, index, copy]]:
constant[
Sanitize an index type to return an ndarray of the underlying, pass
through a non-Index.
]
if compare[name[index] is constant[None]] begin[:]
return[name[data]]
if compare[call[name[len], parameter[name[dat... | keyword[def] identifier[sanitize_index] ( identifier[data] , identifier[index] , identifier[copy] = keyword[False] ):
literal[string]
keyword[if] identifier[index] keyword[is] keyword[None] :
keyword[return] identifier[data]
keyword[if] identifier[len] ( identifier[data] )!= identifie... | def sanitize_index(data, index, copy=False):
"""
Sanitize an index type to return an ndarray of the underlying, pass
through a non-Index.
"""
if index is None:
return data # depends on [control=['if'], data=[]]
if len(data) != len(index):
raise ValueError('Length of values does ... |
def when_children_replaced ( self, object, listener, remove ):
""" Sets up or removes a listener for children being replaced on a
specified object.
"""
object.on_trait_change( listener, "subgraphs", remove = remove,
dispatch = "fast_ui" )
objec... | def function[when_children_replaced, parameter[self, object, listener, remove]]:
constant[ Sets up or removes a listener for children being replaced on a
specified object.
]
call[name[object].on_trait_change, parameter[name[listener], constant[subgraphs]]]
call[name[object].o... | keyword[def] identifier[when_children_replaced] ( identifier[self] , identifier[object] , identifier[listener] , identifier[remove] ):
literal[string]
identifier[object] . identifier[on_trait_change] ( identifier[listener] , literal[string] , identifier[remove] = identifier[remove] ,
ident... | def when_children_replaced(self, object, listener, remove):
""" Sets up or removes a listener for children being replaced on a
specified object.
"""
object.on_trait_change(listener, 'subgraphs', remove=remove, dispatch='fast_ui')
object.on_trait_change(listener, 'clusters', remove=remove... |
def _merge_list_fastqs(files, out_file, config):
"""merge list of fastq files into one"""
if not all(map(fastq.is_fastq, files)):
raise ValueError("Not all of the files to merge are fastq files: %s " % (files))
assert all(map(utils.file_exists, files)), ("Not all of the files to merge "
... | def function[_merge_list_fastqs, parameter[files, out_file, config]]:
constant[merge list of fastq files into one]
if <ast.UnaryOp object at 0x7da1b1831a50> begin[:]
<ast.Raise object at 0x7da1b1831390>
assert[call[name[all], parameter[call[name[map], parameter[name[utils].file_exists, name[... | keyword[def] identifier[_merge_list_fastqs] ( identifier[files] , identifier[out_file] , identifier[config] ):
literal[string]
keyword[if] keyword[not] identifier[all] ( identifier[map] ( identifier[fastq] . identifier[is_fastq] , identifier[files] )):
keyword[raise] identifier[ValueError] ( li... | def _merge_list_fastqs(files, out_file, config):
"""merge list of fastq files into one"""
if not all(map(fastq.is_fastq, files)):
raise ValueError('Not all of the files to merge are fastq files: %s ' % files) # depends on [control=['if'], data=[]]
assert all(map(utils.file_exists, files)), 'Not all... |
def remove(self, document_id, namespace, timestamp):
"""Removes document from Mongo
The input is a python dictionary that represents a mongo document.
The documents has ns and _ts fields.
"""
database, coll = self._db_and_collection(namespace)
meta_collection = self._ge... | def function[remove, parameter[self, document_id, namespace, timestamp]]:
constant[Removes document from Mongo
The input is a python dictionary that represents a mongo document.
The documents has ns and _ts fields.
]
<ast.Tuple object at 0x7da1b1d3bdf0> assign[=] call[name[self]... | keyword[def] identifier[remove] ( identifier[self] , identifier[document_id] , identifier[namespace] , identifier[timestamp] ):
literal[string]
identifier[database] , identifier[coll] = identifier[self] . identifier[_db_and_collection] ( identifier[namespace] )
identifier[meta_collection]... | def remove(self, document_id, namespace, timestamp):
"""Removes document from Mongo
The input is a python dictionary that represents a mongo document.
The documents has ns and _ts fields.
"""
(database, coll) = self._db_and_collection(namespace)
meta_collection = self._get_meta_coll... |
def jquery_js(version=None, migrate=False):
'''A shortcut to render a ``script`` tag for the packaged jQuery'''
version = version or settings.JQUERY_VERSION
suffix = '.min' if not settings.DEBUG else ''
libs = [js_lib('jquery-%s%s.js' % (version, suffix))]
if _boolean(migrate):
libs.append(j... | def function[jquery_js, parameter[version, migrate]]:
constant[A shortcut to render a ``script`` tag for the packaged jQuery]
variable[version] assign[=] <ast.BoolOp object at 0x7da1b1120910>
variable[suffix] assign[=] <ast.IfExp object at 0x7da1b1122e90>
variable[libs] assign[=] list[[<... | keyword[def] identifier[jquery_js] ( identifier[version] = keyword[None] , identifier[migrate] = keyword[False] ):
literal[string]
identifier[version] = identifier[version] keyword[or] identifier[settings] . identifier[JQUERY_VERSION]
identifier[suffix] = literal[string] keyword[if] keyword[not] ... | def jquery_js(version=None, migrate=False):
"""A shortcut to render a ``script`` tag for the packaged jQuery"""
version = version or settings.JQUERY_VERSION
suffix = '.min' if not settings.DEBUG else ''
libs = [js_lib('jquery-%s%s.js' % (version, suffix))]
if _boolean(migrate):
libs.append(j... |
def get_level_nodes(self, level):
"""!
@brief Traverses CF-tree to obtain nodes at the specified level.
@param[in] level (uint): CF-tree level from that nodes should be returned.
@return (list) List of CF-nodes that are located on the specified level of the CF-tre... | def function[get_level_nodes, parameter[self, level]]:
constant[!
@brief Traverses CF-tree to obtain nodes at the specified level.
@param[in] level (uint): CF-tree level from that nodes should be returned.
@return (list) List of CF-nodes that are located on the specifie... | keyword[def] identifier[get_level_nodes] ( identifier[self] , identifier[level] ):
literal[string]
identifier[level_nodes] =[];
keyword[if] ( identifier[level] < identifier[self] . identifier[__height] ):
identifier[level_nodes] = identifier[self] . identifier[__recursiv... | def get_level_nodes(self, level):
"""!
@brief Traverses CF-tree to obtain nodes at the specified level.
@param[in] level (uint): CF-tree level from that nodes should be returned.
@return (list) List of CF-nodes that are located on the specified level of the CF-tree.
... |
def read_ready(self):
"""
Returns true if data is buffered and ready to be read from this
feeder. A ``False`` result does not mean that the feeder has closed;
it means you may need to wait before more data arrives.
:return:
``True`` if a `read` call would immediatel... | def function[read_ready, parameter[self]]:
constant[
Returns true if data is buffered and ready to be read from this
feeder. A ``False`` result does not mean that the feeder has closed;
it means you may need to wait before more data arrives.
:return:
``True`` if a `... | keyword[def] identifier[read_ready] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_lock] . identifier[acquire] ()
keyword[try] :
keyword[if] identifier[len] ( identifier[self] . identifier[_buffer] )== literal[int] :
keyword[return] key... | def read_ready(self):
"""
Returns true if data is buffered and ready to be read from this
feeder. A ``False`` result does not mean that the feeder has closed;
it means you may need to wait before more data arrives.
:return:
``True`` if a `read` call would immediately re... |
def is_connected(C, directed=True):
r"""Return true, if the input count matrix is completely connected.
Effectively checking if the number of connected components equals one.
Parameters
----------
C : scipy.sparse matrix or numpy ndarray
Count matrix specifying edge weights.
directed : ... | def function[is_connected, parameter[C, directed]]:
constant[Return true, if the input count matrix is completely connected.
Effectively checking if the number of connected components equals one.
Parameters
----------
C : scipy.sparse matrix or numpy ndarray
Count matrix specifying edge... | keyword[def] identifier[is_connected] ( identifier[C] , identifier[directed] = keyword[True] ):
literal[string]
identifier[nc] = identifier[csgraph] . identifier[connected_components] ( identifier[C] , identifier[directed] = identifier[directed] , identifier[connection] = literal[string] , identifier[retur... | def is_connected(C, directed=True):
"""Return true, if the input count matrix is completely connected.
Effectively checking if the number of connected components equals one.
Parameters
----------
C : scipy.sparse matrix or numpy ndarray
Count matrix specifying edge weights.
directed : b... |
def get_data(conn_objs, providers):
"""Refresh node data using existing connection-objects."""
cld_svc_map = {"aws": nodes_aws,
"azure": nodes_az,
"gcp": nodes_gcp,
"alicloud": nodes_ali}
sys.stdout.write("\rCollecting Info: ")
sys.stdout.flush()... | def function[get_data, parameter[conn_objs, providers]]:
constant[Refresh node data using existing connection-objects.]
variable[cld_svc_map] assign[=] dictionary[[<ast.Constant object at 0x7da1b26771f0>, <ast.Constant object at 0x7da1b26777f0>, <ast.Constant object at 0x7da1b2677310>, <ast.Constant obj... | keyword[def] identifier[get_data] ( identifier[conn_objs] , identifier[providers] ):
literal[string]
identifier[cld_svc_map] ={ literal[string] : identifier[nodes_aws] ,
literal[string] : identifier[nodes_az] ,
literal[string] : identifier[nodes_gcp] ,
literal[string] : identifier[nodes_ali]... | def get_data(conn_objs, providers):
"""Refresh node data using existing connection-objects."""
cld_svc_map = {'aws': nodes_aws, 'azure': nodes_az, 'gcp': nodes_gcp, 'alicloud': nodes_ali}
sys.stdout.write('\rCollecting Info: ')
sys.stdout.flush()
busy_obj = busy_disp_on()
collec_fn = [[cld_svc_... |
def reset(self):
"""Resets the iterator to the beginning of the data."""
self.curr_idx = 0
#shuffle data in each bucket
random.shuffle(self.idx)
for i, buck in enumerate(self.sentences):
self.indices[i], self.sentences[i], self.characters[i], self.label[i] = shuffle(s... | def function[reset, parameter[self]]:
constant[Resets the iterator to the beginning of the data.]
name[self].curr_idx assign[=] constant[0]
call[name[random].shuffle, parameter[name[self].idx]]
for taget[tuple[[<ast.Name object at 0x7da2054a5300>, <ast.Name object at 0x7da2054a6890>]]] i... | keyword[def] identifier[reset] ( identifier[self] ):
literal[string]
identifier[self] . identifier[curr_idx] = literal[int]
identifier[random] . identifier[shuffle] ( identifier[self] . identifier[idx] )
keyword[for] identifier[i] , identifier[buck] keyword[in] identi... | def reset(self):
"""Resets the iterator to the beginning of the data."""
self.curr_idx = 0
#shuffle data in each bucket
random.shuffle(self.idx)
for (i, buck) in enumerate(self.sentences):
(self.indices[i], self.sentences[i], self.characters[i], self.label[i]) = shuffle(self.indices[i], self... |
def concatenate_variables(scope, variables, container):
'''
This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all
integer inputs would be converted to floats before concatenation.
'''
# Check if it's possible to concatenate those inputs.
... | def function[concatenate_variables, parameter[scope, variables, container]]:
constant[
This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all
integer inputs would be converted to floats before concatenation.
]
variable[type_set] assig... | keyword[def] identifier[concatenate_variables] ( identifier[scope] , identifier[variables] , identifier[container] ):
literal[string]
identifier[type_set] = identifier[set] ( identifier[type] ( identifier[variable] . identifier[type] ) keyword[for] identifier[variable] keyword[in] identifier[varia... | def concatenate_variables(scope, variables, container):
"""
This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all
integer inputs would be converted to floats before concatenation.
"""
# Check if it's possible to concatenate those inputs.
... |
def prepare_plot_data(data_file):
"""
Return a list of Plotly elements representing the network graph
"""
G = ig.Graph.Read_GML(data_file)
layout = G.layout('graphopt')
labels = list(G.vs['label'])
N = len(labels)
E = [e.tuple for e in G.es]
community = G.community_multilevel().m... | def function[prepare_plot_data, parameter[data_file]]:
constant[
Return a list of Plotly elements representing the network graph
]
variable[G] assign[=] call[name[ig].Graph.Read_GML, parameter[name[data_file]]]
variable[layout] assign[=] call[name[G].layout, parameter[constant[graphopt]]... | keyword[def] identifier[prepare_plot_data] ( identifier[data_file] ):
literal[string]
identifier[G] = identifier[ig] . identifier[Graph] . identifier[Read_GML] ( identifier[data_file] )
identifier[layout] = identifier[G] . identifier[layout] ( literal[string] )
identifier[labels] = identifier[l... | def prepare_plot_data(data_file):
"""
Return a list of Plotly elements representing the network graph
"""
G = ig.Graph.Read_GML(data_file)
layout = G.layout('graphopt')
labels = list(G.vs['label'])
N = len(labels)
E = [e.tuple for e in G.es]
community = G.community_multilevel().membe... |
def find_by_workspace(self, workspace, params={}, **options):
"""Returns the compact tag records for all tags in the workspace.
Parameters
----------
workspace : {Id} The workspace or organization to find tags in.
[params] : {Object} Parameters for the request
"""
... | def function[find_by_workspace, parameter[self, workspace, params]]:
constant[Returns the compact tag records for all tags in the workspace.
Parameters
----------
workspace : {Id} The workspace or organization to find tags in.
[params] : {Object} Parameters for the request
... | keyword[def] identifier[find_by_workspace] ( identifier[self] , identifier[workspace] , identifier[params] ={},** identifier[options] ):
literal[string]
identifier[path] = literal[string] %( identifier[workspace] )
keyword[return] identifier[self] . identifier[client] . identifier[get_col... | def find_by_workspace(self, workspace, params={}, **options):
"""Returns the compact tag records for all tags in the workspace.
Parameters
----------
workspace : {Id} The workspace or organization to find tags in.
[params] : {Object} Parameters for the request
"""
path =... |
def parse_sidebar(self, anime_page):
"""Parses the DOM and returns anime attributes in the sidebar.
:type anime_page: :class:`bs4.BeautifulSoup`
:param anime_page: MAL anime page's DOM
:rtype: dict
:return: anime attributes
:raises: :class:`.InvalidAnimeError`, :class:`.MalformedAnimePageErro... | def function[parse_sidebar, parameter[self, anime_page]]:
constant[Parses the DOM and returns anime attributes in the sidebar.
:type anime_page: :class:`bs4.BeautifulSoup`
:param anime_page: MAL anime page's DOM
:rtype: dict
:return: anime attributes
:raises: :class:`.InvalidAnimeError`, ... | keyword[def] identifier[parse_sidebar] ( identifier[self] , identifier[anime_page] ):
literal[string]
identifier[error_tag] = identifier[anime_page] . identifier[find] ( literal[string] ,{ literal[string] : literal[string] })
keyword[if] identifier[error_tag] :
keyword[raise] identifie... | def parse_sidebar(self, anime_page):
"""Parses the DOM and returns anime attributes in the sidebar.
:type anime_page: :class:`bs4.BeautifulSoup`
:param anime_page: MAL anime page's DOM
:rtype: dict
:return: anime attributes
:raises: :class:`.InvalidAnimeError`, :class:`.MalformedAnimePageErro... |
def create_category(cls, category, **kwargs):
"""Create Category
Create a new Category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_category(category, async=True)
>>> result ... | def function[create_category, parameter[cls, category]]:
constant[Create Category
Create a new Category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_category(category, async=True)
... | keyword[def] identifier[create_category] ( identifier[cls] , identifier[category] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier... | def create_category(cls, category, **kwargs):
"""Create Category
Create a new Category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_category(category, async=True)
>>> result = th... |
def aggregate_failed(self) -> List:
"""Count the number of failed jobs per category (name)."""
categories = self.session.query(
self.Job.name.label('name'),
sqa.func.count(self.Job.id).label('count')
).filter(self.Job.status != 'cancelled').group_by(self.Job.name).all()
... | def function[aggregate_failed, parameter[self]]:
constant[Count the number of failed jobs per category (name).]
variable[categories] assign[=] call[call[call[call[name[self].session.query, parameter[call[name[self].Job.name.label, parameter[constant[name]]], call[call[name[sqa].func.count, parameter[nam... | keyword[def] identifier[aggregate_failed] ( identifier[self] )-> identifier[List] :
literal[string]
identifier[categories] = identifier[self] . identifier[session] . identifier[query] (
identifier[self] . identifier[Job] . identifier[name] . identifier[label] ( literal[string] ),
... | def aggregate_failed(self) -> List:
"""Count the number of failed jobs per category (name)."""
categories = self.session.query(self.Job.name.label('name'), sqa.func.count(self.Job.id).label('count')).filter(self.Job.status != 'cancelled').group_by(self.Job.name).all()
data = [{'name': category.name, 'count'... |
def request(self, max_width):
# type: (int) -> Optional[Tuple[int, Chunk]]
"""Requests a sub-chunk of max_width or shorter. Returns None if no chunks left."""
if max_width < 1:
raise ValueError('requires positive integer max_width')
s = self.chunk.s
length = len(s)
... | def function[request, parameter[self, max_width]]:
constant[Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.]
if compare[name[max_width] less[<] constant[1]] begin[:]
<ast.Raise object at 0x7da20e74bd90>
variable[s] assign[=] name[self].chunk.s
variab... | keyword[def] identifier[request] ( identifier[self] , identifier[max_width] ):
literal[string]
keyword[if] identifier[max_width] < literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[s] = identifier[self] . identifier[chunk] . identifier[s] ... | def request(self, max_width):
# type: (int) -> Optional[Tuple[int, Chunk]]
'Requests a sub-chunk of max_width or shorter. Returns None if no chunks left.'
if max_width < 1:
raise ValueError('requires positive integer max_width') # depends on [control=['if'], data=[]]
s = self.chunk.s
length... |
def frame_times(self):
"""This getter returns the frame times, for the corresponding type of
features."""
frame_times = None
# Make sure we have already computed the features
self.features
if self.feat_type is FeatureTypes.framesync:
self._compute_framesync_ti... | def function[frame_times, parameter[self]]:
constant[This getter returns the frame times, for the corresponding type of
features.]
variable[frame_times] assign[=] constant[None]
name[self].features
if compare[name[self].feat_type is name[FeatureTypes].framesync] begin[:]
... | keyword[def] identifier[frame_times] ( identifier[self] ):
literal[string]
identifier[frame_times] = keyword[None]
identifier[self] . identifier[features]
keyword[if] identifier[self] . identifier[feat_type] keyword[is] identifier[FeatureTypes] . identifier[framesync... | def frame_times(self):
"""This getter returns the frame times, for the corresponding type of
features."""
frame_times = None
# Make sure we have already computed the features
self.features
if self.feat_type is FeatureTypes.framesync:
self._compute_framesync_times()
frame_time... |
def _wait_for_keypress():
"""
Wait for a key press on the console and return it.
Borrowed from http://stackoverflow.com/questions/983354/how-do-i-make-python-to-wait-for-a-pressed-key
"""
result = None
if os.name == "nt":
# noinspection PyUnresolvedReferences
import msvcrt
... | def function[_wait_for_keypress, parameter[]]:
constant[
Wait for a key press on the console and return it.
Borrowed from http://stackoverflow.com/questions/983354/how-do-i-make-python-to-wait-for-a-pressed-key
]
variable[result] assign[=] constant[None]
if compare[name[os].name equ... | keyword[def] identifier[_wait_for_keypress] ():
literal[string]
identifier[result] = keyword[None]
keyword[if] identifier[os] . identifier[name] == literal[string] :
keyword[import] identifier[msvcrt]
identifier[result] = identifier[msvcrt] . identifier[getch] ()
keywor... | def _wait_for_keypress():
"""
Wait for a key press on the console and return it.
Borrowed from http://stackoverflow.com/questions/983354/how-do-i-make-python-to-wait-for-a-pressed-key
"""
result = None
if os.name == 'nt':
# noinspection PyUnresolvedReferences
import msvcrt
... |
def as_condition(cls, obj):
"""Convert obj into :class:`Condition`"""
if isinstance(obj, cls):
return obj
else:
return cls(cmap=obj) | def function[as_condition, parameter[cls, obj]]:
constant[Convert obj into :class:`Condition`]
if call[name[isinstance], parameter[name[obj], name[cls]]] begin[:]
return[name[obj]] | keyword[def] identifier[as_condition] ( identifier[cls] , identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[cls] ):
keyword[return] identifier[obj]
keyword[else] :
keyword[return] identifier[cls] ( identifier[... | def as_condition(cls, obj):
"""Convert obj into :class:`Condition`"""
if isinstance(obj, cls):
return obj # depends on [control=['if'], data=[]]
else:
return cls(cmap=obj) |
def _set_symlink_ownership(path, user, group, win_owner):
'''
Set the ownership of a symlink and return a boolean indicating
success/failure
'''
if salt.utils.platform.is_windows():
try:
salt.utils.win_dacl.set_owner(path, win_owner)
except CommandExecutionError:
... | def function[_set_symlink_ownership, parameter[path, user, group, win_owner]]:
constant[
Set the ownership of a symlink and return a boolean indicating
success/failure
]
if call[name[salt].utils.platform.is_windows, parameter[]] begin[:]
<ast.Try object at 0x7da1b20efbb0>
return[... | keyword[def] identifier[_set_symlink_ownership] ( identifier[path] , identifier[user] , identifier[group] , identifier[win_owner] ):
literal[string]
keyword[if] identifier[salt] . identifier[utils] . identifier[platform] . identifier[is_windows] ():
keyword[try] :
identifier[salt] . ... | def _set_symlink_ownership(path, user, group, win_owner):
"""
Set the ownership of a symlink and return a boolean indicating
success/failure
"""
if salt.utils.platform.is_windows():
try:
salt.utils.win_dacl.set_owner(path, win_owner) # depends on [control=['try'], data=[]]
... |
def write_file(self, filename, file_format="xyz"):
"""
Uses OpenBabel to output all supported formats.
Args:
filename: Filename of file to output
file_format: String specifying any OpenBabel supported formats.
"""
mol = pb.Molecule(self._obmol)
re... | def function[write_file, parameter[self, filename, file_format]]:
constant[
Uses OpenBabel to output all supported formats.
Args:
filename: Filename of file to output
file_format: String specifying any OpenBabel supported formats.
]
variable[mol] assign[=... | keyword[def] identifier[write_file] ( identifier[self] , identifier[filename] , identifier[file_format] = literal[string] ):
literal[string]
identifier[mol] = identifier[pb] . identifier[Molecule] ( identifier[self] . identifier[_obmol] )
keyword[return] identifier[mol] . identifier[write... | def write_file(self, filename, file_format='xyz'):
"""
Uses OpenBabel to output all supported formats.
Args:
filename: Filename of file to output
file_format: String specifying any OpenBabel supported formats.
"""
mol = pb.Molecule(self._obmol)
return mol.wri... |
def get_connections_stat(
self, instance, base_url, object_type, vhosts, limit_vhosts, custom_tags, auth=None, ssl_verify=True
):
"""
Collect metrics on currently open connection per vhost.
"""
instance_proxy = self.get_instance_proxy(instance, base_url)
grab_all_dat... | def function[get_connections_stat, parameter[self, instance, base_url, object_type, vhosts, limit_vhosts, custom_tags, auth, ssl_verify]]:
constant[
Collect metrics on currently open connection per vhost.
]
variable[instance_proxy] assign[=] call[name[self].get_instance_proxy, parameter[... | keyword[def] identifier[get_connections_stat] (
identifier[self] , identifier[instance] , identifier[base_url] , identifier[object_type] , identifier[vhosts] , identifier[limit_vhosts] , identifier[custom_tags] , identifier[auth] = keyword[None] , identifier[ssl_verify] = keyword[True]
):
literal[string]
... | def get_connections_stat(self, instance, base_url, object_type, vhosts, limit_vhosts, custom_tags, auth=None, ssl_verify=True):
"""
Collect metrics on currently open connection per vhost.
"""
instance_proxy = self.get_instance_proxy(instance, base_url)
grab_all_data = True
if self._limit... |
def store_meta_data(self, copy_path=None):
"""Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, it will be used instead... | def function[store_meta_data, parameter[self, copy_path]]:
constant[Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, i... | keyword[def] identifier[store_meta_data] ( identifier[self] , identifier[copy_path] = keyword[None] ):
literal[string]
keyword[if] identifier[copy_path] :
identifier[meta_file_json] = identifier[os] . identifier[path] . identifier[join] ( identifier[copy_path] , identifier[storage] . ... | def store_meta_data(self, copy_path=None):
"""Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, it will be used instead of ... |
def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(AssetState, self).Serialize(writer)
writer.WriteUInt256(self.AssetId)
writer.WriteByte(self.AssetType)
writer.WriteVarString(self.Name)
... | def function[Serialize, parameter[self, writer]]:
constant[
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
]
call[call[name[super], parameter[name[AssetState], name[self]]].Serialize, parameter[name[writer]]]
call[name[writer].WriteUInt256, parame... | keyword[def] identifier[Serialize] ( identifier[self] , identifier[writer] ):
literal[string]
identifier[super] ( identifier[AssetState] , identifier[self] ). identifier[Serialize] ( identifier[writer] )
identifier[writer] . identifier[WriteUInt256] ( identifier[self] . identifier[AssetId]... | def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(AssetState, self).Serialize(writer)
writer.WriteUInt256(self.AssetId)
writer.WriteByte(self.AssetType)
writer.WriteVarString(self.Name)
if self.Amount.value ... |
def recall(y, y_pred):
"""Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float... | def function[recall, parameter[y, y_pred]]:
constant[Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
... | keyword[def] identifier[recall] ( identifier[y] , identifier[y_pred] ):
literal[string]
identifier[tp] = identifier[true_positives] ( identifier[y] , identifier[y_pred] )
identifier[fn] = identifier[false_negatives] ( identifier[y] , identifier[y_pred] )
keyword[return] identifier[tp] /( identi... | def recall(y, y_pred):
"""Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float... |
def get_remarks(txt: str) -> ([str], str): # type: ignore
"""
Returns the report split into components and the remarks string
Remarks can include items like RMK and on, NOSIG and on, and BECMG and on
"""
txt = txt.replace('?', '').strip()
# First look for Altimeter in txt
alt_index = len(t... | def function[get_remarks, parameter[txt]]:
constant[
Returns the report split into components and the remarks string
Remarks can include items like RMK and on, NOSIG and on, and BECMG and on
]
variable[txt] assign[=] call[call[name[txt].replace, parameter[constant[?], constant[]]].strip, pa... | keyword[def] identifier[get_remarks] ( identifier[txt] : identifier[str] )->([ identifier[str] ], identifier[str] ):
literal[string]
identifier[txt] = identifier[txt] . identifier[replace] ( literal[string] , literal[string] ). identifier[strip] ()
identifier[alt_index] = identifier[len] ( identi... | def get_remarks(txt: str) -> ([str], str): # type: ignore
'\n Returns the report split into components and the remarks string\n\n Remarks can include items like RMK and on, NOSIG and on, and BECMG and on\n '
txt = txt.replace('?', '').strip()
# First look for Altimeter in txt
alt_index = len(t... |
def is_iterable_of_float(l):
r""" Checks if l is iterable and contains only floating point types """
if not is_iterable(l):
return False
return all(is_float(value) for value in l) | def function[is_iterable_of_float, parameter[l]]:
constant[ Checks if l is iterable and contains only floating point types ]
if <ast.UnaryOp object at 0x7da18f00dab0> begin[:]
return[constant[False]]
return[call[name[all], parameter[<ast.GeneratorExp object at 0x7da18f7217e0>]]] | keyword[def] identifier[is_iterable_of_float] ( identifier[l] ):
literal[string]
keyword[if] keyword[not] identifier[is_iterable] ( identifier[l] ):
keyword[return] keyword[False]
keyword[return] identifier[all] ( identifier[is_float] ( identifier[value] ) keyword[for] identifier[value... | def is_iterable_of_float(l):
""" Checks if l is iterable and contains only floating point types """
if not is_iterable(l):
return False # depends on [control=['if'], data=[]]
return all((is_float(value) for value in l)) |
def get_media_requests(self, item, info):
"""
根据item中的信息, 构造出需要下载的静态资源的Request对象
:param item:
:param info:
:return:
"""
key_generator = item.get(self.QINIU_KEY_GENERATOR_FIELD)
return [Request(x, meta={'qiniu_key_generator': key_generator}) for x in item.... | def function[get_media_requests, parameter[self, item, info]]:
constant[
根据item中的信息, 构造出需要下载的静态资源的Request对象
:param item:
:param info:
:return:
]
variable[key_generator] assign[=] call[name[item].get, parameter[name[self].QINIU_KEY_GENERATOR_FIELD]]
return[<as... | keyword[def] identifier[get_media_requests] ( identifier[self] , identifier[item] , identifier[info] ):
literal[string]
identifier[key_generator] = identifier[item] . identifier[get] ( identifier[self] . identifier[QINIU_KEY_GENERATOR_FIELD] )
keyword[return] [ identifier[Request] ( identi... | def get_media_requests(self, item, info):
"""
根据item中的信息, 构造出需要下载的静态资源的Request对象
:param item:
:param info:
:return:
"""
key_generator = item.get(self.QINIU_KEY_GENERATOR_FIELD)
return [Request(x, meta={'qiniu_key_generator': key_generator}) for x in item.get(self.FIL... |
def effective_sample_size(h):
"""
Calculate the effective sample size for a histogram
the same way as ROOT does.
"""
sum = 0
ew = 0
w = 0
for bin in h.bins(overflow=False):
sum += bin.value
ew = bin.error
w += ew * ew
esum = sum * sum / w
return esum | def function[effective_sample_size, parameter[h]]:
constant[
Calculate the effective sample size for a histogram
the same way as ROOT does.
]
variable[sum] assign[=] constant[0]
variable[ew] assign[=] constant[0]
variable[w] assign[=] constant[0]
for taget[name[bin]] ... | keyword[def] identifier[effective_sample_size] ( identifier[h] ):
literal[string]
identifier[sum] = literal[int]
identifier[ew] = literal[int]
identifier[w] = literal[int]
keyword[for] identifier[bin] keyword[in] identifier[h] . identifier[bins] ( identifier[overflow] = keyword[False] ... | def effective_sample_size(h):
"""
Calculate the effective sample size for a histogram
the same way as ROOT does.
"""
sum = 0
ew = 0
w = 0
for bin in h.bins(overflow=False):
sum += bin.value
ew = bin.error
w += ew * ew # depends on [control=['for'], data=['bin']]
... |
def _qrd_solve_full(a, b, ddiag, dtype=np.float):
"""Solve the equation A^T x = B, D x = 0.
Parameters:
a - an n-by-m array, m >= n
b - an m-vector
ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.)
Returns:
x - n-vector solving the equation.
s - the n-by-n supplementary matrix s.
p... | def function[_qrd_solve_full, parameter[a, b, ddiag, dtype]]:
constant[Solve the equation A^T x = B, D x = 0.
Parameters:
a - an n-by-m array, m >= n
b - an m-vector
ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.)
Returns:
x - n-vector solving the equation.
s - the n-by-n sup... | keyword[def] identifier[_qrd_solve_full] ( identifier[a] , identifier[b] , identifier[ddiag] , identifier[dtype] = identifier[np] . identifier[float] ):
literal[string]
identifier[a] = identifier[np] . identifier[asarray] ( identifier[a] , identifier[dtype] )
identifier[b] = identifier[np] . identifi... | def _qrd_solve_full(a, b, ddiag, dtype=np.float):
"""Solve the equation A^T x = B, D x = 0.
Parameters:
a - an n-by-m array, m >= n
b - an m-vector
ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.)
Returns:
x - n-vector solving the equation.
s - the n-by-n supplementary matrix s.
p... |
def num2bytes(value, size):
"""Convert an unsigned integer to MSB-first bytes with specified size."""
res = []
for _ in range(size):
res.append(value & 0xFF)
value = value >> 8
assert value == 0
return bytes(bytearray(list(reversed(res)))) | def function[num2bytes, parameter[value, size]]:
constant[Convert an unsigned integer to MSB-first bytes with specified size.]
variable[res] assign[=] list[[]]
for taget[name[_]] in starred[call[name[range], parameter[name[size]]]] begin[:]
call[name[res].append, parameter[binary... | keyword[def] identifier[num2bytes] ( identifier[value] , identifier[size] ):
literal[string]
identifier[res] =[]
keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[size] ):
identifier[res] . identifier[append] ( identifier[value] & literal[int] )
identifier[valu... | def num2bytes(value, size):
"""Convert an unsigned integer to MSB-first bytes with specified size."""
res = []
for _ in range(size):
res.append(value & 255)
value = value >> 8 # depends on [control=['for'], data=[]]
assert value == 0
return bytes(bytearray(list(reversed(res)))) |
def verify_jwt_in_request():
"""
Ensure that the requester has a valid access token. This does not check the
freshness of the access token. Raises an appropiate exception there is
no token or if the token is invalid.
"""
if request.method not in config.exempt_methods:
jwt_data = _decode_... | def function[verify_jwt_in_request, parameter[]]:
constant[
Ensure that the requester has a valid access token. This does not check the
freshness of the access token. Raises an appropiate exception there is
no token or if the token is invalid.
]
if compare[name[request].method <ast.NotIn... | keyword[def] identifier[verify_jwt_in_request] ():
literal[string]
keyword[if] identifier[request] . identifier[method] keyword[not] keyword[in] identifier[config] . identifier[exempt_methods] :
identifier[jwt_data] = identifier[_decode_jwt_from_request] ( identifier[request_type] = literal[st... | def verify_jwt_in_request():
"""
Ensure that the requester has a valid access token. This does not check the
freshness of the access token. Raises an appropiate exception there is
no token or if the token is invalid.
"""
if request.method not in config.exempt_methods:
jwt_data = _decode_... |
def get_rotated(self, angle):
"""Rotates this vector through the given anti-clockwise angle
in radians."""
ca = math.cos(angle)
sa = math.sin(angle)
return Point(self.x*ca-self.y*sa, self.x*sa+self.y*ca) | def function[get_rotated, parameter[self, angle]]:
constant[Rotates this vector through the given anti-clockwise angle
in radians.]
variable[ca] assign[=] call[name[math].cos, parameter[name[angle]]]
variable[sa] assign[=] call[name[math].sin, parameter[name[angle]]]
return[call[name... | keyword[def] identifier[get_rotated] ( identifier[self] , identifier[angle] ):
literal[string]
identifier[ca] = identifier[math] . identifier[cos] ( identifier[angle] )
identifier[sa] = identifier[math] . identifier[sin] ( identifier[angle] )
keyword[return] identifier[Point] ( i... | def get_rotated(self, angle):
"""Rotates this vector through the given anti-clockwise angle
in radians."""
ca = math.cos(angle)
sa = math.sin(angle)
return Point(self.x * ca - self.y * sa, self.x * sa + self.y * ca) |
def find_types_removed_from_unions(
old_schema: GraphQLSchema, new_schema: GraphQLSchema
) -> List[BreakingChange]:
"""Find types removed from unions.
Given two schemas, returns a list containing descriptions of any breaking changes
in the new_schema related to removing types from a union type.
"""... | def function[find_types_removed_from_unions, parameter[old_schema, new_schema]]:
constant[Find types removed from unions.
Given two schemas, returns a list containing descriptions of any breaking changes
in the new_schema related to removing types from a union type.
]
variable[old_type_map]... | keyword[def] identifier[find_types_removed_from_unions] (
identifier[old_schema] : identifier[GraphQLSchema] , identifier[new_schema] : identifier[GraphQLSchema]
)-> identifier[List] [ identifier[BreakingChange] ]:
literal[string]
identifier[old_type_map] = identifier[old_schema] . identifier[type_map]
... | def find_types_removed_from_unions(old_schema: GraphQLSchema, new_schema: GraphQLSchema) -> List[BreakingChange]:
"""Find types removed from unions.
Given two schemas, returns a list containing descriptions of any breaking changes
in the new_schema related to removing types from a union type.
"""
o... |
def unwrap_or_else(self, callback: Callable[[], U]) -> Union[T, U]:
"""
Returns the contained value or computes it from ``callback``.
Args:
callback: The the default callback.
Returns:
The contained value if the :py:class:`Option` is ``Some``,
otherw... | def function[unwrap_or_else, parameter[self, callback]]:
constant[
Returns the contained value or computes it from ``callback``.
Args:
callback: The the default callback.
Returns:
The contained value if the :py:class:`Option` is ``Some``,
otherwise `... | keyword[def] identifier[unwrap_or_else] ( identifier[self] , identifier[callback] : identifier[Callable] [[], identifier[U] ])-> identifier[Union] [ identifier[T] , identifier[U] ]:
literal[string]
keyword[return] identifier[self] . identifier[_val] keyword[if] identifier[self] . identifier[_is_... | def unwrap_or_else(self, callback: Callable[[], U]) -> Union[T, U]:
"""
Returns the contained value or computes it from ``callback``.
Args:
callback: The the default callback.
Returns:
The contained value if the :py:class:`Option` is ``Some``,
otherwise ... |
def to_jsonf(self, fpath: str, encoding: str='utf8', indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none... | def function[to_jsonf, parameter[self, fpath, encoding, indent, ignore_none, ignore_empty]]:
constant[From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none: Properties which is None are... | keyword[def] identifier[to_jsonf] ( identifier[self] , identifier[fpath] : identifier[str] , identifier[encoding] : identifier[str] = literal[string] , identifier[indent] : identifier[int] = keyword[None] , identifier[ignore_none] : identifier[bool] = keyword[True] , identifier[ignore_empty] : identifier[bool] = keyw... | def to_jsonf(self, fpath: str, encoding: str='utf8', indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none: Pr... |
def get_rates_from_response_headers(headers):
"""
Returns a namedtuple with values for short - and long usage and limit rates found in provided HTTP response headers
:param headers: HTTP response headers
:type headers: dict
:return: namedtuple with request rates or None if no rate-limit headers pres... | def function[get_rates_from_response_headers, parameter[headers]]:
constant[
Returns a namedtuple with values for short - and long usage and limit rates found in provided HTTP response headers
:param headers: HTTP response headers
:type headers: dict
:return: namedtuple with request rates or Non... | keyword[def] identifier[get_rates_from_response_headers] ( identifier[headers] ):
literal[string]
keyword[try] :
identifier[usage_rates] =[ identifier[int] ( identifier[v] ) keyword[for] identifier[v] keyword[in] identifier[headers] [ literal[string] ]. identifier[split] ( literal[string] )]
... | def get_rates_from_response_headers(headers):
"""
Returns a namedtuple with values for short - and long usage and limit rates found in provided HTTP response headers
:param headers: HTTP response headers
:type headers: dict
:return: namedtuple with request rates or None if no rate-limit headers pres... |
def pull(self):
"""
Pull this image from URL.
:return: None
"""
if not os.path.exists(CONU_IMAGES_STORE):
os.makedirs(CONU_IMAGES_STORE)
logger.debug(
"Try to pull: {} -> {}".format(self.location, self.local_location))
if not self._is_loc... | def function[pull, parameter[self]]:
constant[
Pull this image from URL.
:return: None
]
if <ast.UnaryOp object at 0x7da1b11978b0> begin[:]
call[name[os].makedirs, parameter[name[CONU_IMAGES_STORE]]]
call[name[logger].debug, parameter[call[constant[Try to... | keyword[def] identifier[pull] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[CONU_IMAGES_STORE] ):
identifier[os] . identifier[makedirs] ( identifier[CONU_IMAGES_STORE] )
identifier[logger] .... | def pull(self):
"""
Pull this image from URL.
:return: None
"""
if not os.path.exists(CONU_IMAGES_STORE):
os.makedirs(CONU_IMAGES_STORE) # depends on [control=['if'], data=[]]
logger.debug('Try to pull: {} -> {}'.format(self.location, self.local_location))
if not self._... |
def run(self, N=1, trace_sort=False):
'''Run the sampler, store the history of visited points into
the member variable ``self.samples`` and the importance weights
into ``self.weights``.
.. seealso::
:py:class:`pypmc.tools.History`
:param N:
Integer; the... | def function[run, parameter[self, N, trace_sort]]:
constant[Run the sampler, store the history of visited points into
the member variable ``self.samples`` and the importance weights
into ``self.weights``.
.. seealso::
:py:class:`pypmc.tools.History`
:param N:
... | keyword[def] identifier[run] ( identifier[self] , identifier[N] = literal[int] , identifier[trace_sort] = keyword[False] ):
literal[string]
keyword[if] identifier[N] == literal[int] :
keyword[return] literal[int]
keyword[if] identifier[trace_sort] :
identifie... | def run(self, N=1, trace_sort=False):
"""Run the sampler, store the history of visited points into
the member variable ``self.samples`` and the importance weights
into ``self.weights``.
.. seealso::
:py:class:`pypmc.tools.History`
:param N:
Integer; the num... |
def count_(self):
"""
Returns the number of rows of the main dataframe
"""
try:
num = len(self.df.index)
except Exception as e:
self.err(e, "Can not count data")
return
return num | def function[count_, parameter[self]]:
constant[
Returns the number of rows of the main dataframe
]
<ast.Try object at 0x7da18ede71c0>
return[name[num]] | keyword[def] identifier[count_] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[num] = identifier[len] ( identifier[self] . identifier[df] . identifier[index] )
keyword[except] identifier[Exception] keyword[as] identifier[e] :
identifier[self] .... | def count_(self):
"""
Returns the number of rows of the main dataframe
"""
try:
num = len(self.df.index) # depends on [control=['try'], data=[]]
except Exception as e:
self.err(e, 'Can not count data')
return # depends on [control=['except'], data=['e']]
return ... |
def _to_rest(model, includes=None):
""" Convert the model into a dict for serialization
Notify schematics of the sparse fields requested while
also forcing the resource id & resource type fields to always
be present no matter the request. Additionally, any includes
are implicitly added as well & au... | def function[_to_rest, parameter[model, includes]]:
constant[ Convert the model into a dict for serialization
Notify schematics of the sparse fields requested while
also forcing the resource id & resource type fields to always
be present no matter the request. Additionally, any includes
are imp... | keyword[def] identifier[_to_rest] ( identifier[model] , identifier[includes] = keyword[None] ):
literal[string]
identifier[includes] = identifier[includes] keyword[or] []
identifier[sparse] = identifier[goldman] . identifier[sess] . identifier[req] . identifier[fields] . identifier[get] ( identifier... | def _to_rest(model, includes=None):
""" Convert the model into a dict for serialization
Notify schematics of the sparse fields requested while
also forcing the resource id & resource type fields to always
be present no matter the request. Additionally, any includes
are implicitly added as well & au... |
def is_valid_uid(uid):
"""
:return: True if it is a valid DHIS2 UID, False if not
"""
pattern = r'^[A-Za-z][A-Za-z0-9]{10}$'
if not isinstance(uid, string_types):
return False
return bool(re.compile(pattern).match(uid)) | def function[is_valid_uid, parameter[uid]]:
constant[
:return: True if it is a valid DHIS2 UID, False if not
]
variable[pattern] assign[=] constant[^[A-Za-z][A-Za-z0-9]{10}$]
if <ast.UnaryOp object at 0x7da1b184a500> begin[:]
return[constant[False]]
return[call[name[bool], pa... | keyword[def] identifier[is_valid_uid] ( identifier[uid] ):
literal[string]
identifier[pattern] = literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[uid] , identifier[string_types] ):
keyword[return] keyword[False]
keyword[return] identifier[bool] ( identif... | def is_valid_uid(uid):
"""
:return: True if it is a valid DHIS2 UID, False if not
"""
pattern = '^[A-Za-z][A-Za-z0-9]{10}$'
if not isinstance(uid, string_types):
return False # depends on [control=['if'], data=[]]
return bool(re.compile(pattern).match(uid)) |
def _parse(self, lines, grammar, ignore_comments=False):
""" Given a type and a list, parse it using the more detailed
parse grammar.
"""
results = []
for c in lines:
if c != '' and not (ignore_comments and c[0] == '#'):
try:
result... | def function[_parse, parameter[self, lines, grammar, ignore_comments]]:
constant[ Given a type and a list, parse it using the more detailed
parse grammar.
]
variable[results] assign[=] list[[]]
for taget[name[c]] in starred[name[lines]] begin[:]
if <ast.BoolOp obj... | keyword[def] identifier[_parse] ( identifier[self] , identifier[lines] , identifier[grammar] , identifier[ignore_comments] = keyword[False] ):
literal[string]
identifier[results] =[]
keyword[for] identifier[c] keyword[in] identifier[lines] :
keyword[if] identifier[c] != li... | def _parse(self, lines, grammar, ignore_comments=False):
""" Given a type and a list, parse it using the more detailed
parse grammar.
"""
results = []
for c in lines:
if c != '' and (not (ignore_comments and c[0] == '#')):
try:
results.append(grammar.parse... |
def classifier(self):
""" Returns classifier from classifier.pkl """
clf = pickle.load(open(os.path.join(self.repopath, 'classifier.pkl')))
return clf | def function[classifier, parameter[self]]:
constant[ Returns classifier from classifier.pkl ]
variable[clf] assign[=] call[name[pickle].load, parameter[call[name[open], parameter[call[name[os].path.join, parameter[name[self].repopath, constant[classifier.pkl]]]]]]]
return[name[clf]] | keyword[def] identifier[classifier] ( identifier[self] ):
literal[string]
identifier[clf] = identifier[pickle] . identifier[load] ( identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[repopath] , literal[string] )))
keyword[return] iden... | def classifier(self):
""" Returns classifier from classifier.pkl """
clf = pickle.load(open(os.path.join(self.repopath, 'classifier.pkl')))
return clf |
def _write_to_log(self, output):
"""Write the output string to the log file."""
with open(self.log_file, 'a') as log_file:
log_file.write('\n')
log_file.write(output)
log_file.write('\n') | def function[_write_to_log, parameter[self, output]]:
constant[Write the output string to the log file.]
with call[name[open], parameter[name[self].log_file, constant[a]]] begin[:]
call[name[log_file].write, parameter[constant[
]]]
call[name[log_file].write, parameter[nam... | keyword[def] identifier[_write_to_log] ( identifier[self] , identifier[output] ):
literal[string]
keyword[with] identifier[open] ( identifier[self] . identifier[log_file] , literal[string] ) keyword[as] identifier[log_file] :
identifier[log_file] . identifier[write] ( literal[string]... | def _write_to_log(self, output):
"""Write the output string to the log file."""
with open(self.log_file, 'a') as log_file:
log_file.write('\n')
log_file.write(output)
log_file.write('\n') # depends on [control=['with'], data=['log_file']] |
def getDisplayIdentifier(self):
"""Return the display_identifier if set, else return the claimed_id.
"""
if self.display_identifier is not None:
return self.display_identifier
if self.claimed_id is None:
return None
else:
return urllib.parse.ur... | def function[getDisplayIdentifier, parameter[self]]:
constant[Return the display_identifier if set, else return the claimed_id.
]
if compare[name[self].display_identifier is_not constant[None]] begin[:]
return[name[self].display_identifier]
if compare[name[self].claimed_id is con... | keyword[def] identifier[getDisplayIdentifier] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[display_identifier] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[display_identifier]
keyword[if] ident... | def getDisplayIdentifier(self):
"""Return the display_identifier if set, else return the claimed_id.
"""
if self.display_identifier is not None:
return self.display_identifier # depends on [control=['if'], data=[]]
if self.claimed_id is None:
return None # depends on [control=['if'... |
def get_directory(request):
"""Get API directory as a nested list of lists."""
def get_url(url):
return reverse(url, request=request) if url else url
def is_active_url(path, url):
return path.startswith(url) if url and path else False
path = request.path
directory_list = []
d... | def function[get_directory, parameter[request]]:
constant[Get API directory as a nested list of lists.]
def function[get_url, parameter[url]]:
return[<ast.IfExp object at 0x7da2044c13f0>]
def function[is_active_url, parameter[path, url]]:
return[<ast.IfExp object at 0x7da2044c301... | keyword[def] identifier[get_directory] ( identifier[request] ):
literal[string]
keyword[def] identifier[get_url] ( identifier[url] ):
keyword[return] identifier[reverse] ( identifier[url] , identifier[request] = identifier[request] ) keyword[if] identifier[url] keyword[else] identifier[url] ... | def get_directory(request):
"""Get API directory as a nested list of lists."""
def get_url(url):
return reverse(url, request=request) if url else url
def is_active_url(path, url):
return path.startswith(url) if url and path else False
path = request.path
directory_list = []
de... |
def text_log_steps(self, request, project, pk=None):
"""
Gets a list of steps associated with this job
"""
try:
job = Job.objects.get(repository__name=project,
id=pk)
except ObjectDoesNotExist:
return Response("No job with... | def function[text_log_steps, parameter[self, request, project, pk]]:
constant[
Gets a list of steps associated with this job
]
<ast.Try object at 0x7da1b060c670>
variable[textlog_steps] assign[=] call[call[call[name[TextLogStep].objects.filter, parameter[]].order_by, parameter[consta... | keyword[def] identifier[text_log_steps] ( identifier[self] , identifier[request] , identifier[project] , identifier[pk] = keyword[None] ):
literal[string]
keyword[try] :
identifier[job] = identifier[Job] . identifier[objects] . identifier[get] ( identifier[repository__name] = identifie... | def text_log_steps(self, request, project, pk=None):
"""
Gets a list of steps associated with this job
"""
try:
job = Job.objects.get(repository__name=project, id=pk) # depends on [control=['try'], data=[]]
except ObjectDoesNotExist:
return Response('No job with id: {0}'.for... |
def nlmsg_type(self, value):
"""Message content setter."""
self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0)) | def function[nlmsg_type, parameter[self, value]]:
constant[Message content setter.]
call[name[self].bytearray][call[name[self]._get_slicers, parameter[constant[1]]]] assign[=] call[name[bytearray], parameter[call[name[c_uint16], parameter[<ast.BoolOp object at 0x7da1b26082b0>]]]] | keyword[def] identifier[nlmsg_type] ( identifier[self] , identifier[value] ):
literal[string]
identifier[self] . identifier[bytearray] [ identifier[self] . identifier[_get_slicers] ( literal[int] )]= identifier[bytearray] ( identifier[c_uint16] ( identifier[value] keyword[or] literal[int] )) | def nlmsg_type(self, value):
"""Message content setter."""
self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0)) |
def _allocate_segment(self, session, net_id, source):
"""Allocate segment from pool.
Return allocated db object or None.
"""
with session.begin(subtransactions=True):
hour_lapse = utils.utc_time_lapse(self.seg_timeout)
count = (session.query(self.model).filter(
... | def function[_allocate_segment, parameter[self, session, net_id, source]]:
constant[Allocate segment from pool.
Return allocated db object or None.
]
with call[name[session].begin, parameter[]] begin[:]
variable[hour_lapse] assign[=] call[name[utils].utc_time_lapse, para... | keyword[def] identifier[_allocate_segment] ( identifier[self] , identifier[session] , identifier[net_id] , identifier[source] ):
literal[string]
keyword[with] identifier[session] . identifier[begin] ( identifier[subtransactions] = keyword[True] ):
identifier[hour_lapse] = identifier[... | def _allocate_segment(self, session, net_id, source):
"""Allocate segment from pool.
Return allocated db object or None.
"""
with session.begin(subtransactions=True):
hour_lapse = utils.utc_time_lapse(self.seg_timeout)
count = session.query(self.model).filter(self.model.delete_t... |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Socket(key)
if key not in Socket._member_map_:
extend_enum(Socket, key, default)
return Socket[key] | def function[get, parameter[key, default]]:
constant[Backport support for original codes.]
if call[name[isinstance], parameter[name[key], name[int]]] begin[:]
return[call[name[Socket], parameter[name[key]]]]
if compare[name[key] <ast.NotIn object at 0x7da2590d7190> name[Socket]._member_m... | keyword[def] identifier[get] ( identifier[key] , identifier[default] =- literal[int] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[key] , identifier[int] ):
keyword[return] identifier[Socket] ( identifier[key] )
keyword[if] identifier[key] keyword[not]... | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Socket(key) # depends on [control=['if'], data=[]]
if key not in Socket._member_map_:
extend_enum(Socket, key, default) # depends on [control=['if'], data=['key']]
return Socket[key] |
def saturated_vapor_pressure(t_kelvin):
"""Saturated Vapor Pressure (Pa) at t_kelvin (K).
This function accounts for the different behaviour above vs. below
the freezing point of water.
Note:
[1] W. Wagner and A. Pru:" The IAPWS Formulation 1995 for the Thermodynamic
Properties of Ordi... | def function[saturated_vapor_pressure, parameter[t_kelvin]]:
constant[Saturated Vapor Pressure (Pa) at t_kelvin (K).
This function accounts for the different behaviour above vs. below
the freezing point of water.
Note:
[1] W. Wagner and A. Pru:" The IAPWS Formulation 1995 for the Thermodyn... | keyword[def] identifier[saturated_vapor_pressure] ( identifier[t_kelvin] ):
literal[string]
keyword[if] identifier[t_kelvin] >= literal[int] :
identifier[sig] = literal[int] -( identifier[t_kelvin] / literal[int] )
identifier[sig_polynomial] =(- literal[int] * identifier[sig] )+( l... | def saturated_vapor_pressure(t_kelvin):
"""Saturated Vapor Pressure (Pa) at t_kelvin (K).
This function accounts for the different behaviour above vs. below
the freezing point of water.
Note:
[1] W. Wagner and A. Pru:" The IAPWS Formulation 1995 for the Thermodynamic
Properties of Ordi... |
def confd_state_internal_callpoints_callpoint_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
internal = ET.SubElement(confd_state, "internal")
... | def function[confd_state_internal_callpoints_callpoint_id, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[confd_state] assign[=] call[name[ET].SubElement, parameter[name[config], constant[confd-stat... | keyword[def] identifier[confd_state_internal_callpoints_callpoint_id] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[confd_state] = identifier[ET] . identifier[SubElement] ( identifier[co... | def confd_state_internal_callpoints_callpoint_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
confd_state = ET.SubElement(config, 'confd-state', xmlns='http://tail-f.com/yang/confd-monitoring')
internal = ET.SubElement(confd_state, 'internal')
callpoints = ET.Sub... |
def validate_data_columns(self, data_columns, min_itemsize):
"""take the input data_columns and min_itemize and create a data
columns spec
"""
if not len(self.non_index_axes):
return []
axis, axis_labels = self.non_index_axes[0]
info = self.info.get(axis, di... | def function[validate_data_columns, parameter[self, data_columns, min_itemsize]]:
constant[take the input data_columns and min_itemize and create a data
columns spec
]
if <ast.UnaryOp object at 0x7da1b202ae90> begin[:]
return[list[[]]]
<ast.Tuple object at 0x7da1b2028760>... | keyword[def] identifier[validate_data_columns] ( identifier[self] , identifier[data_columns] , identifier[min_itemsize] ):
literal[string]
keyword[if] keyword[not] identifier[len] ( identifier[self] . identifier[non_index_axes] ):
keyword[return] []
identifier[axis] , iden... | def validate_data_columns(self, data_columns, min_itemsize):
"""take the input data_columns and min_itemize and create a data
columns spec
"""
if not len(self.non_index_axes):
return [] # depends on [control=['if'], data=[]]
(axis, axis_labels) = self.non_index_axes[0]
info = se... |
def open_urlview(self, data):
"""
Pipe a block of text to urlview, which displays a list of urls
contained in the text and allows the user to open them with their
web browser.
"""
urlview = os.getenv('RTV_URLVIEWER') or 'urlview'
command = shlex.split(urlview)
... | def function[open_urlview, parameter[self, data]]:
constant[
Pipe a block of text to urlview, which displays a list of urls
contained in the text and allows the user to open them with their
web browser.
]
variable[urlview] assign[=] <ast.BoolOp object at 0x7da18fe901c0>
... | keyword[def] identifier[open_urlview] ( identifier[self] , identifier[data] ):
literal[string]
identifier[urlview] = identifier[os] . identifier[getenv] ( literal[string] ) keyword[or] literal[string]
identifier[command] = identifier[shlex] . identifier[split] ( identifier[urlview] )
... | def open_urlview(self, data):
"""
Pipe a block of text to urlview, which displays a list of urls
contained in the text and allows the user to open them with their
web browser.
"""
urlview = os.getenv('RTV_URLVIEWER') or 'urlview'
command = shlex.split(urlview)
try:
... |
def run(self):
"""Starts the thread."""
resp = _wait_until(obj=self.obj, att=self.att,
desired=self.desired, callback=None,
interval=self.interval, attempts=self.attempts,
verbose=False, verbose_atts=None)
self.callback(resp) | def function[run, parameter[self]]:
constant[Starts the thread.]
variable[resp] assign[=] call[name[_wait_until], parameter[]]
call[name[self].callback, parameter[name[resp]]] | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[resp] = identifier[_wait_until] ( identifier[obj] = identifier[self] . identifier[obj] , identifier[att] = identifier[self] . identifier[att] ,
identifier[desired] = identifier[self] . identifier[desired] , ident... | def run(self):
"""Starts the thread."""
resp = _wait_until(obj=self.obj, att=self.att, desired=self.desired, callback=None, interval=self.interval, attempts=self.attempts, verbose=False, verbose_atts=None)
self.callback(resp) |
def list(self, **kwargs):
"""
List volumes. Similar to the ``docker volume ls`` command.
Args:
filters (dict): Server-side list filtering options.
Returns:
(list of :py:class:`Volume`): The volumes.
Raises:
:py:class:`docker.errors.APIError`... | def function[list, parameter[self]]:
constant[
List volumes. Similar to the ``docker volume ls`` command.
Args:
filters (dict): Server-side list filtering options.
Returns:
(list of :py:class:`Volume`): The volumes.
Raises:
:py:class:`docker... | keyword[def] identifier[list] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[resp] = identifier[self] . identifier[client] . identifier[api] . identifier[volumes] (** identifier[kwargs] )
keyword[if] keyword[not] identifier[resp] . identifier[get] ( literal[strin... | def list(self, **kwargs):
"""
List volumes. Similar to the ``docker volume ls`` command.
Args:
filters (dict): Server-side list filtering options.
Returns:
(list of :py:class:`Volume`): The volumes.
Raises:
:py:class:`docker.errors.APIError`
... |
def group_id(self):
"""
Returns the @GROUPID.
If derived_from is set, returns that group_id.
"""
if self.derived_from is not None:
return self.derived_from.group_id()
if self.file_uuid is None:
return None
return utils.GROUP_ID_PREFIX + se... | def function[group_id, parameter[self]]:
constant[
Returns the @GROUPID.
If derived_from is set, returns that group_id.
]
if compare[name[self].derived_from is_not constant[None]] begin[:]
return[call[name[self].derived_from.group_id, parameter[]]]
if compare[nam... | keyword[def] identifier[group_id] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[derived_from] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[derived_from] . identifier[group_id] ()
keyword[if] iden... | def group_id(self):
"""
Returns the @GROUPID.
If derived_from is set, returns that group_id.
"""
if self.derived_from is not None:
return self.derived_from.group_id() # depends on [control=['if'], data=[]]
if self.file_uuid is None:
return None # depends on [contro... |
def minify(path):
"""
Load a javascript file and minify.
Parameters
------------
path: str, path of resource
"""
if 'http' in path:
data = requests.get(path).content.decode(
'ascii', errors='ignore')
else:
with open(path, 'rb') as f:
# some of th... | def function[minify, parameter[path]]:
constant[
Load a javascript file and minify.
Parameters
------------
path: str, path of resource
]
if compare[constant[http] in name[path]] begin[:]
variable[data] assign[=] call[call[name[requests].get, parameter[name[path]]].c... | keyword[def] identifier[minify] ( identifier[path] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[path] :
identifier[data] = identifier[requests] . identifier[get] ( identifier[path] ). identifier[content] . identifier[decode] (
literal[string] , identifier[erro... | def minify(path):
"""
Load a javascript file and minify.
Parameters
------------
path: str, path of resource
"""
if 'http' in path:
data = requests.get(path).content.decode('ascii', errors='ignore') # depends on [control=['if'], data=['path']]
else:
with open(path, 'rb'... |
def _generate_version(base_version):
"""Generate a version with information about the git repository"""
pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if not _is_git_repo(pkg_dir) or not _have_git():
return base_version
if _is_release(pkg_dir, base_version) and not _is_d... | def function[_generate_version, parameter[base_version]]:
constant[Generate a version with information about the git repository]
variable[pkg_dir] assign[=] call[name[os].path.abspath, parameter[call[name[os].path.dirname, parameter[call[name[os].path.dirname, parameter[name[__file__]]]]]]]
if <... | keyword[def] identifier[_generate_version] ( identifier[base_version] ):
literal[string]
identifier[pkg_dir] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] )... | def _generate_version(base_version):
"""Generate a version with information about the git repository"""
pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if not _is_git_repo(pkg_dir) or not _have_git():
return base_version # depends on [control=['if'], data=[]]
if _is_releas... |
def media(self):
"""
Incooperate composite field's media.
"""
media_list = []
media_list.append(super(SuperFormMixin, self).media)
for composite_name in self.composite_fields.keys():
form = self.get_composite_field_value(composite_name)
media_list.... | def function[media, parameter[self]]:
constant[
Incooperate composite field's media.
]
variable[media_list] assign[=] list[[]]
call[name[media_list].append, parameter[call[name[super], parameter[name[SuperFormMixin], name[self]]].media]]
for taget[name[composite_name]] in... | keyword[def] identifier[media] ( identifier[self] ):
literal[string]
identifier[media_list] =[]
identifier[media_list] . identifier[append] ( identifier[super] ( identifier[SuperFormMixin] , identifier[self] ). identifier[media] )
keyword[for] identifier[composite_name] keyword[... | def media(self):
"""
Incooperate composite field's media.
"""
media_list = []
media_list.append(super(SuperFormMixin, self).media)
for composite_name in self.composite_fields.keys():
form = self.get_composite_field_value(composite_name)
media_list.append(form.media) # de... |
def get_account_entitlement_for_user(self, user_id, determine_rights=None, create_if_not_exists=None):
"""GetAccountEntitlementForUser.
[Preview API] Get the entitlements for a user
:param str user_id: The id of the user
:param bool determine_rights:
:param bool create_if_not_exi... | def function[get_account_entitlement_for_user, parameter[self, user_id, determine_rights, create_if_not_exists]]:
constant[GetAccountEntitlementForUser.
[Preview API] Get the entitlements for a user
:param str user_id: The id of the user
:param bool determine_rights:
:param bool ... | keyword[def] identifier[get_account_entitlement_for_user] ( identifier[self] , identifier[user_id] , identifier[determine_rights] = keyword[None] , identifier[create_if_not_exists] = keyword[None] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[user_id] keyword[is]... | def get_account_entitlement_for_user(self, user_id, determine_rights=None, create_if_not_exists=None):
"""GetAccountEntitlementForUser.
[Preview API] Get the entitlements for a user
:param str user_id: The id of the user
:param bool determine_rights:
:param bool create_if_not_exists:... |
def field2read_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.dump_only:
attributes["readOnly"] = True
return ... | def function[field2read_only, parameter[self, field]]:
constant[Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict
]
variable[attributes] assign[=] dictionary[[], []]
if name[field].dump_only beg... | keyword[def] identifier[field2read_only] ( identifier[self] , identifier[field] ,** identifier[kwargs] ):
literal[string]
identifier[attributes] ={}
keyword[if] identifier[field] . identifier[dump_only] :
identifier[attributes] [ literal[string] ]= keyword[True]
key... | def field2read_only(self, field, **kwargs):
"""Return the dictionary of OpenAPI field attributes for a dump_only field.
:param Field field: A marshmallow field.
:rtype: dict
"""
attributes = {}
if field.dump_only:
attributes['readOnly'] = True # depends on [control=['if'], ... |
def get_entry_map(self, group=None):
"""Return the entry point map for `group`, or the full entry map"""
try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(
self._get_metadata('entry_points.txt'), self
... | def function[get_entry_map, parameter[self, group]]:
constant[Return the entry point map for `group`, or the full entry map]
<ast.Try object at 0x7da2041d93c0>
if compare[name[group] is_not constant[None]] begin[:]
return[call[name[ep_map].get, parameter[name[group], dictionary[[], []]]]]
... | keyword[def] identifier[get_entry_map] ( identifier[self] , identifier[group] = keyword[None] ):
literal[string]
keyword[try] :
identifier[ep_map] = identifier[self] . identifier[_ep_map]
keyword[except] identifier[AttributeError] :
identifier[ep_map] = identifi... | def get_entry_map(self, group=None):
"""Return the entry point map for `group`, or the full entry map"""
try:
ep_map = self._ep_map # depends on [control=['try'], data=[]]
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self) # de... |
def send_object(bucket, obj, expected_chksum=None,
logger_data=None, restricted=True, as_attachment=False):
"""Send an object for a given bucket.
:param bucket: The bucket (instance or id) to get the object from.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion`... | def function[send_object, parameter[bucket, obj, expected_chksum, logger_data, restricted, as_attachment]]:
constant[Send an object for a given bucket.
:param bucket: The bucket (instance or id) to get the object from.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion`
i... | keyword[def] identifier[send_object] ( identifier[bucket] , identifier[obj] , identifier[expected_chksum] = keyword[None] ,
identifier[logger_data] = keyword[None] , identifier[restricted] = keyword[True] , identifier[as_attachment] = keyword[False] ):
literal[string]
keyword[if] keyword[not] id... | def send_object(bucket, obj, expected_chksum=None, logger_data=None, restricted=True, as_attachment=False):
"""Send an object for a given bucket.
:param bucket: The bucket (instance or id) to get the object from.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion`
instance.
... |
def resolve_parameter_refs(self, input):
"""
Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as
!GetAtt, !Sub or !Ref to non-parameters will be left untouched.
Result is a dictionary where parameter values are inlined. Don't pass... | def function[resolve_parameter_refs, parameter[self, input]]:
constant[
Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as
!GetAtt, !Sub or !Ref to non-parameters will be left untouched.
Result is a dictionary where parameter val... | keyword[def] identifier[resolve_parameter_refs] ( identifier[self] , identifier[input] ):
literal[string]
keyword[return] identifier[self] . identifier[_traverse] ( identifier[input] , identifier[self] . identifier[parameters] , identifier[self] . identifier[_try_resolve_parameter_refs] ) | def resolve_parameter_refs(self, input):
"""
Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as
!GetAtt, !Sub or !Ref to non-parameters will be left untouched.
Result is a dictionary where parameter values are inlined. Don't pass thi... |
def from_isodate(value, strict=False):
"""Convert an ISO formatted date into a Date object.
:param value: The ISO formatted date.
:param strict: If value is ``None``, then if strict is ``True`` it returns
the Date object of today, otherwise it returns ``None``.
(Default: ``False``)
:ret... | def function[from_isodate, parameter[value, strict]]:
constant[Convert an ISO formatted date into a Date object.
:param value: The ISO formatted date.
:param strict: If value is ``None``, then if strict is ``True`` it returns
the Date object of today, otherwise it returns ``None``.
(Def... | keyword[def] identifier[from_isodate] ( identifier[value] , identifier[strict] = keyword[False] ):
literal[string]
keyword[if] identifier[value] keyword[or] identifier[strict] :
keyword[return] identifier[arrow] . identifier[get] ( identifier[value] ). identifier[date] () | def from_isodate(value, strict=False):
"""Convert an ISO formatted date into a Date object.
:param value: The ISO formatted date.
:param strict: If value is ``None``, then if strict is ``True`` it returns
the Date object of today, otherwise it returns ``None``.
(Default: ``False``)
:ret... |
def online(zpool, *vdevs, **kwargs):
'''
.. versionadded:: 2015.5.0
Ensure that the specified devices are online
zpool : string
name of storage pool
vdevs : string
one or more devices
expand : boolean
Expand the device to use all available space.
.. note::
... | def function[online, parameter[zpool]]:
constant[
.. versionadded:: 2015.5.0
Ensure that the specified devices are online
zpool : string
name of storage pool
vdevs : string
one or more devices
expand : boolean
Expand the device to use all available space.
... | keyword[def] identifier[online] ( identifier[zpool] ,* identifier[vdevs] ,** identifier[kwargs] ):
literal[string]
identifier[flags] =[]
identifier[target] =[]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] ):
identifier[flags] . iden... | def online(zpool, *vdevs, **kwargs):
"""
.. versionadded:: 2015.5.0
Ensure that the specified devices are online
zpool : string
name of storage pool
vdevs : string
one or more devices
expand : boolean
Expand the device to use all available space.
.. note::
... |
async def get_nym_role(self, target_did: str = None) -> Role:
"""
Return the cryptonym role for input did from the ledger - note that this may exceed
the role of least privilege for the class.
Raise AbsentNym if current anchor has no cryptonym on the ledger, or WalletState if current DI... | <ast.AsyncFunctionDef object at 0x7da20e74beb0> | keyword[async] keyword[def] identifier[get_nym_role] ( identifier[self] , identifier[target_did] : identifier[str] = keyword[None] )-> identifier[Role] :
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] , identifier[target_did] )
identifier[nym] = identifier[json... | async def get_nym_role(self, target_did: str=None) -> Role:
"""
Return the cryptonym role for input did from the ledger - note that this may exceed
the role of least privilege for the class.
Raise AbsentNym if current anchor has no cryptonym on the ledger, or WalletState if current DID unav... |
def get_addr_of_native_method(self, soot_method):
"""
Get address of the implementation from a native declared Java function.
:param soot_method: Method descriptor of a native declared function.
:return: CLE address of the given method.
"""
for name, symbol in self.nativ... | def function[get_addr_of_native_method, parameter[self, soot_method]]:
constant[
Get address of the implementation from a native declared Java function.
:param soot_method: Method descriptor of a native declared function.
:return: CLE address of the given method.
]
for t... | keyword[def] identifier[get_addr_of_native_method] ( identifier[self] , identifier[soot_method] ):
literal[string]
keyword[for] identifier[name] , identifier[symbol] keyword[in] identifier[self] . identifier[native_symbols] . identifier[items] ():
keyword[if] identifier[soot_method... | def get_addr_of_native_method(self, soot_method):
"""
Get address of the implementation from a native declared Java function.
:param soot_method: Method descriptor of a native declared function.
:return: CLE address of the given method.
"""
for (name, symbol) in self.native_symb... |
def set_throttle(self, name):
""" Assign to throttle group.
"""
if name.lower() == "null":
name = "NULL"
if name.lower() == "none":
name = ''
if name not in self._engine.known_throttle_names:
if self._engine._rpc.throttle.up.max(xmlrpc.NOHASH,... | def function[set_throttle, parameter[self, name]]:
constant[ Assign to throttle group.
]
if compare[call[name[name].lower, parameter[]] equal[==] constant[null]] begin[:]
variable[name] assign[=] constant[NULL]
if compare[call[name[name].lower, parameter[]] equal[==] cons... | keyword[def] identifier[set_throttle] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[name] . identifier[lower] ()== literal[string] :
identifier[name] = literal[string]
keyword[if] identifier[name] . identifier[lower] ()== literal[string] :
... | def set_throttle(self, name):
""" Assign to throttle group.
"""
if name.lower() == 'null':
name = 'NULL' # depends on [control=['if'], data=[]]
if name.lower() == 'none':
name = '' # depends on [control=['if'], data=[]]
if name not in self._engine.known_throttle_names:
... |
def _log_images(self):
"""Creates database logs for all the image file names in the global
variable :data:`thumb_uuid`.
"""
from time import time
from acorn.logging.database import record
entry = {
"m": "plot",
"a": None,
"s": t... | def function[_log_images, parameter[self]]:
constant[Creates database logs for all the image file names in the global
variable :data:`thumb_uuid`.
]
from relative_module[time] import module[time]
from relative_module[acorn.logging.database] import module[record]
variable[entry] a... | keyword[def] identifier[_log_images] ( identifier[self] ):
literal[string]
keyword[from] identifier[time] keyword[import] identifier[time]
keyword[from] identifier[acorn] . identifier[logging] . identifier[database] keyword[import] identifier[record]
identifier[entry] ={
... | def _log_images(self):
"""Creates database logs for all the image file names in the global
variable :data:`thumb_uuid`.
"""
from time import time
from acorn.logging.database import record
entry = {'m': 'plot', 'a': None, 's': time(), 'r': thumb_uuid}
#See if we can match the executed... |
def commit(self, message, author=None):
"""
Commit changes to tracked files in the working tree.
:param message: The commit message (a string).
:param author: Override :attr:`author` (refer to
:func:`coerce_author()` for details
on argument ... | def function[commit, parameter[self, message, author]]:
constant[
Commit changes to tracked files in the working tree.
:param message: The commit message (a string).
:param author: Override :attr:`author` (refer to
:func:`coerce_author()` for details
... | keyword[def] identifier[commit] ( identifier[self] , identifier[message] , identifier[author] = keyword[None] ):
literal[string]
identifier[self] . identifier[ensure_exists] ()
identifier[self] . identifier[ensure_working_tree] ()
identifier[logger] . identifier[info] ( l... | def commit(self, message, author=None):
"""
Commit changes to tracked files in the working tree.
:param message: The commit message (a string).
:param author: Override :attr:`author` (refer to
:func:`coerce_author()` for details
on argument hand... |
def xopen(filename, mode='r', compresslevel=6, threads=None):
"""
A replacement for the "open" function that can also open files that have
been compressed with gzip, bzip2 or xz. If the filename is '-', standard
output (mode 'w') or input (mode 'r') is returned.
The file type is determined based on... | def function[xopen, parameter[filename, mode, compresslevel, threads]]:
constant[
A replacement for the "open" function that can also open files that have
been compressed with gzip, bzip2 or xz. If the filename is '-', standard
output (mode 'w') or input (mode 'r') is returned.
The file type is... | keyword[def] identifier[xopen] ( identifier[filename] , identifier[mode] = literal[string] , identifier[compresslevel] = literal[int] , identifier[threads] = keyword[None] ):
literal[string]
keyword[if] identifier[mode] keyword[in] ( literal[string] , literal[string] , literal[string] ):
identif... | def xopen(filename, mode='r', compresslevel=6, threads=None):
"""
A replacement for the "open" function that can also open files that have
been compressed with gzip, bzip2 or xz. If the filename is '-', standard
output (mode 'w') or input (mode 'r') is returned.
The file type is determined based on... |
def _mixup( self, ps ):
"""Private method to mix up a list of values in-place using a Fisher-Yates
shuffle (see https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
:param ps: the array
:returns: the array, shuffled in-place"""
for i in range(len(ps) - 1, 0, -1):
j =... | def function[_mixup, parameter[self, ps]]:
constant[Private method to mix up a list of values in-place using a Fisher-Yates
shuffle (see https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
:param ps: the array
:returns: the array, shuffled in-place]
for taget[name[i]] in starre... | keyword[def] identifier[_mixup] ( identifier[self] , identifier[ps] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[ps] )- literal[int] , literal[int] ,- literal[int] ):
identifier[j] = identifier[int] ( identifier[numpy] . ... | def _mixup(self, ps):
"""Private method to mix up a list of values in-place using a Fisher-Yates
shuffle (see https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
:param ps: the array
:returns: the array, shuffled in-place"""
for i in range(len(ps) - 1, 0, -1):
j = int(numpy.ran... |
def from_dict(self, description):
"""Configures the task store to be the task_store described
in description"""
assert(self.ident == description['ident'])
self.partitions = description['partitions']
self.indices = description['indices'] | def function[from_dict, parameter[self, description]]:
constant[Configures the task store to be the task_store described
in description]
assert[compare[name[self].ident equal[==] call[name[description]][constant[ident]]]]
name[self].partitions assign[=] call[name[description]][constant[... | keyword[def] identifier[from_dict] ( identifier[self] , identifier[description] ):
literal[string]
keyword[assert] ( identifier[self] . identifier[ident] == identifier[description] [ literal[string] ])
identifier[self] . identifier[partitions] = identifier[description] [ literal[string] ]
... | def from_dict(self, description):
"""Configures the task store to be the task_store described
in description"""
assert self.ident == description['ident']
self.partitions = description['partitions']
self.indices = description['indices'] |
def print_help(self, prog_name, subcommand):
"""
Print the help message for this command, derived from
``self.usage()``.
"""
parser = self.create_parser(prog_name, subcommand)
parser.print_help() | def function[print_help, parameter[self, prog_name, subcommand]]:
constant[
Print the help message for this command, derived from
``self.usage()``.
]
variable[parser] assign[=] call[name[self].create_parser, parameter[name[prog_name], name[subcommand]]]
call[name[par... | keyword[def] identifier[print_help] ( identifier[self] , identifier[prog_name] , identifier[subcommand] ):
literal[string]
identifier[parser] = identifier[self] . identifier[create_parser] ( identifier[prog_name] , identifier[subcommand] )
identifier[parser] . identifier[print_help] () | def print_help(self, prog_name, subcommand):
"""
Print the help message for this command, derived from
``self.usage()``.
"""
parser = self.create_parser(prog_name, subcommand)
parser.print_help() |
def solve_gcp(V,E):
"""solve_gcp -- solve the graph coloring problem with bisection and fixed-k model
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns tuple with number of colors used, and dictionary mapping colors to vertices
"""
LB = 0
... | def function[solve_gcp, parameter[V, E]]:
constant[solve_gcp -- solve the graph coloring problem with bisection and fixed-k model
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns tuple with number of colors used, and dictionary mapping colors to... | keyword[def] identifier[solve_gcp] ( identifier[V] , identifier[E] ):
literal[string]
identifier[LB] = literal[int]
identifier[UB] = identifier[len] ( identifier[V] )
identifier[color] ={}
keyword[while] identifier[UB] - identifier[LB] > literal[int] :
identifier[K] = identifier[i... | def solve_gcp(V, E):
"""solve_gcp -- solve the graph coloring problem with bisection and fixed-k model
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
Returns tuple with number of colors used, and dictionary mapping colors to vertices
"""
LB = 0
... |
def consume(self, cwd=None):
""" Converts the lexer tokens into valid statements. This process
also checks command syntax.
"""
first_pass = Grammar.overall.parseString(self.string)
lowered = { key.lower(): val for key, val in first_pass.iteritems() }
self.commands = ['\n... | def function[consume, parameter[self, cwd]]:
constant[ Converts the lexer tokens into valid statements. This process
also checks command syntax.
]
variable[first_pass] assign[=] call[name[Grammar].overall.parseString, parameter[name[self].string]]
variable[lowered] assign[=] <ast... | keyword[def] identifier[consume] ( identifier[self] , identifier[cwd] = keyword[None] ):
literal[string]
identifier[first_pass] = identifier[Grammar] . identifier[overall] . identifier[parseString] ( identifier[self] . identifier[string] )
identifier[lowered] ={ identifier[key] . identifie... | def consume(self, cwd=None):
""" Converts the lexer tokens into valid statements. This process
also checks command syntax.
"""
first_pass = Grammar.overall.parseString(self.string)
lowered = {key.lower(): val for (key, val) in first_pass.iteritems()}
self.commands = ['\n'.join(self._get(... |
def hydrate(self, iterator):
"""
Pass in an iterator of tweet ids and get back an iterator for the
decoded JSON for each corresponding tweet.
"""
ids = []
url = "https://api.twitter.com/1.1/statuses/lookup.json"
# lookup 100 tweets at a time
for tweet_id ... | def function[hydrate, parameter[self, iterator]]:
constant[
Pass in an iterator of tweet ids and get back an iterator for the
decoded JSON for each corresponding tweet.
]
variable[ids] assign[=] list[[]]
variable[url] assign[=] constant[https://api.twitter.com/1.1/statuse... | keyword[def] identifier[hydrate] ( identifier[self] , identifier[iterator] ):
literal[string]
identifier[ids] =[]
identifier[url] = literal[string]
keyword[for] identifier[tweet_id] keyword[in] identifier[iterator] :
identifier[tweet_id] = identifier[str... | def hydrate(self, iterator):
"""
Pass in an iterator of tweet ids and get back an iterator for the
decoded JSON for each corresponding tweet.
"""
ids = []
url = 'https://api.twitter.com/1.1/statuses/lookup.json'
# lookup 100 tweets at a time
for tweet_id in iterator:
... |
def usermacro_delete(macroids, **kwargs):
'''
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be se... | def function[usermacro_delete, parameter[macroids]]:
constant[
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix pas... | keyword[def] identifier[usermacro_delete] ( identifier[macroids] ,** identifier[kwargs] ):
literal[string]
identifier[conn_args] = identifier[_login] (** identifier[kwargs] )
identifier[ret] ={}
keyword[try] :
keyword[if] identifier[conn_args] :
identifier[method] = literal... | def usermacro_delete(macroids, **kwargs):
"""
Delete host usermacros.
:param macroids: macroids of the host usermacros
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be se... |
def checkout_branch(self, branch_name):
""" git checkout -b <branch_name> """
cmd = [
"git",
"checkout",
"-b",
self.get_cherry_pick_branch(branch_name),
f"{self.upstream}/{branch_name}",
]
try:
self.run_cmd(cmd)
... | def function[checkout_branch, parameter[self, branch_name]]:
constant[ git checkout -b <branch_name> ]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b230a4a0>, <ast.Constant object at 0x7da1b230a440>, <ast.Constant object at 0x7da1b2308d00>, <ast.Call object at 0x7da1b2308cd0>, <ast.Joined... | keyword[def] identifier[checkout_branch] ( identifier[self] , identifier[branch_name] ):
literal[string]
identifier[cmd] =[
literal[string] ,
literal[string] ,
literal[string] ,
identifier[self] . identifier[get_cherry_pick_branch] ( identifier[branch_name] ),
... | def checkout_branch(self, branch_name):
""" git checkout -b <branch_name> """
cmd = ['git', 'checkout', '-b', self.get_cherry_pick_branch(branch_name), f'{self.upstream}/{branch_name}']
try:
self.run_cmd(cmd) # depends on [control=['try'], data=[]]
except subprocess.CalledProcessError as err:
... |
def get(self, key):
"Find the first value within the tree which has the key."
if key in self.keys():
return self[key]
else:
res = None
for v in self.values():
# This could get weird if the actual expected returned value
# is Non... | def function[get, parameter[self, key]]:
constant[Find the first value within the tree which has the key.]
if compare[name[key] in call[name[self].keys, parameter[]]] begin[:]
return[call[name[self]][name[key]]] | keyword[def] identifier[get] ( identifier[self] , identifier[key] ):
literal[string]
keyword[if] identifier[key] keyword[in] identifier[self] . identifier[keys] ():
keyword[return] identifier[self] [ identifier[key] ]
keyword[else] :
identifier[res] = keyword[... | def get(self, key):
"""Find the first value within the tree which has the key."""
if key in self.keys():
return self[key] # depends on [control=['if'], data=['key']]
else:
res = None
for v in self.values():
# This could get weird if the actual expected returned value
... |
def _encode_chunk(self, data, index):
'''
gets a chunk from the input data, converts it to a number and
encodes that number
'''
chunk = self._get_chunk(data, index)
return self._encode_long(self._chunk_to_long(chunk)) | def function[_encode_chunk, parameter[self, data, index]]:
constant[
gets a chunk from the input data, converts it to a number and
encodes that number
]
variable[chunk] assign[=] call[name[self]._get_chunk, parameter[name[data], name[index]]]
return[call[name[self]._encode_lo... | keyword[def] identifier[_encode_chunk] ( identifier[self] , identifier[data] , identifier[index] ):
literal[string]
identifier[chunk] = identifier[self] . identifier[_get_chunk] ( identifier[data] , identifier[index] )
keyword[return] identifier[self] . identifier[_encode_long] ( identifi... | def _encode_chunk(self, data, index):
"""
gets a chunk from the input data, converts it to a number and
encodes that number
"""
chunk = self._get_chunk(data, index)
return self._encode_long(self._chunk_to_long(chunk)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.