code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def merge(base, obj, location=None):
"""
merge is like XmrsPathNode.update() except it raises errors on
unequal non-None values.
"""
# pump object to it's location with dummy nodes
while location:
axis = location.pop()
obj = XmrsPathNode(None, None, links={axis: obj})
if base... | def function[merge, parameter[base, obj, location]]:
constant[
merge is like XmrsPathNode.update() except it raises errors on
unequal non-None values.
]
while name[location] begin[:]
variable[axis] assign[=] call[name[location].pop, parameter[]]
variable[obj] ... | keyword[def] identifier[merge] ( identifier[base] , identifier[obj] , identifier[location] = keyword[None] ):
literal[string]
keyword[while] identifier[location] :
identifier[axis] = identifier[location] . identifier[pop] ()
identifier[obj] = identifier[XmrsPathNode] ( keyword[None]... | def merge(base, obj, location=None):
"""
merge is like XmrsPathNode.update() except it raises errors on
unequal non-None values.
"""
# pump object to it's location with dummy nodes
while location:
axis = location.pop()
obj = XmrsPathNode(None, None, links={axis: obj}) # depends ... |
def updatable_map(cache: MutableMapping[Domain, Range]) -> Operator[Map]:
"""
Returns decorator that calls wrapped function
if nothing was found in cache for its argument
and reuses result afterwards.
Wrapped function arguments should be hashable.
"""
def wrapper(function: Map[Domain, Rang... | def function[updatable_map, parameter[cache]]:
constant[
Returns decorator that calls wrapped function
if nothing was found in cache for its argument
and reuses result afterwards.
Wrapped function arguments should be hashable.
]
def function[wrapper, parameter[function]]:
... | keyword[def] identifier[updatable_map] ( identifier[cache] : identifier[MutableMapping] [ identifier[Domain] , identifier[Range] ])-> identifier[Operator] [ identifier[Map] ]:
literal[string]
keyword[def] identifier[wrapper] ( identifier[function] : identifier[Map] [ identifier[Domain] , identifier[Range... | def updatable_map(cache: MutableMapping[Domain, Range]) -> Operator[Map]:
"""
Returns decorator that calls wrapped function
if nothing was found in cache for its argument
and reuses result afterwards.
Wrapped function arguments should be hashable.
"""
def wrapper(function: Map[Domain, Rang... |
def create_asset_model(self, ):
"""Return a treemodel with the levels: project, assettype, asset and reftrack type
:returns: a treemodel
:rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`
:raises: None
"""
rootdata = treemodel.ListItemData(['Name'])
rootitem = ... | def function[create_asset_model, parameter[self]]:
constant[Return a treemodel with the levels: project, assettype, asset and reftrack type
:returns: a treemodel
:rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`
:raises: None
]
variable[rootdata] assign[=] call[name[t... | keyword[def] identifier[create_asset_model] ( identifier[self] ,):
literal[string]
identifier[rootdata] = identifier[treemodel] . identifier[ListItemData] ([ literal[string] ])
identifier[rootitem] = identifier[treemodel] . identifier[TreeItem] ( identifier[rootdata] )
identifier[... | def create_asset_model(self):
"""Return a treemodel with the levels: project, assettype, asset and reftrack type
:returns: a treemodel
:rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`
:raises: None
"""
rootdata = treemodel.ListItemData(['Name'])
rootitem = treemodel.Tree... |
def channel(self) -> Iterator[amqp.Channel]:
"""Returns a new channel from a new connection as a context manager."""
with self.connection() as conn:
ch = conn.channel()
logger.info('Opened new channel')
with _safe_close(ch):
yield ch | def function[channel, parameter[self]]:
constant[Returns a new channel from a new connection as a context manager.]
with call[name[self].connection, parameter[]] begin[:]
variable[ch] assign[=] call[name[conn].channel, parameter[]]
call[name[logger].info, parameter[consta... | keyword[def] identifier[channel] ( identifier[self] )-> identifier[Iterator] [ identifier[amqp] . identifier[Channel] ]:
literal[string]
keyword[with] identifier[self] . identifier[connection] () keyword[as] identifier[conn] :
identifier[ch] = identifier[conn] . identifier[channel] (... | def channel(self) -> Iterator[amqp.Channel]:
"""Returns a new channel from a new connection as a context manager."""
with self.connection() as conn:
ch = conn.channel()
logger.info('Opened new channel')
with _safe_close(ch):
yield ch # depends on [control=['with'], data=[]] ... |
def unwrap(node):
"""Remove a node, replacing it with its children."""
for child in list(node.childNodes):
node.parentNode.insertBefore(child, node)
remove_node(node) | def function[unwrap, parameter[node]]:
constant[Remove a node, replacing it with its children.]
for taget[name[child]] in starred[call[name[list], parameter[name[node].childNodes]]] begin[:]
call[name[node].parentNode.insertBefore, parameter[name[child], name[node]]]
call[name[re... | keyword[def] identifier[unwrap] ( identifier[node] ):
literal[string]
keyword[for] identifier[child] keyword[in] identifier[list] ( identifier[node] . identifier[childNodes] ):
identifier[node] . identifier[parentNode] . identifier[insertBefore] ( identifier[child] , identifier[node] )
ide... | def unwrap(node):
"""Remove a node, replacing it with its children."""
for child in list(node.childNodes):
node.parentNode.insertBefore(child, node) # depends on [control=['for'], data=['child']]
remove_node(node) |
def async_task(func, *args, **kwargs):
"""Queue a task for the cluster."""
keywords = kwargs.copy()
opt_keys = (
'hook', 'group', 'save', 'sync', 'cached', 'ack_failure', 'iter_count', 'iter_cached', 'chain', 'broker')
q_options = keywords.pop('q_options', {})
# get an id
tag = uuid()
# ... | def function[async_task, parameter[func]]:
constant[Queue a task for the cluster.]
variable[keywords] assign[=] call[name[kwargs].copy, parameter[]]
variable[opt_keys] assign[=] tuple[[<ast.Constant object at 0x7da1b1716ef0>, <ast.Constant object at 0x7da1b1714130>, <ast.Constant object at 0x7da... | keyword[def] identifier[async_task] ( identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[keywords] = identifier[kwargs] . identifier[copy] ()
identifier[opt_keys] =(
literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , li... | def async_task(func, *args, **kwargs):
"""Queue a task for the cluster."""
keywords = kwargs.copy()
opt_keys = ('hook', 'group', 'save', 'sync', 'cached', 'ack_failure', 'iter_count', 'iter_cached', 'chain', 'broker')
q_options = keywords.pop('q_options', {})
# get an id
tag = uuid()
# build... |
def masked_sub_grid_1d_index_to_2d_sub_pixel_index_from_mask(mask, sub_grid_size):
"""Compute a 1D array that maps every unmasked pixel to its corresponding 2d pixel using its (y,x) pixel indexes.
For howtolens if pixel [2,5] corresponds to the second pixel on the 1D array, grid_to_pixel[1] = [2,5]"""
tot... | def function[masked_sub_grid_1d_index_to_2d_sub_pixel_index_from_mask, parameter[mask, sub_grid_size]]:
constant[Compute a 1D array that maps every unmasked pixel to its corresponding 2d pixel using its (y,x) pixel indexes.
For howtolens if pixel [2,5] corresponds to the second pixel on the 1D array, grid_... | keyword[def] identifier[masked_sub_grid_1d_index_to_2d_sub_pixel_index_from_mask] ( identifier[mask] , identifier[sub_grid_size] ):
literal[string]
identifier[total_sub_pixels] = identifier[total_sub_pixels_from_mask_and_sub_grid_size] ( identifier[mask] = identifier[mask] , identifier[sub_grid_size] = id... | def masked_sub_grid_1d_index_to_2d_sub_pixel_index_from_mask(mask, sub_grid_size):
"""Compute a 1D array that maps every unmasked pixel to its corresponding 2d pixel using its (y,x) pixel indexes.
For howtolens if pixel [2,5] corresponds to the second pixel on the 1D array, grid_to_pixel[1] = [2,5]"""
tota... |
def dequeue(self, block=True):
"""Dequeue a record and return item."""
return self.queue.get(block, self.queue_get_timeout) | def function[dequeue, parameter[self, block]]:
constant[Dequeue a record and return item.]
return[call[name[self].queue.get, parameter[name[block], name[self].queue_get_timeout]]] | keyword[def] identifier[dequeue] ( identifier[self] , identifier[block] = keyword[True] ):
literal[string]
keyword[return] identifier[self] . identifier[queue] . identifier[get] ( identifier[block] , identifier[self] . identifier[queue_get_timeout] ) | def dequeue(self, block=True):
"""Dequeue a record and return item."""
return self.queue.get(block, self.queue_get_timeout) |
def _generate_indicators(catalog, validator=None, only_numeric=False):
"""Genera los indicadores de un catálogo individual.
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: diccionario con los indicadores del catálogo provisto
"""
result = {}
# Obteng... | def function[_generate_indicators, parameter[catalog, validator, only_numeric]]:
constant[Genera los indicadores de un catálogo individual.
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: diccionario con los indicadores del catálogo provisto
]
vari... | keyword[def] identifier[_generate_indicators] ( identifier[catalog] , identifier[validator] = keyword[None] , identifier[only_numeric] = keyword[False] ):
literal[string]
identifier[result] ={}
identifier[result] . identifier[update] ( identifier[_generate_status_indicators] ( identifier[catalo... | def _generate_indicators(catalog, validator=None, only_numeric=False):
"""Genera los indicadores de un catálogo individual.
Args:
catalog (dict): diccionario de un data.json parseado
Returns:
dict: diccionario con los indicadores del catálogo provisto
"""
result = {}
# Obtengo ... |
def remove(in_bam):
"""
remove bam file and the index if exists
"""
if utils.file_exists(in_bam):
utils.remove_safe(in_bam)
if utils.file_exists(in_bam + ".bai"):
utils.remove_safe(in_bam + ".bai") | def function[remove, parameter[in_bam]]:
constant[
remove bam file and the index if exists
]
if call[name[utils].file_exists, parameter[name[in_bam]]] begin[:]
call[name[utils].remove_safe, parameter[name[in_bam]]]
if call[name[utils].file_exists, parameter[binary_operati... | keyword[def] identifier[remove] ( identifier[in_bam] ):
literal[string]
keyword[if] identifier[utils] . identifier[file_exists] ( identifier[in_bam] ):
identifier[utils] . identifier[remove_safe] ( identifier[in_bam] )
keyword[if] identifier[utils] . identifier[file_exists] ( identifier[in_... | def remove(in_bam):
"""
remove bam file and the index if exists
"""
if utils.file_exists(in_bam):
utils.remove_safe(in_bam) # depends on [control=['if'], data=[]]
if utils.file_exists(in_bam + '.bai'):
utils.remove_safe(in_bam + '.bai') # depends on [control=['if'], data=[]] |
def get_deliveryserver(self, domainid, serverid):
"""Get a delivery server"""
return self.api_call(
ENDPOINTS['deliveryservers']['get'],
dict(domainid=domainid, serverid=serverid)) | def function[get_deliveryserver, parameter[self, domainid, serverid]]:
constant[Get a delivery server]
return[call[name[self].api_call, parameter[call[call[name[ENDPOINTS]][constant[deliveryservers]]][constant[get]], call[name[dict], parameter[]]]]] | keyword[def] identifier[get_deliveryserver] ( identifier[self] , identifier[domainid] , identifier[serverid] ):
literal[string]
keyword[return] identifier[self] . identifier[api_call] (
identifier[ENDPOINTS] [ literal[string] ][ literal[string] ],
identifier[dict] ( identifier[do... | def get_deliveryserver(self, domainid, serverid):
"""Get a delivery server"""
return self.api_call(ENDPOINTS['deliveryservers']['get'], dict(domainid=domainid, serverid=serverid)) |
def get_application_choices():
"""
Get the select options for the application selector
:return:
"""
result = []
keys = set()
for ct in ContentType.objects.order_by('app_label', 'model'):
try:
if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys... | def function[get_application_choices, parameter[]]:
constant[
Get the select options for the application selector
:return:
]
variable[result] assign[=] list[[]]
variable[keys] assign[=] call[name[set], parameter[]]
for taget[name[ct]] in starred[call[name[ContentType].object... | keyword[def] identifier[get_application_choices] ():
literal[string]
identifier[result] =[]
identifier[keys] = identifier[set] ()
keyword[for] identifier[ct] keyword[in] identifier[ContentType] . identifier[objects] . identifier[order_by] ( literal[string] , literal[string] ):
keyword... | def get_application_choices():
"""
Get the select options for the application selector
:return:
"""
result = []
keys = set()
for ct in ContentType.objects.order_by('app_label', 'model'):
try:
if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys... |
def parallel_epd_worker(task):
'''This is a parallel worker for the function below.
Parameters
----------
task : tuple
- task[0] = lcfile
- task[1] = timecol
- task[2] = magcol
- task[3] = errcol
- task[4] = externalparams
- task[5] = lcformat
- ... | def function[parallel_epd_worker, parameter[task]]:
constant[This is a parallel worker for the function below.
Parameters
----------
task : tuple
- task[0] = lcfile
- task[1] = timecol
- task[2] = magcol
- task[3] = errcol
- task[4] = externalparams
... | keyword[def] identifier[parallel_epd_worker] ( identifier[task] ):
literal[string]
( identifier[lcfile] , identifier[timecol] , identifier[magcol] , identifier[errcol] ,
identifier[externalparams] , identifier[lcformat] , identifier[lcformatdir] , identifier[magsarefluxes] ,
identifier[epdsmooth_... | def parallel_epd_worker(task):
"""This is a parallel worker for the function below.
Parameters
----------
task : tuple
- task[0] = lcfile
- task[1] = timecol
- task[2] = magcol
- task[3] = errcol
- task[4] = externalparams
- task[5] = lcformat
- ... |
def _set_vrf(self, v, load=False):
"""
Setter method for vrf, mapped from YANG variable /routing_system/interface/ve/vrf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vrf is considered as a private
method. Backends looking to populate this variable shou... | def function[_set_vrf, parameter[self, v, load]]:
constant[
Setter method for vrf, mapped from YANG variable /routing_system/interface/ve/vrf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vrf is considered as a private
method. Backends looking to po... | keyword[def] identifier[_set_vrf] ( 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] :
identifier... | def _set_vrf(self, v, load=False):
"""
Setter method for vrf, mapped from YANG variable /routing_system/interface/ve/vrf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vrf is considered as a private
method. Backends looking to populate this variable shou... |
def format_log_context(msg, connection=None, keyspace=None):
"""Format log message to add keyspace and connection context"""
connection_info = connection or 'DEFAULT_CONNECTION'
if keyspace:
msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg)
else:
msg = ... | def function[format_log_context, parameter[msg, connection, keyspace]]:
constant[Format log message to add keyspace and connection context]
variable[connection_info] assign[=] <ast.BoolOp object at 0x7da2044c2b30>
if name[keyspace] begin[:]
variable[msg] assign[=] call[constant[[... | keyword[def] identifier[format_log_context] ( identifier[msg] , identifier[connection] = keyword[None] , identifier[keyspace] = keyword[None] ):
literal[string]
identifier[connection_info] = identifier[connection] keyword[or] literal[string]
keyword[if] identifier[keyspace] :
identifier[... | def format_log_context(msg, connection=None, keyspace=None):
"""Format log message to add keyspace and connection context"""
connection_info = connection or 'DEFAULT_CONNECTION'
if keyspace:
msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg) # depends on [control=['... |
def compliance_schedule(self, column=None, value=None, **kwargs):
"""
A sequence of activities with associated milestones which pertains to a
given permit.
>>> PCS().compliance_schedule('cmpl_schd_evt', '62099')
"""
return self._resolve_call('PCS_CMPL_SCHD', column, valu... | def function[compliance_schedule, parameter[self, column, value]]:
constant[
A sequence of activities with associated milestones which pertains to a
given permit.
>>> PCS().compliance_schedule('cmpl_schd_evt', '62099')
]
return[call[name[self]._resolve_call, parameter[consta... | keyword[def] identifier[compliance_schedule] ( identifier[self] , identifier[column] = keyword[None] , identifier[value] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_resolve_call] ( literal[string] , identifier[column] , identifier[value]... | def compliance_schedule(self, column=None, value=None, **kwargs):
"""
A sequence of activities with associated milestones which pertains to a
given permit.
>>> PCS().compliance_schedule('cmpl_schd_evt', '62099')
"""
return self._resolve_call('PCS_CMPL_SCHD', column, value, **kwa... |
def getdesc(self, actual=True):
"""Get the table description.
By default it returns the actual description (thus telling the
actual array shapes and data managers used).
`actual=False` means that the original description as made by
:func:`maketabdesc` is returned.
"""
... | def function[getdesc, parameter[self, actual]]:
constant[Get the table description.
By default it returns the actual description (thus telling the
actual array shapes and data managers used).
`actual=False` means that the original description as made by
:func:`maketabdesc` is re... | keyword[def] identifier[getdesc] ( identifier[self] , identifier[actual] = keyword[True] ):
literal[string]
identifier[tabledesc] = identifier[self] . identifier[_getdesc] ( identifier[actual] , keyword[True] )
identifier[hcdefs] = identifier[tabledesc] . identifier[get... | def getdesc(self, actual=True):
"""Get the table description.
By default it returns the actual description (thus telling the
actual array shapes and data managers used).
`actual=False` means that the original description as made by
:func:`maketabdesc` is returned.
"""
ta... |
def _exec(self, detach=True):
"""
daemonize and exec main()
"""
kwargs = {
'pidfile': self.pidfile,
'working_directory': self.home_dir,
}
# FIXME - doesn't work
if not detach:
kwargs.update({
'detach_process... | def function[_exec, parameter[self, detach]]:
constant[
daemonize and exec main()
]
variable[kwargs] assign[=] dictionary[[<ast.Constant object at 0x7da18fe92b90>, <ast.Constant object at 0x7da18fe938e0>], [<ast.Attribute object at 0x7da18fe924a0>, <ast.Attribute object at 0x7da18fe91750... | keyword[def] identifier[_exec] ( identifier[self] , identifier[detach] = keyword[True] ):
literal[string]
identifier[kwargs] ={
literal[string] : identifier[self] . identifier[pidfile] ,
literal[string] : identifier[self] . identifier[home_dir] ,
}
keywo... | def _exec(self, detach=True):
"""
daemonize and exec main()
"""
kwargs = {'pidfile': self.pidfile, 'working_directory': self.home_dir}
# FIXME - doesn't work
if not detach:
kwargs.update({'detach_process': False, 'files_preserve': [0, 1, 2], 'stdout': sys.stdout, 'stderr': sys.st... |
def intersection(self, *args):
"""
Produce an array that contains every item shared between all the
passed-in arrays.
"""
if type(self.obj[0]) is int:
a = self.obj
else:
a = tuple(self.obj[0])
setobj = set(a)
for i, v in enumerate(a... | def function[intersection, parameter[self]]:
constant[
Produce an array that contains every item shared between all the
passed-in arrays.
]
if compare[call[name[type], parameter[call[name[self].obj][constant[0]]]] is name[int]] begin[:]
variable[a] assign[=] name[... | keyword[def] identifier[intersection] ( identifier[self] ,* identifier[args] ):
literal[string]
keyword[if] identifier[type] ( identifier[self] . identifier[obj] [ literal[int] ]) keyword[is] identifier[int] :
identifier[a] = identifier[self] . identifier[obj]
keyword[else]... | def intersection(self, *args):
"""
Produce an array that contains every item shared between all the
passed-in arrays.
"""
if type(self.obj[0]) is int:
a = self.obj # depends on [control=['if'], data=[]]
else:
a = tuple(self.obj[0])
setobj = set(a)
for (i, v) ... |
def unpack_nfirst(seq, nfirst):
"""Unpack the nfrist items from the list and return the rest.
>>> a, b, c, rest = unpack_nfirst((1, 2, 3, 4, 5), 3)
>>> a, b, c
(1, 2, 3)
>>> rest
(4, 5)
"""
iterator = iter(seq)
for _ in range(nfirst):
yield next(iterator, None)
yield tu... | def function[unpack_nfirst, parameter[seq, nfirst]]:
constant[Unpack the nfrist items from the list and return the rest.
>>> a, b, c, rest = unpack_nfirst((1, 2, 3, 4, 5), 3)
>>> a, b, c
(1, 2, 3)
>>> rest
(4, 5)
]
variable[iterator] assign[=] call[name[iter], parameter[name[se... | keyword[def] identifier[unpack_nfirst] ( identifier[seq] , identifier[nfirst] ):
literal[string]
identifier[iterator] = identifier[iter] ( identifier[seq] )
keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[nfirst] ):
keyword[yield] identifier[next] ( identifier[iterat... | def unpack_nfirst(seq, nfirst):
"""Unpack the nfrist items from the list and return the rest.
>>> a, b, c, rest = unpack_nfirst((1, 2, 3, 4, 5), 3)
>>> a, b, c
(1, 2, 3)
>>> rest
(4, 5)
"""
iterator = iter(seq)
for _ in range(nfirst):
yield next(iterator, None) # depends o... |
def delete_collection_storage_class(self, **kwargs): # noqa: E501
"""delete_collection_storage_class # noqa: E501
delete collection of StorageClass # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | def function[delete_collection_storage_class, parameter[self]]:
constant[delete_collection_storage_class # noqa: E501
delete collection of StorageClass # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=Tru... | keyword[def] identifier[delete_collection_storage_class] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self]... | def delete_collection_storage_class(self, **kwargs): # noqa: E501
'delete_collection_storage_class # noqa: E501\n\n delete collection of StorageClass # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n ... |
def mass_erase():
"""Performs a MASS erase (i.e. erases the entire device."""
# Send DNLOAD with first byte=0x41
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE,
"\x41", __TIMEOUT)
# Execute last command
if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
ra... | def function[mass_erase, parameter[]]:
constant[Performs a MASS erase (i.e. erases the entire device.]
call[name[__dev].ctrl_transfer, parameter[constant[33], name[__DFU_DNLOAD], constant[0], name[__DFU_INTERFACE], constant[A], name[__TIMEOUT]]]
if compare[call[name[get_status], parameter[]] not... | keyword[def] identifier[mass_erase] ():
literal[string]
identifier[__dev] . identifier[ctrl_transfer] ( literal[int] , identifier[__DFU_DNLOAD] , literal[int] , identifier[__DFU_INTERFACE] ,
literal[string] , identifier[__TIMEOUT] )
keyword[if] identifier[get_status] ()!= identifier[_... | def mass_erase():
"""Performs a MASS erase (i.e. erases the entire device."""
# Send DNLOAD with first byte=0x41
__dev.ctrl_transfer(33, __DFU_DNLOAD, 0, __DFU_INTERFACE, 'A', __TIMEOUT)
# Execute last command
if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY:
raise Exception('DFU: erase fail... |
def rewrite_filters_in_optional_blocks(ir_blocks):
"""In optional contexts, add a check for null that allows non-existent optional data through.
Optional traversals in Gremlin represent missing optional data by setting the current vertex
to null until the exit from the optional scope. Therefore, filtering ... | def function[rewrite_filters_in_optional_blocks, parameter[ir_blocks]]:
constant[In optional contexts, add a check for null that allows non-existent optional data through.
Optional traversals in Gremlin represent missing optional data by setting the current vertex
to null until the exit from the option... | keyword[def] identifier[rewrite_filters_in_optional_blocks] ( identifier[ir_blocks] ):
literal[string]
identifier[new_ir_blocks] =[]
identifier[optional_context_depth] = literal[int]
keyword[for] identifier[block] keyword[in] identifier[ir_blocks] :
identifier[new_block] = identifie... | def rewrite_filters_in_optional_blocks(ir_blocks):
"""In optional contexts, add a check for null that allows non-existent optional data through.
Optional traversals in Gremlin represent missing optional data by setting the current vertex
to null until the exit from the optional scope. Therefore, filtering ... |
def ansi_density(color, density_standard):
"""
Calculates density for the given SpectralColor using the spectral weighting
function provided. For example, ANSI_STATUS_T_RED. These may be found in
:py:mod:`colormath.density_standards`.
:param SpectralColor color: The SpectralColor object to calculat... | def function[ansi_density, parameter[color, density_standard]]:
constant[
Calculates density for the given SpectralColor using the spectral weighting
function provided. For example, ANSI_STATUS_T_RED. These may be found in
:py:mod:`colormath.density_standards`.
:param SpectralColor color: The S... | keyword[def] identifier[ansi_density] ( identifier[color] , identifier[density_standard] ):
literal[string]
identifier[sample] = identifier[color] . identifier[get_numpy_array] ()
identifier[intermediate] = identifier[sample] * identifier[density_standard]
identifier[numerator] =... | def ansi_density(color, density_standard):
"""
Calculates density for the given SpectralColor using the spectral weighting
function provided. For example, ANSI_STATUS_T_RED. These may be found in
:py:mod:`colormath.density_standards`.
:param SpectralColor color: The SpectralColor object to calculat... |
def __fetch_issues(self, from_date, to_date):
"""Fetch the issues"""
issues_groups = self.client.issues(from_date=from_date)
for raw_issues in issues_groups:
issues = json.loads(raw_issues)
for issue in issues:
if str_to_datetime(issue['updated_at']) > ... | def function[__fetch_issues, parameter[self, from_date, to_date]]:
constant[Fetch the issues]
variable[issues_groups] assign[=] call[name[self].client.issues, parameter[]]
for taget[name[raw_issues]] in starred[name[issues_groups]] begin[:]
variable[issues] assign[=] call[name[js... | keyword[def] identifier[__fetch_issues] ( identifier[self] , identifier[from_date] , identifier[to_date] ):
literal[string]
identifier[issues_groups] = identifier[self] . identifier[client] . identifier[issues] ( identifier[from_date] = identifier[from_date] )
keyword[for] identifier[ra... | def __fetch_issues(self, from_date, to_date):
"""Fetch the issues"""
issues_groups = self.client.issues(from_date=from_date)
for raw_issues in issues_groups:
issues = json.loads(raw_issues)
for issue in issues:
if str_to_datetime(issue['updated_at']) > to_date:
re... |
def write_dftbp(filename, atoms):
"""Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure
"""
scale_pos = dftbpToBohr
lines = ""
# 1. line, use absolute positions
natoms... | def function[write_dftbp, parameter[filename, atoms]]:
constant[Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure
]
variable[scale_pos] assign[=] name[dftbpToBohr]
... | keyword[def] identifier[write_dftbp] ( identifier[filename] , identifier[atoms] ):
literal[string]
identifier[scale_pos] = identifier[dftbpToBohr]
identifier[lines] = literal[string]
identifier[natoms] = identifier[atoms] . identifier[get_number_of_atoms] ()
identifier[lines] += ide... | def write_dftbp(filename, atoms):
"""Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure
"""
scale_pos = dftbpToBohr
lines = ''
# 1. line, use absolute positions
natoms =... |
def _fetch_article(self, article_id):
"""Fetch article data
:param article_id: id of the article to fetch
"""
fetched_data = self.handler.article(article_id)
data = {
'number': fetched_data[1].number,
'message_id': fetched_data[1].message_id,
... | def function[_fetch_article, parameter[self, article_id]]:
constant[Fetch article data
:param article_id: id of the article to fetch
]
variable[fetched_data] assign[=] call[name[self].handler.article, parameter[name[article_id]]]
variable[data] assign[=] dictionary[[<ast.Constan... | keyword[def] identifier[_fetch_article] ( identifier[self] , identifier[article_id] ):
literal[string]
identifier[fetched_data] = identifier[self] . identifier[handler] . identifier[article] ( identifier[article_id] )
identifier[data] ={
literal[string] : identifier[fetched_data] ... | def _fetch_article(self, article_id):
"""Fetch article data
:param article_id: id of the article to fetch
"""
fetched_data = self.handler.article(article_id)
data = {'number': fetched_data[1].number, 'message_id': fetched_data[1].message_id, 'lines': fetched_data[1].lines}
return data |
def table(self,x,*args,**kwargs):
"""
returns the values of column x
in an n-dimensional array, each
dimension being the values from
a dimension in *args
at the moment very slow due to generate :/
"""
reduce_func = kwargs.get('reduce',... | def function[table, parameter[self, x]]:
constant[
returns the values of column x
in an n-dimensional array, each
dimension being the values from
a dimension in *args
at the moment very slow due to generate :/
]
variable[reduce_func] a... | keyword[def] identifier[table] ( identifier[self] , identifier[x] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[reduce_func] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[lambda] identifier[x] : identifier[x] )
identifier[data] =[]
... | def table(self, x, *args, **kwargs):
"""
returns the values of column x
in an n-dimensional array, each
dimension being the values from
a dimension in *args
at the moment very slow due to generate :/
"""
reduce_func = kwargs.get('reduce', lamb... |
def addreadergroup(self, newgroup):
"""Add a reader group"""
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if 0 != hresult:
raise error(
'Failed to establish context: ' + \
SCardGetErrorMessage(hresult))
try:
hresult ... | def function[addreadergroup, parameter[self, newgroup]]:
constant[Add a reader group]
<ast.Tuple object at 0x7da1b23eca30> assign[=] call[name[SCardEstablishContext], parameter[name[SCARD_SCOPE_USER]]]
if compare[constant[0] not_equal[!=] name[hresult]] begin[:]
<ast.Raise object at 0x7d... | keyword[def] identifier[addreadergroup] ( identifier[self] , identifier[newgroup] ):
literal[string]
identifier[hresult] , identifier[hcontext] = identifier[SCardEstablishContext] ( identifier[SCARD_SCOPE_USER] )
keyword[if] literal[int] != identifier[hresult] :
keyword[rais... | def addreadergroup(self, newgroup):
"""Add a reader group"""
(hresult, hcontext) = SCardEstablishContext(SCARD_SCOPE_USER)
if 0 != hresult:
raise error('Failed to establish context: ' + SCardGetErrorMessage(hresult)) # depends on [control=['if'], data=['hresult']]
try:
hresult = SCardIn... |
def set_general_setting(key, value, qsettings=None):
"""Set value to QSettings based on key.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use t... | def function[set_general_setting, parameter[key, value, qsettings]]:
constant[Set value to QSettings based on key.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defi... | keyword[def] identifier[set_general_setting] ( identifier[key] , identifier[value] , identifier[qsettings] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[qsettings] :
identifier[qsettings] = identifier[QSettings] ()
identifier[qsettings] . identifier[setValue] ( ide... | def set_general_setting(key, value, qsettings=None):
"""Set value to QSettings based on key.
:param key: Unique key for setting.
:type key: basestring
:param value: Value to be saved.
:type value: QVariant
:param qsettings: A custom QSettings to use. If it's not defined, it will
use t... |
def hkdf_expand(pseudo_random_key, info=b"", length=32, hash=hashlib.sha512):
'''
Expand `pseudo_random_key` and `info` into a key of length `bytes` using
HKDF's expand function based on HMAC with the provided hash (default
SHA-512). See the HKDF draft RFC and paper for usage notes.
'''
hash_len = hash().digest_s... | def function[hkdf_expand, parameter[pseudo_random_key, info, length, hash]]:
constant[
Expand `pseudo_random_key` and `info` into a key of length `bytes` using
HKDF's expand function based on HMAC with the provided hash (default
SHA-512). See the HKDF draft RFC and paper for usage notes.
]
variable[... | keyword[def] identifier[hkdf_expand] ( identifier[pseudo_random_key] , identifier[info] = literal[string] , identifier[length] = literal[int] , identifier[hash] = identifier[hashlib] . identifier[sha512] ):
literal[string]
identifier[hash_len] = identifier[hash] (). identifier[digest_size]
identifier[length] ... | def hkdf_expand(pseudo_random_key, info=b'', length=32, hash=hashlib.sha512):
"""
Expand `pseudo_random_key` and `info` into a key of length `bytes` using
HKDF's expand function based on HMAC with the provided hash (default
SHA-512). See the HKDF draft RFC and paper for usage notes.
"""
hash_len = hash().di... |
def render_response(self):
"""Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style).
"""
# Use whatever renderers are defined for name and value.
# (.attributes() is responsible for all other rendering.)
name, value = self.name, self.value... | def function[render_response, parameter[self]]:
constant[Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style).
]
<ast.Tuple object at 0x7da2044c39a0> assign[=] tuple[[<ast.Attribute object at 0x7da2044c10f0>, <ast.Attribute object at 0x7da2044c3040>]]
... | keyword[def] identifier[render_response] ( identifier[self] ):
literal[string]
identifier[name] , identifier[value] = identifier[self] . identifier[name] , identifier[self] . identifier[value]
identifier[renderer] = identifier[self] . identifier[attribute_renderers] . id... | def render_response(self):
"""Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style).
"""
# Use whatever renderers are defined for name and value.
# (.attributes() is responsible for all other rendering.)
(name, value) = (self.name, self.value)
rendere... |
def createsuperuser(settings_module,
username,
email,
bin_env=None,
database=None,
pythonpath=None,
env=None,
runas=None):
'''
Create a super user for the database.
Thi... | def function[createsuperuser, parameter[settings_module, username, email, bin_env, database, pythonpath, env, runas]]:
constant[
Create a super user for the database.
This function defaults to use the ``--noinput`` flag which prevents the
creation of a password for the superuser.
CLI Example:
... | keyword[def] identifier[createsuperuser] ( identifier[settings_module] ,
identifier[username] ,
identifier[email] ,
identifier[bin_env] = keyword[None] ,
identifier[database] = keyword[None] ,
identifier[pythonpath] = keyword[None] ,
identifier[env] = keyword[None] ,
identifier[runas] = keyword[None] ):
l... | def createsuperuser(settings_module, username, email, bin_env=None, database=None, pythonpath=None, env=None, runas=None):
"""
Create a super user for the database.
This function defaults to use the ``--noinput`` flag which prevents the
creation of a password for the superuser.
CLI Example:
..... |
def _is_domain_valid(self, url, tld):
"""
Checks if given URL has valid domain name (ignores subdomains)
:param str url: complete URL that we want to check
:param str tld: TLD that should be found at the end of URL (hostname)
:return: True if URL is valid, False otherwise
... | def function[_is_domain_valid, parameter[self, url, tld]]:
constant[
Checks if given URL has valid domain name (ignores subdomains)
:param str url: complete URL that we want to check
:param str tld: TLD that should be found at the end of URL (hostname)
:return: True if URL is va... | keyword[def] identifier[_is_domain_valid] ( identifier[self] , identifier[url] , identifier[tld] ):
literal[string]
keyword[if] keyword[not] identifier[url] :
keyword[return] keyword[False]
identifier[scheme_pos] = identifier[url] . identifier[find] ( literal[string] )
... | def _is_domain_valid(self, url, tld):
"""
Checks if given URL has valid domain name (ignores subdomains)
:param str url: complete URL that we want to check
:param str tld: TLD that should be found at the end of URL (hostname)
:return: True if URL is valid, False otherwise
:r... |
def _convert_to_image_color(self, color):
""":return: a color that can be used by the image"""
rgb = self._convert_color_to_rrggbb(color)
return self._convert_rrggbb_to_image_color(rgb) | def function[_convert_to_image_color, parameter[self, color]]:
constant[:return: a color that can be used by the image]
variable[rgb] assign[=] call[name[self]._convert_color_to_rrggbb, parameter[name[color]]]
return[call[name[self]._convert_rrggbb_to_image_color, parameter[name[rgb]]]] | keyword[def] identifier[_convert_to_image_color] ( identifier[self] , identifier[color] ):
literal[string]
identifier[rgb] = identifier[self] . identifier[_convert_color_to_rrggbb] ( identifier[color] )
keyword[return] identifier[self] . identifier[_convert_rrggbb_to_image_color] ( identi... | def _convert_to_image_color(self, color):
""":return: a color that can be used by the image"""
rgb = self._convert_color_to_rrggbb(color)
return self._convert_rrggbb_to_image_color(rgb) |
def get_supported_unary_ops():
'''
Returns a dictionary of the Weld supported unary ops, with values being their Weld symbol.
'''
unary_ops = {}
unary_ops[np.exp.__name__] = 'exp'
unary_ops[np.log.__name__] = 'log'
unary_ops[np.sqrt.__name__] = 'sqrt'
return unary_ops | def function[get_supported_unary_ops, parameter[]]:
constant[
Returns a dictionary of the Weld supported unary ops, with values being their Weld symbol.
]
variable[unary_ops] assign[=] dictionary[[], []]
call[name[unary_ops]][name[np].exp.__name__] assign[=] constant[exp]
call[na... | keyword[def] identifier[get_supported_unary_ops] ():
literal[string]
identifier[unary_ops] ={}
identifier[unary_ops] [ identifier[np] . identifier[exp] . identifier[__name__] ]= literal[string]
identifier[unary_ops] [ identifier[np] . identifier[log] . identifier[__name__] ]= literal[string]
... | def get_supported_unary_ops():
"""
Returns a dictionary of the Weld supported unary ops, with values being their Weld symbol.
"""
unary_ops = {}
unary_ops[np.exp.__name__] = 'exp'
unary_ops[np.log.__name__] = 'log'
unary_ops[np.sqrt.__name__] = 'sqrt'
return unary_ops |
def fire_event(self, event, *args, **kwargs):
""" Execute the listeners for this event passing any arguments
along. """
remove = []
event_stack = self._events[event]
for x in event_stack:
x['callback'](*args, **kwargs)
if x['single']:
remov... | def function[fire_event, parameter[self, event]]:
constant[ Execute the listeners for this event passing any arguments
along. ]
variable[remove] assign[=] list[[]]
variable[event_stack] assign[=] call[name[self]._events][name[event]]
for taget[name[x]] in starred[name[event_stack... | keyword[def] identifier[fire_event] ( identifier[self] , identifier[event] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[remove] =[]
identifier[event_stack] = identifier[self] . identifier[_events] [ identifier[event] ]
keyword[for] identifier[x] keywo... | def fire_event(self, event, *args, **kwargs):
""" Execute the listeners for this event passing any arguments
along. """
remove = []
event_stack = self._events[event]
for x in event_stack:
x['callback'](*args, **kwargs)
if x['single']:
remove.append(x) # depends on [c... |
def bandpass(ts, low_hz, high_hz, order=3):
"""forward-backward butterworth band-pass filter"""
orig_ndim = ts.ndim
if ts.ndim is 1:
ts = ts[:, np.newaxis]
channels = ts.shape[1]
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
nyq = 0.5 * fs
low = low_hz/nyq
high = high_hz/ny... | def function[bandpass, parameter[ts, low_hz, high_hz, order]]:
constant[forward-backward butterworth band-pass filter]
variable[orig_ndim] assign[=] name[ts].ndim
if compare[name[ts].ndim is constant[1]] begin[:]
variable[ts] assign[=] call[name[ts]][tuple[[<ast.Slice object at 0... | keyword[def] identifier[bandpass] ( identifier[ts] , identifier[low_hz] , identifier[high_hz] , identifier[order] = literal[int] ):
literal[string]
identifier[orig_ndim] = identifier[ts] . identifier[ndim]
keyword[if] identifier[ts] . identifier[ndim] keyword[is] literal[int] :
identifier... | def bandpass(ts, low_hz, high_hz, order=3):
"""forward-backward butterworth band-pass filter"""
orig_ndim = ts.ndim
if ts.ndim is 1:
ts = ts[:, np.newaxis] # depends on [control=['if'], data=[]]
channels = ts.shape[1]
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
nyq = 0.5 * fs
... |
def get_product_metadata_name(self):
"""
:return: name of product metadata file
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
name = _edit_name(self.product_id, 'MTD', 'SAFL1C')
else:
name = 'MTD_{}'.format(self.product_id.split('_')[1... | def function[get_product_metadata_name, parameter[self]]:
constant[
:return: name of product metadata file
:rtype: str
]
if compare[name[self].safe_type equal[==] name[EsaSafeType].OLD_TYPE] begin[:]
variable[name] assign[=] call[name[_edit_name], parameter[name[s... | keyword[def] identifier[get_product_metadata_name] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[safe_type] == identifier[EsaSafeType] . identifier[OLD_TYPE] :
identifier[name] = identifier[_edit_name] ( identifier[self] . identifier[product_id] , lit... | def get_product_metadata_name(self):
"""
:return: name of product metadata file
:rtype: str
"""
if self.safe_type == EsaSafeType.OLD_TYPE:
name = _edit_name(self.product_id, 'MTD', 'SAFL1C') # depends on [control=['if'], data=[]]
else:
name = 'MTD_{}'.format(self.pro... |
def get_context_data(self, **kwargs):
"""
Returns view context dictionary.
:rtype: dict.
"""
kwargs.update({
'entries': Entry.objects.get_for_tag(
self.kwargs.get('slug', 0)
)
})
return super(EntriesView, self).get_context... | def function[get_context_data, parameter[self]]:
constant[
Returns view context dictionary.
:rtype: dict.
]
call[name[kwargs].update, parameter[dictionary[[<ast.Constant object at 0x7da1b10e7970>], [<ast.Call object at 0x7da1b10e6830>]]]]
return[call[call[name[super], parame... | keyword[def] identifier[get_context_data] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] . identifier[update] ({
literal[string] : identifier[Entry] . identifier[objects] . identifier[get_for_tag] (
identifier[self] . identifier[kwargs] . identifie... | def get_context_data(self, **kwargs):
"""
Returns view context dictionary.
:rtype: dict.
"""
kwargs.update({'entries': Entry.objects.get_for_tag(self.kwargs.get('slug', 0))})
return super(EntriesView, self).get_context_data(**kwargs) |
def getCandScoresMap(self, profile):
"""
Returns a dictionary that associates integer representations of each candidate with their
maximin score.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to conta... | def function[getCandScoresMap, parameter[self, profile]]:
constant[
Returns a dictionary that associates integer representations of each candidate with their
maximin score.
:ivar Profile profile: A Profile object that represents an election profile.
]
variable[elecType] ... | keyword[def] identifier[getCandScoresMap] ( identifier[self] , identifier[profile] ):
literal[string]
identifier[elecType] = identifier[profile] . identifier[getElecType] ()
keyword[if] identifier[elecType] != literal[string] keyword[and] identifier[elecType] != liter... | def getCandScoresMap(self, profile):
"""
Returns a dictionary that associates integer representations of each candidate with their
maximin score.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to contain comple... |
def _transform_array(self, X):
r"""Projects the data onto the dominant independent components.
Parameters
----------
X : ndarray(n, m)
the input data
Returns
-------
Y : ndarray(n,)
the projected data
"""
X_meanfree = X - ... | def function[_transform_array, parameter[self, X]]:
constant[Projects the data onto the dominant independent components.
Parameters
----------
X : ndarray(n, m)
the input data
Returns
-------
Y : ndarray(n,)
the projected data
]
... | keyword[def] identifier[_transform_array] ( identifier[self] , identifier[X] ):
literal[string]
identifier[X_meanfree] = identifier[X] - identifier[self] . identifier[mean]
identifier[Y] = identifier[np] . identifier[dot] ( identifier[X_meanfree] , identifier[self] . identifier[eigenvecto... | def _transform_array(self, X):
"""Projects the data onto the dominant independent components.
Parameters
----------
X : ndarray(n, m)
the input data
Returns
-------
Y : ndarray(n,)
the projected data
"""
X_meanfree = X - self.mean... |
def list_services(self, limit=None, marker=None):
"""List CDN services."""
return self._services_manager.list(limit=limit, marker=marker) | def function[list_services, parameter[self, limit, marker]]:
constant[List CDN services.]
return[call[name[self]._services_manager.list, parameter[]]] | keyword[def] identifier[list_services] ( identifier[self] , identifier[limit] = keyword[None] , identifier[marker] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_services_manager] . identifier[list] ( identifier[limit] = identifier[limit] , identifier[marker] = i... | def list_services(self, limit=None, marker=None):
"""List CDN services."""
return self._services_manager.list(limit=limit, marker=marker) |
def expireat(self, key, when):
"""Emulate expireat"""
expire_time = datetime.fromtimestamp(when)
key = self._encode(key)
if key in self.redis:
self.timeouts[key] = expire_time
return True
return False | def function[expireat, parameter[self, key, when]]:
constant[Emulate expireat]
variable[expire_time] assign[=] call[name[datetime].fromtimestamp, parameter[name[when]]]
variable[key] assign[=] call[name[self]._encode, parameter[name[key]]]
if compare[name[key] in name[self].redis] begin[... | keyword[def] identifier[expireat] ( identifier[self] , identifier[key] , identifier[when] ):
literal[string]
identifier[expire_time] = identifier[datetime] . identifier[fromtimestamp] ( identifier[when] )
identifier[key] = identifier[self] . identifier[_encode] ( identifier[key] )
... | def expireat(self, key, when):
"""Emulate expireat"""
expire_time = datetime.fromtimestamp(when)
key = self._encode(key)
if key in self.redis:
self.timeouts[key] = expire_time
return True # depends on [control=['if'], data=['key']]
return False |
def check(self, topic, value):
""" Checking the value if it fits into the given specification """
datatype_key = topic.meta.get('datatype', 'none')
self._datatypes[datatype_key].check(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
self._d... | def function[check, parameter[self, topic, value]]:
constant[ Checking the value if it fits into the given specification ]
variable[datatype_key] assign[=] call[name[topic].meta.get, parameter[constant[datatype], constant[none]]]
call[call[name[self]._datatypes][name[datatype_key]].check, parame... | keyword[def] identifier[check] ( identifier[self] , identifier[topic] , identifier[value] ):
literal[string]
identifier[datatype_key] = identifier[topic] . identifier[meta] . identifier[get] ( literal[string] , literal[string] )
identifier[self] . identifier[_datatypes] [ identifier[dataty... | def check(self, topic, value):
""" Checking the value if it fits into the given specification """
datatype_key = topic.meta.get('datatype', 'none')
self._datatypes[datatype_key].check(topic, value)
validate_dt = topic.meta.get('validate', None)
if validate_dt:
self._datatypes[validate_dt].ch... |
def log_ndtr(x, series_order=3, name="log_ndtr"):
"""Log Normal distribution function.
For details of the Normal distribution function see `ndtr`.
This function calculates `(log o ndtr)(x)` by either calling `log(ndtr(x))` or
using an asymptotic series. Specifically:
- For `x > upper_segment`, use the appro... | def function[log_ndtr, parameter[x, series_order, name]]:
constant[Log Normal distribution function.
For details of the Normal distribution function see `ndtr`.
This function calculates `(log o ndtr)(x)` by either calling `log(ndtr(x))` or
using an asymptotic series. Specifically:
- For `x > upper_seg... | keyword[def] identifier[log_ndtr] ( identifier[x] , identifier[series_order] = literal[int] , identifier[name] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[series_order] , identifier[int] ):
keyword[raise] identifier[TypeError] ( literal[string] )
... | def log_ndtr(x, series_order=3, name='log_ndtr'):
"""Log Normal distribution function.
For details of the Normal distribution function see `ndtr`.
This function calculates `(log o ndtr)(x)` by either calling `log(ndtr(x))` or
using an asymptotic series. Specifically:
- For `x > upper_segment`, use the app... |
def change_mpl_backend(self, command):
"""
If the user is trying to change Matplotlib backends with
%matplotlib, send the same command again to the kernel to
correctly change it.
Fixes issue 4002
"""
if command.startswith('%matplotlib') and \
len(comman... | def function[change_mpl_backend, parameter[self, command]]:
constant[
If the user is trying to change Matplotlib backends with
%matplotlib, send the same command again to the kernel to
correctly change it.
Fixes issue 4002
]
if <ast.BoolOp object at 0x7da20c6c4f1... | keyword[def] identifier[change_mpl_backend] ( identifier[self] , identifier[command] ):
literal[string]
keyword[if] identifier[command] . identifier[startswith] ( literal[string] ) keyword[and] identifier[len] ( identifier[command] . identifier[splitlines] ())== literal[int] :
keywor... | def change_mpl_backend(self, command):
"""
If the user is trying to change Matplotlib backends with
%matplotlib, send the same command again to the kernel to
correctly change it.
Fixes issue 4002
"""
if command.startswith('%matplotlib') and len(command.splitlines()) == 1... |
def LifoQueue(self, name, initial=None, maxsize=None):
"""The LIFO queue datatype.
:param name: The name of the queue.
:keyword initial: Initial items in the queue.
See :class:`redish.types.LifoQueue`.
"""
return types.LifoQueue(name, self.api,
... | def function[LifoQueue, parameter[self, name, initial, maxsize]]:
constant[The LIFO queue datatype.
:param name: The name of the queue.
:keyword initial: Initial items in the queue.
See :class:`redish.types.LifoQueue`.
]
return[call[name[types].LifoQueue, parameter[name[na... | keyword[def] identifier[LifoQueue] ( identifier[self] , identifier[name] , identifier[initial] = keyword[None] , identifier[maxsize] = keyword[None] ):
literal[string]
keyword[return] identifier[types] . identifier[LifoQueue] ( identifier[name] , identifier[self] . identifier[api] ,
ident... | def LifoQueue(self, name, initial=None, maxsize=None):
"""The LIFO queue datatype.
:param name: The name of the queue.
:keyword initial: Initial items in the queue.
See :class:`redish.types.LifoQueue`.
"""
return types.LifoQueue(name, self.api, initial=initial, maxsize=maxsize... |
def get_user(self, user_id):
"""Returns the current user from the session data.
If authenticated, this return the user object based on the user ID
and session data.
.. note::
This required monkey-patching the ``contrib.auth`` middleware
to make the ``request`` obje... | def function[get_user, parameter[self, user_id]]:
constant[Returns the current user from the session data.
If authenticated, this return the user object based on the user ID
and session data.
.. note::
This required monkey-patching the ``contrib.auth`` middleware
t... | keyword[def] identifier[get_user] ( identifier[self] , identifier[user_id] ):
literal[string]
keyword[if] ( identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and]
identifier[user_id] == identifier[self] . identifier[request] . identifier[session] [ literal[string] ]):
... | def get_user(self, user_id):
"""Returns the current user from the session data.
If authenticated, this return the user object based on the user ID
and session data.
.. note::
This required monkey-patching the ``contrib.auth`` middleware
to make the ``request`` object a... |
def get_tmaster(self, topologyName, callback=None):
"""
Get tmaster
"""
if callback:
self.tmaster_watchers[topologyName].append(callback)
else:
tmaster_path = self.get_tmaster_path(topologyName)
with open(tmaster_path) as f:
data = f.read()
tmaster = TMasterLocation... | def function[get_tmaster, parameter[self, topologyName, callback]]:
constant[
Get tmaster
]
if name[callback] begin[:]
call[call[name[self].tmaster_watchers][name[topologyName]].append, parameter[name[callback]]] | keyword[def] identifier[get_tmaster] ( identifier[self] , identifier[topologyName] , identifier[callback] = keyword[None] ):
literal[string]
keyword[if] identifier[callback] :
identifier[self] . identifier[tmaster_watchers] [ identifier[topologyName] ]. identifier[append] ( identifier[callback] )
... | def get_tmaster(self, topologyName, callback=None):
"""
Get tmaster
"""
if callback:
self.tmaster_watchers[topologyName].append(callback) # depends on [control=['if'], data=[]]
else:
tmaster_path = self.get_tmaster_path(topologyName)
with open(tmaster_path) as f:
... |
def updateColumnValues(self, networkId, tableType, columnName, default, body, verbose=None):
"""
Sets the values for cells in the table specified by the `tableType` and `networkId` parameters.
If the 'default` parameter is not specified, the message body should consist of key-value pair... | def function[updateColumnValues, parameter[self, networkId, tableType, columnName, default, body, verbose]]:
constant[
Sets the values for cells in the table specified by the `tableType` and `networkId` parameters.
If the 'default` parameter is not specified, the message body should con... | keyword[def] identifier[updateColumnValues] ( identifier[self] , identifier[networkId] , identifier[tableType] , identifier[columnName] , identifier[default] , identifier[body] , identifier[verbose] = keyword[None] ):
literal[string]
identifier[response] = identifier[api] ( identifier[url] = ident... | def updateColumnValues(self, networkId, tableType, columnName, default, body, verbose=None):
"""
Sets the values for cells in the table specified by the `tableType` and `networkId` parameters.
If the 'default` parameter is not specified, the message body should consist of key-value pairs wi... |
def _compute_distance_scaling(self, C, rrup, mag):
"""
Returns the distance scaling term
"""
rscale1 = rrup + C["c2"] * (10.0 ** (C["c3"] * mag))
return -np.log10(rscale1) - (C["c4"] * rrup) | def function[_compute_distance_scaling, parameter[self, C, rrup, mag]]:
constant[
Returns the distance scaling term
]
variable[rscale1] assign[=] binary_operation[name[rrup] + binary_operation[call[name[C]][constant[c2]] * binary_operation[constant[10.0] ** binary_operation[call[name[C]]... | keyword[def] identifier[_compute_distance_scaling] ( identifier[self] , identifier[C] , identifier[rrup] , identifier[mag] ):
literal[string]
identifier[rscale1] = identifier[rrup] + identifier[C] [ literal[string] ]*( literal[int] **( identifier[C] [ literal[string] ]* identifier[mag] ))
... | def _compute_distance_scaling(self, C, rrup, mag):
"""
Returns the distance scaling term
"""
rscale1 = rrup + C['c2'] * 10.0 ** (C['c3'] * mag)
return -np.log10(rscale1) - C['c4'] * rrup |
def sample_from_largest_budget(self, info_dict):
"""We opted for a single multidimensional KDE compared to the
hierarchy of one-dimensional KDEs used in TPE. The dimensional is
seperated by budget. This function sample a configuration from
largest budget. Firstly we sample "num_samples" ... | def function[sample_from_largest_budget, parameter[self, info_dict]]:
constant[We opted for a single multidimensional KDE compared to the
hierarchy of one-dimensional KDEs used in TPE. The dimensional is
seperated by budget. This function sample a configuration from
largest budget. First... | keyword[def] identifier[sample_from_largest_budget] ( identifier[self] , identifier[info_dict] ):
literal[string]
identifier[best] = identifier[np] . identifier[inf]
identifier[best_vector] = keyword[None]
identifier[budget] = identifier[max] ( identifier[self] . identifier[kde... | def sample_from_largest_budget(self, info_dict):
"""We opted for a single multidimensional KDE compared to the
hierarchy of one-dimensional KDEs used in TPE. The dimensional is
seperated by budget. This function sample a configuration from
largest budget. Firstly we sample "num_samples" conf... |
def set_elem(elem_ref, elem):
"""
Sets element referenced by the elem_ref. Returns the elem.
:param elem_ref:
:param elem:
:return:
"""
if elem_ref is None or elem_ref == elem or not is_elem_ref(elem_ref):
return elem
elif elem_ref[0] == ElemRefObj:
setattr(elem_ref[1],... | def function[set_elem, parameter[elem_ref, elem]]:
constant[
Sets element referenced by the elem_ref. Returns the elem.
:param elem_ref:
:param elem:
:return:
]
if <ast.BoolOp object at 0x7da1b2437b20> begin[:]
return[name[elem]] | keyword[def] identifier[set_elem] ( identifier[elem_ref] , identifier[elem] ):
literal[string]
keyword[if] identifier[elem_ref] keyword[is] keyword[None] keyword[or] identifier[elem_ref] == identifier[elem] keyword[or] keyword[not] identifier[is_elem_ref] ( identifier[elem_ref] ):
keyword[... | def set_elem(elem_ref, elem):
"""
Sets element referenced by the elem_ref. Returns the elem.
:param elem_ref:
:param elem:
:return:
"""
if elem_ref is None or elem_ref == elem or (not is_elem_ref(elem_ref)):
return elem # depends on [control=['if'], data=[]]
elif elem_ref[0] ==... |
def get_fields_dict(self, row):
"""
Returns a dict of field name and cleaned value pairs to initialize the model.
Beware, it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV.
Whitespace around the value of the cell is stripped.
... | def function[get_fields_dict, parameter[self, row]]:
constant[
Returns a dict of field name and cleaned value pairs to initialize the model.
Beware, it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV.
Whitespace around the value of the... | keyword[def] identifier[get_fields_dict] ( identifier[self] , identifier[row] ):
literal[string]
keyword[return] { identifier[k] : identifier[getattr] ( identifier[self] , literal[string] . identifier[format] ( identifier[k] ), keyword[lambda] identifier[x] : identifier[x] )( identifier[v] . ident... | def get_fields_dict(self, row):
"""
Returns a dict of field name and cleaned value pairs to initialize the model.
Beware, it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV.
Whitespace around the value of the cell is stripped.
"""
... |
def check_network_health(self):
r"""
This method check the network topological health by checking for:
(1) Isolated pores
(2) Islands or isolated clusters of pores
(3) Duplicate throats
(4) Bidirectional throats (ie. symmetrical adjacency matrix)
... | def function[check_network_health, parameter[self]]:
constant[
This method check the network topological health by checking for:
(1) Isolated pores
(2) Islands or isolated clusters of pores
(3) Duplicate throats
(4) Bidirectional throats (ie. symmetrical ... | keyword[def] identifier[check_network_health] ( identifier[self] ):
literal[string]
identifier[health] = identifier[HealthDict] ()
identifier[health] [ literal[string] ]=[]
identifier[health] [ literal[string] ]=[]
identifier[health] [ literal[string] ]=[]
ident... | def check_network_health(self):
"""
This method check the network topological health by checking for:
(1) Isolated pores
(2) Islands or isolated clusters of pores
(3) Duplicate throats
(4) Bidirectional throats (ie. symmetrical adjacency matrix)
(... |
def get_density_matrix(self, surface_divider = 20.0):
"""!
@brief Calculates density matrix (P-Matrix).
@param[in] surface_divider (double): Divider in each dimension that affect radius for density measurement.
@return (list) Density matrix (P-Matrix).
... | def function[get_density_matrix, parameter[self, surface_divider]]:
constant[!
@brief Calculates density matrix (P-Matrix).
@param[in] surface_divider (double): Divider in each dimension that affect radius for density measurement.
@return (list) Density matrix (P-Matrix... | keyword[def] identifier[get_density_matrix] ( identifier[self] , identifier[surface_divider] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[__ccore_som_pointer] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[_weights] = iden... | def get_density_matrix(self, surface_divider=20.0):
"""!
@brief Calculates density matrix (P-Matrix).
@param[in] surface_divider (double): Divider in each dimension that affect radius for density measurement.
@return (list) Density matrix (P-Matrix).
@see g... |
def _set_ldp_params(self, v, load=False):
"""
Setter method for ldp_params, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/ldp_params (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_params is considered as a private
... | def function[_set_ldp_params, parameter[self, v, load]]:
constant[
Setter method for ldp_params, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/ldp_params (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_params is co... | keyword[def] identifier[_set_ldp_params] ( 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] :
ide... | def _set_ldp_params(self, v, load=False):
"""
Setter method for ldp_params, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/ldp_params (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_params is considered as a private
... |
def get(self, center, target, date):
"""Retrieve the position and velocity of a target with respect to a center
Args:
center (Target):
target (Target):
date (Date):
Return:
numpy.array: length-6 array position and velocity (in m and m/s) of the
... | def function[get, parameter[self, center, target, date]]:
constant[Retrieve the position and velocity of a target with respect to a center
Args:
center (Target):
target (Target):
date (Date):
Return:
numpy.array: length-6 array position and veloci... | keyword[def] identifier[get] ( identifier[self] , identifier[center] , identifier[target] , identifier[date] ):
literal[string]
keyword[if] ( identifier[center] . identifier[index] , identifier[target] . identifier[index] ) keyword[in] identifier[self] . identifier[segments] :
identi... | def get(self, center, target, date):
"""Retrieve the position and velocity of a target with respect to a center
Args:
center (Target):
target (Target):
date (Date):
Return:
numpy.array: length-6 array position and velocity (in m and m/s) of the
... |
def normalize_num_type(num_type):
"""
Work out what a sensible type for the array is. if the default type
is float32, downcast 64bit float to float32. For ints, assume int32
"""
if isinstance(num_type, tf.DType):
num_type = num_type.as_numpy_dtype.type
if num_type in [np.float32, np.flo... | def function[normalize_num_type, parameter[num_type]]:
constant[
Work out what a sensible type for the array is. if the default type
is float32, downcast 64bit float to float32. For ints, assume int32
]
if call[name[isinstance], parameter[name[num_type], name[tf].DType]] begin[:]
... | keyword[def] identifier[normalize_num_type] ( identifier[num_type] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[num_type] , identifier[tf] . identifier[DType] ):
identifier[num_type] = identifier[num_type] . identifier[as_numpy_dtype] . identifier[type]
keyword[if] i... | def normalize_num_type(num_type):
"""
Work out what a sensible type for the array is. if the default type
is float32, downcast 64bit float to float32. For ints, assume int32
"""
if isinstance(num_type, tf.DType):
num_type = num_type.as_numpy_dtype.type # depends on [control=['if'], data=[]]... |
def previous_history(self, e): # (C-p)
u'''Move back through the history list, fetching the previous
command. '''
self._history.previous_history(self.l_buffer)
self.l_buffer.point = lineobj.EndOfLine
self.finalize() | def function[previous_history, parameter[self, e]]:
constant[Move back through the history list, fetching the previous
command. ]
call[name[self]._history.previous_history, parameter[name[self].l_buffer]]
name[self].l_buffer.point assign[=] name[lineobj].EndOfLine
call[name[self]... | keyword[def] identifier[previous_history] ( identifier[self] , identifier[e] ):
literal[string]
identifier[self] . identifier[_history] . identifier[previous_history] ( identifier[self] . identifier[l_buffer] )
identifier[self] . identifier[l_buffer] . identifier[point] = identifier[lin... | def previous_history(self, e): # (C-p)
u'Move back through the history list, fetching the previous\n command. '
self._history.previous_history(self.l_buffer)
self.l_buffer.point = lineobj.EndOfLine
self.finalize() |
def ChunkedTransformerLM(vocab_size,
feature_depth=512,
feedforward_depth=2048,
num_layers=6,
num_heads=8,
dropout=0.1,
chunk_selector=None,
max_... | def function[ChunkedTransformerLM, parameter[vocab_size, feature_depth, feedforward_depth, num_layers, num_heads, dropout, chunk_selector, max_len, mode]]:
constant[Transformer language model operating on chunks.
The input to this model is a sequence presented as a list or tuple of chunks:
(chunk1, chun... | keyword[def] identifier[ChunkedTransformerLM] ( identifier[vocab_size] ,
identifier[feature_depth] = literal[int] ,
identifier[feedforward_depth] = literal[int] ,
identifier[num_layers] = literal[int] ,
identifier[num_heads] = literal[int] ,
identifier[dropout] = literal[int] ,
identifier[chunk_selector] = keyw... | def ChunkedTransformerLM(vocab_size, feature_depth=512, feedforward_depth=2048, num_layers=6, num_heads=8, dropout=0.1, chunk_selector=None, max_len=2048, mode='train'):
"""Transformer language model operating on chunks.
The input to this model is a sequence presented as a list or tuple of chunks:
(chunk1, ... |
def add_partition_with_environment_context(self, new_part, environment_context):
"""
Parameters:
- new_part
- environment_context
"""
self.send_add_partition_with_environment_context(new_part, environment_context)
return self.recv_add_partition_with_environment_context() | def function[add_partition_with_environment_context, parameter[self, new_part, environment_context]]:
constant[
Parameters:
- new_part
- environment_context
]
call[name[self].send_add_partition_with_environment_context, parameter[name[new_part], name[environment_context]]]
return[c... | keyword[def] identifier[add_partition_with_environment_context] ( identifier[self] , identifier[new_part] , identifier[environment_context] ):
literal[string]
identifier[self] . identifier[send_add_partition_with_environment_context] ( identifier[new_part] , identifier[environment_context] )
keyword[r... | def add_partition_with_environment_context(self, new_part, environment_context):
"""
Parameters:
- new_part
- environment_context
"""
self.send_add_partition_with_environment_context(new_part, environment_context)
return self.recv_add_partition_with_environment_context() |
def motion_detection_sensitivity(self):
"""Sensitivity level of Camera motion detection."""
if not self.triggers:
return None
for trigger in self.triggers:
if trigger.get("type") != "pirMotionActive":
continue
sensitivity = trigger.get("sensi... | def function[motion_detection_sensitivity, parameter[self]]:
constant[Sensitivity level of Camera motion detection.]
if <ast.UnaryOp object at 0x7da204623760> begin[:]
return[constant[None]]
for taget[name[trigger]] in starred[name[self].triggers] begin[:]
if compare[call... | keyword[def] identifier[motion_detection_sensitivity] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[triggers] :
keyword[return] keyword[None]
keyword[for] identifier[trigger] keyword[in] identifier[self] . identifier[trigg... | def motion_detection_sensitivity(self):
"""Sensitivity level of Camera motion detection."""
if not self.triggers:
return None # depends on [control=['if'], data=[]]
for trigger in self.triggers:
if trigger.get('type') != 'pirMotionActive':
continue # depends on [control=['if'],... |
def _add_attr_values_from_insert_to_original(original_code, insert_code, insert_code_list, attribute_name, op_list):
"""
This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If some bytecode instruction in the ... | def function[_add_attr_values_from_insert_to_original, parameter[original_code, insert_code, insert_code_list, attribute_name, op_list]]:
constant[
This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If so... | keyword[def] identifier[_add_attr_values_from_insert_to_original] ( identifier[original_code] , identifier[insert_code] , identifier[insert_code_list] , identifier[attribute_name] , identifier[op_list] ):
literal[string]
identifier[orig_value] = identifier[getattr] ( identifier[original_code] , identifier[... | def _add_attr_values_from_insert_to_original(original_code, insert_code, insert_code_list, attribute_name, op_list):
"""
This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If some bytecode instruction in the ... |
def asset(url=None):
"""
Asset helper
Generates path to a static asset based on configuration base path and
support for versioning. Will easily allow you to move your assets away to
a CDN without changing templates. Versioning allows you to cache your asset
changes forever by the webserver.
... | def function[asset, parameter[url]]:
constant[
Asset helper
Generates path to a static asset based on configuration base path and
support for versioning. Will easily allow you to move your assets away to
a CDN without changing templates. Versioning allows you to cache your asset
changes fore... | keyword[def] identifier[asset] ( identifier[url] = keyword[None] ):
literal[string]
identifier[url] = identifier[url] . identifier[lstrip] ( literal[string] )
identifier[assets_path] = identifier[app] . identifier[config] . identifier[get] ( literal[string] )
keyword[if] keyword[not] iden... | def asset(url=None):
"""
Asset helper
Generates path to a static asset based on configuration base path and
support for versioning. Will easily allow you to move your assets away to
a CDN without changing templates. Versioning allows you to cache your asset
changes forever by the webserver.
... |
def alignICP(source, target, iters=100, rigid=False):
"""
Return a copy of source actor which is aligned to
target actor through the `Iterative Closest Point` algorithm.
The core of the algorithm is to match each vertex in one surface with
the closest surface point on the other, then apply the tran... | def function[alignICP, parameter[source, target, iters, rigid]]:
constant[
Return a copy of source actor which is aligned to
target actor through the `Iterative Closest Point` algorithm.
The core of the algorithm is to match each vertex in one surface with
the closest surface point on the other... | keyword[def] identifier[alignICP] ( identifier[source] , identifier[target] , identifier[iters] = literal[int] , identifier[rigid] = keyword[False] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[source] , identifier[Actor] ):
identifier[source] = identifier[source] . identifie... | def alignICP(source, target, iters=100, rigid=False):
"""
Return a copy of source actor which is aligned to
target actor through the `Iterative Closest Point` algorithm.
The core of the algorithm is to match each vertex in one surface with
the closest surface point on the other, then apply the tran... |
def add_artifact(
self,
filename,
name=None,
metadata=None,
content_type=None,
):
"""Add a file as an artifact.
In Sacred terminology an artifact is a file produced by the experiment
run. In case of a MongoObserver that means stori... | def function[add_artifact, parameter[self, filename, name, metadata, content_type]]:
constant[Add a file as an artifact.
In Sacred terminology an artifact is a file produced by the experiment
run. In case of a MongoObserver that means storing the file in the
database.
This func... | keyword[def] identifier[add_artifact] (
identifier[self] ,
identifier[filename] ,
identifier[name] = keyword[None] ,
identifier[metadata] = keyword[None] ,
identifier[content_type] = keyword[None] ,
):
literal[string]
keyword[assert] identifier[self] . identifier[current_run] keyword[is] ke... | def add_artifact(self, filename, name=None, metadata=None, content_type=None):
"""Add a file as an artifact.
In Sacred terminology an artifact is a file produced by the experiment
run. In case of a MongoObserver that means storing the file in the
database.
This function can only be... |
def has_read_permission(self, request, path):
"""
Just return True if the user is an authenticated staff member.
Extensions could base the permissions on the path too.
"""
user = request.user
if not user.is_authenticated():
return False
elif user.is_su... | def function[has_read_permission, parameter[self, request, path]]:
constant[
Just return True if the user is an authenticated staff member.
Extensions could base the permissions on the path too.
]
variable[user] assign[=] name[request].user
if <ast.UnaryOp object at 0x7da... | keyword[def] identifier[has_read_permission] ( identifier[self] , identifier[request] , identifier[path] ):
literal[string]
identifier[user] = identifier[request] . identifier[user]
keyword[if] keyword[not] identifier[user] . identifier[is_authenticated] ():
keyword[return]... | def has_read_permission(self, request, path):
"""
Just return True if the user is an authenticated staff member.
Extensions could base the permissions on the path too.
"""
user = request.user
if not user.is_authenticated():
return False # depends on [control=['if'], data=[]]... |
def points(self, include_hidden=False):
"""Return the number of points awarded to this submission."""
return sum(x.points for x in self.testable_results
if include_hidden or not x.testable.is_hidden) | def function[points, parameter[self, include_hidden]]:
constant[Return the number of points awarded to this submission.]
return[call[name[sum], parameter[<ast.GeneratorExp object at 0x7da1b0a818a0>]]] | keyword[def] identifier[points] ( identifier[self] , identifier[include_hidden] = keyword[False] ):
literal[string]
keyword[return] identifier[sum] ( identifier[x] . identifier[points] keyword[for] identifier[x] keyword[in] identifier[self] . identifier[testable_results]
keyword[if] ... | def points(self, include_hidden=False):
"""Return the number of points awarded to this submission."""
return sum((x.points for x in self.testable_results if include_hidden or not x.testable.is_hidden)) |
def play_track(self, track_id=DEFAULT_TRACK_ID, position=0):
"""Plays a track at the given position."""
self.publish(
action='playTrack',
resource='audioPlayback/player',
publish_response=False,
properties={'trackId': track_id, 'position': position}
... | def function[play_track, parameter[self, track_id, position]]:
constant[Plays a track at the given position.]
call[name[self].publish, parameter[]] | keyword[def] identifier[play_track] ( identifier[self] , identifier[track_id] = identifier[DEFAULT_TRACK_ID] , identifier[position] = literal[int] ):
literal[string]
identifier[self] . identifier[publish] (
identifier[action] = literal[string] ,
identifier[resource] = literal[stri... | def play_track(self, track_id=DEFAULT_TRACK_ID, position=0):
"""Plays a track at the given position."""
self.publish(action='playTrack', resource='audioPlayback/player', publish_response=False, properties={'trackId': track_id, 'position': position}) |
def convert_basis(basis_dict, fmt, header=None):
'''
Returns the basis set data as a string representing
the data in the specified output format
'''
# make converters case insensitive
fmt = fmt.lower()
if fmt not in _converter_map:
raise RuntimeError('Unknown basis set format "{}"'.... | def function[convert_basis, parameter[basis_dict, fmt, header]]:
constant[
Returns the basis set data as a string representing
the data in the specified output format
]
variable[fmt] assign[=] call[name[fmt].lower, parameter[]]
if compare[name[fmt] <ast.NotIn object at 0x7da2590d7190... | keyword[def] identifier[convert_basis] ( identifier[basis_dict] , identifier[fmt] , identifier[header] = keyword[None] ):
literal[string]
identifier[fmt] = identifier[fmt] . identifier[lower] ()
keyword[if] identifier[fmt] keyword[not] keyword[in] identifier[_converter_map] :
keywor... | def convert_basis(basis_dict, fmt, header=None):
"""
Returns the basis set data as a string representing
the data in the specified output format
"""
# make converters case insensitive
fmt = fmt.lower()
if fmt not in _converter_map:
raise RuntimeError('Unknown basis set format "{}"'.f... |
def get_thellier_gui_meas_mapping(input_df, output=2):
"""
Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
outp... | def function[get_thellier_gui_meas_mapping, parameter[input_df, output]]:
constant[
Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
... | keyword[def] identifier[get_thellier_gui_meas_mapping] ( identifier[input_df] , identifier[output] = literal[int] ):
literal[string]
keyword[if] identifier[int] ( identifier[output] )== literal[int] :
identifier[thellier_gui_meas3_2_meas2_map] = identifier[meas_magic3_2_magic2_map] . identifier[c... | def get_thellier_gui_meas_mapping(input_df, output=2):
"""
Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
outp... |
def get_multifile_object_child_location(self, parent_item_prefix: str, child_name: str) -> str:
"""
Implementation of the parent abstract method.
In this mode the attribute is a file inside the parent object folder
:param parent_item_prefix: the absolute file prefix of the parent item.
... | def function[get_multifile_object_child_location, parameter[self, parent_item_prefix, child_name]]:
constant[
Implementation of the parent abstract method.
In this mode the attribute is a file inside the parent object folder
:param parent_item_prefix: the absolute file prefix of the par... | keyword[def] identifier[get_multifile_object_child_location] ( identifier[self] , identifier[parent_item_prefix] : identifier[str] , identifier[child_name] : identifier[str] )-> identifier[str] :
literal[string]
identifier[check_var] ( identifier[parent_item_prefix] , identifier[var_types] = identi... | def get_multifile_object_child_location(self, parent_item_prefix: str, child_name: str) -> str:
"""
Implementation of the parent abstract method.
In this mode the attribute is a file inside the parent object folder
:param parent_item_prefix: the absolute file prefix of the parent item.
... |
def remove_patch(self, patch):
""" Remove a patch from the patches list """
self._check_patch(patch)
patchline = self.patch2line[patch]
del self.patch2line[patch]
self.patchlines.remove(patchline) | def function[remove_patch, parameter[self, patch]]:
constant[ Remove a patch from the patches list ]
call[name[self]._check_patch, parameter[name[patch]]]
variable[patchline] assign[=] call[name[self].patch2line][name[patch]]
<ast.Delete object at 0x7da20c6aa350>
call[name[self].patc... | keyword[def] identifier[remove_patch] ( identifier[self] , identifier[patch] ):
literal[string]
identifier[self] . identifier[_check_patch] ( identifier[patch] )
identifier[patchline] = identifier[self] . identifier[patch2line] [ identifier[patch] ]
keyword[del] identifier[self] ... | def remove_patch(self, patch):
""" Remove a patch from the patches list """
self._check_patch(patch)
patchline = self.patch2line[patch]
del self.patch2line[patch]
self.patchlines.remove(patchline) |
def cmd_graph(self, args):
'''graph command'''
if len(args) == 0:
# list current graphs
for i in range(len(self.graphs)):
print("Graph %u: %s" % (i, self.graphs[i].fields))
return
elif args[0] == "help":
print("graph <timespan|tick... | def function[cmd_graph, parameter[self, args]]:
constant[graph command]
if compare[call[name[len], parameter[name[args]]] equal[==] constant[0]] begin[:]
for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter[name[self].graphs]]]]] begin[:]
... | keyword[def] identifier[cmd_graph] ( identifier[self] , identifier[args] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[self] . identifier[graphs] ... | def cmd_graph(self, args):
"""graph command"""
if len(args) == 0:
# list current graphs
for i in range(len(self.graphs)):
print('Graph %u: %s' % (i, self.graphs[i].fields)) # depends on [control=['for'], data=['i']]
return # depends on [control=['if'], data=[]]
elif arg... |
def centre_of_atoms(atoms, mass_weighted=True):
""" Returns centre point of any list of atoms.
Parameters
----------
atoms : list
List of AMPAL atom objects.
mass_weighted : bool, optional
If True returns centre of mass, otherwise just geometric centre of points.
Returns
--... | def function[centre_of_atoms, parameter[atoms, mass_weighted]]:
constant[ Returns centre point of any list of atoms.
Parameters
----------
atoms : list
List of AMPAL atom objects.
mass_weighted : bool, optional
If True returns centre of mass, otherwise just geometric centre of p... | keyword[def] identifier[centre_of_atoms] ( identifier[atoms] , identifier[mass_weighted] = keyword[True] ):
literal[string]
identifier[points] =[ identifier[x] . identifier[_vector] keyword[for] identifier[x] keyword[in] identifier[atoms] ]
keyword[if] identifier[mass_weighted] :
identif... | def centre_of_atoms(atoms, mass_weighted=True):
""" Returns centre point of any list of atoms.
Parameters
----------
atoms : list
List of AMPAL atom objects.
mass_weighted : bool, optional
If True returns centre of mass, otherwise just geometric centre of points.
Returns
--... |
def get_user_id(self, attributes):
"""
For use when CAS_CREATE_USER_WITH_ID is True. Will raise ImproperlyConfigured
exceptions when a user_id cannot be accessed. This is important because we
shouldn't create Users with automatically assigned ids if we are trying to
keep User pri... | def function[get_user_id, parameter[self, attributes]]:
constant[
For use when CAS_CREATE_USER_WITH_ID is True. Will raise ImproperlyConfigured
exceptions when a user_id cannot be accessed. This is important because we
shouldn't create Users with automatically assigned ids if we are tryi... | keyword[def] identifier[get_user_id] ( identifier[self] , identifier[attributes] ):
literal[string]
keyword[if] keyword[not] identifier[attributes] :
keyword[raise] identifier[ImproperlyConfigured] ( literal[string]
literal[string] )
identifier[user_id] = ide... | def get_user_id(self, attributes):
"""
For use when CAS_CREATE_USER_WITH_ID is True. Will raise ImproperlyConfigured
exceptions when a user_id cannot be accessed. This is important because we
shouldn't create Users with automatically assigned ids if we are trying to
keep User primary... |
def sanitize(self, val):
"""Given a Variable and a value, cleans it out"""
if self.type == NUMBER:
try:
return clamp(self.min, self.max, float(val))
except ValueError:
return 0.0
elif self.type == TEXT:
try:
retu... | def function[sanitize, parameter[self, val]]:
constant[Given a Variable and a value, cleans it out]
if compare[name[self].type equal[==] name[NUMBER]] begin[:]
<ast.Try object at 0x7da1aff4f100> | keyword[def] identifier[sanitize] ( identifier[self] , identifier[val] ):
literal[string]
keyword[if] identifier[self] . identifier[type] == identifier[NUMBER] :
keyword[try] :
keyword[return] identifier[clamp] ( identifier[self] . identifier[min] , identifier[self] ... | def sanitize(self, val):
"""Given a Variable and a value, cleans it out"""
if self.type == NUMBER:
try:
return clamp(self.min, self.max, float(val)) # depends on [control=['try'], data=[]]
except ValueError:
return 0.0 # depends on [control=['except'], data=[]] # depen... |
def load_model(itos_filename, classifier_filename, num_classes):
"""Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
... | def function[load_model, parameter[itos_filename, classifier_filename, num_classes]]:
constant[Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the tra... | keyword[def] identifier[load_model] ( identifier[itos_filename] , identifier[classifier_filename] , identifier[num_classes] ):
literal[string]
identifier[itos] = identifier[pickle] . identifier[load] ( identifier[Path] ( identifier[itos_filename] ). identifier[open] ( literal[string] ))
ide... | def load_model(itos_filename, classifier_filename, num_classes):
"""Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
... |
def section(self, title=None):
""" Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return.
"""
for section in self.sections():
if section.title.lower() == title.lower(... | def function[section, parameter[self, title]]:
constant[ Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return.
]
for taget[name[section]] in starred[call[name[self].sections, pa... | keyword[def] identifier[section] ( identifier[self] , identifier[title] = keyword[None] ):
literal[string]
keyword[for] identifier[section] keyword[in] identifier[self] . identifier[sections] ():
keyword[if] identifier[section] . identifier[title] . identifier[lower] ()== identifie... | def section(self, title=None):
""" Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return.
"""
for section in self.sections():
if section.title.lower() == title.lower():
... |
def fully_correlated_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
This function handles conditioning of multi-output GPs in the case where the conditioning
points are all fully correlated, in both the prior and posterior.
:param Kmn: LM x N x P
... | def function[fully_correlated_conditional, parameter[Kmn, Kmm, Knn, f]]:
constant[
This function handles conditioning of multi-output GPs in the case where the conditioning
points are all fully correlated, in both the prior and posterior.
:param Kmn: LM x N x P
:param Kmm: LM x LM
:param Knn... | keyword[def] identifier[fully_correlated_conditional] ( identifier[Kmn] , identifier[Kmm] , identifier[Knn] , identifier[f] ,*, identifier[full_cov] = keyword[False] , identifier[full_output_cov] = keyword[False] , identifier[q_sqrt] = keyword[None] , identifier[white] = keyword[False] ):
literal[string]
i... | def fully_correlated_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
This function handles conditioning of multi-output GPs in the case where the conditioning
points are all fully correlated, in both the prior and posterior.
:param Kmn: LM x N x P
... |
def getBehavior(name, id=None):
"""
Return a matching behavior if it exists, or None.
If id is None, return the default for name.
"""
name = name.upper()
if name in __behaviorRegistry:
if id:
for n, behavior in __behaviorRegistry[name]:
if n == id:
... | def function[getBehavior, parameter[name, id]]:
constant[
Return a matching behavior if it exists, or None.
If id is None, return the default for name.
]
variable[name] assign[=] call[name[name].upper, parameter[]]
if compare[name[name] in name[__behaviorRegistry]] begin[:]
... | keyword[def] identifier[getBehavior] ( identifier[name] , identifier[id] = keyword[None] ):
literal[string]
identifier[name] = identifier[name] . identifier[upper] ()
keyword[if] identifier[name] keyword[in] identifier[__behaviorRegistry] :
keyword[if] identifier[id] :
keywor... | def getBehavior(name, id=None):
"""
Return a matching behavior if it exists, or None.
If id is None, return the default for name.
"""
name = name.upper()
if name in __behaviorRegistry:
if id:
for (n, behavior) in __behaviorRegistry[name]:
if n == id:
... |
def get_group_members(self, group):
"""Returns a ``list`` with the group's members or ``None`` if
unsuccessful.
:param str group: Group we want users for.
"""
conn = self.bind
try:
records = conn.search_s(
current_app.config['LDAP_BASE_DN'], ... | def function[get_group_members, parameter[self, group]]:
constant[Returns a ``list`` with the group's members or ``None`` if
unsuccessful.
:param str group: Group we want users for.
]
variable[conn] assign[=] name[self].bind
<ast.Try object at 0x7da204566380> | keyword[def] identifier[get_group_members] ( identifier[self] , identifier[group] ):
literal[string]
identifier[conn] = identifier[self] . identifier[bind]
keyword[try] :
identifier[records] = identifier[conn] . identifier[search_s] (
identifier[current_app] . i... | def get_group_members(self, group):
"""Returns a ``list`` with the group's members or ``None`` if
unsuccessful.
:param str group: Group we want users for.
"""
conn = self.bind
try:
records = conn.search_s(current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, ldap_filter.fi... |
def hold(name, seconds):
'''
Wait for a given period of time, then fire a result of True, requiring
this state allows for an action to be blocked for evaluation based on
time
USAGE:
.. code-block:: yaml
hold_on_a_moment:
timer.hold:
- seconds: 30
'''
ret ... | def function[hold, parameter[name, seconds]]:
constant[
Wait for a given period of time, then fire a result of True, requiring
this state allows for an action to be blocked for evaluation based on
time
USAGE:
.. code-block:: yaml
hold_on_a_moment:
timer.hold:
... | keyword[def] identifier[hold] ( identifier[name] , identifier[seconds] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] : keyword[False] ,
literal[string] : literal[string] ,
literal[string] :{}}
identifier[start] = identifier[time] . identifier... | def hold(name, seconds):
"""
Wait for a given period of time, then fire a result of True, requiring
this state allows for an action to be blocked for evaluation based on
time
USAGE:
.. code-block:: yaml
hold_on_a_moment:
timer.hold:
- seconds: 30
"""
ret ... |
def LoadConfig(config_obj,
config_file=None,
config_fd=None,
secondary_configs=None,
contexts=None,
reset=False,
parser=ConfigFileParser):
"""Initialize a ConfigManager with the specified options.
Args:
config_obj: The Co... | def function[LoadConfig, parameter[config_obj, config_file, config_fd, secondary_configs, contexts, reset, parser]]:
constant[Initialize a ConfigManager with the specified options.
Args:
config_obj: The ConfigManager object to use and update. If None, one will be
created.
config_file: Filename ... | keyword[def] identifier[LoadConfig] ( identifier[config_obj] ,
identifier[config_file] = keyword[None] ,
identifier[config_fd] = keyword[None] ,
identifier[secondary_configs] = keyword[None] ,
identifier[contexts] = keyword[None] ,
identifier[reset] = keyword[False] ,
identifier[parser] = identifier[ConfigFileP... | def LoadConfig(config_obj, config_file=None, config_fd=None, secondary_configs=None, contexts=None, reset=False, parser=ConfigFileParser):
"""Initialize a ConfigManager with the specified options.
Args:
config_obj: The ConfigManager object to use and update. If None, one will be
created.
config_fil... |
def _inception_table_links(self, href_list):
"""
Sometimes the EPA likes to nest their models and tables -- model within
a model within a model -- so this internal method tries to clear all
that up.
"""
tables = set()
for link in href_list:
if not link... | def function[_inception_table_links, parameter[self, href_list]]:
constant[
Sometimes the EPA likes to nest their models and tables -- model within
a model within a model -- so this internal method tries to clear all
that up.
]
variable[tables] assign[=] call[name[set], p... | keyword[def] identifier[_inception_table_links] ( identifier[self] , identifier[href_list] ):
literal[string]
identifier[tables] = identifier[set] ()
keyword[for] identifier[link] keyword[in] identifier[href_list] :
keyword[if] keyword[not] identifier[link] . identifier[s... | def _inception_table_links(self, href_list):
"""
Sometimes the EPA likes to nest their models and tables -- model within
a model within a model -- so this internal method tries to clear all
that up.
"""
tables = set()
for link in href_list:
if not link.startswith('htt... |
def _word_ngrams(self, tokens):
"""
Turn tokens into a tokens of n-grams
ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153
"""
# handle stop words
if self.stop_words is not None:
tokens = [w for w in ... | def function[_word_ngrams, parameter[self, tokens]]:
constant[
Turn tokens into a tokens of n-grams
ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153
]
if compare[name[self].stop_words is_not constant[None]] begin[:]
... | keyword[def] identifier[_word_ngrams] ( identifier[self] , identifier[tokens] ):
literal[string]
keyword[if] identifier[self] . identifier[stop_words] keyword[is] keyword[not] keyword[None] :
identifier[tokens] =[ identifier[w] keyword[for] identifier[w] keyword[in] id... | def _word_ngrams(self, tokens):
"""
Turn tokens into a tokens of n-grams
ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153
"""
# handle stop words
if self.stop_words is not None:
tokens = [w for w in tokens if w not ... |
def selection_ranges(self):
"""
Return a list of (from, to) tuples for the selection or none if nothing
was selected. start and end position are always included in the
selection.
This will yield several (from, to) tuples in case of a BLOCK selection.
"""
if self... | def function[selection_ranges, parameter[self]]:
constant[
Return a list of (from, to) tuples for the selection or none if nothing
was selected. start and end position are always included in the
selection.
This will yield several (from, to) tuples in case of a BLOCK selection.
... | keyword[def] identifier[selection_ranges] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[selection] :
identifier[from_] , identifier[to] = identifier[sorted] ([ identifier[self] . identifier[cursor_position] , identifier[self] . identifier[selection] .... | def selection_ranges(self):
"""
Return a list of (from, to) tuples for the selection or none if nothing
was selected. start and end position are always included in the
selection.
This will yield several (from, to) tuples in case of a BLOCK selection.
"""
if self.selecti... |
def update_from_object(self, obj, criterion=lambda key: key.isupper()):
"""
Update dict from the attributes of a module, class or other object.
By default only attributes with all-uppercase names will be retrieved.
Use the ``criterion`` argument to modify that behaviour.
:arg o... | def function[update_from_object, parameter[self, obj, criterion]]:
constant[
Update dict from the attributes of a module, class or other object.
By default only attributes with all-uppercase names will be retrieved.
Use the ``criterion`` argument to modify that behaviour.
:arg ... | keyword[def] identifier[update_from_object] ( identifier[self] , identifier[obj] , identifier[criterion] = keyword[lambda] identifier[key] : identifier[key] . identifier[isupper] ()):
literal[string]
identifier[log] . identifier[debug] ( literal[string] . identifier[format] ( identifier[obj] ))
... | def update_from_object(self, obj, criterion=lambda key: key.isupper()):
"""
Update dict from the attributes of a module, class or other object.
By default only attributes with all-uppercase names will be retrieved.
Use the ``criterion`` argument to modify that behaviour.
:arg obj: ... |
async def asynchronously_get_data(self, url):
""" Asynchronously get data from Chunked transfer encoding of https://smartcity.rbccps.org/api/0.1.0/subscribe.
(Only this function requires Python 3. Rest of the functions can be run in python2.
Args:
url (string): url to subscribe
... | <ast.AsyncFunctionDef object at 0x7da18dc07550> | keyword[async] keyword[def] identifier[asynchronously_get_data] ( identifier[self] , identifier[url] ):
literal[string]
identifier[headers] ={ literal[string] : identifier[self] . identifier[entity_api_key] }
keyword[try] :
keyword[async] keyword[with] identifier[aiohttp] .... | async def asynchronously_get_data(self, url):
""" Asynchronously get data from Chunked transfer encoding of https://smartcity.rbccps.org/api/0.1.0/subscribe.
(Only this function requires Python 3. Rest of the functions can be run in python2.
Args:
url (string): url to subscribe
... |
def n1qlQueryAll(self, *args, **kwargs):
"""
Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
This metho... | def function[n1qlQueryAll, parameter[self]]:
constant[
Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
... | keyword[def] identifier[n1qlQueryAll] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[connected] :
identifier[cb] = keyword[lambda] identifier[x] : identifier[self] . identifier[n1qlQueryAll] (* ... | def n1qlQueryAll(self, *args, **kwargs):
"""
Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
This method is... |
def list_alerts(self, limit=None, cursor=None):
'''**Description**
List the current set of scanning alerts.
**Arguments**
- limit: Maximum number of alerts in the response.
- cursor: An opaque string representing the current position in the list of alerts. It's provi... | def function[list_alerts, parameter[self, limit, cursor]]:
constant[**Description**
List the current set of scanning alerts.
**Arguments**
- limit: Maximum number of alerts in the response.
- cursor: An opaque string representing the current position in the list of a... | keyword[def] identifier[list_alerts] ( identifier[self] , identifier[limit] = keyword[None] , identifier[cursor] = keyword[None] ):
literal[string]
identifier[url] = identifier[self] . identifier[url] + literal[string]
keyword[if] identifier[limit] :
identifier[url] += liter... | def list_alerts(self, limit=None, cursor=None):
"""**Description**
List the current set of scanning alerts.
**Arguments**
- limit: Maximum number of alerts in the response.
- cursor: An opaque string representing the current position in the list of alerts. It's provided ... |
def map(self, coro, *args, **kwargs):
"""
Schedule a given coroutine call for each plugin.
The coro called get the Plugin instance as first argument of its method call
:param coro: coro to call on each plugin
:param filter_plugins: list of plugin names to filter (only plugin whos... | def function[map, parameter[self, coro]]:
constant[
Schedule a given coroutine call for each plugin.
The coro called get the Plugin instance as first argument of its method call
:param coro: coro to call on each plugin
:param filter_plugins: list of plugin names to filter (only p... | keyword[def] identifier[map] ( identifier[self] , identifier[coro] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[p_list] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
keyword[if] identifier[p_list] keyword[is] keyword[None] :
... | def map(self, coro, *args, **kwargs):
"""
Schedule a given coroutine call for each plugin.
The coro called get the Plugin instance as first argument of its method call
:param coro: coro to call on each plugin
:param filter_plugins: list of plugin names to filter (only plugin whose na... |
def handle_heart_failure(self, heart):
"""handler to attach to heartbeater.
called when a previously registered heart fails to respond to beat request.
triggers unregistration"""
self.log.debug("heartbeat::handle_heart_failure(%r)", heart)
eid = self.hearts.get(heart, None)
... | def function[handle_heart_failure, parameter[self, heart]]:
constant[handler to attach to heartbeater.
called when a previously registered heart fails to respond to beat request.
triggers unregistration]
call[name[self].log.debug, parameter[constant[heartbeat::handle_heart_failure(%r)], ... | keyword[def] identifier[handle_heart_failure] ( identifier[self] , identifier[heart] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] , identifier[heart] )
identifier[eid] = identifier[self] . identifier[hearts] . identifier[get] ( identifier[hear... | def handle_heart_failure(self, heart):
"""handler to attach to heartbeater.
called when a previously registered heart fails to respond to beat request.
triggers unregistration"""
self.log.debug('heartbeat::handle_heart_failure(%r)', heart)
eid = self.hearts.get(heart, None)
queue = self.... |
def write(self, request):
"""Write a Request."""
if FLAGS.sc2_verbose_protocol:
self._log(" Writing request ".center(60, "-") + "\n")
self._log_packet(request)
self._write(request) | def function[write, parameter[self, request]]:
constant[Write a Request.]
if name[FLAGS].sc2_verbose_protocol begin[:]
call[name[self]._log, parameter[binary_operation[call[constant[ Writing request ].center, parameter[constant[60], constant[-]]] + constant[
]]]]
call[nam... | keyword[def] identifier[write] ( identifier[self] , identifier[request] ):
literal[string]
keyword[if] identifier[FLAGS] . identifier[sc2_verbose_protocol] :
identifier[self] . identifier[_log] ( literal[string] . identifier[center] ( literal[int] , literal[string] )+ literal[string] )
ident... | def write(self, request):
"""Write a Request."""
if FLAGS.sc2_verbose_protocol:
self._log(' Writing request '.center(60, '-') + '\n')
self._log_packet(request) # depends on [control=['if'], data=[]]
self._write(request) |
def balance_of_contacts(records, weighted=True):
"""
The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\\forall \\,\\text{contact}\\,c,\\;\\text{balance}\,(c) = \\fra... | def function[balance_of_contacts, parameter[records, weighted]]:
constant[
The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\forall \,\text{contact}\,c,\;\text{b... | keyword[def] identifier[balance_of_contacts] ( identifier[records] , identifier[weighted] = keyword[True] ):
literal[string]
identifier[counter_out] = identifier[defaultdict] ( identifier[int] )
identifier[counter] = identifier[defaultdict] ( identifier[int] )
keyword[for] identifier[r] keywor... | def balance_of_contacts(records, weighted=True):
"""
The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\\forall \\,\\text{contact}\\,c,\\;\\text{balance}\\,(c) = \\fr... |
def _fast_write(self, outfile, value):
"""Function for fast writing to motor files."""
outfile.truncate(0)
outfile.write(str(int(value)))
outfile.flush() | def function[_fast_write, parameter[self, outfile, value]]:
constant[Function for fast writing to motor files.]
call[name[outfile].truncate, parameter[constant[0]]]
call[name[outfile].write, parameter[call[name[str], parameter[call[name[int], parameter[name[value]]]]]]]
call[name[outfile... | keyword[def] identifier[_fast_write] ( identifier[self] , identifier[outfile] , identifier[value] ):
literal[string]
identifier[outfile] . identifier[truncate] ( literal[int] )
identifier[outfile] . identifier[write] ( identifier[str] ( identifier[int] ( identifier[value] )))
iden... | def _fast_write(self, outfile, value):
"""Function for fast writing to motor files."""
outfile.truncate(0)
outfile.write(str(int(value)))
outfile.flush() |
def read_namespaced_replica_set(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replica_set # noqa: E501
read the specified ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=T... | def function[read_namespaced_replica_set, parameter[self, name, namespace]]:
constant[read_namespaced_replica_set # noqa: E501
read the specified ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_re... | keyword[def] identifier[read_namespaced_replica_set] ( identifier[self] , identifier[name] , identifier[namespace] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def read_namespaced_replica_set(self, name, namespace, **kwargs): # noqa: E501
"read_namespaced_replica_set # noqa: E501\n\n read the specified ReplicaSet # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=Tru... |
def keyword(self, token_stream, token, operators):
"""Lowest level parsing function.
A keyword consists of zero or more prefix operators (NOT, or
COMPARISON) followed by a TEXT, COLOR, or NUMBER block.
"""
if token[0] == 'TEXT' or token[0] == 'COLOR':
return SearchK... | def function[keyword, parameter[self, token_stream, token, operators]]:
constant[Lowest level parsing function.
A keyword consists of zero or more prefix operators (NOT, or
COMPARISON) followed by a TEXT, COLOR, or NUMBER block.
]
if <ast.BoolOp object at 0x7da20c991090> begin[... | keyword[def] identifier[keyword] ( identifier[self] , identifier[token_stream] , identifier[token] , identifier[operators] ):
literal[string]
keyword[if] identifier[token] [ literal[int] ]== literal[string] keyword[or] identifier[token] [ literal[int] ]== literal[string] :
keyword[r... | def keyword(self, token_stream, token, operators):
"""Lowest level parsing function.
A keyword consists of zero or more prefix operators (NOT, or
COMPARISON) followed by a TEXT, COLOR, or NUMBER block.
"""
if token[0] == 'TEXT' or token[0] == 'COLOR':
return SearchKeyword(token... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.