code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _set_bridge(self, v, load=False):
"""
Setter method for bridge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/bridge (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bridge is considered as a private
... | def function[_set_bridge, parameter[self, v, load]]:
constant[
Setter method for bridge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/bridge (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bridge is co... | keyword[def] identifier[_set_bridge] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identif... | def _set_bridge(self, v, load=False):
"""
Setter method for bridge, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info/output/spanning_tree_info/pvstp/bridge (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bridge is considered as a private
... |
def preorder(self):
""" iterator for nodes: root, left, right """
if not self:
return
yield self
if self.left:
for x in self.left.preorder():
yield x
if self.right:
for x in self.right.preorder():
yield x | def function[preorder, parameter[self]]:
constant[ iterator for nodes: root, left, right ]
if <ast.UnaryOp object at 0x7da1b05089a0> begin[:]
return[None]
<ast.Yield object at 0x7da1b0509060>
if name[self].left begin[:]
for taget[name[x]] in starred[call[name[self... | keyword[def] identifier[preorder] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] :
keyword[return]
keyword[yield] identifier[self]
keyword[if] identifier[self] . identifier[left] :
keyword[for] identifier[x] key... | def preorder(self):
""" iterator for nodes: root, left, right """
if not self:
return # depends on [control=['if'], data=[]]
yield self
if self.left:
for x in self.left.preorder():
yield x # depends on [control=['for'], data=['x']] # depends on [control=['if'], data=[]]
... |
def check_call(cmd_args):
"""
Calls the command
Parameters
----------
cmd_args: list of str
Command name to call and its arguments in a list.
Returns
-------
Command output
"""
p = subprocess.Popen(cmd_args, stdout=subprocess.PIPE)
(output, err) = p.communicate()
... | def function[check_call, parameter[cmd_args]]:
constant[
Calls the command
Parameters
----------
cmd_args: list of str
Command name to call and its arguments in a list.
Returns
-------
Command output
]
variable[p] assign[=] call[name[subprocess].Popen, parameter... | keyword[def] identifier[check_call] ( identifier[cmd_args] ):
literal[string]
identifier[p] = identifier[subprocess] . identifier[Popen] ( identifier[cmd_args] , identifier[stdout] = identifier[subprocess] . identifier[PIPE] )
( identifier[output] , identifier[err] )= identifier[p] . identifier[communi... | def check_call(cmd_args):
"""
Calls the command
Parameters
----------
cmd_args: list of str
Command name to call and its arguments in a list.
Returns
-------
Command output
"""
p = subprocess.Popen(cmd_args, stdout=subprocess.PIPE)
(output, err) = p.communicate()
... |
def get_rg_from_id(vmss_id):
'''get a resource group name from a VMSS ID string'''
rgname = re.search('Groups/(.+?)/providers', vmss_id).group(1)
print('Resource group: ' + rgname)
return rgname | def function[get_rg_from_id, parameter[vmss_id]]:
constant[get a resource group name from a VMSS ID string]
variable[rgname] assign[=] call[call[name[re].search, parameter[constant[Groups/(.+?)/providers], name[vmss_id]]].group, parameter[constant[1]]]
call[name[print], parameter[binary_operatio... | keyword[def] identifier[get_rg_from_id] ( identifier[vmss_id] ):
literal[string]
identifier[rgname] = identifier[re] . identifier[search] ( literal[string] , identifier[vmss_id] ). identifier[group] ( literal[int] )
identifier[print] ( literal[string] + identifier[rgname] )
keyword[return] ident... | def get_rg_from_id(vmss_id):
"""get a resource group name from a VMSS ID string"""
rgname = re.search('Groups/(.+?)/providers', vmss_id).group(1)
print('Resource group: ' + rgname)
return rgname |
def curie(path_to_file='.', file_name='', magic=False,
window_length=3, save=False, save_folder='.', fmt='svg', t_begin="", t_end=""):
"""
Plots and interprets curie temperature data.
***
The 1st derivative is calculated from smoothed M-T curve (convolution
with trianfular window with widt... | def function[curie, parameter[path_to_file, file_name, magic, window_length, save, save_folder, fmt, t_begin, t_end]]:
constant[
Plots and interprets curie temperature data.
***
The 1st derivative is calculated from smoothed M-T curve (convolution
with trianfular window with width= <-w> degrees)... | keyword[def] identifier[curie] ( identifier[path_to_file] = literal[string] , identifier[file_name] = literal[string] , identifier[magic] = keyword[False] ,
identifier[window_length] = literal[int] , identifier[save] = keyword[False] , identifier[save_folder] = literal[string] , identifier[fmt] = literal[string] , i... | def curie(path_to_file='.', file_name='', magic=False, window_length=3, save=False, save_folder='.', fmt='svg', t_begin='', t_end=''):
"""
Plots and interprets curie temperature data.
***
The 1st derivative is calculated from smoothed M-T curve (convolution
with trianfular window with width= <-w> de... |
def _tensor_product(self, other, reverse=False):
"""Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel subclass.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False... | def function[_tensor_product, parameter[self, other, reverse]]:
constant[Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel subclass.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ ... | keyword[def] identifier[_tensor_product] ( identifier[self] , identifier[other] , identifier[reverse] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[other] , identifier[Kraus] ):
identifier[other] = identifier[Kraus] ( identi... | def _tensor_product(self, other, reverse=False):
"""Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel subclass.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False
... |
def dirs(self, pattern=None):
""" D.dirs() -> List of this directory's subdirectories.
The elements of the list are Path objects.
This does not walk recursively into subdirectories
(but see :meth:`walkdirs`).
With the optional `pattern` argument, this only lists
directo... | def function[dirs, parameter[self, pattern]]:
constant[ D.dirs() -> List of this directory's subdirectories.
The elements of the list are Path objects.
This does not walk recursively into subdirectories
(but see :meth:`walkdirs`).
With the optional `pattern` argument, this only... | keyword[def] identifier[dirs] ( identifier[self] , identifier[pattern] = keyword[None] ):
literal[string]
keyword[return] [ identifier[p] keyword[for] identifier[p] keyword[in] identifier[self] . identifier[listdir] ( identifier[pattern] ) keyword[if] identifier[p] . identifier[isdir] ()] | def dirs(self, pattern=None):
""" D.dirs() -> List of this directory's subdirectories.
The elements of the list are Path objects.
This does not walk recursively into subdirectories
(but see :meth:`walkdirs`).
With the optional `pattern` argument, this only lists
directories... |
def get_list_w_id2nts(ids, id2nts, flds, dflt_null=""):
"""Return a new list of namedtuples by combining "dicts" of namedtuples or objects."""
combined_nt_list = []
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple("Nt", " ".join(flds))
# 2. Fill dict with namedtuple objects for desired ids
... | def function[get_list_w_id2nts, parameter[ids, id2nts, flds, dflt_null]]:
constant[Return a new list of namedtuples by combining "dicts" of namedtuples or objects.]
variable[combined_nt_list] assign[=] list[[]]
variable[ntobj] assign[=] call[name[cx].namedtuple, parameter[constant[Nt], call[cons... | keyword[def] identifier[get_list_w_id2nts] ( identifier[ids] , identifier[id2nts] , identifier[flds] , identifier[dflt_null] = literal[string] ):
literal[string]
identifier[combined_nt_list] =[]
identifier[ntobj] = identifier[cx] . identifier[namedtuple] ( literal[string] , literal[string] . iden... | def get_list_w_id2nts(ids, id2nts, flds, dflt_null=''):
"""Return a new list of namedtuples by combining "dicts" of namedtuples or objects."""
combined_nt_list = []
# 1. Instantiate namedtuple object
ntobj = cx.namedtuple('Nt', ' '.join(flds))
# 2. Fill dict with namedtuple objects for desired ids
... |
def find_spec(self, fullname, path, target=None):
"""
Claims modules that are under ipynb.fs
"""
if fullname.startswith(self.package_prefix):
for path in self._get_paths(fullname):
if os.path.exists(path):
return ModuleSpec(
... | def function[find_spec, parameter[self, fullname, path, target]]:
constant[
Claims modules that are under ipynb.fs
]
if call[name[fullname].startswith, parameter[name[self].package_prefix]] begin[:]
for taget[name[path]] in starred[call[name[self]._get_paths, parameter[na... | keyword[def] identifier[find_spec] ( identifier[self] , identifier[fullname] , identifier[path] , identifier[target] = keyword[None] ):
literal[string]
keyword[if] identifier[fullname] . identifier[startswith] ( identifier[self] . identifier[package_prefix] ):
keyword[for] identifier... | def find_spec(self, fullname, path, target=None):
"""
Claims modules that are under ipynb.fs
"""
if fullname.startswith(self.package_prefix):
for path in self._get_paths(fullname):
if os.path.exists(path):
return ModuleSpec(name=fullname, loader=self.loader_cl... |
def _send_block_request(self, transaction):
"""
A former request resulted in a block wise transfer. With this method, the block wise transfer
will be continued, including triggering of the retry mechanism.
:param transaction: The former transaction including the request which sh... | def function[_send_block_request, parameter[self, transaction]]:
constant[
A former request resulted in a block wise transfer. With this method, the block wise transfer
will be continued, including triggering of the retry mechanism.
:param transaction: The former transaction inc... | keyword[def] identifier[_send_block_request] ( identifier[self] , identifier[transaction] ):
literal[string]
identifier[transaction] = identifier[self] . identifier[_messageLayer] . identifier[send_request] ( identifier[transaction] . identifier[request] )
identifier[transaction] ... | def _send_block_request(self, transaction):
"""
A former request resulted in a block wise transfer. With this method, the block wise transfer
will be continued, including triggering of the retry mechanism.
:param transaction: The former transaction including the request which should... |
def make_tarball(
base_name,
base_dir,
compress="gzip",
verbose=0,
dry_run=0,
owner=None,
group=None,
):
"""Create a tar file from all the files under 'base_dir'.
This file may be compressed.
:param compress: Compression algorithms. Supported algorithms are:
'gzip': (the... | def function[make_tarball, parameter[base_name, base_dir, compress, verbose, dry_run, owner, group]]:
constant[Create a tar file from all the files under 'base_dir'.
This file may be compressed.
:param compress: Compression algorithms. Supported algorithms are:
'gzip': (the default)
'co... | keyword[def] identifier[make_tarball] (
identifier[base_name] ,
identifier[base_dir] ,
identifier[compress] = literal[string] ,
identifier[verbose] = literal[int] ,
identifier[dry_run] = literal[int] ,
identifier[owner] = keyword[None] ,
identifier[group] = keyword[None] ,
):
literal[string]
... | def make_tarball(base_name, base_dir, compress='gzip', verbose=0, dry_run=0, owner=None, group=None):
"""Create a tar file from all the files under 'base_dir'.
This file may be compressed.
:param compress: Compression algorithms. Supported algorithms are:
'gzip': (the default)
'compress'
... |
def _compute_resized_shape(from_shape, to_shape):
"""
Computes the intended new shape of an image-like array after resizing.
Parameters
----------
from_shape : tuple or ndarray
Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or
alternativel... | def function[_compute_resized_shape, parameter[from_shape, to_shape]]:
constant[
Computes the intended new shape of an image-like array after resizing.
Parameters
----------
from_shape : tuple or ndarray
Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, ... | keyword[def] identifier[_compute_resized_shape] ( identifier[from_shape] , identifier[to_shape] ):
literal[string]
keyword[if] identifier[is_np_array] ( identifier[from_shape] ):
identifier[from_shape] = identifier[from_shape] . identifier[shape]
keyword[if] identifier[is_np_array] ( ident... | def _compute_resized_shape(from_shape, to_shape):
"""
Computes the intended new shape of an image-like array after resizing.
Parameters
----------
from_shape : tuple or ndarray
Old shape of the array. Usually expected to be a tuple of form ``(H, W)`` or ``(H, W, C)`` or
alternativel... |
def get_pyenv_paths(pyenv_root_func=None):
"""Returns a list of paths to Python interpreters managed by pyenv.
:param pyenv_root_func: A no-arg function that returns the pyenv root. Defaults to
running `pyenv root`, but can be overridden for testing.
"""
pyenv_root_func = py... | def function[get_pyenv_paths, parameter[pyenv_root_func]]:
constant[Returns a list of paths to Python interpreters managed by pyenv.
:param pyenv_root_func: A no-arg function that returns the pyenv root. Defaults to
running `pyenv root`, but can be overridden for testing.
]
... | keyword[def] identifier[get_pyenv_paths] ( identifier[pyenv_root_func] = keyword[None] ):
literal[string]
identifier[pyenv_root_func] = identifier[pyenv_root_func] keyword[or] identifier[get_pyenv_root]
identifier[pyenv_root] = identifier[pyenv_root_func] ()
keyword[if] identifier[pyenv_root]... | def get_pyenv_paths(pyenv_root_func=None):
"""Returns a list of paths to Python interpreters managed by pyenv.
:param pyenv_root_func: A no-arg function that returns the pyenv root. Defaults to
running `pyenv root`, but can be overridden for testing.
"""
pyenv_root_func = py... |
def render_user(self, *args, **kwargs):
'''
render, with userinfo
fun(kind, num)
fun(kind, num, with_tag = val1)
fun(kind, num, with_tag = val1, user_id = val2)
fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
'''
kind = kwargs.get('kind', ar... | def function[render_user, parameter[self]]:
constant[
render, with userinfo
fun(kind, num)
fun(kind, num, with_tag = val1)
fun(kind, num, with_tag = val1, user_id = val2)
fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
]
variable[kind] assign... | keyword[def] identifier[render_user] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[kind] = identifier[kwargs] . identifier[get] ( literal[string] , identifier[args] [ literal[int] ])
identifier[num] = identifier[kwargs] . identifier[get] ( lit... | def render_user(self, *args, **kwargs):
"""
render, with userinfo
fun(kind, num)
fun(kind, num, with_tag = val1)
fun(kind, num, with_tag = val1, user_id = val2)
fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
"""
kind = kwargs.get('kind', args[0])
... |
def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name... | def function[workflow, parameter[ctx, client]]:
constant[List or manage workflows with subcommands.]
if compare[name[ctx].invoked_subcommand is constant[None]] begin[:]
from relative_module[renku.models.refs] import module[LinkReference]
variable[names] assign[=] call[name[defaul... | keyword[def] identifier[workflow] ( identifier[ctx] , identifier[client] ):
literal[string]
keyword[if] identifier[ctx] . identifier[invoked_subcommand] keyword[is] keyword[None] :
keyword[from] identifier[renku] . identifier[models] . identifier[refs] keyword[import] identifier[LinkReferenc... | def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name]... |
def import_entries(self, items):
"""
Loops over items and find entry to import,
an entry need to have 'post_type' set to 'post' and
have content.
"""
self.write_out(self.style.STEP('- Importing entries\n'))
for item_node in items:
title = (item_node.f... | def function[import_entries, parameter[self, items]]:
constant[
Loops over items and find entry to import,
an entry need to have 'post_type' set to 'post' and
have content.
]
call[name[self].write_out, parameter[call[name[self].style.STEP, parameter[constant[- Importing e... | keyword[def] identifier[import_entries] ( identifier[self] , identifier[items] ):
literal[string]
identifier[self] . identifier[write_out] ( identifier[self] . identifier[style] . identifier[STEP] ( literal[string] ))
keyword[for] identifier[item_node] keyword[in] identifier[items] :
... | def import_entries(self, items):
"""
Loops over items and find entry to import,
an entry need to have 'post_type' set to 'post' and
have content.
"""
self.write_out(self.style.STEP('- Importing entries\n'))
for item_node in items:
title = (item_node.find('title').text... |
def copy_mode(pymux, variables):
"""
Enter copy mode.
"""
go_up = variables['-u'] # Go in copy mode and page-up directly.
# TODO: handle '-u'
pane = pymux.arrangement.get_active_pane()
pane.enter_copy_mode() | def function[copy_mode, parameter[pymux, variables]]:
constant[
Enter copy mode.
]
variable[go_up] assign[=] call[name[variables]][constant[-u]]
variable[pane] assign[=] call[name[pymux].arrangement.get_active_pane, parameter[]]
call[name[pane].enter_copy_mode, parameter[]] | keyword[def] identifier[copy_mode] ( identifier[pymux] , identifier[variables] ):
literal[string]
identifier[go_up] = identifier[variables] [ literal[string] ]
identifier[pane] = identifier[pymux] . identifier[arrangement] . identifier[get_active_pane] ()
identifier[pane] . identifier[enter... | def copy_mode(pymux, variables):
"""
Enter copy mode.
"""
go_up = variables['-u'] # Go in copy mode and page-up directly.
# TODO: handle '-u'
pane = pymux.arrangement.get_active_pane()
pane.enter_copy_mode() |
def next_position(self, pos):
"""returns the next position in depth-first order"""
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidat... | def function[next_position, parameter[self, pos]]:
constant[returns the next position in depth-first order]
variable[candidate] assign[=] constant[None]
if compare[name[pos] is_not constant[None]] begin[:]
variable[candidate] assign[=] call[name[self].first_child_position, parame... | keyword[def] identifier[next_position] ( identifier[self] , identifier[pos] ):
literal[string]
identifier[candidate] = keyword[None]
keyword[if] identifier[pos] keyword[is] keyword[not] keyword[None] :
identifier[candidate] = identifier[self] . identifier[first_child_posi... | def next_position(self, pos):
"""returns the next position in depth-first order"""
candidate = None
if pos is not None:
candidate = self.first_child_position(pos)
if candidate is None:
candidate = self.next_sibling_position(pos)
if candidate is None:
c... |
def intercept_callback_query_origin(fn=pair, origins='all'):
"""
:return:
a pair producer that enables dynamic callback query origin mapping
across seeder and delegator.
:param origins:
``all`` or a list of origin types (``chat``, ``inline``).
Origin mapping is only enabled ... | def function[intercept_callback_query_origin, parameter[fn, origins]]:
constant[
:return:
a pair producer that enables dynamic callback query origin mapping
across seeder and delegator.
:param origins:
``all`` or a list of origin types (``chat``, ``inline``).
Origin mapp... | keyword[def] identifier[intercept_callback_query_origin] ( identifier[fn] = identifier[pair] , identifier[origins] = literal[string] ):
literal[string]
identifier[origin_map] = identifier[helper] . identifier[SafeDict] ()
keyword[def] identifier[tuplize] ( identifier[fn] ):
k... | def intercept_callback_query_origin(fn=pair, origins='all'):
"""
:return:
a pair producer that enables dynamic callback query origin mapping
across seeder and delegator.
:param origins:
``all`` or a list of origin types (``chat``, ``inline``).
Origin mapping is only enabled ... |
def mute(returns_output=False):
"""
`returns_output` - Returns all print output in a list.
Capture or ignore all print output generated by a function.
Usage:
output = mute(returns_output=True)(module.my_func)(args)
"""
def decorator(func):
@wraps(func)
def wrapper(*args, ... | def function[mute, parameter[returns_output]]:
constant[
`returns_output` - Returns all print output in a list.
Capture or ignore all print output generated by a function.
Usage:
output = mute(returns_output=True)(module.my_func)(args)
]
def function[decorator, parameter[func]]:
... | keyword[def] identifier[mute] ( identifier[returns_output] = keyword[False] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[func] ):
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
ide... | def mute(returns_output=False):
"""
`returns_output` - Returns all print output in a list.
Capture or ignore all print output generated by a function.
Usage:
output = mute(returns_output=True)(module.my_func)(args)
"""
def decorator(func):
@wraps(func)
def wrapper(*args... |
def from_config(cls, config, name, section_key="scoring_contexts"):
"""
Expects:
scoring_contexts:
enwiki:
scorer_models:
damaging: enwiki_damaging_2014
good-faith: enwiki_good-faith_2014
... | def function[from_config, parameter[cls, config, name, section_key]]:
constant[
Expects:
scoring_contexts:
enwiki:
scorer_models:
damaging: enwiki_damaging_2014
good-faith: enwiki_good-faith_2014
... | keyword[def] identifier[from_config] ( identifier[cls] , identifier[config] , identifier[name] , identifier[section_key] = literal[string] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[cls] . identifier[__name__] , identifier[name] ))
... | def from_config(cls, config, name, section_key='scoring_contexts'):
"""
Expects:
scoring_contexts:
enwiki:
scorer_models:
damaging: enwiki_damaging_2014
good-faith: enwiki_good-faith_2014
ext... |
def _reverse_indexer(self):
"""
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(li... | def function[_reverse_indexer, parameter[self]]:
constant[
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In... | keyword[def] identifier[_reverse_indexer] ( identifier[self] ):
literal[string]
identifier[categories] = identifier[self] . identifier[categories]
identifier[r] , identifier[counts] = identifier[libalgos] . identifier[groupsort_indexer] ( identifier[self] . identifier[codes] . identifier[... | def _reverse_indexer(self):
"""
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('... |
def ice_days(tasmax, freq='YS'):
r"""Number of ice/freezing days
Number of days where daily maximum temperatures are below 0℃.
Parameters
----------
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
... | def function[ice_days, parameter[tasmax, freq]]:
constant[Number of ice/freezing days
Number of days where daily maximum temperatures are below 0℃.
Parameters
----------
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
... | keyword[def] identifier[ice_days] ( identifier[tasmax] , identifier[freq] = literal[string] ):
literal[string]
identifier[tu] = identifier[units] . identifier[parse_units] ( identifier[tasmax] . identifier[attrs] [ literal[string] ]. identifier[replace] ( literal[string] , literal[string] ))
identifie... | def ice_days(tasmax, freq='YS'):
"""Number of ice/freezing days
Number of days where daily maximum temperatures are below 0℃.
Parameters
----------
tasmax : xarrray.DataArray
Maximum daily temperature [℃] or [K]
freq : str, optional
Resampling frequency
Returns
-------
... |
def _write_var_data_sparse(self, f, zVar, var, dataType, numElems, recVary,
oneblock):
'''
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this ... | def function[_write_var_data_sparse, parameter[self, f, zVar, var, dataType, numElems, recVary, oneblock]]:
constant[
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this is f... | keyword[def] identifier[_write_var_data_sparse] ( identifier[self] , identifier[f] , identifier[zVar] , identifier[var] , identifier[dataType] , identifier[numElems] , identifier[recVary] ,
identifier[oneblock] ):
literal[string]
identifier[rec_start] = identifier[oneblock] [ literal[int] ]
... | def _write_var_data_sparse(self, f, zVar, var, dataType, numElems, recVary, oneblock):
"""
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this is for a z variable
var... |
def signout(request, next_page=userena_settings.USERENA_REDIRECT_ON_SIGNOUT,
template_name='userena/signout.html', *args, **kwargs):
"""
Signs out the user and adds a success message ``You have been signed
out.`` If next_page is defined you will be redirected to the URI. If
not the template ... | def function[signout, parameter[request, next_page, template_name]]:
constant[
Signs out the user and adds a success message ``You have been signed
out.`` If next_page is defined you will be redirected to the URI. If
not the template in template_name is used.
:param next_page:
A string ... | keyword[def] identifier[signout] ( identifier[request] , identifier[next_page] = identifier[userena_settings] . identifier[USERENA_REDIRECT_ON_SIGNOUT] ,
identifier[template_name] = literal[string] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[request] . identifier[... | def signout(request, next_page=userena_settings.USERENA_REDIRECT_ON_SIGNOUT, template_name='userena/signout.html', *args, **kwargs):
"""
Signs out the user and adds a success message ``You have been signed
out.`` If next_page is defined you will be redirected to the URI. If
not the template in template_... |
def BitmathType(bmstring):
"""An 'argument type' for integrations with the argparse module.
For more information, see
https://docs.python.org/2/library/argparse.html#type Of particular
interest to us is this bit:
``type=`` can take any callable that takes a single string
argument and returns the converted v... | def function[BitmathType, parameter[bmstring]]:
constant[An 'argument type' for integrations with the argparse module.
For more information, see
https://docs.python.org/2/library/argparse.html#type Of particular
interest to us is this bit:
``type=`` can take any callable that takes a single string
argum... | keyword[def] identifier[BitmathType] ( identifier[bmstring] ):
literal[string]
keyword[try] :
identifier[argvalue] = identifier[bitmath] . identifier[parse_string] ( identifier[bmstring] )
keyword[except] identifier[ValueError] :
keyword[raise] identifier[argparse] . identifier[Arg... | def BitmathType(bmstring):
"""An 'argument type' for integrations with the argparse module.
For more information, see
https://docs.python.org/2/library/argparse.html#type Of particular
interest to us is this bit:
``type=`` can take any callable that takes a single string
argument and returns the converted v... |
def context_list_users(zap_helper, context_name):
"""List the users available for a given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name)
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
user_list = ', '.join([user['name'] for use... | def function[context_list_users, parameter[zap_helper, context_name]]:
constant[List the users available for a given context.]
with call[name[zap_error_handler], parameter[]] begin[:]
variable[info] assign[=] call[name[zap_helper].get_context_info, parameter[name[context_name]]]
... | keyword[def] identifier[context_list_users] ( identifier[zap_helper] , identifier[context_name] ):
literal[string]
keyword[with] identifier[zap_error_handler] ():
identifier[info] = identifier[zap_helper] . identifier[get_context_info] ( identifier[context_name] )
identifier[users] = identi... | def context_list_users(zap_helper, context_name):
"""List the users available for a given context."""
with zap_error_handler():
info = zap_helper.get_context_info(context_name) # depends on [control=['with'], data=[]]
users = zap_helper.zap.users.users_list(info['id'])
if len(users):
us... |
def _format_range_dt(self, d):
"""Format range filter datetime to the closest aggregation interval."""
if not isinstance(d, six.string_types):
d = d.isoformat()
return '{0}||/{1}'.format(
d, self.dt_rounding_map[self.aggregation_interval]) | def function[_format_range_dt, parameter[self, d]]:
constant[Format range filter datetime to the closest aggregation interval.]
if <ast.UnaryOp object at 0x7da1afe668c0> begin[:]
variable[d] assign[=] call[name[d].isoformat, parameter[]]
return[call[constant[{0}||/{1}].format, parame... | keyword[def] identifier[_format_range_dt] ( identifier[self] , identifier[d] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[d] , identifier[six] . identifier[string_types] ):
identifier[d] = identifier[d] . identifier[isoformat] ()
keyword[re... | def _format_range_dt(self, d):
"""Format range filter datetime to the closest aggregation interval."""
if not isinstance(d, six.string_types):
d = d.isoformat() # depends on [control=['if'], data=[]]
return '{0}||/{1}'.format(d, self.dt_rounding_map[self.aggregation_interval]) |
def cortex_plot_2D(the_map,
color=None, cmap=None, vmin=None, vmax=None, alpha=None,
underlay='curvature', mask=None, axes=None, triangulation=None):
'''
cortex_plot_2D(map) yields a plot of the given 2D cortical mesh, map.
The following options are accepted:
* c... | def function[cortex_plot_2D, parameter[the_map, color, cmap, vmin, vmax, alpha, underlay, mask, axes, triangulation]]:
constant[
cortex_plot_2D(map) yields a plot of the given 2D cortical mesh, map.
The following options are accepted:
* color (default: None) specifies the color to plot for each v... | keyword[def] identifier[cortex_plot_2D] ( identifier[the_map] ,
identifier[color] = keyword[None] , identifier[cmap] = keyword[None] , identifier[vmin] = keyword[None] , identifier[vmax] = keyword[None] , identifier[alpha] = keyword[None] ,
identifier[underlay] = literal[string] , identifier[mask] = keyword[None] ,... | def cortex_plot_2D(the_map, color=None, cmap=None, vmin=None, vmax=None, alpha=None, underlay='curvature', mask=None, axes=None, triangulation=None):
"""
cortex_plot_2D(map) yields a plot of the given 2D cortical mesh, map.
The following options are accepted:
* color (default: None) specifies the col... |
def closest_allzero_pixel(self, pixel, direction, w=13, t=0.5):
"""Starting at pixel, moves pixel by direction * t until all
zero pixels within a radius w of pixel. Then, returns pixel.
Parameters
----------
pixel : :obj:`numpy.ndarray` of float
The initial pixel loc... | def function[closest_allzero_pixel, parameter[self, pixel, direction, w, t]]:
constant[Starting at pixel, moves pixel by direction * t until all
zero pixels within a radius w of pixel. Then, returns pixel.
Parameters
----------
pixel : :obj:`numpy.ndarray` of float
T... | keyword[def] identifier[closest_allzero_pixel] ( identifier[self] , identifier[pixel] , identifier[direction] , identifier[w] = literal[int] , identifier[t] = literal[int] ):
literal[string]
identifier[y] , identifier[x] = identifier[np] . identifier[meshgrid] ( identifier[np] . identifier... | def closest_allzero_pixel(self, pixel, direction, w=13, t=0.5):
"""Starting at pixel, moves pixel by direction * t until all
zero pixels within a radius w of pixel. Then, returns pixel.
Parameters
----------
pixel : :obj:`numpy.ndarray` of float
The initial pixel locatio... |
def mirtrace_contamination_check(self):
""" Generate the miRTrace Contamination Check"""
# A library of 24 colors. Should be enough for this plot
color_lib = ['rgb(166,206,227)', 'rgb(31,120,180)', 'rgb(178,223,138)', 'rgb(51,160,44)', 'rgb(251,154,153)', 'rgb(227,26,28)', 'rgb(253,191,111)', '... | def function[mirtrace_contamination_check, parameter[self]]:
constant[ Generate the miRTrace Contamination Check]
variable[color_lib] assign[=] list[[<ast.Constant object at 0x7da20e9b23e0>, <ast.Constant object at 0x7da20e9b2ef0>, <ast.Constant object at 0x7da20e9b2c20>, <ast.Constant object at 0x7da20... | keyword[def] identifier[mirtrace_contamination_check] ( identifier[self] ):
literal[string]
identifier[color_lib] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[st... | def mirtrace_contamination_check(self):
""" Generate the miRTrace Contamination Check"""
# A library of 24 colors. Should be enough for this plot
color_lib = ['rgb(166,206,227)', 'rgb(31,120,180)', 'rgb(178,223,138)', 'rgb(51,160,44)', 'rgb(251,154,153)', 'rgb(227,26,28)', 'rgb(253,191,111)', 'rgb(255,127,0... |
def aes_encrypt(mode, aes_key, aes_iv, *data):
"""Encrypt data with AES in specified mode."""
encryptor = Cipher(
algorithms.AES(aes_key),
mode(aes_iv),
backend=default_backend()).encryptor()
result = None
for value in data:
result = encryptor.update(value)
encryptor... | def function[aes_encrypt, parameter[mode, aes_key, aes_iv]]:
constant[Encrypt data with AES in specified mode.]
variable[encryptor] assign[=] call[call[name[Cipher], parameter[call[name[algorithms].AES, parameter[name[aes_key]]], call[name[mode], parameter[name[aes_iv]]]]].encryptor, parameter[]]
... | keyword[def] identifier[aes_encrypt] ( identifier[mode] , identifier[aes_key] , identifier[aes_iv] ,* identifier[data] ):
literal[string]
identifier[encryptor] = identifier[Cipher] (
identifier[algorithms] . identifier[AES] ( identifier[aes_key] ),
identifier[mode] ( identifier[aes_iv] ),
id... | def aes_encrypt(mode, aes_key, aes_iv, *data):
"""Encrypt data with AES in specified mode."""
encryptor = Cipher(algorithms.AES(aes_key), mode(aes_iv), backend=default_backend()).encryptor()
result = None
for value in data:
result = encryptor.update(value) # depends on [control=['for'], data=['... |
def extract_site_packages(archive, target_path, compile_pyc, compile_workers=0, force=False):
"""Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
"""
parent = targe... | def function[extract_site_packages, parameter[archive, target_path, compile_pyc, compile_workers, force]]:
constant[Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
... | keyword[def] identifier[extract_site_packages] ( identifier[archive] , identifier[target_path] , identifier[compile_pyc] , identifier[compile_workers] = literal[int] , identifier[force] = keyword[False] ):
literal[string]
identifier[parent] = identifier[target_path] . identifier[parent]
identifier[ta... | def extract_site_packages(archive, target_path, compile_pyc, compile_workers=0, force=False):
"""Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
"""
parent = targe... |
def from_json(json_str, allow_pickle=False):
"""
Decodes a JSON object specified in the utool convention
Args:
json_str (str):
allow_pickle (bool): (default = False)
Returns:
object: val
CommandLine:
python -m utool.util_cache from_json --show
Example:
... | def function[from_json, parameter[json_str, allow_pickle]]:
constant[
Decodes a JSON object specified in the utool convention
Args:
json_str (str):
allow_pickle (bool): (default = False)
Returns:
object: val
CommandLine:
python -m utool.util_cache from_json --s... | keyword[def] identifier[from_json] ( identifier[json_str] , identifier[allow_pickle] = keyword[False] ):
literal[string]
keyword[if] identifier[six] . identifier[PY3] :
keyword[if] identifier[isinstance] ( identifier[json_str] , identifier[bytes] ):
identifier[json_str] = identifier... | def from_json(json_str, allow_pickle=False):
"""
Decodes a JSON object specified in the utool convention
Args:
json_str (str):
allow_pickle (bool): (default = False)
Returns:
object: val
CommandLine:
python -m utool.util_cache from_json --show
Example:
... |
def delete(self, id):
"""delete."""
project = db.session.query(Project).filter_by(id=id).first()
if project is None:
response = jsonify({
'projects': None,
'message': 'No interface defined for URL.'
})
return response, 404
... | def function[delete, parameter[self, id]]:
constant[delete.]
variable[project] assign[=] call[call[call[name[db].session.query, parameter[name[Project]]].filter_by, parameter[]].first, parameter[]]
if compare[name[project] is constant[None]] begin[:]
variable[response] assign[=] ... | keyword[def] identifier[delete] ( identifier[self] , identifier[id] ):
literal[string]
identifier[project] = identifier[db] . identifier[session] . identifier[query] ( identifier[Project] ). identifier[filter_by] ( identifier[id] = identifier[id] ). identifier[first] ()
keyword[if] ident... | def delete(self, id):
"""delete."""
project = db.session.query(Project).filter_by(id=id).first()
if project is None:
response = jsonify({'projects': None, 'message': 'No interface defined for URL.'})
return (response, 404) # depends on [control=['if'], data=[]]
db.session.delete(project... |
def format_timestamp(
ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
) -> str:
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>... | def function[format_timestamp, parameter[ts]]:
constant[Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 ... | keyword[def] identifier[format_timestamp] (
identifier[ts] : identifier[Union] [ identifier[int] , identifier[float] , identifier[tuple] , identifier[time] . identifier[struct_time] , identifier[datetime] . identifier[datetime] ]
)-> identifier[str] :
literal[string]
keyword[if] identifier[isinstance] ( ... | def format_timestamp(ts: Union[int, float, tuple, time.struct_time, datetime.datetime]) -> str:
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> for... |
def fetch_items(self, category, **kwargs):
"""Fetch the contents
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Fetching historical contents of '%... | def function[fetch_items, parameter[self, category]]:
constant[Fetch the contents
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
]
variable[from_date] assign[=] call[name[kwargs]][constant[from_date]]
... | keyword[def] identifier[fetch_items] ( identifier[self] , identifier[category] ,** identifier[kwargs] ):
literal[string]
identifier[from_date] = identifier[kwargs] [ literal[string] ]
identifier[logger] . identifier[info] ( literal[string] ,
identifier[self] . identifier[url] , ... | def fetch_items(self, category, **kwargs):
"""Fetch the contents
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Fetching historical contents of '%s' from %s", s... |
def login(self, login, password):
"""
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
"""
self.client.read_until('Username: ')
self.... | def function[login, parameter[self, login, password]]:
constant[
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
]
call[name[self].client.re... | keyword[def] identifier[login] ( identifier[self] , identifier[login] , identifier[password] ):
literal[string]
identifier[self] . identifier[client] . identifier[read_until] ( literal[string] )
identifier[self] . identifier[client] . identifier[write] ( identifier[login] + literal[string]... | def login(self, login, password):
"""
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
"""
self.client.read_until('Username: ')
self.client.write... |
def get_relations(self, rel_id=None, **kwargs):
"""
Alias for get_elements() but filter the result by Relation
:param rel_id: Id of the relation
:type rel_id: Integer
:return: List of elements
"""
return self.get_elements(Relation, elem_id=rel_id, **kwargs) | def function[get_relations, parameter[self, rel_id]]:
constant[
Alias for get_elements() but filter the result by Relation
:param rel_id: Id of the relation
:type rel_id: Integer
:return: List of elements
]
return[call[name[self].get_elements, parameter[name[Relation... | keyword[def] identifier[get_relations] ( identifier[self] , identifier[rel_id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[get_elements] ( identifier[Relation] , identifier[elem_id] = identifier[rel_id] ,** identifier[kwargs] ) | def get_relations(self, rel_id=None, **kwargs):
"""
Alias for get_elements() but filter the result by Relation
:param rel_id: Id of the relation
:type rel_id: Integer
:return: List of elements
"""
return self.get_elements(Relation, elem_id=rel_id, **kwargs) |
def get_required_fields(self):
"""Return the names of fields that are required according to the schema."""
return [m.name for m in self._ast_node.members if m.member_schema.required] | def function[get_required_fields, parameter[self]]:
constant[Return the names of fields that are required according to the schema.]
return[<ast.ListComp object at 0x7da20c76d750>] | keyword[def] identifier[get_required_fields] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[m] . identifier[name] keyword[for] identifier[m] keyword[in] identifier[self] . identifier[_ast_node] . identifier[members] keyword[if] identifier[m] . identifier[member_schema] . identifie... | def get_required_fields(self):
"""Return the names of fields that are required according to the schema."""
return [m.name for m in self._ast_node.members if m.member_schema.required] |
def setCmd(self, cmd):
"""Check the cmd is valid, FrameError will be raised if its not."""
cmd = cmd.upper()
if cmd not in VALID_COMMANDS:
raise FrameError("The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % (
cmd, VALID_COMMANDS, STOMP_VERSION)
... | def function[setCmd, parameter[self, cmd]]:
constant[Check the cmd is valid, FrameError will be raised if its not.]
variable[cmd] assign[=] call[name[cmd].upper, parameter[]]
if compare[name[cmd] <ast.NotIn object at 0x7da2590d7190> name[VALID_COMMANDS]] begin[:]
<ast.Raise object at 0x7... | keyword[def] identifier[setCmd] ( identifier[self] , identifier[cmd] ):
literal[string]
identifier[cmd] = identifier[cmd] . identifier[upper] ()
keyword[if] identifier[cmd] keyword[not] keyword[in] identifier[VALID_COMMANDS] :
keyword[raise] identifier[FrameError] ( liter... | def setCmd(self, cmd):
"""Check the cmd is valid, FrameError will be raised if its not."""
cmd = cmd.upper()
if cmd not in VALID_COMMANDS:
raise FrameError("The cmd '%s' is not valid! It must be one of '%s' (STOMP v%s)." % (cmd, VALID_COMMANDS, STOMP_VERSION)) # depends on [control=['if'], data=['c... |
def validateDeviceTypeConfiguration(self, typeId):
"""
Validate the device type configuration.
Parameters:
- typeId (string) - the platform device type
Throws APIException on failure.
"""
req = ApiClient.draftDeviceTypeUrl % (self.host, typeId)
body = ... | def function[validateDeviceTypeConfiguration, parameter[self, typeId]]:
constant[
Validate the device type configuration.
Parameters:
- typeId (string) - the platform device type
Throws APIException on failure.
]
variable[req] assign[=] binary_operation[name[A... | keyword[def] identifier[validateDeviceTypeConfiguration] ( identifier[self] , identifier[typeId] ):
literal[string]
identifier[req] = identifier[ApiClient] . identifier[draftDeviceTypeUrl] %( identifier[self] . identifier[host] , identifier[typeId] )
identifier[body] ={ literal[string] : l... | def validateDeviceTypeConfiguration(self, typeId):
"""
Validate the device type configuration.
Parameters:
- typeId (string) - the platform device type
Throws APIException on failure.
"""
req = ApiClient.draftDeviceTypeUrl % (self.host, typeId)
body = {'operation'... |
def _check_1st_line(line, **kwargs):
"""First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:para... | def function[_check_1st_line, parameter[line]]:
constant[First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type... | keyword[def] identifier[_check_1st_line] ( identifier[line] ,** identifier[kwargs] ):
literal[string]
identifier[components] = identifier[kwargs] . identifier[get] ( literal[string] ,())
identifier[max_first_line] = identifier[kwargs] . identifier[get] ( literal[string] , literal[int] )
identifi... | def _check_1st_line(line, **kwargs):
"""First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:para... |
def __extractOntologies(self, exclude_BNodes = False, return_string=False):
"""
returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
"""
out = []
... | def function[__extractOntologies, parameter[self, exclude_BNodes, return_string]]:
constant[
returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
]
variab... | keyword[def] identifier[__extractOntologies] ( identifier[self] , identifier[exclude_BNodes] = keyword[False] , identifier[return_string] = keyword[False] ):
literal[string]
identifier[out] =[]
identifier[qres] = identifier[self] . identifier[queryHelper] . identifier[getOntology] ()
... | def __extractOntologies(self, exclude_BNodes=False, return_string=False):
"""
returns Ontology class instances
[ a owl:Ontology ;
vann:preferredNamespacePrefix "bsym" ;
vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
"""
out = []
qres = self.qu... |
def sg_transpose(tensor, opt):
r"""Permutes the dimensions according to `opt.perm`.
See `tf.transpose()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
perm: A permutation of the dimensions of `tensor`. The target shape.
name: If provided, replace ... | def function[sg_transpose, parameter[tensor, opt]]:
constant[Permutes the dimensions according to `opt.perm`.
See `tf.transpose()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
perm: A permutation of the dimensions of `tensor`. The target shape.
... | keyword[def] identifier[sg_transpose] ( identifier[tensor] , identifier[opt] ):
literal[string]
keyword[assert] identifier[opt] . identifier[perm] keyword[is] keyword[not] keyword[None] , literal[string]
keyword[return] identifier[tf] . identifier[transpose] ( identifier[tensor] , identifier[opt... | def sg_transpose(tensor, opt):
"""Permutes the dimensions according to `opt.perm`.
See `tf.transpose()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
perm: A permutation of the dimensions of `tensor`. The target shape.
name: If provided, replace c... |
def namespace_for_prefix(self, prefix):
"""Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
"""
try:
ni = self.... | def function[namespace_for_prefix, parameter[self, prefix]]:
constant[Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
]
<ast.T... | keyword[def] identifier[namespace_for_prefix] ( identifier[self] , identifier[prefix] ):
literal[string]
keyword[try] :
identifier[ni] = identifier[self] . identifier[__lookup_prefix] ( identifier[prefix] )
keyword[except] identifier[PrefixNotFoundError] :
keywor... | def namespace_for_prefix(self, prefix):
"""Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
"""
try:
ni = self.__lookup_pre... |
def horiz_string(*args, **kwargs):
"""
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep... | def function[horiz_string, parameter[]]:
constant[
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs... | keyword[def] identifier[horiz_string] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[unicodedata]
identifier[precision] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] )
identifier[sep] = identifier[kwargs] . identifier[get] ( ... | def horiz_string(*args, **kwargs):
"""
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep... |
def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
"""
results = []
exclude_question_wor... | def function[evaluate_analogy, parameter[args, token_embedding, ctx, logfile, global_step]]:
constant[Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
]
variable[re... | keyword[def] identifier[evaluate_analogy] ( identifier[args] , identifier[token_embedding] , identifier[ctx] , identifier[logfile] = keyword[None] , identifier[global_step] = literal[int] ):
literal[string]
identifier[results] =[]
identifier[exclude_question_words] = keyword[not] identifier[args] . i... | def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets.
The analogy task is an open vocabulary task, make sure to pass a
token_embedding with a sufficiently large number of supported tokens.
"""
results = []
exclude_question_wor... |
def text_result(text: str,
extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,
filename: str = None) -> WSGI_TUPLE_TYPE:
"""
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text.
"""
extraheaders = extraheaders or []
if filename:
extraheaders.append... | def function[text_result, parameter[text, extraheaders, filename]]:
constant[
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text.
]
variable[extraheaders] assign[=] <ast.BoolOp object at 0x7da18c4cfa60>
if name[filename] begin[:]
call[name[extraheaders].ap... | keyword[def] identifier[text_result] ( identifier[text] : identifier[str] ,
identifier[extraheaders] : identifier[TYPE_WSGI_RESPONSE_HEADERS] = keyword[None] ,
identifier[filename] : identifier[str] = keyword[None] )-> identifier[WSGI_TUPLE_TYPE] :
literal[string]
identifier[extraheaders] = identifier[ex... | def text_result(text: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS=None, filename: str=None) -> WSGI_TUPLE_TYPE:
"""
Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 text.
"""
extraheaders = extraheaders or []
if filename:
extraheaders.append(('content-disposition', 'inline; fi... |
def discretizer(reader,
transform=None,
cluster=None,
run=True,
stride=1,
chunksize=None):
r""" Specialized pipeline: From trajectories to clustering.
Constructs a pipeline that consists of three stages:
1. an input stage (... | def function[discretizer, parameter[reader, transform, cluster, run, stride, chunksize]]:
constant[ Specialized pipeline: From trajectories to clustering.
Constructs a pipeline that consists of three stages:
1. an input stage (mandatory)
2. a transformer stage (optional)
3. a clusteri... | keyword[def] identifier[discretizer] ( identifier[reader] ,
identifier[transform] = keyword[None] ,
identifier[cluster] = keyword[None] ,
identifier[run] = keyword[True] ,
identifier[stride] = literal[int] ,
identifier[chunksize] = keyword[None] ):
literal[string]
keyword[from] identifier[pyemma] . i... | def discretizer(reader, transform=None, cluster=None, run=True, stride=1, chunksize=None):
""" Specialized pipeline: From trajectories to clustering.
Constructs a pipeline that consists of three stages:
1. an input stage (mandatory)
2. a transformer stage (optional)
3. a clustering stage ... |
def insert(self, fields, values):
'''
insert new db entry
:param fields: list of fields to insert
:param values: list of values to insert
:return: row id of the new row
'''
if fields:
_fields = ' (%s) ' % ','.join(fields)
else:
_fi... | def function[insert, parameter[self, fields, values]]:
constant[
insert new db entry
:param fields: list of fields to insert
:param values: list of values to insert
:return: row id of the new row
]
if name[fields] begin[:]
variable[_fields] assign... | keyword[def] identifier[insert] ( identifier[self] , identifier[fields] , identifier[values] ):
literal[string]
keyword[if] identifier[fields] :
identifier[_fields] = literal[string] % literal[string] . identifier[join] ( identifier[fields] )
keyword[else] :
iden... | def insert(self, fields, values):
"""
insert new db entry
:param fields: list of fields to insert
:param values: list of values to insert
:return: row id of the new row
"""
if fields:
_fields = ' (%s) ' % ','.join(fields) # depends on [control=['if'], data=[]]
... |
def register_manifest(app, filename='manifest.json'):
'''Register an assets json manifest'''
if current_app.config.get('TESTING'):
return # Do not spend time here when testing
if not has_manifest(app, filename):
msg = '{filename} not found for {app}'.format(**locals())
raise ValueEr... | def function[register_manifest, parameter[app, filename]]:
constant[Register an assets json manifest]
if call[name[current_app].config.get, parameter[constant[TESTING]]] begin[:]
return[None]
if <ast.UnaryOp object at 0x7da1b11919c0> begin[:]
variable[msg] assign[=] call[... | keyword[def] identifier[register_manifest] ( identifier[app] , identifier[filename] = literal[string] ):
literal[string]
keyword[if] identifier[current_app] . identifier[config] . identifier[get] ( literal[string] ):
keyword[return]
keyword[if] keyword[not] identifier[has_manifest] ( iden... | def register_manifest(app, filename='manifest.json'):
"""Register an assets json manifest"""
if current_app.config.get('TESTING'):
return # Do not spend time here when testing # depends on [control=['if'], data=[]]
if not has_manifest(app, filename):
msg = '{filename} not found for {app}'.... |
def _ensure_file_path(self):
"""
Ensure the storage path exists.
If it doesn't, create it with "go-rwx" permissions.
"""
storage_root = os.path.dirname(self.file_path)
needs_storage_root = storage_root and not os.path.isdir(storage_root)
if needs_storage_root: # ... | def function[_ensure_file_path, parameter[self]]:
constant[
Ensure the storage path exists.
If it doesn't, create it with "go-rwx" permissions.
]
variable[storage_root] assign[=] call[name[os].path.dirname, parameter[name[self].file_path]]
variable[needs_storage_root] ass... | keyword[def] identifier[_ensure_file_path] ( identifier[self] ):
literal[string]
identifier[storage_root] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[self] . identifier[file_path] )
identifier[needs_storage_root] = identifier[storage_root] keyword[and] keyword[... | def _ensure_file_path(self):
"""
Ensure the storage path exists.
If it doesn't, create it with "go-rwx" permissions.
"""
storage_root = os.path.dirname(self.file_path)
needs_storage_root = storage_root and (not os.path.isdir(storage_root))
if needs_storage_root: # pragma: no cov... |
def __iter_read_spectrum_meta(self):
"""
This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is pruned, i.e. the <spectrumLi... | def function[__iter_read_spectrum_meta, parameter[self]]:
constant[
This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is p... | keyword[def] identifier[__iter_read_spectrum_meta] ( identifier[self] ):
literal[string]
identifier[mz_group] = identifier[int_group] = keyword[None]
identifier[slist] = keyword[None]
identifier[elem_iterator] = identifier[self] . identifier[iterparse] ( identifier[self] . ident... | def __iter_read_spectrum_meta(self):
"""
This method should only be called by __init__. Reads the data formats, coordinates and offsets from
the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum
metadata is pruned, i.e. the <spectrumList> ... |
def contains_c_extension(module: ModuleType,
import_all_submodules: bool = True,
include_external_imports: bool = False,
seen: List[ModuleType] = None) -> bool:
"""
Extends :func:`is_c_extension` by asking: is this module, or any of its
... | def function[contains_c_extension, parameter[module, import_all_submodules, include_external_imports, seen]]:
constant[
Extends :func:`is_c_extension` by asking: is this module, or any of its
submodules, a C extension?
Args:
module: Previously imported module object to be tested.
im... | keyword[def] identifier[contains_c_extension] ( identifier[module] : identifier[ModuleType] ,
identifier[import_all_submodules] : identifier[bool] = keyword[True] ,
identifier[include_external_imports] : identifier[bool] = keyword[False] ,
identifier[seen] : identifier[List] [ identifier[ModuleType] ]= keyword[Non... | def contains_c_extension(module: ModuleType, import_all_submodules: bool=True, include_external_imports: bool=False, seen: List[ModuleType]=None) -> bool:
"""
Extends :func:`is_c_extension` by asking: is this module, or any of its
submodules, a C extension?
Args:
module: Previously imported mod... |
def stats(self):
"""Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
"""
ret = '{name}:\n' \
' sample_num={sample_num}, batch_num={batch_num}\n' \
... | def function[stats, parameter[self]]:
constant[Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
]
variable[ret] assign[=] call[constant[{name}:
sample_num={sam... | keyword[def] identifier[stats] ( identifier[self] ):
literal[string]
identifier[ret] = literal[string] literal[string] literal[string] literal[string] literal[string] . identifier[format] ( identifier[name] = identifier[self] . identifier[__class__] . identifier[__name__] ,
identifier[... | def stats(self):
"""Return a string representing the statistics of the bucketing sampler.
Returns
-------
ret : str
String representing the statistics of the buckets.
"""
ret = '{name}:\n sample_num={sample_num}, batch_num={batch_num}\n key={bucket_keys}\n cnt={bu... |
def write_bytes(self, data):
"""
Open the file in bytes mode, write to it, and close the file.
"""
if not isinstance(data, six.binary_type):
raise TypeError(
'data must be %s, not %s' %
(six.binary_type.__class__.__name__, data.__class__.__name... | def function[write_bytes, parameter[self, data]]:
constant[
Open the file in bytes mode, write to it, and close the file.
]
if <ast.UnaryOp object at 0x7da20c6e7400> begin[:]
<ast.Raise object at 0x7da20c6e6590>
with call[name[self].open, parameter[]] begin[:]
ret... | keyword[def] identifier[write_bytes] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[data] , identifier[six] . identifier[binary_type] ):
keyword[raise] identifier[TypeError] (
literal[string] %
... | def write_bytes(self, data):
"""
Open the file in bytes mode, write to it, and close the file.
"""
if not isinstance(data, six.binary_type):
raise TypeError('data must be %s, not %s' % (six.binary_type.__class__.__name__, data.__class__.__name__)) # depends on [control=['if'], data=[]]
... |
def from_lal(cls, lalfs, copy=True):
"""Generate a new `FrequencySeries` from a LAL `FrequencySeries` of any type
"""
from ..utils.lal import from_lal_unit
try:
unit = from_lal_unit(lalfs.sampleUnits)
except TypeError:
unit = None
channel = Channel... | def function[from_lal, parameter[cls, lalfs, copy]]:
constant[Generate a new `FrequencySeries` from a LAL `FrequencySeries` of any type
]
from relative_module[utils.lal] import module[from_lal_unit]
<ast.Try object at 0x7da20e9b3b80>
variable[channel] assign[=] call[name[Channel], parame... | keyword[def] identifier[from_lal] ( identifier[cls] , identifier[lalfs] , identifier[copy] = keyword[True] ):
literal[string]
keyword[from] .. identifier[utils] . identifier[lal] keyword[import] identifier[from_lal_unit]
keyword[try] :
identifier[unit] = identifier[from_lal... | def from_lal(cls, lalfs, copy=True):
"""Generate a new `FrequencySeries` from a LAL `FrequencySeries` of any type
"""
from ..utils.lal import from_lal_unit
try:
unit = from_lal_unit(lalfs.sampleUnits) # depends on [control=['try'], data=[]]
except TypeError:
unit = None # depen... |
def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\... | def function[clean_title, parameter[title]]:
constant[
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
]
variable[date_pattern] assign[=] ... | keyword[def] identifier[clean_title] ( identifier[title] ):
literal[string]
identifier[date_pattern] = identifier[re] . identifier[compile] ( literal[string]
literal[string]
literal[string]
literal[string]
literal[string]
literal[string]
literal[string] )
identifier... | def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile('\\W*\\d{1,2}[/\\-.]\\d{1,2}[/\\-.](?=\\... |
def set_autoclear(self, value, auth_no_user_interaction=None):
"""Set autoclear flag for loop partition."""
return self._M.Loop.SetAutoclear(
'(ba{sv})',
value,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
... | def function[set_autoclear, parameter[self, value, auth_no_user_interaction]]:
constant[Set autoclear flag for loop partition.]
return[call[name[self]._M.Loop.SetAutoclear, parameter[constant[(ba{sv})], name[value], call[name[filter_opt], parameter[dictionary[[<ast.Constant object at 0x7da18c4cfb80>], [<ast... | keyword[def] identifier[set_autoclear] ( identifier[self] , identifier[value] , identifier[auth_no_user_interaction] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_M] . identifier[Loop] . identifier[SetAutoclear] (
literal[string] ,
identifier[v... | def set_autoclear(self, value, auth_no_user_interaction=None):
"""Set autoclear flag for loop partition."""
return self._M.Loop.SetAutoclear('(ba{sv})', value, filter_opt({'auth.no_user_interaction': ('b', auth_no_user_interaction)})) |
def encode(self):
"""Encode this record into a binary blob.
This binary blob could be parsed via a call to FromBinary().
Returns:
bytearray: The binary encoded script.
"""
blob = bytearray()
for record in self.records:
blob += record.encode()
... | def function[encode, parameter[self]]:
constant[Encode this record into a binary blob.
This binary blob could be parsed via a call to FromBinary().
Returns:
bytearray: The binary encoded script.
]
variable[blob] assign[=] call[name[bytearray], parameter[]]
f... | keyword[def] identifier[encode] ( identifier[self] ):
literal[string]
identifier[blob] = identifier[bytearray] ()
keyword[for] identifier[record] keyword[in] identifier[self] . identifier[records] :
identifier[blob] += identifier[record] . identifier[encode] ()
... | def encode(self):
"""Encode this record into a binary blob.
This binary blob could be parsed via a call to FromBinary().
Returns:
bytearray: The binary encoded script.
"""
blob = bytearray()
for record in self.records:
blob += record.encode() # depends on [cont... |
def _create_fw(self, tenant_id, data):
"""Internal routine that gets called when a FW is created. """
LOG.debug("In creating Native FW data is %s", data)
# TODO(padkrish):
# Check if router is already added and only then add, needed for
# restart cases since native doesn't have a... | def function[_create_fw, parameter[self, tenant_id, data]]:
constant[Internal routine that gets called when a FW is created. ]
call[name[LOG].debug, parameter[constant[In creating Native FW data is %s], name[data]]]
<ast.Tuple object at 0x7da1b1b7f010> assign[=] call[name[self].attach_intf_route... | keyword[def] identifier[_create_fw] ( identifier[self] , identifier[tenant_id] , identifier[data] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] , identifier[data] )
identifier[ret] , identifier[in_sub] , identifier[out_sub] = identifier... | def _create_fw(self, tenant_id, data):
"""Internal routine that gets called when a FW is created. """
LOG.debug('In creating Native FW data is %s', data)
# TODO(padkrish):
# Check if router is already added and only then add, needed for
# restart cases since native doesn't have a special DB
(ret... |
def _parse_expiry(response_data):
"""Parses the expiry field from a response into a datetime.
Args:
response_data (Mapping): The JSON-parsed response data.
Returns:
Optional[datetime]: The expiration or ``None`` if no expiration was
specified.
"""
expires_in = response_... | def function[_parse_expiry, parameter[response_data]]:
constant[Parses the expiry field from a response into a datetime.
Args:
response_data (Mapping): The JSON-parsed response data.
Returns:
Optional[datetime]: The expiration or ``None`` if no expiration was
specified.
... | keyword[def] identifier[_parse_expiry] ( identifier[response_data] ):
literal[string]
identifier[expires_in] = identifier[response_data] . identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[expires_in] keyword[is] keyword[not] keyword[None] :
keyword[return] iden... | def _parse_expiry(response_data):
"""Parses the expiry field from a response into a datetime.
Args:
response_data (Mapping): The JSON-parsed response data.
Returns:
Optional[datetime]: The expiration or ``None`` if no expiration was
specified.
"""
expires_in = response_... |
def view_export(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#export-view"
api_path = "/api/v2/views/{id}/export.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | def function[view_export, parameter[self, id]]:
constant[https://developer.zendesk.com/rest_api/docs/core/views#export-view]
variable[api_path] assign[=] constant[/api/v2/views/{id}/export.json]
variable[api_path] assign[=] call[name[api_path].format, parameter[]]
return[call[name[self].call... | keyword[def] identifier[view_export] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[format] ( identifier[id] = identifier[id] )
keyword[return] identifi... | def view_export(self, id, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/views#export-view"""
api_path = '/api/v2/views/{id}/export.json'
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) |
def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
... | def function[evaluate_perceptron, parameter[ctx, model, corpus]]:
constant[Evaluate performance of Averaged Perceptron POS Tagger.]
call[name[click].echo, parameter[constant[chemdataextractor.pos.evaluate]]]
if compare[name[corpus] equal[==] constant[wsj]] begin[:]
variable[evalu... | keyword[def] identifier[evaluate_perceptron] ( identifier[ctx] , identifier[model] , identifier[corpus] ):
literal[string]
identifier[click] . identifier[echo] ( literal[string] )
keyword[if] identifier[corpus] == literal[string] :
identifier[evaluation] = identifier[wsj_evaluation]
... | def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for (i, wsj_sent) in enumerate(sents):
... |
def set_cmap_cb(self, w, index):
"""This callback is invoked when the user selects a new color
map from the preferences pane."""
name = cmap.get_names()[index]
self.t_.set(color_map=name) | def function[set_cmap_cb, parameter[self, w, index]]:
constant[This callback is invoked when the user selects a new color
map from the preferences pane.]
variable[name] assign[=] call[call[name[cmap].get_names, parameter[]]][name[index]]
call[name[self].t_.set, parameter[]] | keyword[def] identifier[set_cmap_cb] ( identifier[self] , identifier[w] , identifier[index] ):
literal[string]
identifier[name] = identifier[cmap] . identifier[get_names] ()[ identifier[index] ]
identifier[self] . identifier[t_] . identifier[set] ( identifier[color_map] = identifier[name] ... | def set_cmap_cb(self, w, index):
"""This callback is invoked when the user selects a new color
map from the preferences pane."""
name = cmap.get_names()[index]
self.t_.set(color_map=name) |
def save_png_with_metadata(fig, filename, fig_kwds, kwds):
""" Save a matplotlib figure to a png with metadata
"""
from PIL import Image, PngImagePlugin
fig.savefig(filename, **fig_kwds)
im = Image.open(filename)
meta = PngImagePlugin.PngInfo()
for key in kwds:
meta.add_text(str(ke... | def function[save_png_with_metadata, parameter[fig, filename, fig_kwds, kwds]]:
constant[ Save a matplotlib figure to a png with metadata
]
from relative_module[PIL] import module[Image], module[PngImagePlugin]
call[name[fig].savefig, parameter[name[filename]]]
variable[im] assign[=] cal... | keyword[def] identifier[save_png_with_metadata] ( identifier[fig] , identifier[filename] , identifier[fig_kwds] , identifier[kwds] ):
literal[string]
keyword[from] identifier[PIL] keyword[import] identifier[Image] , identifier[PngImagePlugin]
identifier[fig] . identifier[savefig] ( identifier[file... | def save_png_with_metadata(fig, filename, fig_kwds, kwds):
""" Save a matplotlib figure to a png with metadata
"""
from PIL import Image, PngImagePlugin
fig.savefig(filename, **fig_kwds)
im = Image.open(filename)
meta = PngImagePlugin.PngInfo()
for key in kwds:
meta.add_text(str(key)... |
def print_progress_bar(self, task):
"""
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
"""
str_format = "{0:." + str(task... | def function[print_progress_bar, parameter[self, task]]:
constant[
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
]
varia... | keyword[def] identifier[print_progress_bar] ( identifier[self] , identifier[task] ):
literal[string]
identifier[str_format] = literal[string] + identifier[str] ( identifier[task] . identifier[decimals] )+ literal[string]
identifier[percents] = identifier[str_format] . identifier[format] (... | def print_progress_bar(self, task):
"""
Draws a progress bar on screen based on the given information using standard output (stdout).
:param task: TaskProgress object containing all required information to draw a progress bar at the given state.
"""
str_format = '{0:.' + str(task.decimal... |
def set_interpolation_coefficients(self):
"""
computes the coefficients for the single polynomials of the spline.
"""
left_boundary_slope = 0
right_boundary_slope = 0
if isinstance(self.boundary_condition, tuple):
left_boundary_slope = self.boundary_conditio... | def function[set_interpolation_coefficients, parameter[self]]:
constant[
computes the coefficients for the single polynomials of the spline.
]
variable[left_boundary_slope] assign[=] constant[0]
variable[right_boundary_slope] assign[=] constant[0]
if call[name[isinstance]... | keyword[def] identifier[set_interpolation_coefficients] ( identifier[self] ):
literal[string]
identifier[left_boundary_slope] = literal[int]
identifier[right_boundary_slope] = literal[int]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[boundary_condition] ... | def set_interpolation_coefficients(self):
"""
computes the coefficients for the single polynomials of the spline.
"""
left_boundary_slope = 0
right_boundary_slope = 0
if isinstance(self.boundary_condition, tuple):
left_boundary_slope = self.boundary_condition[0]
right_bou... |
def main():
"""
Example application that prints messages from the panel to the terminal.
"""
try:
# Retrieve the first USB device
device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))
# Set up an event handler and open the device
device.on_lrr_message += handle_lr... | def function[main, parameter[]]:
constant[
Example application that prints messages from the panel to the terminal.
]
<ast.Try object at 0x7da1b28f4790> | keyword[def] identifier[main] ():
literal[string]
keyword[try] :
identifier[device] = identifier[AlarmDecoder] ( identifier[SerialDevice] ( identifier[interface] = identifier[SERIAL_DEVICE] ))
identifier[device] . identifier[on_lrr_message] += identifier[handle_lrr_message]... | def main():
"""
Example application that prints messages from the panel to the terminal.
"""
try:
# Retrieve the first USB device
device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))
# Set up an event handler and open the device
device.on_lrr_message += handle_lrr... |
def handle_new_selection(self, models):
"""Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the previous selection, the pa... | def function[handle_new_selection, parameter[self, models]]:
constant[Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the... | keyword[def] identifier[handle_new_selection] ( identifier[self] , identifier[models] ):
literal[string]
identifier[models] = identifier[self] . identifier[_check_model_types] ( identifier[models] )
keyword[if] identifier[extend_selection] ():
identifier[already_selected_ele... | def handle_new_selection(self, models):
"""Handles the selection for generic widgets
This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
of newly selected (or clicked on) models.
The method looks at the previous selection, the passed... |
def _set_area_value(self, v, load=False):
"""
Setter method for area_value, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/area_value (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_value is considered as a private
me... | def function[_set_area_value, parameter[self, v, load]]:
constant[
Setter method for area_value, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/area_value (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_value is consi... | keyword[def] identifier[_set_area_value] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
identifier[parent] = identifier[getattr] ( identifier[self] , literal[string] , keyword[None] )
keyword[if] identifier[parent] keyword[is] keyword[not] keyword[None] ... | def _set_area_value(self, v, load=False):
"""
Setter method for area_value, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/area_value (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_value is considered as a private
me... |
def setup_user_signals(self, ):
"""Setup the signals for the user page
:returns: None
:rtype: None
:raises: None
"""
log.debug("Setting up user page signals.")
self.user_task_view_pb.clicked.connect(self.user_view_task)
self.user_prj_view_pb.clicked.conne... | def function[setup_user_signals, parameter[self]]:
constant[Setup the signals for the user page
:returns: None
:rtype: None
:raises: None
]
call[name[log].debug, parameter[constant[Setting up user page signals.]]]
call[name[self].user_task_view_pb.clicked.connect... | keyword[def] identifier[setup_user_signals] ( identifier[self] ,):
literal[string]
identifier[log] . identifier[debug] ( literal[string] )
identifier[self] . identifier[user_task_view_pb] . identifier[clicked] . identifier[connect] ( identifier[self] . identifier[user_view_task] )
... | def setup_user_signals(self):
"""Setup the signals for the user page
:returns: None
:rtype: None
:raises: None
"""
log.debug('Setting up user page signals.')
self.user_task_view_pb.clicked.connect(self.user_view_task)
self.user_prj_view_pb.clicked.connect(self.user_view_... |
def existing_versions(self):
"""
Returns data with different cfgstr values that were previously computed
with this cacher.
"""
import glob
pattern = self.fname + '_*' + self.ext
for fname in glob.glob1(self.dpath, pattern):
fpath = join(self.dpath, fna... | def function[existing_versions, parameter[self]]:
constant[
Returns data with different cfgstr values that were previously computed
with this cacher.
]
import module[glob]
variable[pattern] assign[=] binary_operation[binary_operation[name[self].fname + constant[_*]] + name[se... | keyword[def] identifier[existing_versions] ( identifier[self] ):
literal[string]
keyword[import] identifier[glob]
identifier[pattern] = identifier[self] . identifier[fname] + literal[string] + identifier[self] . identifier[ext]
keyword[for] identifier[fname] keyword[in] iden... | def existing_versions(self):
"""
Returns data with different cfgstr values that were previously computed
with this cacher.
"""
import glob
pattern = self.fname + '_*' + self.ext
for fname in glob.glob1(self.dpath, pattern):
fpath = join(self.dpath, fname)
yield fp... |
def set_dst_mode(self, index, dst):
'''Enable/disable daylight savings
Values: True, False
'''
body = {
'selection': {
'selectionType': 'thermostats',
'selectionMatch': self.thermostats[index]['identifier']},
'thermostat': ... | def function[set_dst_mode, parameter[self, index, dst]]:
constant[Enable/disable daylight savings
Values: True, False
]
variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da1b0354a30>, <ast.Constant object at 0x7da1b0354040>], [<ast.Dict object at 0x7da1b0354070>, <ast.Dict ... | keyword[def] identifier[set_dst_mode] ( identifier[self] , identifier[index] , identifier[dst] ):
literal[string]
identifier[body] ={
literal[string] :{
literal[string] : literal[string] ,
literal[string] : identifier[self] . identifier[thermostats] [ identifier[index] ]... | def set_dst_mode(self, index, dst):
"""Enable/disable daylight savings
Values: True, False
"""
body = {'selection': {'selectionType': 'thermostats', 'selectionMatch': self.thermostats[index]['identifier']}, 'thermostat': {'location': {'isDaylightSaving': dst}}}
log_msg_action = 'set dst mode... |
def DeserializeUnsigned(self, reader):
"""
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadUInt32()
self.PrevHash = reader.ReadUInt256()
self.MerkleRoot = reader.ReadUInt256()
self.Timestamp = ... | def function[DeserializeUnsigned, parameter[self, reader]]:
constant[
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
]
name[self].Version assign[=] call[name[reader].ReadUInt32, parameter[]]
name[self].PrevHash assign[=] call[name[reader]... | keyword[def] identifier[DeserializeUnsigned] ( identifier[self] , identifier[reader] ):
literal[string]
identifier[self] . identifier[Version] = identifier[reader] . identifier[ReadUInt32] ()
identifier[self] . identifier[PrevHash] = identifier[reader] . identifier[ReadUInt256] ()
... | def DeserializeUnsigned(self, reader):
"""
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadUInt32()
self.PrevHash = reader.ReadUInt256()
self.MerkleRoot = reader.ReadUInt256()
self.Timestamp = reader.ReadUInt32()
... |
def from_job_desc(cls, warm_start_config):
"""Creates an instance of ``WarmStartConfig`` class, from warm start configuration response from
DescribeTrainingJob.
Args:
warm_start_config (dict): The expected format of the ``warm_start_config`` contains two first-class
fiel... | def function[from_job_desc, parameter[cls, warm_start_config]]:
constant[Creates an instance of ``WarmStartConfig`` class, from warm start configuration response from
DescribeTrainingJob.
Args:
warm_start_config (dict): The expected format of the ``warm_start_config`` contains two f... | keyword[def] identifier[from_job_desc] ( identifier[cls] , identifier[warm_start_config] ):
literal[string]
keyword[if] keyword[not] identifier[warm_start_config] keyword[or] identifier[WARM_START_TYPE] keyword[not] keyword[in] identifier[warm_start_config] keyword[or] identifier[PARENT_HY... | def from_job_desc(cls, warm_start_config):
"""Creates an instance of ``WarmStartConfig`` class, from warm start configuration response from
DescribeTrainingJob.
Args:
warm_start_config (dict): The expected format of the ``warm_start_config`` contains two first-class
fields:
... |
def to_files(self, resource, directory):
"""
Dumps the given resource and all resources linked to it into a set of
representation files in the given directory.
"""
collections = self.__collect(resource)
for (mb_cls, coll) in iteritems_(collections):
fn = get_w... | def function[to_files, parameter[self, resource, directory]]:
constant[
Dumps the given resource and all resources linked to it into a set of
representation files in the given directory.
]
variable[collections] assign[=] call[name[self].__collect, parameter[name[resource]]]
... | keyword[def] identifier[to_files] ( identifier[self] , identifier[resource] , identifier[directory] ):
literal[string]
identifier[collections] = identifier[self] . identifier[__collect] ( identifier[resource] )
keyword[for] ( identifier[mb_cls] , identifier[coll] ) keyword[in] identifier[... | def to_files(self, resource, directory):
"""
Dumps the given resource and all resources linked to it into a set of
representation files in the given directory.
"""
collections = self.__collect(resource)
for (mb_cls, coll) in iteritems_(collections):
fn = get_write_collection_... |
def stop_app(self, callback_function_param=False):
""" Stops the current running app on the Chromecast. """
self.logger.info("Receiver:Stopping current app '%s'", self.app_id)
return self.send_message(
{MESSAGE_TYPE: 'STOP'},
inc_session_id=True, callback_function=callbac... | def function[stop_app, parameter[self, callback_function_param]]:
constant[ Stops the current running app on the Chromecast. ]
call[name[self].logger.info, parameter[constant[Receiver:Stopping current app '%s'], name[self].app_id]]
return[call[name[self].send_message, parameter[dictionary[[<ast.Name... | keyword[def] identifier[stop_app] ( identifier[self] , identifier[callback_function_param] = keyword[False] ):
literal[string]
identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[self] . identifier[app_id] )
keyword[return] identifier[self] . identifier... | def stop_app(self, callback_function_param=False):
""" Stops the current running app on the Chromecast. """
self.logger.info("Receiver:Stopping current app '%s'", self.app_id)
return self.send_message({MESSAGE_TYPE: 'STOP'}, inc_session_id=True, callback_function=callback_function_param) |
def schema(tg):
"""
Convert the table and column descriptions of a `TableGroup` into specifications for the
DB schema.
:param ds:
:return: A pair (tables, reference_tables).
"""
tables = {}
for tname, table in tg.tabledict.items():
t = TableSpec.from_table_metadata(table)
... | def function[schema, parameter[tg]]:
constant[
Convert the table and column descriptions of a `TableGroup` into specifications for the
DB schema.
:param ds:
:return: A pair (tables, reference_tables).
]
variable[tables] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name... | keyword[def] identifier[schema] ( identifier[tg] ):
literal[string]
identifier[tables] ={}
keyword[for] identifier[tname] , identifier[table] keyword[in] identifier[tg] . identifier[tabledict] . identifier[items] ():
identifier[t] = identifier[TableSpec] . identifier[from_table_metadata] (... | def schema(tg):
"""
Convert the table and column descriptions of a `TableGroup` into specifications for the
DB schema.
:param ds:
:return: A pair (tables, reference_tables).
"""
tables = {}
for (tname, table) in tg.tabledict.items():
t = TableSpec.from_table_metadata(table)
... |
def get_height_for_line(self, lineno, width):
"""
Return the height that a given line would need if it is rendered in a
space with the given width.
"""
try:
return self._line_heights[lineno, width]
except KeyError:
text = token_list_to_text(self.ge... | def function[get_height_for_line, parameter[self, lineno, width]]:
constant[
Return the height that a given line would need if it is rendered in a
space with the given width.
]
<ast.Try object at 0x7da204345990> | keyword[def] identifier[get_height_for_line] ( identifier[self] , identifier[lineno] , identifier[width] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_line_heights] [ identifier[lineno] , identifier[width] ]
keyword[except] identifier[KeyEr... | def get_height_for_line(self, lineno, width):
"""
Return the height that a given line would need if it is rendered in a
space with the given width.
"""
try:
return self._line_heights[lineno, width] # depends on [control=['try'], data=[]]
except KeyError:
text = token... |
def _send_update_port_statuses(self, port_ids, status):
"""Sends update notifications to set the operational status of the
list of router ports provided. To make each notification doesn't exceed
the RPC length, each message contains a maximum of MAX_PORTS_IN_BATCH
port ids.
:par... | def function[_send_update_port_statuses, parameter[self, port_ids, status]]:
constant[Sends update notifications to set the operational status of the
list of router ports provided. To make each notification doesn't exceed
the RPC length, each message contains a maximum of MAX_PORTS_IN_BATCH
... | keyword[def] identifier[_send_update_port_statuses] ( identifier[self] , identifier[port_ids] , identifier[status] ):
literal[string]
keyword[if] keyword[not] identifier[port_ids] :
keyword[return]
identifier[MAX_PORTS_IN_BATCH] = literal[int]
identifier[list_chu... | def _send_update_port_statuses(self, port_ids, status):
"""Sends update notifications to set the operational status of the
list of router ports provided. To make each notification doesn't exceed
the RPC length, each message contains a maximum of MAX_PORTS_IN_BATCH
port ids.
:param p... |
def retry_it(exceptions=(Exception, ), tries=10, wait=0, handler=None,
raised_exception=ReusablesError, raised_message=None):
"""
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of ex... | def function[retry_it, parameter[exceptions, tries, wait, handler, raised_exception, raised_message]]:
constant[
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of exceptions to catch
:par... | keyword[def] identifier[retry_it] ( identifier[exceptions] =( identifier[Exception] ,), identifier[tries] = literal[int] , identifier[wait] = literal[int] , identifier[handler] = keyword[None] ,
identifier[raised_exception] = identifier[ReusablesError] , identifier[raised_message] = keyword[None] ):
literal[str... | def retry_it(exceptions=(Exception,), tries=10, wait=0, handler=None, raised_exception=ReusablesError, raised_message=None):
"""
Retry a function if an exception is raised, or if output_check returns
False.
Message format options: {func} {args} {kwargs}
:param exceptions: tuple of exceptions to ca... |
def get_select_sql(self):
"""
Gets the SELECT field portion for the field without the alias. If the field
has a table, it will be included here like table.field
:return: Gets the SELECT field portion for the field without the alias
:rtype: str
"""
if self.table:
... | def function[get_select_sql, parameter[self]]:
constant[
Gets the SELECT field portion for the field without the alias. If the field
has a table, it will be included here like table.field
:return: Gets the SELECT field portion for the field without the alias
:rtype: str
... | keyword[def] identifier[get_select_sql] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[table] :
keyword[return] literal[string] . identifier[format] ( identifier[self] . identifier[table] . identifier[get_identifier] (), identifier[self] . identifier[... | def get_select_sql(self):
"""
Gets the SELECT field portion for the field without the alias. If the field
has a table, it will be included here like table.field
:return: Gets the SELECT field portion for the field without the alias
:rtype: str
"""
if self.table:
... |
def get_data(datastore, path):
'''
Get the configuration of the device tree at the given path
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the val... | def function[get_data, parameter[datastore, path]]:
constant[
Get the configuration of the device tree at the given path
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path:... | keyword[def] identifier[get_data] ( identifier[datastore] , identifier[path] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[path] , identifier[six] . identifier[string_types] ):
identifier[path] = literal[string] . identifier[split] ( identifier[path] )
keyword[return] i... | def get_data(datastore, path):
"""
Get the configuration of the device tree at the given path
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`DatastoreType` (``str`` enum).
:param path: The device path to set the val... |
def CoerceValue(value, value_type):
"""Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
"timeofday".
Returns:
... | def function[CoerceValue, parameter[value, value_type]]:
constant[Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
... | keyword[def] identifier[CoerceValue] ( identifier[value] , identifier[value_type] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[tuple] ):
keyword[if] ( identifier[len] ( identifier[value] ) keyword[not] keyword[in] [ literal[int] , literal[int] ] ... | def CoerceValue(value, value_type):
"""Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
"timeofday".
Returns:
... |
def solve(self, X, rank, max_iter=500, stopping_criterion=1e-5,
lambda_reg=0.0, dtype=np.float32, rng=None):
"""Solve CPD
Args:
X (numpy.ndarray): Target tensor of CPD.
rank (int): Rank of the approximate tensor.
max_iter (int): Max iteration of the ALS... | def function[solve, parameter[self, X, rank, max_iter, stopping_criterion, lambda_reg, dtype, rng]]:
constant[Solve CPD
Args:
X (numpy.ndarray): Target tensor of CPD.
rank (int): Rank of the approximate tensor.
max_iter (int): Max iteration of the ALS.
st... | keyword[def] identifier[solve] ( identifier[self] , identifier[X] , identifier[rank] , identifier[max_iter] = literal[int] , identifier[stopping_criterion] = literal[int] ,
identifier[lambda_reg] = literal[int] , identifier[dtype] = identifier[np] . identifier[float32] , identifier[rng] = keyword[None] ):
l... | def solve(self, X, rank, max_iter=500, stopping_criterion=1e-05, lambda_reg=0.0, dtype=np.float32, rng=None):
"""Solve CPD
Args:
X (numpy.ndarray): Target tensor of CPD.
rank (int): Rank of the approximate tensor.
max_iter (int): Max iteration of the ALS.
sto... |
async def _drain_writer(self, timeout: NumType = None) -> None:
"""
Wraps writer.drain() with error handling.
"""
if self._stream_writer is None:
raise SMTPServerDisconnected("Client not connected")
# Wrapping drain in a task makes mypy happy
drain_task = asy... | <ast.AsyncFunctionDef object at 0x7da18fe93550> | keyword[async] keyword[def] identifier[_drain_writer] ( identifier[self] , identifier[timeout] : identifier[NumType] = keyword[None] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[_stream_writer] keyword[is] keyword[None] :
keyword[raise] identifier[... | async def _drain_writer(self, timeout: NumType=None) -> None:
"""
Wraps writer.drain() with error handling.
"""
if self._stream_writer is None:
raise SMTPServerDisconnected('Client not connected') # depends on [control=['if'], data=[]]
# Wrapping drain in a task makes mypy happy
... |
def pausable_restart_on_change(restart_map, stopstart=False,
restart_functions=None):
"""A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(.... | def function[pausable_restart_on_change, parameter[restart_map, stopstart, restart_functions]]:
constant[A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(...) decorat... | keyword[def] identifier[pausable_restart_on_change] ( identifier[restart_map] , identifier[stopstart] = keyword[False] ,
identifier[restart_functions] = keyword[None] ):
literal[string]
keyword[def] identifier[wrap] ( identifier[f] ):
identifier[__restart_map_cache] ={ literal[string] ... | def pausable_restart_on_change(restart_map, stopstart=False, restart_functions=None):
"""A restart_on_change decorator that checks to see if the unit is
paused. If it is paused then the decorated function doesn't fire.
This is provided as a helper, as the @restart_on_change(...) decorator
is in core.ho... |
def cmd_distclean(self, *args):
'''Clean the whole Buildozer environment.
'''
print("Warning: Your ndk, sdk and all other cached packages will be"
" removed. Continue? (y/n)")
if sys.stdin.readline().lower()[0] == 'y':
self.info('Clean the global build directory... | def function[cmd_distclean, parameter[self]]:
constant[Clean the whole Buildozer environment.
]
call[name[print], parameter[constant[Warning: Your ndk, sdk and all other cached packages will be removed. Continue? (y/n)]]]
if compare[call[call[call[name[sys].stdin.readline, parameter[]].l... | keyword[def] identifier[cmd_distclean] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[print] ( literal[string]
literal[string] )
keyword[if] identifier[sys] . identifier[stdin] . identifier[readline] (). identifier[lower] ()[ literal[int] ]== literal[string... | def cmd_distclean(self, *args):
"""Clean the whole Buildozer environment.
"""
print('Warning: Your ndk, sdk and all other cached packages will be removed. Continue? (y/n)')
if sys.stdin.readline().lower()[0] == 'y':
self.info('Clean the global build directory')
if not exists(self.glo... |
def _parse_canonical_decimal128(doc):
"""Decode a JSON decimal128 to bson.decimal128.Decimal128."""
d_str = doc['$numberDecimal']
if len(doc) != 1:
raise TypeError('Bad $numberDecimal, extra field(s): %s' % (doc,))
if not isinstance(d_str, string_type):
raise TypeError('$numberDecimal mu... | def function[_parse_canonical_decimal128, parameter[doc]]:
constant[Decode a JSON decimal128 to bson.decimal128.Decimal128.]
variable[d_str] assign[=] call[name[doc]][constant[$numberDecimal]]
if compare[call[name[len], parameter[name[doc]]] not_equal[!=] constant[1]] begin[:]
<ast.Raise... | keyword[def] identifier[_parse_canonical_decimal128] ( identifier[doc] ):
literal[string]
identifier[d_str] = identifier[doc] [ literal[string] ]
keyword[if] identifier[len] ( identifier[doc] )!= literal[int] :
keyword[raise] identifier[TypeError] ( literal[string] %( identifier[doc] ,))
... | def _parse_canonical_decimal128(doc):
"""Decode a JSON decimal128 to bson.decimal128.Decimal128."""
d_str = doc['$numberDecimal']
if len(doc) != 1:
raise TypeError('Bad $numberDecimal, extra field(s): %s' % (doc,)) # depends on [control=['if'], data=[]]
if not isinstance(d_str, string_type):
... |
def combine_time_series(
time_series_dict: Dict, kind: str, *, split_directions: bool = False
) -> DataFrame:
"""
Combine the many time series DataFrames in the given dictionary
into one time series DataFrame with hierarchical columns.
Parameters
----------
time_series_dict : dictionary
... | def function[combine_time_series, parameter[time_series_dict, kind]]:
constant[
Combine the many time series DataFrames in the given dictionary
into one time series DataFrame with hierarchical columns.
Parameters
----------
time_series_dict : dictionary
Has the form string -> time s... | keyword[def] identifier[combine_time_series] (
identifier[time_series_dict] : identifier[Dict] , identifier[kind] : identifier[str] ,*, identifier[split_directions] : identifier[bool] = keyword[False]
)-> identifier[DataFrame] :
literal[string]
keyword[if] identifier[kind] keyword[not] keyword[in] [ l... | def combine_time_series(time_series_dict: Dict, kind: str, *, split_directions: bool=False) -> DataFrame:
"""
Combine the many time series DataFrames in the given dictionary
into one time series DataFrame with hierarchical columns.
Parameters
----------
time_series_dict : dictionary
Has... |
def to_yaml(cls, representer, node):
"""How to serialize this class back to yaml."""
return representer.represent_scalar(cls.yaml_tag, node.value) | def function[to_yaml, parameter[cls, representer, node]]:
constant[How to serialize this class back to yaml.]
return[call[name[representer].represent_scalar, parameter[name[cls].yaml_tag, name[node].value]]] | keyword[def] identifier[to_yaml] ( identifier[cls] , identifier[representer] , identifier[node] ):
literal[string]
keyword[return] identifier[representer] . identifier[represent_scalar] ( identifier[cls] . identifier[yaml_tag] , identifier[node] . identifier[value] ) | def to_yaml(cls, representer, node):
"""How to serialize this class back to yaml."""
return representer.represent_scalar(cls.yaml_tag, node.value) |
def setup():
"""
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
"""
# create an index template
index_template = BlogPost._index.as_template(ALIAS, PATTERN)
# upload the templat... | def function[setup, parameter[]]:
constant[
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
]
variable[index_template] assign[=] call[name[BlogPost]._index.as_template, paramete... | keyword[def] identifier[setup] ():
literal[string]
identifier[index_template] = identifier[BlogPost] . identifier[_index] . identifier[as_template] ( identifier[ALIAS] , identifier[PATTERN] )
identifier[index_template] . identifier[save] ()
keyword[if] keyword[not] identifi... | def setup():
"""
Create the index template in elasticsearch specifying the mappings and any
settings to be used. This can be run at any time, ideally at every new code
deploy.
"""
# create an index template
index_template = BlogPost._index.as_template(ALIAS, PATTERN)
# upload the templat... |
def _get_chunks(chunksize, *iterables):
"""Iterates over zip()ed iterables in chunks. """
if sys.version_info < (3, 3):
it = itertools.izip(*iterables)
else:
it = zip(*iterables)
while True:
chunk = tuple(itertools.islice(it, chunksize))
if not chunk:
return
... | def function[_get_chunks, parameter[chunksize]]:
constant[Iterates over zip()ed iterables in chunks. ]
if compare[name[sys].version_info less[<] tuple[[<ast.Constant object at 0x7da18f7219f0>, <ast.Constant object at 0x7da18f722bf0>]]] begin[:]
variable[it] assign[=] call[name[itertools]... | keyword[def] identifier[_get_chunks] ( identifier[chunksize] ,* identifier[iterables] ):
literal[string]
keyword[if] identifier[sys] . identifier[version_info] <( literal[int] , literal[int] ):
identifier[it] = identifier[itertools] . identifier[izip] (* identifier[iterables] )
keyword[else]... | def _get_chunks(chunksize, *iterables):
"""Iterates over zip()ed iterables in chunks. """
if sys.version_info < (3, 3):
it = itertools.izip(*iterables) # depends on [control=['if'], data=[]]
else:
it = zip(*iterables)
while True:
chunk = tuple(itertools.islice(it, chunksize))
... |
def get_message_content(self):
"""
Given the Slap XML, extract out the payload.
"""
body = self.doc.find(
".//{http://salmon-protocol.org/ns/magic-env}data").text
body = urlsafe_b64decode(body.encode("ascii"))
logger.debug("diaspora.protocol.get_message_cont... | def function[get_message_content, parameter[self]]:
constant[
Given the Slap XML, extract out the payload.
]
variable[body] assign[=] call[name[self].doc.find, parameter[constant[.//{http://salmon-protocol.org/ns/magic-env}data]]].text
variable[body] assign[=] call[name[urlsafe_b... | keyword[def] identifier[get_message_content] ( identifier[self] ):
literal[string]
identifier[body] = identifier[self] . identifier[doc] . identifier[find] (
literal[string] ). identifier[text]
identifier[body] = identifier[urlsafe_b64decode] ( identifier[body] . identifier[enco... | def get_message_content(self):
"""
Given the Slap XML, extract out the payload.
"""
body = self.doc.find('.//{http://salmon-protocol.org/ns/magic-env}data').text
body = urlsafe_b64decode(body.encode('ascii'))
logger.debug('diaspora.protocol.get_message_content: %s', body)
return body |
def pretty_print(self, printer: Optional[Printer] = None, min_width: int = 1, min_unit_width: int = 1):
"""
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min... | def function[pretty_print, parameter[self, printer, min_width, min_unit_width]]:
constant[
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min_unit_width = 2:
... | keyword[def] identifier[pretty_print] ( identifier[self] , identifier[printer] : identifier[Optional] [ identifier[Printer] ]= keyword[None] , identifier[min_width] : identifier[int] = literal[int] , identifier[min_unit_width] : identifier[int] = literal[int] ):
literal[string]
identifier[unit] , i... | def pretty_print(self, printer: Optional[Printer]=None, min_width: int=1, min_unit_width: int=1):
"""
Prints the file size (and it's unit), reserving places for longer sizes and units.
For example:
min_unit_width = 1:
793 B
100 KB
min_unit_widt... |
def lstrip_ws_and_chars(string, chars):
"""Remove leading whitespace and characters from a string.
Parameters
----------
string : `str`
String to strip.
chars : `str`
Characters to remove.
Returns
-------
`str`
Stripped string.
Examples
--------
>>>... | def function[lstrip_ws_and_chars, parameter[string, chars]]:
constant[Remove leading whitespace and characters from a string.
Parameters
----------
string : `str`
String to strip.
chars : `str`
Characters to remove.
Returns
-------
`str`
Stripped string.
... | keyword[def] identifier[lstrip_ws_and_chars] ( identifier[string] , identifier[chars] ):
literal[string]
identifier[res] = identifier[string] . identifier[lstrip] (). identifier[lstrip] ( identifier[chars] )
keyword[while] identifier[len] ( identifier[res] )!= identifier[len] ( identifier[string] ):
... | def lstrip_ws_and_chars(string, chars):
"""Remove leading whitespace and characters from a string.
Parameters
----------
string : `str`
String to strip.
chars : `str`
Characters to remove.
Returns
-------
`str`
Stripped string.
Examples
--------
>>>... |
def forward_exception(self, etype, evalue, tb):
"""
Forward the exception onto the backup copy that was made of the sys.__excepthook__
:param etype: Exceoption type
:param evalue: Exception value
:param tb: Traceback
:return:
"""
self._excepthook(etype, e... | def function[forward_exception, parameter[self, etype, evalue, tb]]:
constant[
Forward the exception onto the backup copy that was made of the sys.__excepthook__
:param etype: Exceoption type
:param evalue: Exception value
:param tb: Traceback
:return:
]
... | keyword[def] identifier[forward_exception] ( identifier[self] , identifier[etype] , identifier[evalue] , identifier[tb] ):
literal[string]
identifier[self] . identifier[_excepthook] ( identifier[etype] , identifier[evalue] , identifier[tb] ) | def forward_exception(self, etype, evalue, tb):
"""
Forward the exception onto the backup copy that was made of the sys.__excepthook__
:param etype: Exceoption type
:param evalue: Exception value
:param tb: Traceback
:return:
"""
self._excepthook(etype, evalue, t... |
def kernel():
"""
Handle linux kernel update
"""
print('================================')
print(' WARNING: upgrading the kernel')
print('================================')
time.sleep(5)
print('-[kernel]----------')
cmd('rpi-update', True)
print(' >> You MUST reboot to load the new kernel <<') | def function[kernel, parameter[]]:
constant[
Handle linux kernel update
]
call[name[print], parameter[constant[================================]]]
call[name[print], parameter[constant[ WARNING: upgrading the kernel]]]
call[name[print], parameter[constant[==============================... | keyword[def] identifier[kernel] ():
literal[string]
identifier[print] ( literal[string] )
identifier[print] ( literal[string] )
identifier[print] ( literal[string] )
identifier[time] . identifier[sleep] ( literal[int] )
identifier[print] ( literal[string] )
identifier[cmd] ( literal[string] , keyword[... | def kernel():
"""
Handle linux kernel update
"""
print('================================')
print(' WARNING: upgrading the kernel')
print('================================')
time.sleep(5)
print('-[kernel]----------')
cmd('rpi-update', True)
print(' >> You MUST reboot to load the new ke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.