code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def get_account_details(account):
""" Get the account details. """
result = []
for datastore in _get_datastores():
value = datastore.get_account_details(account)
value['datastore'] = datastore.config['DESCRIPTION']
result.append(value)
return result | def function[get_account_details, parameter[account]]:
constant[ Get the account details. ]
variable[result] assign[=] list[[]]
for taget[name[datastore]] in starred[call[name[_get_datastores], parameter[]]] begin[:]
variable[value] assign[=] call[name[datastore].get_account_deta... | keyword[def] identifier[get_account_details] ( identifier[account] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[datastore] keyword[in] identifier[_get_datastores] ():
identifier[value] = identifier[datastore] . identifier[get_account_details] ( identifier[account] )
... | def get_account_details(account):
""" Get the account details. """
result = []
for datastore in _get_datastores():
value = datastore.get_account_details(account)
value['datastore'] = datastore.config['DESCRIPTION']
result.append(value) # depends on [control=['for'], data=['datastore... |
def doeqdi(x, y, UP=False):
"""
Takes digitized x,y, data and returns the dec,inc, assuming an
equal area projection
Parameters
__________________
x : array of digitized x from point on equal area projection
y : array of igitized y from point on equal area projection
UP : if... | def function[doeqdi, parameter[x, y, UP]]:
constant[
Takes digitized x,y, data and returns the dec,inc, assuming an
equal area projection
Parameters
__________________
x : array of digitized x from point on equal area projection
y : array of igitized y from point on equal area p... | keyword[def] identifier[doeqdi] ( identifier[x] , identifier[y] , identifier[UP] = keyword[False] ):
literal[string]
identifier[xp] , identifier[yp] = identifier[y] , identifier[x]
identifier[r] = identifier[np] . identifier[sqrt] ( identifier[xp] ** literal[int] + identifier[yp] ** literal[int] )
... | def doeqdi(x, y, UP=False):
"""
Takes digitized x,y, data and returns the dec,inc, assuming an
equal area projection
Parameters
__________________
x : array of digitized x from point on equal area projection
y : array of igitized y from point on equal area projection
UP : if... |
def is_legal_subject(self, c: OntologyClass) -> bool:
"""
is_legal_subject(c) = true if
- c in included_domains(self) or
- super_classes_closure(c) intersection included_domains(self) is not empty
There is no need to check the included_domains(super_properties_closure(self)) bec... | def function[is_legal_subject, parameter[self, c]]:
constant[
is_legal_subject(c) = true if
- c in included_domains(self) or
- super_classes_closure(c) intersection included_domains(self) is not empty
There is no need to check the included_domains(super_properties_closure(self))... | keyword[def] identifier[is_legal_subject] ( identifier[self] , identifier[c] : identifier[OntologyClass] )-> identifier[bool] :
literal[string]
identifier[domains] = identifier[self] . identifier[included_domains] ()
keyword[return] identifier[c] keyword[and] ( keyword[not] identifier[d... | def is_legal_subject(self, c: OntologyClass) -> bool:
"""
is_legal_subject(c) = true if
- c in included_domains(self) or
- super_classes_closure(c) intersection included_domains(self) is not empty
There is no need to check the included_domains(super_properties_closure(self)) because... |
def grouped_count_sizes(fileslist, fgrouped): # pragma: no cover
'''Compute the total size per group and total number of files. Useful to check that everything is OK.'''
fsizes = {}
total_files = 0
allitems = None
if isinstance(fgrouped, dict):
allitems = fgrouped.iteritems()
elif isins... | def function[grouped_count_sizes, parameter[fileslist, fgrouped]]:
constant[Compute the total size per group and total number of files. Useful to check that everything is OK.]
variable[fsizes] assign[=] dictionary[[], []]
variable[total_files] assign[=] constant[0]
variable[allitems] ass... | keyword[def] identifier[grouped_count_sizes] ( identifier[fileslist] , identifier[fgrouped] ):
literal[string]
identifier[fsizes] ={}
identifier[total_files] = literal[int]
identifier[allitems] = keyword[None]
keyword[if] identifier[isinstance] ( identifier[fgrouped] , identifier[dict] ):... | def grouped_count_sizes(fileslist, fgrouped): # pragma: no cover
'Compute the total size per group and total number of files. Useful to check that everything is OK.'
fsizes = {}
total_files = 0
allitems = None
if isinstance(fgrouped, dict):
allitems = fgrouped.iteritems() # depends on [con... |
def add_condition(self, condition: z3.BoolRef) -> None:
"""
Add condition to the dependence map
:param condition: The condition that is to be added to the dependence map
"""
variables = set(_get_expr_variables(condition))
relevant_buckets = set()
for variable in v... | def function[add_condition, parameter[self, condition]]:
constant[
Add condition to the dependence map
:param condition: The condition that is to be added to the dependence map
]
variable[variables] assign[=] call[name[set], parameter[call[name[_get_expr_variables], parameter[nam... | keyword[def] identifier[add_condition] ( identifier[self] , identifier[condition] : identifier[z3] . identifier[BoolRef] )-> keyword[None] :
literal[string]
identifier[variables] = identifier[set] ( identifier[_get_expr_variables] ( identifier[condition] ))
identifier[relevant_buckets] = i... | def add_condition(self, condition: z3.BoolRef) -> None:
"""
Add condition to the dependence map
:param condition: The condition that is to be added to the dependence map
"""
variables = set(_get_expr_variables(condition))
relevant_buckets = set()
for variable in variables:
... |
def looking_for(self):
"""Copy looking for attributes from the source profile to the
destination profile.
"""
looking_for = self.source_profile.looking_for
return self.dest_user.profile.looking_for.update(
gentation=looking_for.gentation,
single=looking_fo... | def function[looking_for, parameter[self]]:
constant[Copy looking for attributes from the source profile to the
destination profile.
]
variable[looking_for] assign[=] name[self].source_profile.looking_for
return[call[name[self].dest_user.profile.looking_for.update, parameter[]]] | keyword[def] identifier[looking_for] ( identifier[self] ):
literal[string]
identifier[looking_for] = identifier[self] . identifier[source_profile] . identifier[looking_for]
keyword[return] identifier[self] . identifier[dest_user] . identifier[profile] . identifier[looking_for] . identifi... | def looking_for(self):
"""Copy looking for attributes from the source profile to the
destination profile.
"""
looking_for = self.source_profile.looking_for
return self.dest_user.profile.looking_for.update(gentation=looking_for.gentation, single=looking_for.single, near_me=looking_for.near_me... |
def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db()
res = _call_brew('outdated --json=v1')
ret =... | def function[list_upgrades, parameter[refresh]]:
constant[
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
]
if name[refresh] begin[:]
call[name[refresh_db], parameter[]]
variabl... | keyword[def] identifier[list_upgrades] ( identifier[refresh] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[refresh] :
identifier[refresh_db] ()
identifier[res] = identifier[_call_brew] ( literal[string] )
identifier[ret] ={}
keyword[try] :
... | def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613
"\n Check whether or not an upgrade is available for all packages\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_upgrades\n "
if refresh:
refresh_db() # depends on [control=['if'], data=[]]
res =... |
def update(self, pointvol):
"""Update the bounding ellipsoid using the current set of
live points."""
# Check if we should use the provided pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the ellipsoid.
... | def function[update, parameter[self, pointvol]]:
constant[Update the bounding ellipsoid using the current set of
live points.]
if name[self].use_pool_update begin[:]
variable[pool] assign[=] name[self].pool
call[name[self].ell.update, parameter[name[self].live_u]]
... | keyword[def] identifier[update] ( identifier[self] , identifier[pointvol] ):
literal[string]
keyword[if] identifier[self] . identifier[use_pool_update] :
identifier[pool] = identifier[self] . identifier[pool]
keyword[else] :
identifier[pool] = keyword[... | def update(self, pointvol):
"""Update the bounding ellipsoid using the current set of
live points."""
# Check if we should use the provided pool for updating.
if self.use_pool_update:
pool = self.pool # depends on [control=['if'], data=[]]
else:
pool = None
# Update the elli... |
def get_allowed_reset_keys_values(self):
"""Get the allowed values for resetting the system.
:returns: A set with the allowed values.
"""
reset_keys_action = self._get_reset_keys_action_element()
if not reset_keys_action.allowed_values:
LOG.warning('Could not figure... | def function[get_allowed_reset_keys_values, parameter[self]]:
constant[Get the allowed values for resetting the system.
:returns: A set with the allowed values.
]
variable[reset_keys_action] assign[=] call[name[self]._get_reset_keys_action_element, parameter[]]
if <ast.UnaryOp o... | keyword[def] identifier[get_allowed_reset_keys_values] ( identifier[self] ):
literal[string]
identifier[reset_keys_action] = identifier[self] . identifier[_get_reset_keys_action_element] ()
keyword[if] keyword[not] identifier[reset_keys_action] . identifier[allowed_values] :
... | def get_allowed_reset_keys_values(self):
"""Get the allowed values for resetting the system.
:returns: A set with the allowed values.
"""
reset_keys_action = self._get_reset_keys_action_element()
if not reset_keys_action.allowed_values:
LOG.warning('Could not figure out the allowed ... |
def _set_version(self, v, load=False):
"""
Setter method for version, mapped from YANG variable /rbridge_id/openflow/logical_instance/version (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_version is considered as a private
method. Backends looking to populat... | def function[_set_version, parameter[self, v, load]]:
constant[
Setter method for version, mapped from YANG variable /rbridge_id/openflow/logical_instance/version (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_version is considered as a private
method. Ba... | keyword[def] identifier[_set_version] ( 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] :
identi... | def _set_version(self, v, load=False):
"""
Setter method for version, mapped from YANG variable /rbridge_id/openflow/logical_instance/version (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_version is considered as a private
method. Backends looking to populat... |
def imagetransformer_moe_tiny():
"""Set of hyperparameters for a very small imagetransformer with MoE."""
hparams = imagetransformer_tiny()
hparams.hidden_size = 64
hparams.batch_size = 1
hparams.num_hidden_layers = 3
hparams.dec_attention_type = cia.AttentionType.MOE_LOCAL_1D
hparams.add_hparam("moe_laye... | def function[imagetransformer_moe_tiny, parameter[]]:
constant[Set of hyperparameters for a very small imagetransformer with MoE.]
variable[hparams] assign[=] call[name[imagetransformer_tiny], parameter[]]
name[hparams].hidden_size assign[=] constant[64]
name[hparams].batch_size assign[=... | keyword[def] identifier[imagetransformer_moe_tiny] ():
literal[string]
identifier[hparams] = identifier[imagetransformer_tiny] ()
identifier[hparams] . identifier[hidden_size] = literal[int]
identifier[hparams] . identifier[batch_size] = literal[int]
identifier[hparams] . identifier[num_hidden_layer... | def imagetransformer_moe_tiny():
"""Set of hyperparameters for a very small imagetransformer with MoE."""
hparams = imagetransformer_tiny()
hparams.hidden_size = 64
hparams.batch_size = 1
hparams.num_hidden_layers = 3
hparams.dec_attention_type = cia.AttentionType.MOE_LOCAL_1D
hparams.add_hp... |
def load_tf_weights_in_bert(model, tf_checkpoint_path):
""" Load tf checkpoints in a pytorch model
"""
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please ... | def function[load_tf_weights_in_bert, parameter[model, tf_checkpoint_path]]:
constant[ Load tf checkpoints in a pytorch model
]
<ast.Try object at 0x7da1b20a9a20>
variable[tf_path] assign[=] call[name[os].path.abspath, parameter[name[tf_checkpoint_path]]]
call[name[print], parameter[call... | keyword[def] identifier[load_tf_weights_in_bert] ( identifier[model] , identifier[tf_checkpoint_path] ):
literal[string]
keyword[try] :
keyword[import] identifier[re]
keyword[import] identifier[numpy] keyword[as] identifier[np]
keyword[import] identifier[tensorflow] keywo... | def load_tf_weights_in_bert(model, tf_checkpoint_path):
""" Load tf checkpoints in a pytorch model
"""
try:
import re
import numpy as np
import tensorflow as tf # depends on [control=['try'], data=[]]
except ImportError:
print('Loading a TensorFlow models in PyTorch, req... |
def native_container(self):
"""Native container object."""
if self.__native is None:
self.__native = self._get_container()
return self.__native | def function[native_container, parameter[self]]:
constant[Native container object.]
if compare[name[self].__native is constant[None]] begin[:]
name[self].__native assign[=] call[name[self]._get_container, parameter[]]
return[name[self].__native] | keyword[def] identifier[native_container] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__native] keyword[is] keyword[None] :
identifier[self] . identifier[__native] = identifier[self] . identifier[_get_container] ()
keyword[return] ident... | def native_container(self):
"""Native container object."""
if self.__native is None:
self.__native = self._get_container() # depends on [control=['if'], data=[]]
return self.__native |
def plot_losses(calc_id, bins=7):
"""
losses_by_event plotter
"""
# read the hazard data
dstore = util.read(calc_id)
losses_by_rlzi = dict(extract(dstore, 'losses_by_event'))
oq = dstore['oqparam']
plt = make_figure(losses_by_rlzi, oq.loss_dt().names, bins)
plt.show() | def function[plot_losses, parameter[calc_id, bins]]:
constant[
losses_by_event plotter
]
variable[dstore] assign[=] call[name[util].read, parameter[name[calc_id]]]
variable[losses_by_rlzi] assign[=] call[name[dict], parameter[call[name[extract], parameter[name[dstore], constant[losses_by... | keyword[def] identifier[plot_losses] ( identifier[calc_id] , identifier[bins] = literal[int] ):
literal[string]
identifier[dstore] = identifier[util] . identifier[read] ( identifier[calc_id] )
identifier[losses_by_rlzi] = identifier[dict] ( identifier[extract] ( identifier[dstore] , literal[strin... | def plot_losses(calc_id, bins=7):
"""
losses_by_event plotter
"""
# read the hazard data
dstore = util.read(calc_id)
losses_by_rlzi = dict(extract(dstore, 'losses_by_event'))
oq = dstore['oqparam']
plt = make_figure(losses_by_rlzi, oq.loss_dt().names, bins)
plt.show() |
def array(source_array, ctx=None, dtype=None):
"""Creates an array from any object exposing the array interface.
Parameters
----------
source_array : array_like
An object exposing the array interface, an object whose `__array__`
method returns an array, or any (nested) sequence.
ctx... | def function[array, parameter[source_array, ctx, dtype]]:
constant[Creates an array from any object exposing the array interface.
Parameters
----------
source_array : array_like
An object exposing the array interface, an object whose `__array__`
method returns an array, or any (nest... | keyword[def] identifier[array] ( identifier[source_array] , identifier[ctx] = keyword[None] , identifier[dtype] = keyword[None] ):
literal[string]
keyword[if] identifier[spsp] keyword[is] keyword[not] keyword[None] keyword[and] identifier[isinstance] ( identifier[source_array] , identifier[spsp] . id... | def array(source_array, ctx=None, dtype=None):
"""Creates an array from any object exposing the array interface.
Parameters
----------
source_array : array_like
An object exposing the array interface, an object whose `__array__`
method returns an array, or any (nested) sequence.
ctx... |
def members(self):
"""Returns a list of :class:`Member` that are currently inside this voice channel."""
ret = []
for user_id, state in self.guild._voice_states.items():
if state.channel.id == self.id:
member = self.guild.get_member(user_id)
if member ... | def function[members, parameter[self]]:
constant[Returns a list of :class:`Member` that are currently inside this voice channel.]
variable[ret] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b2046e30>, <ast.Name object at 0x7da1b2046380>]]] in starred[call[name[self].guild._voice_... | keyword[def] identifier[members] ( identifier[self] ):
literal[string]
identifier[ret] =[]
keyword[for] identifier[user_id] , identifier[state] keyword[in] identifier[self] . identifier[guild] . identifier[_voice_states] . identifier[items] ():
keyword[if] identifier[state... | def members(self):
"""Returns a list of :class:`Member` that are currently inside this voice channel."""
ret = []
for (user_id, state) in self.guild._voice_states.items():
if state.channel.id == self.id:
member = self.guild.get_member(user_id)
if member is not None:
... |
def cublasChpr(handle, uplo, n, alpha, x, incx, AP):
"""
Rank-1 operation on Hermitian-packed matrix.
"""
status = _libcublas.cublasChpr_v2(handle,
_CUBLAS_FILL_MODE[uplo],
n, ctypes.byref(ctypes.c_float(alpha)),
... | def function[cublasChpr, parameter[handle, uplo, n, alpha, x, incx, AP]]:
constant[
Rank-1 operation on Hermitian-packed matrix.
]
variable[status] assign[=] call[name[_libcublas].cublasChpr_v2, parameter[name[handle], call[name[_CUBLAS_FILL_MODE]][name[uplo]], name[n], call[name[ctypes].by... | keyword[def] identifier[cublasChpr] ( identifier[handle] , identifier[uplo] , identifier[n] , identifier[alpha] , identifier[x] , identifier[incx] , identifier[AP] ):
literal[string]
identifier[status] = identifier[_libcublas] . identifier[cublasChpr_v2] ( identifier[handle] ,
identifier[_CUBLAS_FILL... | def cublasChpr(handle, uplo, n, alpha, x, incx, AP):
"""
Rank-1 operation on Hermitian-packed matrix.
"""
status = _libcublas.cublasChpr_v2(handle, _CUBLAS_FILL_MODE[uplo], n, ctypes.byref(ctypes.c_float(alpha)), int(x), incx, int(AP))
cublasCheckStatus(status) |
def add_platform(name, platform_set, server_url):
'''
To add an ASAM platform using the specified ASAM platform set on the Novell
Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com
'''
config = _get_asam_config... | def function[add_platform, parameter[name, platform_set, server_url]]:
constant[
To add an ASAM platform using the specified ASAM platform set on the Novell
Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com
]
... | keyword[def] identifier[add_platform] ( identifier[name] , identifier[platform_set] , identifier[server_url] ):
literal[string]
identifier[config] = identifier[_get_asam_configuration] ( identifier[server_url] )
keyword[if] keyword[not] identifier[config] :
keyword[return] keyword[False]
... | def add_platform(name, platform_set, server_url):
"""
To add an ASAM platform using the specified ASAM platform set on the Novell
Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com
"""
config = _get_asam_config... |
def trim_path(path, length=30):
"""
trim path to specified length, for example:
>>> a = '/project/apps/default/settings.ini'
>>> trim_path(a)
'.../apps/default/settings.ini'
The real length will be length-4, it'll left '.../' for output.
"""
s = path.replace('\\', '/').split('/')
... | def function[trim_path, parameter[path, length]]:
constant[
trim path to specified length, for example:
>>> a = '/project/apps/default/settings.ini'
>>> trim_path(a)
'.../apps/default/settings.ini'
The real length will be length-4, it'll left '.../' for output.
]
variable[s]... | keyword[def] identifier[trim_path] ( identifier[path] , identifier[length] = literal[int] ):
literal[string]
identifier[s] = identifier[path] . identifier[replace] ( literal[string] , literal[string] ). identifier[split] ( literal[string] )
identifier[t] =- literal[int]
keyword[for] identifier[... | def trim_path(path, length=30):
"""
trim path to specified length, for example:
>>> a = '/project/apps/default/settings.ini'
>>> trim_path(a)
'.../apps/default/settings.ini'
The real length will be length-4, it'll left '.../' for output.
"""
s = path.replace('\\', '/').split('/')
... |
def MakeTargetMask(target, pad=0):
"""Create an attention mask to hide padding and future words."""
target_mask = (target != pad)[ :, np.newaxis, :]
target_dtype = target_mask.dtype
causal_mask = onp.tril(onp.ones((1, target.shape[-1], target.shape[-1]),
dtype=target_dtype), k=... | def function[MakeTargetMask, parameter[target, pad]]:
constant[Create an attention mask to hide padding and future words.]
variable[target_mask] assign[=] call[compare[name[target] not_equal[!=] name[pad]]][tuple[[<ast.Slice object at 0x7da18f58c430>, <ast.Attribute object at 0x7da18f58d9c0>, <ast.Slice... | keyword[def] identifier[MakeTargetMask] ( identifier[target] , identifier[pad] = literal[int] ):
literal[string]
identifier[target_mask] =( identifier[target] != identifier[pad] )[:, identifier[np] . identifier[newaxis] ,:]
identifier[target_dtype] = identifier[target_mask] . identifier[dtype]
identifie... | def MakeTargetMask(target, pad=0):
"""Create an attention mask to hide padding and future words."""
target_mask = (target != pad)[:, np.newaxis, :]
target_dtype = target_mask.dtype
causal_mask = onp.tril(onp.ones((1, target.shape[-1], target.shape[-1]), dtype=target_dtype), k=0)
target_mask = target... |
def normalize_codec_name(name):
'''Return the Python name of the encoder/decoder
Returns:
str, None
'''
name = UnicodeDammit.CHARSET_ALIASES.get(name.lower(), name)
try:
return codecs.lookup(name).name
except (LookupError, TypeError, ValueError):
# TypeError occurs when... | def function[normalize_codec_name, parameter[name]]:
constant[Return the Python name of the encoder/decoder
Returns:
str, None
]
variable[name] assign[=] call[name[UnicodeDammit].CHARSET_ALIASES.get, parameter[call[name[name].lower, parameter[]], name[name]]]
<ast.Try object at 0x7d... | keyword[def] identifier[normalize_codec_name] ( identifier[name] ):
literal[string]
identifier[name] = identifier[UnicodeDammit] . identifier[CHARSET_ALIASES] . identifier[get] ( identifier[name] . identifier[lower] (), identifier[name] )
keyword[try] :
keyword[return] identifier[codecs] . ... | def normalize_codec_name(name):
"""Return the Python name of the encoder/decoder
Returns:
str, None
"""
name = UnicodeDammit.CHARSET_ALIASES.get(name.lower(), name)
try:
return codecs.lookup(name).name # depends on [control=['try'], data=[]]
except (LookupError, TypeError, Valu... |
def SerializeExclusiveData(self, writer):
"""
Serialize object.
Args:
writer (neo.IO.BinaryWriter):
"""
writer.WriteVarBytes(self.Script)
if self.Version >= 1:
writer.WriteFixed8(self.Gas) | def function[SerializeExclusiveData, parameter[self, writer]]:
constant[
Serialize object.
Args:
writer (neo.IO.BinaryWriter):
]
call[name[writer].WriteVarBytes, parameter[name[self].Script]]
if compare[name[self].Version greater_or_equal[>=] constant[1]] beg... | keyword[def] identifier[SerializeExclusiveData] ( identifier[self] , identifier[writer] ):
literal[string]
identifier[writer] . identifier[WriteVarBytes] ( identifier[self] . identifier[Script] )
keyword[if] identifier[self] . identifier[Version] >= literal[int] :
identifier[... | def SerializeExclusiveData(self, writer):
"""
Serialize object.
Args:
writer (neo.IO.BinaryWriter):
"""
writer.WriteVarBytes(self.Script)
if self.Version >= 1:
writer.WriteFixed8(self.Gas) # depends on [control=['if'], data=[]] |
def _write_method(schema):
"""Add a write method for named schema to a class.
"""
def method(
self,
filename=None,
schema=schema,
id_col='uid',
sequence_col='sequence',
extra_data=None,
alphabet=None,
**kwargs):
# Use generic write clas... | def function[_write_method, parameter[schema]]:
constant[Add a write method for named schema to a class.
]
def function[method, parameter[self, filename, schema, id_col, sequence_col, extra_data, alphabet]]:
return[call[name[_write], parameter[name[self]._data]]]
name[method].__doc__... | keyword[def] identifier[_write_method] ( identifier[schema] ):
literal[string]
keyword[def] identifier[method] (
identifier[self] ,
identifier[filename] = keyword[None] ,
identifier[schema] = identifier[schema] ,
identifier[id_col] = literal[string] ,
identifier[sequence_col] = li... | def _write_method(schema):
"""Add a write method for named schema to a class.
"""
def method(self, filename=None, schema=schema, id_col='uid', sequence_col='sequence', extra_data=None, alphabet=None, **kwargs):
# Use generic write class to write data.
return _write(self._data, filename=file... |
def AddWiFiDevice(self, device_name, iface_name, state):
'''Add a WiFi Device.
You have to specify device_name, device interface name (e. g. wlan0) and
state. You can use the predefined DeviceState values (e. g.
DeviceState.ACTIVATED) or supply a numeric value. For valid state values,
please visit... | def function[AddWiFiDevice, parameter[self, device_name, iface_name, state]]:
constant[Add a WiFi Device.
You have to specify device_name, device interface name (e. g. wlan0) and
state. You can use the predefined DeviceState values (e. g.
DeviceState.ACTIVATED) or supply a numeric value. For valid... | keyword[def] identifier[AddWiFiDevice] ( identifier[self] , identifier[device_name] , identifier[iface_name] , identifier[state] ):
literal[string]
identifier[path] = literal[string] + identifier[device_name]
identifier[self] . identifier[AddObject] ( identifier[path] ,
identifier[WIRELESS_DEVI... | def AddWiFiDevice(self, device_name, iface_name, state):
"""Add a WiFi Device.
You have to specify device_name, device interface name (e. g. wlan0) and
state. You can use the predefined DeviceState values (e. g.
DeviceState.ACTIVATED) or supply a numeric value. For valid state values,
please visit... |
def request(self, filter=None):
"""Retrieve running configuration and device state information.
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
:seealso: :ref:`filter_params`
"""
node = new_ele("get-bulk")
i... | def function[request, parameter[self, filter]]:
constant[Retrieve running configuration and device state information.
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
:seealso: :ref:`filter_params`
]
variable[node] a... | keyword[def] identifier[request] ( identifier[self] , identifier[filter] = keyword[None] ):
literal[string]
identifier[node] = identifier[new_ele] ( literal[string] )
keyword[if] identifier[filter] keyword[is] keyword[not] keyword[None] :
identifier[node] . identifier[appe... | def request(self, filter=None):
"""Retrieve running configuration and device state information.
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
:seealso: :ref:`filter_params`
"""
node = new_ele('get-bulk')
if filter is ... |
def _process_loop(self):
'''Fetch URL including redirects.
Coroutine.
'''
while not self._web_client_session.done():
self._item_session.request = self._web_client_session.next_request()
verdict, reason = self._should_fetch_reason()
_logger.debug('Fi... | def function[_process_loop, parameter[self]]:
constant[Fetch URL including redirects.
Coroutine.
]
while <ast.UnaryOp object at 0x7da2043456c0> begin[:]
name[self]._item_session.request assign[=] call[name[self]._web_client_session.next_request, parameter[]]
... | keyword[def] identifier[_process_loop] ( identifier[self] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[_web_client_session] . identifier[done] ():
identifier[self] . identifier[_item_session] . identifier[request] = identifier[self] . identifier[_web_c... | def _process_loop(self):
"""Fetch URL including redirects.
Coroutine.
"""
while not self._web_client_session.done():
self._item_session.request = self._web_client_session.next_request()
(verdict, reason) = self._should_fetch_reason()
_logger.debug('Filter verdict {} reas... |
def _resolve_path(self, path):
"""
Resolve static file paths
"""
filepath = None
mimetype = None
for root, dirs, files in self.filter_files(self.path):
# Does it exist in error path?
error_path = os.path.join(os.path.dirname(os.path.abspath(__file... | def function[_resolve_path, parameter[self, path]]:
constant[
Resolve static file paths
]
variable[filepath] assign[=] constant[None]
variable[mimetype] assign[=] constant[None]
for taget[tuple[[<ast.Name object at 0x7da1b1920520>, <ast.Name object at 0x7da1b1920fa0>, <as... | keyword[def] identifier[_resolve_path] ( identifier[self] , identifier[path] ):
literal[string]
identifier[filepath] = keyword[None]
identifier[mimetype] = keyword[None]
keyword[for] identifier[root] , identifier[dirs] , identifier[files] keyword[in] identifier[self] . ident... | def _resolve_path(self, path):
"""
Resolve static file paths
"""
filepath = None
mimetype = None
for (root, dirs, files) in self.filter_files(self.path):
# Does it exist in error path?
error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error_templates'... |
def wind_shear(shear: str, unit_alt: str = 'ft', unit_wind: str = 'kt') -> str:
"""
Format wind shear string into a spoken word string
"""
unit_alt = SPOKEN_UNITS.get(unit_alt, unit_alt)
unit_wind = SPOKEN_UNITS.get(unit_wind, unit_wind)
return translate.wind_shear(shear, unit_alt, unit_wind, sp... | def function[wind_shear, parameter[shear, unit_alt, unit_wind]]:
constant[
Format wind shear string into a spoken word string
]
variable[unit_alt] assign[=] call[name[SPOKEN_UNITS].get, parameter[name[unit_alt], name[unit_alt]]]
variable[unit_wind] assign[=] call[name[SPOKEN_UNITS].get, ... | keyword[def] identifier[wind_shear] ( identifier[shear] : identifier[str] , identifier[unit_alt] : identifier[str] = literal[string] , identifier[unit_wind] : identifier[str] = literal[string] )-> identifier[str] :
literal[string]
identifier[unit_alt] = identifier[SPOKEN_UNITS] . identifier[get] ( identifi... | def wind_shear(shear: str, unit_alt: str='ft', unit_wind: str='kt') -> str:
"""
Format wind shear string into a spoken word string
"""
unit_alt = SPOKEN_UNITS.get(unit_alt, unit_alt)
unit_wind = SPOKEN_UNITS.get(unit_wind, unit_wind)
return translate.wind_shear(shear, unit_alt, unit_wind, spoken... |
def connect_autoscale(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.ec2.autosc... | def function[connect_autoscale, parameter[aws_access_key_id, aws_secret_access_key]]:
constant[
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto... | keyword[def] identifier[connect_autoscale] ( identifier[aws_access_key_id] = keyword[None] , identifier[aws_secret_access_key] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[boto] . identifier[ec2] . identifier[autoscale] keyword[import] identifier[AutoScaleConnection... | def connect_autoscale(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.ec2.autosc... |
def _elidable_begin(self, word):
"""Check word beginning to see if it is elidable. Elidable beginnings include:
1) A word begins with 'h'
2) A word begins with a vowel
3) A word begins with a diphthong
:param word: syllabified/'qu' fixed word
:return: True if the beginni... | def function[_elidable_begin, parameter[self, word]]:
constant[Check word beginning to see if it is elidable. Elidable beginnings include:
1) A word begins with 'h'
2) A word begins with a vowel
3) A word begins with a diphthong
:param word: syllabified/'qu' fixed word
:... | keyword[def] identifier[_elidable_begin] ( identifier[self] , identifier[word] ):
literal[string]
keyword[if] identifier[str] ( identifier[word] [ literal[int] ]). identifier[startswith] ( literal[string] ):
keyword[return] keyword[True]
keyword[elif] identifier[str] ( ide... | def _elidable_begin(self, word):
"""Check word beginning to see if it is elidable. Elidable beginnings include:
1) A word begins with 'h'
2) A word begins with a vowel
3) A word begins with a diphthong
:param word: syllabified/'qu' fixed word
:return: True if the beginning o... |
def readAlignments(self, reads):
"""
Read lines of JSON from self._filename, convert them to read alignments
and yield them.
@param reads: An iterable of L{Read} instances, corresponding to the
reads that were given to BLAST.
@raise ValueError: If any of the lines in... | def function[readAlignments, parameter[self, reads]]:
constant[
Read lines of JSON from self._filename, convert them to read alignments
and yield them.
@param reads: An iterable of L{Read} instances, corresponding to the
reads that were given to BLAST.
@raise ValueEr... | keyword[def] identifier[readAlignments] ( identifier[self] , identifier[reads] ):
literal[string]
keyword[if] identifier[self] . identifier[_fp] keyword[is] keyword[None] :
identifier[self] . identifier[_open] ( identifier[self] . identifier[_filename] )
identifier[reads] ... | def readAlignments(self, reads):
"""
Read lines of JSON from self._filename, convert them to read alignments
and yield them.
@param reads: An iterable of L{Read} instances, corresponding to the
reads that were given to BLAST.
@raise ValueError: If any of the lines in the... |
def formatwarning(message, category, filename, lineno, line=None):
"""
Override default Warning layout, from:
/PATH/TO/dutree.py:326: UserWarning:
[Errno 2] No such file or directory: '/0.d/05.d'
warnings.warn(str(e))
To:
dutree.py:330: UserWarning:
[Errn... | def function[formatwarning, parameter[message, category, filename, lineno, line]]:
constant[
Override default Warning layout, from:
/PATH/TO/dutree.py:326: UserWarning:
[Errno 2] No such file or directory: '/0.d/05.d'
warnings.warn(str(e))
To:
dutree.py:330: User... | keyword[def] identifier[formatwarning] ( identifier[message] , identifier[category] , identifier[filename] , identifier[lineno] , identifier[line] = keyword[None] ):
literal[string]
keyword[return] literal[string] . identifier[format] (
identifier[basename] = identifier[path] . identifier[basename] (... | def formatwarning(message, category, filename, lineno, line=None):
"""
Override default Warning layout, from:
/PATH/TO/dutree.py:326: UserWarning:
[Errno 2] No such file or directory: '/0.d/05.d'
warnings.warn(str(e))
To:
dutree.py:330: UserWarning:
[Errn... |
def remote_sys_desc_uneq_store(self, remote_system_desc):
"""This function saves the system desc, if different from stored. """
if remote_system_desc != self.remote_system_desc:
self.remote_system_desc = remote_system_desc
return True
return False | def function[remote_sys_desc_uneq_store, parameter[self, remote_system_desc]]:
constant[This function saves the system desc, if different from stored. ]
if compare[name[remote_system_desc] not_equal[!=] name[self].remote_system_desc] begin[:]
name[self].remote_system_desc assign[=] name[... | keyword[def] identifier[remote_sys_desc_uneq_store] ( identifier[self] , identifier[remote_system_desc] ):
literal[string]
keyword[if] identifier[remote_system_desc] != identifier[self] . identifier[remote_system_desc] :
identifier[self] . identifier[remote_system_desc] = identifier[r... | def remote_sys_desc_uneq_store(self, remote_system_desc):
"""This function saves the system desc, if different from stored. """
if remote_system_desc != self.remote_system_desc:
self.remote_system_desc = remote_system_desc
return True # depends on [control=['if'], data=['remote_system_desc']]
... |
def format_unix_var(text):
"""
Example::
this_is_very_good
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
raise ValueError("can not be empty string!")
else:
if text[0] in string.digits:
raise ValueError("variable can not start with d... | def function[format_unix_var, parameter[text]]:
constant[
Example::
this_is_very_good
]
variable[text] assign[=] call[name[text].strip, parameter[]]
if compare[call[name[len], parameter[name[text]]] equal[==] constant[0]] begin[:]
<ast.Raise object at 0x7da1b2506ad0> | keyword[def] identifier[format_unix_var] ( identifier[text] ):
literal[string]
identifier[text] = identifier[text] . identifier[strip] ()
keyword[if] identifier[len] ( identifier[text] )== literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[else] :
... | def format_unix_var(text):
"""
Example::
this_is_very_good
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
raise ValueError('can not be empty string!') # depends on [control=['if'], data=[]]
else:
if text[0] in string.digits:
raise V... |
def update_adjustments(self, adjustments, method):
"""
Merge ``adjustments`` with existing adjustments, handling index
collisions according to ``method``.
Parameters
----------
adjustments : dict[int -> list[Adjustment]]
The mapping of row indices to lists of... | def function[update_adjustments, parameter[self, adjustments, method]]:
constant[
Merge ``adjustments`` with existing adjustments, handling index
collisions according to ``method``.
Parameters
----------
adjustments : dict[int -> list[Adjustment]]
The mapping... | keyword[def] identifier[update_adjustments] ( identifier[self] , identifier[adjustments] , identifier[method] ):
literal[string]
keyword[try] :
identifier[merge_func] = identifier[_merge_methods] [ identifier[method] ]
keyword[except] identifier[KeyError] :
keywo... | def update_adjustments(self, adjustments, method):
"""
Merge ``adjustments`` with existing adjustments, handling index
collisions according to ``method``.
Parameters
----------
adjustments : dict[int -> list[Adjustment]]
The mapping of row indices to lists of adj... |
def start(self):
'''
Startup the kafka consumer.
'''
log.debug('Creating the consumer using the bootstrap servers: %s and the group ID: %s',
self.bootstrap_servers,
self.group_id)
try:
self.consumer = kafka.KafkaConsumer(bootstrap_s... | def function[start, parameter[self]]:
constant[
Startup the kafka consumer.
]
call[name[log].debug, parameter[constant[Creating the consumer using the bootstrap servers: %s and the group ID: %s], name[self].bootstrap_servers, name[self].group_id]]
<ast.Try object at 0x7da18bcca890>
... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] ,
identifier[self] . identifier[bootstrap_servers] ,
identifier[self] . identifier[group_id] )
keyword[try] :
identifier[self] . identif... | def start(self):
"""
Startup the kafka consumer.
"""
log.debug('Creating the consumer using the bootstrap servers: %s and the group ID: %s', self.bootstrap_servers, self.group_id)
try:
self.consumer = kafka.KafkaConsumer(bootstrap_servers=self.bootstrap_servers, group_id=self.group_i... |
def check_num_slices(num_slices, img_shape=None, num_dims=3):
"""Ensures requested number of slices is valid.
Atleast 1 and atmost the image size, if available
"""
if not isinstance(num_slices, Iterable) or len(num_slices) == 1:
num_slices = np.repeat(num_slices, num_dims)
if img_shape is... | def function[check_num_slices, parameter[num_slices, img_shape, num_dims]]:
constant[Ensures requested number of slices is valid.
Atleast 1 and atmost the image size, if available
]
if <ast.BoolOp object at 0x7da1b2547a00> begin[:]
variable[num_slices] assign[=] call[name[np].re... | keyword[def] identifier[check_num_slices] ( identifier[num_slices] , identifier[img_shape] = keyword[None] , identifier[num_dims] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[num_slices] , identifier[Iterable] ) keyword[or] identifier[len] ( identifier[... | def check_num_slices(num_slices, img_shape=None, num_dims=3):
"""Ensures requested number of slices is valid.
Atleast 1 and atmost the image size, if available
"""
if not isinstance(num_slices, Iterable) or len(num_slices) == 1:
num_slices = np.repeat(num_slices, num_dims) # depends on [contro... |
def updateLink(page, lnk):
""" Update a link on the current page. """
CheckParent(page)
annot = getLinkText(page, lnk)
if annot == "":
raise ValueError("link kind not supported")
page.parent._updateObject(lnk["xref"], annot, page = page)
return | def function[updateLink, parameter[page, lnk]]:
constant[ Update a link on the current page. ]
call[name[CheckParent], parameter[name[page]]]
variable[annot] assign[=] call[name[getLinkText], parameter[name[page], name[lnk]]]
if compare[name[annot] equal[==] constant[]] begin[:]
... | keyword[def] identifier[updateLink] ( identifier[page] , identifier[lnk] ):
literal[string]
identifier[CheckParent] ( identifier[page] )
identifier[annot] = identifier[getLinkText] ( identifier[page] , identifier[lnk] )
keyword[if] identifier[annot] == literal[string] :
keyword[raise] ... | def updateLink(page, lnk):
""" Update a link on the current page. """
CheckParent(page)
annot = getLinkText(page, lnk)
if annot == '':
raise ValueError('link kind not supported') # depends on [control=['if'], data=[]]
page.parent._updateObject(lnk['xref'], annot, page=page)
return |
def fill_shifts_view(request, semester):
"""
Allows managers to quickly fill in the default workshifts for a few given
workshift pools.
"""
page_name = "Fill Shifts"
fill_regular_shifts_form = None
fill_social_shifts_form = None
fill_humor_shifts_form = None
fill_bathroom_shifts_for... | def function[fill_shifts_view, parameter[request, semester]]:
constant[
Allows managers to quickly fill in the default workshifts for a few given
workshift pools.
]
variable[page_name] assign[=] constant[Fill Shifts]
variable[fill_regular_shifts_form] assign[=] constant[None]
... | keyword[def] identifier[fill_shifts_view] ( identifier[request] , identifier[semester] ):
literal[string]
identifier[page_name] = literal[string]
identifier[fill_regular_shifts_form] = keyword[None]
identifier[fill_social_shifts_form] = keyword[None]
identifier[fill_humor_shifts_form] = ... | def fill_shifts_view(request, semester):
"""
Allows managers to quickly fill in the default workshifts for a few given
workshift pools.
"""
page_name = 'Fill Shifts'
fill_regular_shifts_form = None
fill_social_shifts_form = None
fill_humor_shifts_form = None
fill_bathroom_shifts_form... |
def _fixNS(self, namespace):
"""Convert an input value into the internally used values of
this object
@param namespace: The string or constant to convert
@type namespace: str or unicode or BARE_NS or OPENID_NS
"""
if namespace == OPENID_NS:
if self._openid_ns... | def function[_fixNS, parameter[self, namespace]]:
constant[Convert an input value into the internally used values of
this object
@param namespace: The string or constant to convert
@type namespace: str or unicode or BARE_NS or OPENID_NS
]
if compare[name[namespace] equal... | keyword[def] identifier[_fixNS] ( identifier[self] , identifier[namespace] ):
literal[string]
keyword[if] identifier[namespace] == identifier[OPENID_NS] :
keyword[if] identifier[self] . identifier[_openid_ns_uri] keyword[is] keyword[None] :
keyword[raise] identifi... | def _fixNS(self, namespace):
"""Convert an input value into the internally used values of
this object
@param namespace: The string or constant to convert
@type namespace: str or unicode or BARE_NS or OPENID_NS
"""
if namespace == OPENID_NS:
if self._openid_ns_uri is None... |
def qname(self, stmt):
"""Return (prefixed) node name of `stmt`.
The result is prefixed with the local prefix unless we are
inside a global grouping.
"""
if self.gg_level: return stmt.arg
return self.prefix_stack[-1] + ":" + stmt.arg | def function[qname, parameter[self, stmt]]:
constant[Return (prefixed) node name of `stmt`.
The result is prefixed with the local prefix unless we are
inside a global grouping.
]
if name[self].gg_level begin[:]
return[name[stmt].arg]
return[binary_operation[binary_op... | keyword[def] identifier[qname] ( identifier[self] , identifier[stmt] ):
literal[string]
keyword[if] identifier[self] . identifier[gg_level] : keyword[return] identifier[stmt] . identifier[arg]
keyword[return] identifier[self] . identifier[prefix_stack] [- literal[int] ]+ literal[string... | def qname(self, stmt):
"""Return (prefixed) node name of `stmt`.
The result is prefixed with the local prefix unless we are
inside a global grouping.
"""
if self.gg_level:
return stmt.arg # depends on [control=['if'], data=[]]
return self.prefix_stack[-1] + ':' + stmt.arg |
def get_paths(rlz):
"""
:param rlz:
a logic tree realization (composite or simple)
:returns:
a dict {'source_model_tree_path': string, 'gsim_tree_path': string}
"""
dic = {}
if hasattr(rlz, 'sm_lt_path'): # composite realization
dic['source_model_tree_path'] = '_'.join(r... | def function[get_paths, parameter[rlz]]:
constant[
:param rlz:
a logic tree realization (composite or simple)
:returns:
a dict {'source_model_tree_path': string, 'gsim_tree_path': string}
]
variable[dic] assign[=] dictionary[[], []]
if call[name[hasattr], parameter[na... | keyword[def] identifier[get_paths] ( identifier[rlz] ):
literal[string]
identifier[dic] ={}
keyword[if] identifier[hasattr] ( identifier[rlz] , literal[string] ):
identifier[dic] [ literal[string] ]= literal[string] . identifier[join] ( identifier[rlz] . identifier[sm_lt_path] )
ide... | def get_paths(rlz):
"""
:param rlz:
a logic tree realization (composite or simple)
:returns:
a dict {'source_model_tree_path': string, 'gsim_tree_path': string}
"""
dic = {}
if hasattr(rlz, 'sm_lt_path'): # composite realization
dic['source_model_tree_path'] = '_'.join(r... |
def max_speed(self):
"""
Returns the maximum value that is accepted by the `speed_sp` attribute. This
may be slightly different than the maximum speed that a particular motor can
reach - it's the maximum theoretical speed.
"""
(self._max_speed, value) = self.get_cached_at... | def function[max_speed, parameter[self]]:
constant[
Returns the maximum value that is accepted by the `speed_sp` attribute. This
may be slightly different than the maximum speed that a particular motor can
reach - it's the maximum theoretical speed.
]
<ast.Tuple object at... | keyword[def] identifier[max_speed] ( identifier[self] ):
literal[string]
( identifier[self] . identifier[_max_speed] , identifier[value] )= identifier[self] . identifier[get_cached_attr_int] ( identifier[self] . identifier[_max_speed] , literal[string] )
keyword[return] identifier[value] | def max_speed(self):
"""
Returns the maximum value that is accepted by the `speed_sp` attribute. This
may be slightly different than the maximum speed that a particular motor can
reach - it's the maximum theoretical speed.
"""
(self._max_speed, value) = self.get_cached_attr_int(s... |
def process_input(self, question):
"""
takes a question and returns the best answer based on known skills
"""
ans = ''
if self.status == 'EXIT':
print('bye')
sys.exit()
if '?' in question:
ans = self.info.find_answer(question)
... | def function[process_input, parameter[self, question]]:
constant[
takes a question and returns the best answer based on known skills
]
variable[ans] assign[=] constant[]
if compare[name[self].status equal[==] constant[EXIT]] begin[:]
call[name[print], parameter[co... | keyword[def] identifier[process_input] ( identifier[self] , identifier[question] ):
literal[string]
identifier[ans] = literal[string]
keyword[if] identifier[self] . identifier[status] == literal[string] :
identifier[print] ( literal[string] )
identifier[sys] . i... | def process_input(self, question):
"""
takes a question and returns the best answer based on known skills
"""
ans = ''
if self.status == 'EXIT':
print('bye')
sys.exit() # depends on [control=['if'], data=[]]
if '?' in question:
ans = self.info.find_answer(questio... |
def _folder_item_duedate(self, analysis_brain, item):
"""Set the analysis' due date to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
# Note that if the analysis is a Reference... | def function[_folder_item_duedate, parameter[self, analysis_brain, item]]:
constant[Set the analysis' due date to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
]
variable[due_date]... | keyword[def] identifier[_folder_item_duedate] ( identifier[self] , identifier[analysis_brain] , identifier[item] ):
literal[string]
identifier[due_date] = identifier[analysis_brain] . identifier[getDueDate]
keyword[if] keyword[not] identifier[due_date] :
... | def _folder_item_duedate(self, analysis_brain, item):
"""Set the analysis' due date to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
# Note that if the analysis is a Reference Analysis... |
async def wait_until_ready(
self, timeout: Optional[float] = None, no_raise: bool = False
) -> bool:
"""
Waits for the underlying node to become ready.
If no_raise is set, returns false when a timeout occurs instead of propogating TimeoutError.
A timeout of None means to wai... | <ast.AsyncFunctionDef object at 0x7da20c76fb80> | keyword[async] keyword[def] identifier[wait_until_ready] (
identifier[self] , identifier[timeout] : identifier[Optional] [ identifier[float] ]= keyword[None] , identifier[no_raise] : identifier[bool] = keyword[False]
)-> identifier[bool] :
literal[string]
keyword[if] identifier[self] . identifi... | async def wait_until_ready(self, timeout: Optional[float]=None, no_raise: bool=False) -> bool:
"""
Waits for the underlying node to become ready.
If no_raise is set, returns false when a timeout occurs instead of propogating TimeoutError.
A timeout of None means to wait indefinitely.
... |
def create_port(self, context, network_id, port_id, **kwargs):
"""Create a port.
:param context: neutron api request context.
:param network_id: neutron network id.
:param port_id: neutron port id.
:param kwargs:
required keys - device_id: neutron port device_id (ins... | def function[create_port, parameter[self, context, network_id, port_id]]:
constant[Create a port.
:param context: neutron api request context.
:param network_id: neutron network id.
:param port_id: neutron port id.
:param kwargs:
required keys - device_id: neutron po... | keyword[def] identifier[create_port] ( identifier[self] , identifier[context] , identifier[network_id] , identifier[port_id] ,** identifier[kwargs] ):
literal[string]
identifier[LOG] . identifier[info] ( literal[string] %( identifier[context] . identifier[tenant_id] , identifier[network_id] ,
... | def create_port(self, context, network_id, port_id, **kwargs):
"""Create a port.
:param context: neutron api request context.
:param network_id: neutron network id.
:param port_id: neutron port id.
:param kwargs:
required keys - device_id: neutron port device_id (instanc... |
def do_set_log_file(self, args):
"""Set the log file.
Usage:
set_log_file filename
Parameters:
filename: log file name to write to
THIS CAN ONLY BE CALLED ONCE AND MUST BE CALLED
BEFORE ANY LOGGING STARTS.
"""
params = args.split()
... | def function[do_set_log_file, parameter[self, args]]:
constant[Set the log file.
Usage:
set_log_file filename
Parameters:
filename: log file name to write to
THIS CAN ONLY BE CALLED ONCE AND MUST BE CALLED
BEFORE ANY LOGGING STARTS.
]
var... | keyword[def] identifier[do_set_log_file] ( identifier[self] , identifier[args] ):
literal[string]
identifier[params] = identifier[args] . identifier[split] ()
keyword[try] :
identifier[filename] = identifier[params] [ literal[int] ]
identifier[logging] . identifie... | def do_set_log_file(self, args):
"""Set the log file.
Usage:
set_log_file filename
Parameters:
filename: log file name to write to
THIS CAN ONLY BE CALLED ONCE AND MUST BE CALLED
BEFORE ANY LOGGING STARTS.
"""
params = args.split()
try:
... |
def _create_widget_content(sender, instance, created=False, **kwargs):
"""
create a widget content instance when a WidgetContentModel is deleted
"""
if not issubclass(sender, WidgetContentModel):
return
# create a WidgetContent Entry
if created:
instance.create_widget_content_en... | def function[_create_widget_content, parameter[sender, instance, created]]:
constant[
create a widget content instance when a WidgetContentModel is deleted
]
if <ast.UnaryOp object at 0x7da20e957040> begin[:]
return[None]
if name[created] begin[:]
call[name[instan... | keyword[def] identifier[_create_widget_content] ( identifier[sender] , identifier[instance] , identifier[created] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[issubclass] ( identifier[sender] , identifier[WidgetContentModel] ):
keyword[return]
... | def _create_widget_content(sender, instance, created=False, **kwargs):
"""
create a widget content instance when a WidgetContentModel is deleted
"""
if not issubclass(sender, WidgetContentModel):
return # depends on [control=['if'], data=[]]
# create a WidgetContent Entry
if created:
... |
def get_current_future_chain(self, continuous_future, dt):
"""
Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification.
Returns
-------
future_chain : list[Future]
A list of active futures, where the firs... | def function[get_current_future_chain, parameter[self, continuous_future, dt]]:
constant[
Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification.
Returns
-------
future_chain : list[Future]
A list of act... | keyword[def] identifier[get_current_future_chain] ( identifier[self] , identifier[continuous_future] , identifier[dt] ):
literal[string]
identifier[rf] = identifier[self] . identifier[_roll_finders] [ identifier[continuous_future] . identifier[roll_style] ]
identifier[session] = identifier... | def get_current_future_chain(self, continuous_future, dt):
"""
Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification.
Returns
-------
future_chain : list[Future]
A list of active futures, where the first in... |
def connect_to_rackspace(region,
access_key_id,
secret_access_key):
""" returns a connection object to Rackspace """
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(access_key_id, secret_access_key)... | def function[connect_to_rackspace, parameter[region, access_key_id, secret_access_key]]:
constant[ returns a connection object to Rackspace ]
call[name[pyrax].set_setting, parameter[constant[identity_type], constant[rackspace]]]
call[name[pyrax].set_default_region, parameter[name[region]]]
... | keyword[def] identifier[connect_to_rackspace] ( identifier[region] ,
identifier[access_key_id] ,
identifier[secret_access_key] ):
literal[string]
identifier[pyrax] . identifier[set_setting] ( literal[string] , literal[string] )
identifier[pyrax] . identifier[set_default_region] ( identifier[region] ... | def connect_to_rackspace(region, access_key_id, secret_access_key):
""" returns a connection object to Rackspace """
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(access_key_id, secret_access_key)
nova = pyrax.connect_to_cloudservers(region=r... |
def mimetype_icon(path, fallback=None):
"""
Tries to create an icon from theme using the file mimetype.
E.g.::
return self.mimetype_icon(
path, fallback=':/icons/text-x-python.png')
:param path: file path for which the icon must be created
:param fa... | def function[mimetype_icon, parameter[path, fallback]]:
constant[
Tries to create an icon from theme using the file mimetype.
E.g.::
return self.mimetype_icon(
path, fallback=':/icons/text-x-python.png')
:param path: file path for which the icon must be cre... | keyword[def] identifier[mimetype_icon] ( identifier[path] , identifier[fallback] = keyword[None] ):
literal[string]
identifier[mime] = identifier[mimetypes] . identifier[guess_type] ( identifier[path] )[ literal[int] ]
keyword[if] identifier[mime] :
identifier[icon] = identif... | def mimetype_icon(path, fallback=None):
"""
Tries to create an icon from theme using the file mimetype.
E.g.::
return self.mimetype_icon(
path, fallback=':/icons/text-x-python.png')
:param path: file path for which the icon must be created
:param fallba... |
def disallowed_table(*tables):
"""Returns True if a set of tables is in the blacklist or, if a whitelist is set,
any of the tables is not in the whitelist. False otherwise."""
# XXX: When using a black or white list, this has to be done EVERY query;
# It'd be nice to make this as fast as possible. In g... | def function[disallowed_table, parameter[]]:
constant[Returns True if a set of tables is in the blacklist or, if a whitelist is set,
any of the tables is not in the whitelist. False otherwise.]
return[<ast.IfExp object at 0x7da18f7200d0>] | keyword[def] identifier[disallowed_table] (* identifier[tables] ):
literal[string]
keyword[return] keyword[not] identifier[bool] ( identifier[settings] . identifier[WHITELIST] . identifier[issuperset] ( identifier[tables] )) keyword[if] identifier[settings] . identifier[WHITELIS... | def disallowed_table(*tables):
"""Returns True if a set of tables is in the blacklist or, if a whitelist is set,
any of the tables is not in the whitelist. False otherwise."""
# XXX: When using a black or white list, this has to be done EVERY query;
# It'd be nice to make this as fast as possible. In g... |
def schema_from_json(self, file_or_path):
"""Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects.
"""
if isinstance(file_or_path, io.IOBase):
return self._schema_from_json_file_object(fi... | def function[schema_from_json, parameter[self, file_or_path]]:
constant[Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects.
]
if call[name[isinstance], parameter[name[file_or_path], name[io].IOBase... | keyword[def] identifier[schema_from_json] ( identifier[self] , identifier[file_or_path] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[file_or_path] , identifier[io] . identifier[IOBase] ):
keyword[return] identifier[self] . identifier[_schema_from_json_file_objec... | def schema_from_json(self, file_or_path):
"""Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects.
"""
if isinstance(file_or_path, io.IOBase):
return self._schema_from_json_file_object(file_or_path) ... |
def deserialize_block(value):
"""
Deserialize a byte string into a BlockWrapper
Args:
value (bytes): the byte string to deserialze
Returns:
BlockWrapper: a block wrapper instance
"""
# Block id strings are stored under batch/txn ids for reference... | def function[deserialize_block, parameter[value]]:
constant[
Deserialize a byte string into a BlockWrapper
Args:
value (bytes): the byte string to deserialze
Returns:
BlockWrapper: a block wrapper instance
]
variable[block] assign[=] call[name[Bl... | keyword[def] identifier[deserialize_block] ( identifier[value] ):
literal[string]
identifier[block] = identifier[Block] ()
identifier[block] . identifier[ParseFromString] ( identifier[value] )
keyword[return] identifier[BlockWrapper] (
identifier[block]... | def deserialize_block(value):
"""
Deserialize a byte string into a BlockWrapper
Args:
value (bytes): the byte string to deserialze
Returns:
BlockWrapper: a block wrapper instance
"""
# Block id strings are stored under batch/txn ids for reference.
# ... |
def decimate_percentile(self, a, maxpoints, **kwargs):
"""Return data *a* percentile-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the percentile *per* in each bin as the decimated data, using
:func:`numkit.timeseries.percentile_histogrammed_funct... | def function[decimate_percentile, parameter[self, a, maxpoints]]:
constant[Return data *a* percentile-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the percentile *per* in each bin as the decimated data, using
:func:`numkit.timeseries.percentile_h... | keyword[def] identifier[decimate_percentile] ( identifier[self] , identifier[a] , identifier[maxpoints] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_decimate] ( identifier[numkit] . identifier[timeseries] . identifier[percentile_histogrammed_function] , ... | def decimate_percentile(self, a, maxpoints, **kwargs):
"""Return data *a* percentile-decimated on *maxpoints*.
Histograms each column into *maxpoints* bins and calculates
the percentile *per* in each bin as the decimated data, using
:func:`numkit.timeseries.percentile_histogrammed_function`... |
def _read_callback(connection_id, data_buffer, data_length_pointer):
"""
Callback called by Secure Transport to actually read the socket
:param connection_id:
An integer identifing the connection
:param data_buffer:
A char pointer FFI type to write the data to
:param data_length_p... | def function[_read_callback, parameter[connection_id, data_buffer, data_length_pointer]]:
constant[
Callback called by Secure Transport to actually read the socket
:param connection_id:
An integer identifing the connection
:param data_buffer:
A char pointer FFI type to write the da... | keyword[def] identifier[_read_callback] ( identifier[connection_id] , identifier[data_buffer] , identifier[data_length_pointer] ):
literal[string]
identifier[self] = keyword[None]
keyword[try] :
identifier[self] = identifier[_connection_refs] . identifier[get] ( identifier[connection_id] )
... | def _read_callback(connection_id, data_buffer, data_length_pointer):
"""
Callback called by Secure Transport to actually read the socket
:param connection_id:
An integer identifing the connection
:param data_buffer:
A char pointer FFI type to write the data to
:param data_length_p... |
def removeUserGroups(self, users=None):
"""Removes users' groups.
Args:
users (str): A comma delimited list of user names.
Defaults to ``None``.
Warning:
When ``users`` is not provided (``None``), all users
in the organization... | def function[removeUserGroups, parameter[self, users]]:
constant[Removes users' groups.
Args:
users (str): A comma delimited list of user names.
Defaults to ``None``.
Warning:
When ``users`` is not provided (``None``), all users
... | keyword[def] identifier[removeUserGroups] ( identifier[self] , identifier[users] = keyword[None] ):
literal[string]
identifier[admin] = keyword[None]
identifier[userCommunity] = keyword[None]
identifier[portal] = keyword[None]
identifier[groupAdmin] = keyword[None]
... | def removeUserGroups(self, users=None):
"""Removes users' groups.
Args:
users (str): A comma delimited list of user names.
Defaults to ``None``.
Warning:
When ``users`` is not provided (``None``), all users
in the organization wil... |
def update_initiators(self, iqns=None, wwns=None):
"""Primarily for puppet-unity use.
Update the iSCSI and FC initiators if needed.
"""
# First get current iqns
iqns = set(iqns) if iqns else set()
current_iqns = set()
if self.iscsi_host_initiators:
cu... | def function[update_initiators, parameter[self, iqns, wwns]]:
constant[Primarily for puppet-unity use.
Update the iSCSI and FC initiators if needed.
]
variable[iqns] assign[=] <ast.IfExp object at 0x7da20c6c5a20>
variable[current_iqns] assign[=] call[name[set], parameter[]]
... | keyword[def] identifier[update_initiators] ( identifier[self] , identifier[iqns] = keyword[None] , identifier[wwns] = keyword[None] ):
literal[string]
identifier[iqns] = identifier[set] ( identifier[iqns] ) keyword[if] identifier[iqns] keyword[else] identifier[set] ()
identifie... | def update_initiators(self, iqns=None, wwns=None):
"""Primarily for puppet-unity use.
Update the iSCSI and FC initiators if needed.
"""
# First get current iqns
iqns = set(iqns) if iqns else set()
current_iqns = set()
if self.iscsi_host_initiators:
current_iqns = {initiator.... |
def flattencopy(lst):
"""flatten and return a copy of the list
indefficient on large lists"""
# modified from
# http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
thelist = copy.deepcopy(lst)
list_is_nested = True
while list_is_nested: # outer loop
... | def function[flattencopy, parameter[lst]]:
constant[flatten and return a copy of the list
indefficient on large lists]
variable[thelist] assign[=] call[name[copy].deepcopy, parameter[name[lst]]]
variable[list_is_nested] assign[=] constant[True]
while name[list_is_nested] begin[:]
... | keyword[def] identifier[flattencopy] ( identifier[lst] ):
literal[string]
identifier[thelist] = identifier[copy] . identifier[deepcopy] ( identifier[lst] )
identifier[list_is_nested] = keyword[True]
keyword[while] identifier[list_is_nested] :
identifier[keepchecking] = keywor... | def flattencopy(lst):
"""flatten and return a copy of the list
indefficient on large lists"""
# modified from
# http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python
thelist = copy.deepcopy(lst)
list_is_nested = True
while list_is_nested: # outer loop
... |
def neighbor_atoms(self, atom_symbol=None):
"""Access neighbor atoms.
:param str atom_symbol: Atom symbol.
:return: List of neighbor atoms.
:rtype: :py:class:`list`.
"""
if not atom_symbol:
return self.neighbors
else:
return [atom for atom... | def function[neighbor_atoms, parameter[self, atom_symbol]]:
constant[Access neighbor atoms.
:param str atom_symbol: Atom symbol.
:return: List of neighbor atoms.
:rtype: :py:class:`list`.
]
if <ast.UnaryOp object at 0x7da1b2462260> begin[:]
return[name[self].neig... | keyword[def] identifier[neighbor_atoms] ( identifier[self] , identifier[atom_symbol] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[atom_symbol] :
keyword[return] identifier[self] . identifier[neighbors]
keyword[else] :
keyword[return] ... | def neighbor_atoms(self, atom_symbol=None):
"""Access neighbor atoms.
:param str atom_symbol: Atom symbol.
:return: List of neighbor atoms.
:rtype: :py:class:`list`.
"""
if not atom_symbol:
return self.neighbors # depends on [control=['if'], data=[]]
else:
r... |
def update_elements(self, line, column, charcount, docdelta=0):
"""Updates all the element instances that are children of this module
to have new start and end charindex values based on an operation that
was performed on the module source code.
:arg line: the line number of the *start* ... | def function[update_elements, parameter[self, line, column, charcount, docdelta]]:
constant[Updates all the element instances that are children of this module
to have new start and end charindex values based on an operation that
was performed on the module source code.
:arg line: the li... | keyword[def] identifier[update_elements] ( identifier[self] , identifier[line] , identifier[column] , identifier[charcount] , identifier[docdelta] = literal[int] ):
literal[string]
identifier[target] = identifier[self] . identifier[charindex] ( identifier[line] , identifier[column] )+ identifier[ch... | def update_elements(self, line, column, charcount, docdelta=0):
"""Updates all the element instances that are children of this module
to have new start and end charindex values based on an operation that
was performed on the module source code.
:arg line: the line number of the *start* of t... |
def delete_dependency(self, from_task_name, to_task_name):
""" Delete a dependency between two tasks. """
logger.debug('Deleting dependency from {0} to {1}'.format(from_task_name, to_task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in it... | def function[delete_dependency, parameter[self, from_task_name, to_task_name]]:
constant[ Delete a dependency between two tasks. ]
call[name[logger].debug, parameter[call[constant[Deleting dependency from {0} to {1}].format, parameter[name[from_task_name], name[to_task_name]]]]]
if <ast.UnaryOp ... | keyword[def] identifier[delete_dependency] ( identifier[self] , identifier[from_task_name] , identifier[to_task_name] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[from_task_name] , identifier[to_task_name] ))
keyword[if] ke... | def delete_dependency(self, from_task_name, to_task_name):
""" Delete a dependency between two tasks. """
logger.debug('Deleting dependency from {0} to {1}'.format(from_task_name, to_task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: ... |
def initialize(self, configfile=None):
"""
Initialize the module
"""
method = "initialize"
A = None
metadata = {method: configfile}
send_array(self.socket, A, metadata)
A, metadata = recv_array(
self.socket, poll=self.poll, poll_timeout=self... | def function[initialize, parameter[self, configfile]]:
constant[
Initialize the module
]
variable[method] assign[=] constant[initialize]
variable[A] assign[=] constant[None]
variable[metadata] assign[=] dictionary[[<ast.Name object at 0x7da20c794a90>], [<ast.Name object a... | keyword[def] identifier[initialize] ( identifier[self] , identifier[configfile] = keyword[None] ):
literal[string]
identifier[method] = literal[string]
identifier[A] = keyword[None]
identifier[metadata] ={ identifier[method] : identifier[configfile] }
identifier[send... | def initialize(self, configfile=None):
"""
Initialize the module
"""
method = 'initialize'
A = None
metadata = {method: configfile}
send_array(self.socket, A, metadata)
(A, metadata) = recv_array(self.socket, poll=self.poll, poll_timeout=self.poll_timeout, flags=self.zmq_flags) |
def get_activity_ids_by_objective_bank(self, objective_bank_id):
"""Gets the list of ``Activity`` ``Ids`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.id.IdList) - list of related activity ``Ids``
... | def function[get_activity_ids_by_objective_bank, parameter[self, objective_bank_id]]:
constant[Gets the list of ``Activity`` ``Ids`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.id.IdList) - list of ... | keyword[def] identifier[get_activity_ids_by_objective_bank] ( identifier[self] , identifier[objective_bank_id] ):
literal[string]
identifier[id_list] =[]
keyword[for] identifier[activity] keyword[in] identifier[self] . identifier[get_activities_by_objective_bank] ( ide... | def get_activity_ids_by_objective_bank(self, objective_bank_id):
"""Gets the list of ``Activity`` ``Ids`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.id.IdList) - list of related activity ``Ids``
... |
def fromcsv(source=None, encoding=None, errors='strict', header=None,
**csvargs):
"""
Extract a table from a delimited file. E.g.::
>>> import petl as etl
>>> import csv
>>> # set up a CSV file to demonstrate with
... table1 = [['foo', 'bar'],
... ... | def function[fromcsv, parameter[source, encoding, errors, header]]:
constant[
Extract a table from a delimited file. E.g.::
>>> import petl as etl
>>> import csv
>>> # set up a CSV file to demonstrate with
... table1 = [['foo', 'bar'],
... ['a', 1],
... | keyword[def] identifier[fromcsv] ( identifier[source] = keyword[None] , identifier[encoding] = keyword[None] , identifier[errors] = literal[string] , identifier[header] = keyword[None] ,
** identifier[csvargs] ):
literal[string]
identifier[source] = identifier[read_source_from_arg] ( identifier[source] )
... | def fromcsv(source=None, encoding=None, errors='strict', header=None, **csvargs):
"""
Extract a table from a delimited file. E.g.::
>>> import petl as etl
>>> import csv
>>> # set up a CSV file to demonstrate with
... table1 = [['foo', 'bar'],
... ['a', 1],
... |
def set_placeholder(self, text):
"""Set the placeholder text that will be displayed
when the text is empty and the widget is out of focus
:param text: The text for the placeholder
:type text: str
:raises: None
"""
if self._placeholder != text:
self._p... | def function[set_placeholder, parameter[self, text]]:
constant[Set the placeholder text that will be displayed
when the text is empty and the widget is out of focus
:param text: The text for the placeholder
:type text: str
:raises: None
]
if compare[name[self]._p... | keyword[def] identifier[set_placeholder] ( identifier[self] , identifier[text] ):
literal[string]
keyword[if] identifier[self] . identifier[_placeholder] != identifier[text] :
identifier[self] . identifier[_placeholder] = identifier[text]
keyword[if] keyword[not] ident... | def set_placeholder(self, text):
"""Set the placeholder text that will be displayed
when the text is empty and the widget is out of focus
:param text: The text for the placeholder
:type text: str
:raises: None
"""
if self._placeholder != text:
self._placeholder =... |
def get_lldp_neighbors_detail(self, interface=""):
"""Detailed view of the LLDP neighbors."""
lldp_neighbors = defaultdict(list)
lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device)
if not interface:
try:
lldp_table.get()
except ... | def function[get_lldp_neighbors_detail, parameter[self, interface]]:
constant[Detailed view of the LLDP neighbors.]
variable[lldp_neighbors] assign[=] call[name[defaultdict], parameter[name[list]]]
variable[lldp_table] assign[=] call[name[junos_views].junos_lldp_neighbors_detail_table, parameter... | keyword[def] identifier[get_lldp_neighbors_detail] ( identifier[self] , identifier[interface] = literal[string] ):
literal[string]
identifier[lldp_neighbors] = identifier[defaultdict] ( identifier[list] )
identifier[lldp_table] = identifier[junos_views] . identifier[junos_lldp_neighbors_de... | def get_lldp_neighbors_detail(self, interface=''):
"""Detailed view of the LLDP neighbors."""
lldp_neighbors = defaultdict(list)
lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device)
if not interface:
try:
lldp_table.get() # depends on [control=['try'], data=[]]
... |
def loss(logits, labels, batch_size=None):
"""Adds all losses for the model.
Note the final loss is not returned. Instead, the list of losses are collected
by slim.losses. The losses are accumulated in tower_loss() and summed to
calculate the total loss.
Args:
logits: List of logits from inference(). Ea... | def function[loss, parameter[logits, labels, batch_size]]:
constant[Adds all losses for the model.
Note the final loss is not returned. Instead, the list of losses are collected
by slim.losses. The losses are accumulated in tower_loss() and summed to
calculate the total loss.
Args:
logits: List of... | keyword[def] identifier[loss] ( identifier[logits] , identifier[labels] , identifier[batch_size] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[batch_size] :
identifier[batch_size] = identifier[FLAGS] . identifier[batch_size]
identifier[sparse_labels] = identifier[... | def loss(logits, labels, batch_size=None):
"""Adds all losses for the model.
Note the final loss is not returned. Instead, the list of losses are collected
by slim.losses. The losses are accumulated in tower_loss() and summed to
calculate the total loss.
Args:
logits: List of logits from inference(). ... |
def pip_command_output(pip_args):
"""
Get output (as a string) from pip command
:param pip_args: list o pip switches to pass
:return: string with results
"""
import sys
import pip
from io import StringIO
# as pip will write to stdout we use some nasty hacks
# to substitute system... | def function[pip_command_output, parameter[pip_args]]:
constant[
Get output (as a string) from pip command
:param pip_args: list o pip switches to pass
:return: string with results
]
import module[sys]
import module[pip]
from relative_module[io] import module[StringIO]
variab... | keyword[def] identifier[pip_command_output] ( identifier[pip_args] ):
literal[string]
keyword[import] identifier[sys]
keyword[import] identifier[pip]
keyword[from] identifier[io] keyword[import] identifier[StringIO]
identifier[old_stdout] = identifier[sys] . identifier[stdo... | def pip_command_output(pip_args):
"""
Get output (as a string) from pip command
:param pip_args: list o pip switches to pass
:return: string with results
"""
import sys
import pip
from io import StringIO
# as pip will write to stdout we use some nasty hacks
# to substitute system... |
def _AddEnumValues(descriptor, cls):
"""Sets class-level attributes for all enum fields defined in this message.
Also exporting a class-level object that can name enum values.
Args:
descriptor: Descriptor object for this message type.
cls: Class we're constructing for this message type.
"""
for enum... | def function[_AddEnumValues, parameter[descriptor, cls]]:
constant[Sets class-level attributes for all enum fields defined in this message.
Also exporting a class-level object that can name enum values.
Args:
descriptor: Descriptor object for this message type.
cls: Class we're constructing for th... | keyword[def] identifier[_AddEnumValues] ( identifier[descriptor] , identifier[cls] ):
literal[string]
keyword[for] identifier[enum_type] keyword[in] identifier[descriptor] . identifier[enum_types] :
identifier[setattr] ( identifier[cls] , identifier[enum_type] . identifier[name] , identifier[enum_type_... | def _AddEnumValues(descriptor, cls):
"""Sets class-level attributes for all enum fields defined in this message.
Also exporting a class-level object that can name enum values.
Args:
descriptor: Descriptor object for this message type.
cls: Class we're constructing for this message type.
"""
for ... |
def format(self, exclude_class=False):
"""Format this exception as a string including class name.
Args:
exclude_class (bool): Whether to exclude the exception class
name when formatting this exception
Returns:
string: a multiline string with the message,... | def function[format, parameter[self, exclude_class]]:
constant[Format this exception as a string including class name.
Args:
exclude_class (bool): Whether to exclude the exception class
name when formatting this exception
Returns:
string: a multiline str... | keyword[def] identifier[format] ( identifier[self] , identifier[exclude_class] = keyword[False] ):
literal[string]
keyword[if] identifier[exclude_class] :
identifier[msg] = identifier[self] . identifier[msg]
keyword[else] :
identifier[msg] = literal[string] %( ... | def format(self, exclude_class=False):
"""Format this exception as a string including class name.
Args:
exclude_class (bool): Whether to exclude the exception class
name when formatting this exception
Returns:
string: a multiline string with the message, cla... |
def _create_path(self):
"""Create the path to hold the database, if one wwas specified."""
if self.driver == 'sqlite' and 'memory' not in self.dsn and self.dsn != 'sqlite://':
dir_ = os.path.dirname(self.path)
if dir_ and not os.path.exists(dir_):
try:
... | def function[_create_path, parameter[self]]:
constant[Create the path to hold the database, if one wwas specified.]
if <ast.BoolOp object at 0x7da20c795330> begin[:]
variable[dir_] assign[=] call[name[os].path.dirname, parameter[name[self].path]]
if <ast.BoolOp object at ... | keyword[def] identifier[_create_path] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[driver] == literal[string] keyword[and] literal[string] keyword[not] keyword[in] identifier[self] . identifier[dsn] keyword[and] identifier[self] . identifier[dsn] != liter... | def _create_path(self):
"""Create the path to hold the database, if one wwas specified."""
if self.driver == 'sqlite' and 'memory' not in self.dsn and (self.dsn != 'sqlite://'):
dir_ = os.path.dirname(self.path)
if dir_ and (not os.path.exists(dir_)):
try:
# Multiple ... |
def process_event(self, event_name: str, data: dict) -> None:
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
... | def function[process_event, parameter[self, event_name, data]]:
constant[
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Ret... | keyword[def] identifier[process_event] ( identifier[self] , identifier[event_name] : identifier[str] , identifier[data] : identifier[dict] )-> keyword[None] :
literal[string]
keyword[if] identifier[event_name] == literal[string] :
identifier[self] . identifier[epochs_done] = identifie... | def process_event(self, event_name: str, data: dict) -> None:
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
... |
def obfn_fvar(self):
"""Variable to be evaluated in computing regularisation term,
depending on 'fEvalX' option value.
"""
if self.opt['fEvalX']:
return self.X
else:
return self.cnst_c() - self.cnst_B(self.Y) | def function[obfn_fvar, parameter[self]]:
constant[Variable to be evaluated in computing regularisation term,
depending on 'fEvalX' option value.
]
if call[name[self].opt][constant[fEvalX]] begin[:]
return[name[self].X] | keyword[def] identifier[obfn_fvar] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[opt] [ literal[string] ]:
keyword[return] identifier[self] . identifier[X]
keyword[else] :
keyword[return] identifier[self] . identifier[cnst_c]... | def obfn_fvar(self):
"""Variable to be evaluated in computing regularisation term,
depending on 'fEvalX' option value.
"""
if self.opt['fEvalX']:
return self.X # depends on [control=['if'], data=[]]
else:
return self.cnst_c() - self.cnst_B(self.Y) |
def find_path_package_name(thepath):
"""
Takes a file system path and returns the name of the python package
the said path belongs to. If the said path can not be determined, it
returns None.
"""
module_found = False
last_module_found = None
continue_ = True
while contin... | def function[find_path_package_name, parameter[thepath]]:
constant[
Takes a file system path and returns the name of the python package
the said path belongs to. If the said path can not be determined, it
returns None.
]
variable[module_found] assign[=] constant[False]
... | keyword[def] identifier[find_path_package_name] ( identifier[thepath] ):
literal[string]
identifier[module_found] = keyword[False]
identifier[last_module_found] = keyword[None]
identifier[continue_] = keyword[True]
keyword[while] identifier[continue_] :
identifier[module_found] ... | def find_path_package_name(thepath):
"""
Takes a file system path and returns the name of the python package
the said path belongs to. If the said path can not be determined, it
returns None.
"""
module_found = False
last_module_found = None
continue_ = True
while contin... |
def main(**kwargs):
"""
Entry point for dx-build-app(let).
Don't call this function as a subroutine in your program! It is liable to
sys.exit your program when it detects certain error conditions, so you
can't recover from those as you could if it raised exceptions. Instead,
call dx_build_app.b... | def function[main, parameter[]]:
constant[
Entry point for dx-build-app(let).
Don't call this function as a subroutine in your program! It is liable to
sys.exit your program when it detects certain error conditions, so you
can't recover from those as you could if it raised exceptions. Instead,
... | keyword[def] identifier[main] (** identifier[kwargs] ):
literal[string]
keyword[if] identifier[len] ( identifier[sys] . identifier[argv] )> literal[int] :
keyword[if] identifier[sys] . identifier[argv] [ literal[int] ]. identifier[endswith] ( literal[string] ):
identifier[logging] ... | def main(**kwargs):
"""
Entry point for dx-build-app(let).
Don't call this function as a subroutine in your program! It is liable to
sys.exit your program when it detects certain error conditions, so you
can't recover from those as you could if it raised exceptions. Instead,
call dx_build_app.b... |
def _einsum_equation(input_shapes, output_shape):
"""Turn shapes into an einsum equation.
e.g. "ij,jk->ik"
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Returns:
a string
"""
ret = []
next_letter = ord("a")
dim_to_letter = {}
for shape_num, shape in enumerate(input_shapes + ... | def function[_einsum_equation, parameter[input_shapes, output_shape]]:
constant[Turn shapes into an einsum equation.
e.g. "ij,jk->ik"
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Returns:
a string
]
variable[ret] assign[=] list[[]]
variable[next_letter] assign... | keyword[def] identifier[_einsum_equation] ( identifier[input_shapes] , identifier[output_shape] ):
literal[string]
identifier[ret] =[]
identifier[next_letter] = identifier[ord] ( literal[string] )
identifier[dim_to_letter] ={}
keyword[for] identifier[shape_num] , identifier[shape] keyword[in] ident... | def _einsum_equation(input_shapes, output_shape):
"""Turn shapes into an einsum equation.
e.g. "ij,jk->ik"
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Returns:
a string
"""
ret = []
next_letter = ord('a')
dim_to_letter = {}
for (shape_num, shape) in enumerate(inp... |
def benchmark_gops(N, gates, reps):
"""Return benchmark performance in GOPS (Gate operations per second)"""
t = timeit.timeit(lambda: benchmark(N, gates), number=reps)
gops = (GATES*REPS)/t
gops = int((gops * 100) + 0.5) / 100.0
return gops | def function[benchmark_gops, parameter[N, gates, reps]]:
constant[Return benchmark performance in GOPS (Gate operations per second)]
variable[t] assign[=] call[name[timeit].timeit, parameter[<ast.Lambda object at 0x7da18f7214e0>]]
variable[gops] assign[=] binary_operation[binary_operation[name[G... | keyword[def] identifier[benchmark_gops] ( identifier[N] , identifier[gates] , identifier[reps] ):
literal[string]
identifier[t] = identifier[timeit] . identifier[timeit] ( keyword[lambda] : identifier[benchmark] ( identifier[N] , identifier[gates] ), identifier[number] = identifier[reps] )
identifier[... | def benchmark_gops(N, gates, reps):
"""Return benchmark performance in GOPS (Gate operations per second)"""
t = timeit.timeit(lambda : benchmark(N, gates), number=reps)
gops = GATES * REPS / t
gops = int(gops * 100 + 0.5) / 100.0
return gops |
def _generic_definefont_parser(self, obj):
"""A generic parser for several DefineFontX."""
obj.FontID = unpack_ui16(self._src)
bc = BitConsumer(self._src)
obj.FontFlagsHasLayout = bc.u_get(1)
obj.FontFlagsShiftJIS = bc.u_get(1)
obj.FontFlagsSmallText = bc.u_get(1)
... | def function[_generic_definefont_parser, parameter[self, obj]]:
constant[A generic parser for several DefineFontX.]
name[obj].FontID assign[=] call[name[unpack_ui16], parameter[name[self]._src]]
variable[bc] assign[=] call[name[BitConsumer], parameter[name[self]._src]]
name[obj].FontFlag... | keyword[def] identifier[_generic_definefont_parser] ( identifier[self] , identifier[obj] ):
literal[string]
identifier[obj] . identifier[FontID] = identifier[unpack_ui16] ( identifier[self] . identifier[_src] )
identifier[bc] = identifier[BitConsumer] ( identifier[self] . identifier[_src]... | def _generic_definefont_parser(self, obj):
"""A generic parser for several DefineFontX."""
obj.FontID = unpack_ui16(self._src)
bc = BitConsumer(self._src)
obj.FontFlagsHasLayout = bc.u_get(1)
obj.FontFlagsShiftJIS = bc.u_get(1)
obj.FontFlagsSmallText = bc.u_get(1)
obj.FontFlagsANSI = bc.u_ge... |
def order_replicant_volume(self, volume_id, snapshot_schedule,
location, tier=None, os_type=None):
"""Places an order for a replicant block volume.
:param volume_id: The ID of the primary volume to be replicated
:param snapshot_schedule: The primary volume's snaps... | def function[order_replicant_volume, parameter[self, volume_id, snapshot_schedule, location, tier, os_type]]:
constant[Places an order for a replicant block volume.
:param volume_id: The ID of the primary volume to be replicated
:param snapshot_schedule: The primary volume's snapshot
... | keyword[def] identifier[order_replicant_volume] ( identifier[self] , identifier[volume_id] , identifier[snapshot_schedule] ,
identifier[location] , identifier[tier] = keyword[None] , identifier[os_type] = keyword[None] ):
literal[string]
identifier[block_mask] = literal[string] literal[string] ... | def order_replicant_volume(self, volume_id, snapshot_schedule, location, tier=None, os_type=None):
"""Places an order for a replicant block volume.
:param volume_id: The ID of the primary volume to be replicated
:param snapshot_schedule: The primary volume's snapshot
... |
def merge(bedfiles):
"""
given a BED file or list of BED files merge them an return a bedtools object
"""
if isinstance(bedfiles, list):
catted = concat(bedfiles)
else:
catted = concat([bedfiles])
if catted:
return concat(bedfiles).sort().merge()
else:
return ... | def function[merge, parameter[bedfiles]]:
constant[
given a BED file or list of BED files merge them an return a bedtools object
]
if call[name[isinstance], parameter[name[bedfiles], name[list]]] begin[:]
variable[catted] assign[=] call[name[concat], parameter[name[bedfiles]]]
... | keyword[def] identifier[merge] ( identifier[bedfiles] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[bedfiles] , identifier[list] ):
identifier[catted] = identifier[concat] ( identifier[bedfiles] )
keyword[else] :
identifier[catted] = identifier[concat] ([ identi... | def merge(bedfiles):
"""
given a BED file or list of BED files merge them an return a bedtools object
"""
if isinstance(bedfiles, list):
catted = concat(bedfiles) # depends on [control=['if'], data=[]]
else:
catted = concat([bedfiles])
if catted:
return concat(bedfiles).... |
def load_conf(cfg_path):
"""
Try to load the given conf file.
"""
global config
try:
cfg = open(cfg_path, 'r')
except Exception as ex:
if verbose:
print("Unable to open {0}".format(cfg_path))
print(str(ex))
return False
# Read the entire conte... | def function[load_conf, parameter[cfg_path]]:
constant[
Try to load the given conf file.
]
<ast.Global object at 0x7da20c7c8370>
<ast.Try object at 0x7da20c7ca290>
variable[cfg_json] assign[=] call[name[cfg].read, parameter[]]
call[name[cfg].close, parameter[]]
<ast.Try objec... | keyword[def] identifier[load_conf] ( identifier[cfg_path] ):
literal[string]
keyword[global] identifier[config]
keyword[try] :
identifier[cfg] = identifier[open] ( identifier[cfg_path] , literal[string] )
keyword[except] identifier[Exception] keyword[as] identifier[ex] :
ke... | def load_conf(cfg_path):
"""
Try to load the given conf file.
"""
global config
try:
cfg = open(cfg_path, 'r') # depends on [control=['try'], data=[]]
except Exception as ex:
if verbose:
print('Unable to open {0}'.format(cfg_path))
print(str(ex)) # depen... |
def update_time_range(form_data):
"""Move since and until to time_range."""
if 'since' in form_data or 'until' in form_data:
form_data['time_range'] = '{} : {}'.format(
form_data.pop('since', '') or '',
form_data.pop('until', '') or '',
) | def function[update_time_range, parameter[form_data]]:
constant[Move since and until to time_range.]
if <ast.BoolOp object at 0x7da1b1e13820> begin[:]
call[name[form_data]][constant[time_range]] assign[=] call[constant[{} : {}].format, parameter[<ast.BoolOp object at 0x7da1b20f9120>, <as... | keyword[def] identifier[update_time_range] ( identifier[form_data] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[form_data] keyword[or] literal[string] keyword[in] identifier[form_data] :
identifier[form_data] [ literal[string] ]= literal[string] . identifier[format]... | def update_time_range(form_data):
"""Move since and until to time_range."""
if 'since' in form_data or 'until' in form_data:
form_data['time_range'] = '{} : {}'.format(form_data.pop('since', '') or '', form_data.pop('until', '') or '') # depends on [control=['if'], data=[]] |
def setHighQualityOverlay(self, ulOverlayHandle):
"""
Specify which overlay to use the high quality render path. This overlay will be composited in during the distortion pass which
results in it drawing on top of everything else, but also at a higher quality as it samples the source texture dir... | def function[setHighQualityOverlay, parameter[self, ulOverlayHandle]]:
constant[
Specify which overlay to use the high quality render path. This overlay will be composited in during the distortion pass which
results in it drawing on top of everything else, but also at a higher quality as it sam... | keyword[def] identifier[setHighQualityOverlay] ( identifier[self] , identifier[ulOverlayHandle] ):
literal[string]
identifier[fn] = identifier[self] . identifier[function_table] . identifier[setHighQualityOverlay]
identifier[result] = identifier[fn] ( identifier[ulOverlayHandle] )
... | def setHighQualityOverlay(self, ulOverlayHandle):
"""
Specify which overlay to use the high quality render path. This overlay will be composited in during the distortion pass which
results in it drawing on top of everything else, but also at a higher quality as it samples the source texture directl... |
def status(self, status_id, raise_exception_on_failure=False):
"""Return the status of the generation job."""
query = {"output": "json", "user_credentials": self.api_key}
resp = requests.get(
"%sstatus/%s" % (self._url, status_id), params=query, timeout=self._timeout
)
... | def function[status, parameter[self, status_id, raise_exception_on_failure]]:
constant[Return the status of the generation job.]
variable[query] assign[=] dictionary[[<ast.Constant object at 0x7da20c76d3c0>, <ast.Constant object at 0x7da20c76cb80>], [<ast.Constant object at 0x7da20c76f460>, <ast.Attribu... | keyword[def] identifier[status] ( identifier[self] , identifier[status_id] , identifier[raise_exception_on_failure] = keyword[False] ):
literal[string]
identifier[query] ={ literal[string] : literal[string] , literal[string] : identifier[self] . identifier[api_key] }
identifier[resp] = id... | def status(self, status_id, raise_exception_on_failure=False):
"""Return the status of the generation job."""
query = {'output': 'json', 'user_credentials': self.api_key}
resp = requests.get('%sstatus/%s' % (self._url, status_id), params=query, timeout=self._timeout)
if raise_exception_on_failure and re... |
def module_name(self, jamfile_location):
"""Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location."""
assert isinstance(jamfile_location, basestring)
module = self.location2modul... | def function[module_name, parameter[self, jamfile_location]]:
constant[Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location.]
assert[call[name[isinstance], parameter[name[jamfile_location],... | keyword[def] identifier[module_name] ( identifier[self] , identifier[jamfile_location] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[jamfile_location] , identifier[basestring] )
identifier[module] = identifier[self] . identifier[location2module] . identifier[get] ... | def module_name(self, jamfile_location):
"""Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location."""
assert isinstance(jamfile_location, basestring)
module = self.location2module.get(jamfil... |
def get_tiltplanes(self, sequence):
'''
Extract tilting planes basing on distance map
'''
tilting_planes = []
distance_map = []
for i in range(1, len(sequence)):
distance_map.append([ sequence[i], self.virtual_atoms.get_distance( sequence[0], sequence[i] ) ])... | def function[get_tiltplanes, parameter[self, sequence]]:
constant[
Extract tilting planes basing on distance map
]
variable[tilting_planes] assign[=] list[[]]
variable[distance_map] assign[=] list[[]]
for taget[name[i]] in starred[call[name[range], parameter[constant[1], ... | keyword[def] identifier[get_tiltplanes] ( identifier[self] , identifier[sequence] ):
literal[string]
identifier[tilting_planes] =[]
identifier[distance_map] =[]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[sequence] )):... | def get_tiltplanes(self, sequence):
"""
Extract tilting planes basing on distance map
"""
tilting_planes = []
distance_map = []
for i in range(1, len(sequence)):
distance_map.append([sequence[i], self.virtual_atoms.get_distance(sequence[0], sequence[i])]) # depends on [control=[... |
def save(self, fname):
"""Saves symbol to a file.
You can also use pickle to do the job if you only work on python.
The advantage of `load`/`save` functions is that the file contents are language agnostic.
This means the model saved by one language binding can be loaded by a different
... | def function[save, parameter[self, fname]]:
constant[Saves symbol to a file.
You can also use pickle to do the job if you only work on python.
The advantage of `load`/`save` functions is that the file contents are language agnostic.
This means the model saved by one language binding can... | keyword[def] identifier[save] ( identifier[self] , identifier[fname] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[fname] , identifier[string_types] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[check_call] ( identi... | def save(self, fname):
"""Saves symbol to a file.
You can also use pickle to do the job if you only work on python.
The advantage of `load`/`save` functions is that the file contents are language agnostic.
This means the model saved by one language binding can be loaded by a different
... |
def write(elem, a_writer):
'''
Write a MicroXML element node (yes, even one representign a whole document)
elem - Amara MicroXML element node to be written out
writer - instance of amara3.uxml.writer to implement the writing process
'''
a_writer.start_element(elem.xml_name, attribs=elem.xml_attr... | def function[write, parameter[elem, a_writer]]:
constant[
Write a MicroXML element node (yes, even one representign a whole document)
elem - Amara MicroXML element node to be written out
writer - instance of amara3.uxml.writer to implement the writing process
]
call[name[a_writer].start_... | keyword[def] identifier[write] ( identifier[elem] , identifier[a_writer] ):
literal[string]
identifier[a_writer] . identifier[start_element] ( identifier[elem] . identifier[xml_name] , identifier[attribs] = identifier[elem] . identifier[xml_attributes] )
keyword[for] identifier[node] keyword[in] id... | def write(elem, a_writer):
"""
Write a MicroXML element node (yes, even one representign a whole document)
elem - Amara MicroXML element node to be written out
writer - instance of amara3.uxml.writer to implement the writing process
"""
a_writer.start_element(elem.xml_name, attribs=elem.xml_attr... |
def read_string(buff, byteorder='big'):
"""Read a string from a file-like object."""
length = read_numeric(USHORT, buff, byteorder)
return buff.read(length).decode('utf-8') | def function[read_string, parameter[buff, byteorder]]:
constant[Read a string from a file-like object.]
variable[length] assign[=] call[name[read_numeric], parameter[name[USHORT], name[buff], name[byteorder]]]
return[call[call[name[buff].read, parameter[name[length]]].decode, parameter[constant[utf-... | keyword[def] identifier[read_string] ( identifier[buff] , identifier[byteorder] = literal[string] ):
literal[string]
identifier[length] = identifier[read_numeric] ( identifier[USHORT] , identifier[buff] , identifier[byteorder] )
keyword[return] identifier[buff] . identifier[read] ( identifier[leng... | def read_string(buff, byteorder='big'):
"""Read a string from a file-like object."""
length = read_numeric(USHORT, buff, byteorder)
return buff.read(length).decode('utf-8') |
def AnalizarLiquidacion(self, aut, liq=None, ajuste=False):
"Método interno para analizar la respuesta de AFIP"
# proceso los datos básicos de la liquidación (devuelto por consultar):
if liq:
self.params_out = dict(
pto_emision=liq.get('ptoEmision'),
... | def function[AnalizarLiquidacion, parameter[self, aut, liq, ajuste]]:
constant[Método interno para analizar la respuesta de AFIP]
if name[liq] begin[:]
name[self].params_out assign[=] call[name[dict], parameter[]]
if name[ajuste] begin[:]
call[name... | keyword[def] identifier[AnalizarLiquidacion] ( identifier[self] , identifier[aut] , identifier[liq] = keyword[None] , identifier[ajuste] = keyword[False] ):
literal[string]
keyword[if] identifier[liq] :
identifier[self] . identifier[params_out] = identifier[dict] (
... | def AnalizarLiquidacion(self, aut, liq=None, ajuste=False):
"""Método interno para analizar la respuesta de AFIP"""
# proceso los datos básicos de la liquidación (devuelto por consultar):
if liq:
self.params_out = dict(pto_emision=liq.get('ptoEmision'), nro_orden=liq.get('nroOrden'), cuit_comprador=... |
def build(self, pipeline_def, artifacts_persisted):
'''Builds the execution plan.
'''
# Construct dependency dictionary
deps = {step.key: set() for step in self.steps}
for step in self.steps:
for step_input in step.step_inputs:
deps[step.key].add(ste... | def function[build, parameter[self, pipeline_def, artifacts_persisted]]:
constant[Builds the execution plan.
]
variable[deps] assign[=] <ast.DictComp object at 0x7da1b03a6470>
for taget[name[step]] in starred[name[self].steps] begin[:]
for taget[name[step_input]] in starr... | keyword[def] identifier[build] ( identifier[self] , identifier[pipeline_def] , identifier[artifacts_persisted] ):
literal[string]
identifier[deps] ={ identifier[step] . identifier[key] : identifier[set] () keyword[for] identifier[step] keyword[in] identifier[self] . identifier[steps] }... | def build(self, pipeline_def, artifacts_persisted):
"""Builds the execution plan.
"""
# Construct dependency dictionary
deps = {step.key: set() for step in self.steps}
for step in self.steps:
for step_input in step.step_inputs:
deps[step.key].add(step_input.prev_output_handle... |
def _filter_cluster_data(self):
"""
Filter the cluster data catalog into the filtered_data
catalog, which is what is shown in the H-R diagram.
Filter on the values of the sliders, as well as the lasso
selection in the skyviewer.
"""
min_temp = self.temperature_ra... | def function[_filter_cluster_data, parameter[self]]:
constant[
Filter the cluster data catalog into the filtered_data
catalog, which is what is shown in the H-R diagram.
Filter on the values of the sliders, as well as the lasso
selection in the skyviewer.
]
varia... | keyword[def] identifier[_filter_cluster_data] ( identifier[self] ):
literal[string]
identifier[min_temp] = identifier[self] . identifier[temperature_range_slider] . identifier[value] [ literal[int] ]
identifier[max_temp] = identifier[self] . identifier[temperature_range_slider] . identifie... | def _filter_cluster_data(self):
"""
Filter the cluster data catalog into the filtered_data
catalog, which is what is shown in the H-R diagram.
Filter on the values of the sliders, as well as the lasso
selection in the skyviewer.
"""
min_temp = self.temperature_range_slid... |
def upload(
cls, files, metadata=None, tags=None, project=None, coerce_ascii=False, progressbar=None
):
"""Uploads a series of files to the One Codex server.
Parameters
----------
files : `string` or `tuple`
A single path to a file on the system, or a tuple conta... | def function[upload, parameter[cls, files, metadata, tags, project, coerce_ascii, progressbar]]:
constant[Uploads a series of files to the One Codex server.
Parameters
----------
files : `string` or `tuple`
A single path to a file on the system, or a tuple containing a pairs... | keyword[def] identifier[upload] (
identifier[cls] , identifier[files] , identifier[metadata] = keyword[None] , identifier[tags] = keyword[None] , identifier[project] = keyword[None] , identifier[coerce_ascii] = keyword[False] , identifier[progressbar] = keyword[None]
):
literal[string]
identifier... | def upload(cls, files, metadata=None, tags=None, project=None, coerce_ascii=False, progressbar=None):
"""Uploads a series of files to the One Codex server.
Parameters
----------
files : `string` or `tuple`
A single path to a file on the system, or a tuple containing a pairs of p... |
def _validate_function(self, func, name):
"""
Tests `self.style_function` and `self.highlight_function` to ensure
they are functions returning dictionaries.
"""
test_feature = self.data['features'][0]
if not callable(func) or not isinstance(func(test_feature), dict):
... | def function[_validate_function, parameter[self, func, name]]:
constant[
Tests `self.style_function` and `self.highlight_function` to ensure
they are functions returning dictionaries.
]
variable[test_feature] assign[=] call[call[name[self].data][constant[features]]][constant[0]]
... | keyword[def] identifier[_validate_function] ( identifier[self] , identifier[func] , identifier[name] ):
literal[string]
identifier[test_feature] = identifier[self] . identifier[data] [ literal[string] ][ literal[int] ]
keyword[if] keyword[not] identifier[callable] ( identifier[func] ) ke... | def _validate_function(self, func, name):
"""
Tests `self.style_function` and `self.highlight_function` to ensure
they are functions returning dictionaries.
"""
test_feature = self.data['features'][0]
if not callable(func) or not isinstance(func(test_feature), dict):
raise Va... |
def move_pos(line=1, column=1, file=sys.stdout):
""" Move the cursor to a new position. Values are 1-based, and default
to 1.
Esc[<line>;<column>H
or
Esc[<line>;<column>f
"""
move.pos(line=line, col=column).write(file=file) | def function[move_pos, parameter[line, column, file]]:
constant[ Move the cursor to a new position. Values are 1-based, and default
to 1.
Esc[<line>;<column>H
or
Esc[<line>;<column>f
]
call[call[name[move].pos, parameter[]].write, parameter[]] | keyword[def] identifier[move_pos] ( identifier[line] = literal[int] , identifier[column] = literal[int] , identifier[file] = identifier[sys] . identifier[stdout] ):
literal[string]
identifier[move] . identifier[pos] ( identifier[line] = identifier[line] , identifier[col] = identifier[column] ). identifier[... | def move_pos(line=1, column=1, file=sys.stdout):
""" Move the cursor to a new position. Values are 1-based, and default
to 1.
Esc[<line>;<column>H
or
Esc[<line>;<column>f
"""
move.pos(line=line, col=column).write(file=file) |
def batch_iterable(iterable, count):
"""
Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. I... | def function[batch_iterable, parameter[iterable, count]]:
constant[
Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param coun... | keyword[def] identifier[batch_iterable] ( identifier[iterable] , identifier[count] ):
literal[string]
keyword[if] identifier[count] <= literal[int] :
keyword[return]
identifier[current_batch] =[]
keyword[for] identifier[item] keyword[in] identifier[iterable] :
keyword[if] ... | def batch_iterable(iterable, count):
"""
Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. I... |
def discover(self):
"""Method to send a discovery message
"""
if self.transport:
if self.discovery_countdown <= 0:
self.discovery_countdown = self.discovery_interval
msg = GetService(BROADCAST_MAC, self.source_id, seq_num=0, payload={}, ack_requested=F... | def function[discover, parameter[self]]:
constant[Method to send a discovery message
]
if name[self].transport begin[:]
if compare[name[self].discovery_countdown less_or_equal[<=] constant[0]] begin[:]
name[self].discovery_countdown assign[=] name[self].di... | keyword[def] identifier[discover] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[transport] :
keyword[if] identifier[self] . identifier[discovery_countdown] <= literal[int] :
identifier[self] . identifier[discovery_countdown] = identi... | def discover(self):
"""Method to send a discovery message
"""
if self.transport:
if self.discovery_countdown <= 0:
self.discovery_countdown = self.discovery_interval
msg = GetService(BROADCAST_MAC, self.source_id, seq_num=0, payload={}, ack_requested=False, response_reque... |
def key_from_keybase(username, fingerprint=None):
"""Look up a public key from a username"""
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
j_resp = json.loads(polite_string(resp.content))
if 'them' in j_resp and len(j_resp['them']) == 1:
... | def function[key_from_keybase, parameter[username, fingerprint]]:
constant[Look up a public key from a username]
variable[url] assign[=] call[name[keybase_lookup_url], parameter[name[username]]]
variable[resp] assign[=] call[name[requests].get, parameter[name[url]]]
if compare[name[resp]... | keyword[def] identifier[key_from_keybase] ( identifier[username] , identifier[fingerprint] = keyword[None] ):
literal[string]
identifier[url] = identifier[keybase_lookup_url] ( identifier[username] )
identifier[resp] = identifier[requests] . identifier[get] ( identifier[url] )
keyword[if] identi... | def key_from_keybase(username, fingerprint=None):
"""Look up a public key from a username"""
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
j_resp = json.loads(polite_string(resp.content))
if 'them' in j_resp and len(j_resp['them']) == 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.