code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def __shouldSysExit(self, iteration):
"""
Checks to see if the model should exit based on the exitAfter dummy
parameter
"""
if self._exitAfter is None \
or iteration < self._exitAfter:
return False
results = self._jobsDAO.modelsGetFieldsForJob(self._jobID, ['params'])
modelID... | def function[__shouldSysExit, parameter[self, iteration]]:
constant[
Checks to see if the model should exit based on the exitAfter dummy
parameter
]
if <ast.BoolOp object at 0x7da18c4cfc70> begin[:]
return[constant[False]]
variable[results] assign[=] call[name[self]._jobsDAO.... | keyword[def] identifier[__shouldSysExit] ( identifier[self] , identifier[iteration] ):
literal[string]
keyword[if] identifier[self] . identifier[_exitAfter] keyword[is] keyword[None] keyword[or] identifier[iteration] < identifier[self] . identifier[_exitAfter] :
keyword[return] keyword[False]... | def __shouldSysExit(self, iteration):
"""
Checks to see if the model should exit based on the exitAfter dummy
parameter
"""
if self._exitAfter is None or iteration < self._exitAfter:
return False # depends on [control=['if'], data=[]]
results = self._jobsDAO.modelsGetFieldsForJob(self._... |
def _le_ropenarrow(self, annot, p1, p2, lr):
"""Make stream commands for right open arrow line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = self._le_annot_parms(annot, p1, p2)
shift = 2.5
d = shift * max(1, w)
p2 = R - (d... | def function[_le_ropenarrow, parameter[self, annot, p1, p2, lr]]:
constant[Make stream commands for right open arrow line end symbol. "lr" denotes left (False) or right point.
]
<ast.Tuple object at 0x7da18f00d660> assign[=] call[name[self]._le_annot_parms, parameter[name[annot], name[p1], name[... | keyword[def] identifier[_le_ropenarrow] ( identifier[self] , identifier[annot] , identifier[p1] , identifier[p2] , identifier[lr] ):
literal[string]
identifier[m] , identifier[im] , identifier[L] , identifier[R] , identifier[w] , identifier[scol] , identifier[fcol] , identifier[opacity] = identifie... | def _le_ropenarrow(self, annot, p1, p2, lr):
"""Make stream commands for right open arrow line end symbol. "lr" denotes left (False) or right point.
"""
(m, im, L, R, w, scol, fcol, opacity) = self._le_annot_parms(annot, p1, p2)
shift = 2.5
d = shift * max(1, w)
p2 = R - (d / 3.0, 0) if lr e... |
def delete_cookie(self, key, **kwargs):
''' Delete a cookie. Be sure to use the same `domain` and `path`
parameters as used to create the cookie. '''
kwargs['max_age'] = -1
kwargs['expires'] = 0
self.set_cookie(key, '', **kwargs) | def function[delete_cookie, parameter[self, key]]:
constant[ Delete a cookie. Be sure to use the same `domain` and `path`
parameters as used to create the cookie. ]
call[name[kwargs]][constant[max_age]] assign[=] <ast.UnaryOp object at 0x7da1b18ac460>
call[name[kwargs]][constant[expi... | keyword[def] identifier[delete_cookie] ( identifier[self] , identifier[key] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]=- literal[int]
identifier[kwargs] [ literal[string] ]= literal[int]
identifier[self] . identifier[set_cookie] ( identifier... | def delete_cookie(self, key, **kwargs):
""" Delete a cookie. Be sure to use the same `domain` and `path`
parameters as used to create the cookie. """
kwargs['max_age'] = -1
kwargs['expires'] = 0
self.set_cookie(key, '', **kwargs) |
def timeout_selecting(self):
"""Timeout of selecting on SELECTING state.
Not specifiyed in [:rfc:`7844`].
See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`.
"""
logger.debug('C2.1: T In %s, timeout receiving response to select.',
self.current_st... | def function[timeout_selecting, parameter[self]]:
constant[Timeout of selecting on SELECTING state.
Not specifiyed in [:rfc:`7844`].
See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`.
]
call[name[logger].debug, parameter[constant[C2.1: T In %s, timeout receiving res... | keyword[def] identifier[timeout_selecting] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] ,
identifier[self] . identifier[current_state] )
keyword[if] identifier[len] ( identifier[self] . identifier[offers] )>= identifier[MAX_OFFER... | def timeout_selecting(self):
"""Timeout of selecting on SELECTING state.
Not specifiyed in [:rfc:`7844`].
See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`.
"""
logger.debug('C2.1: T In %s, timeout receiving response to select.', self.current_state)
if len(self.offers) ... |
def exists(self, vars_list: List[str]) -> 'TensorFluent':
'''Returns the TensorFluent for the exists aggregation function.
Args:
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the exists aggregation function.
'''
... | def function[exists, parameter[self, vars_list]]:
constant[Returns the TensorFluent for the exists aggregation function.
Args:
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the exists aggregation function.
]
return[... | keyword[def] identifier[exists] ( identifier[self] , identifier[vars_list] : identifier[List] [ identifier[str] ])-> literal[string] :
literal[string]
keyword[return] identifier[self] . identifier[_aggregation_op] ( identifier[tf] . identifier[reduce_any] , identifier[self] , identifier[vars_list]... | def exists(self, vars_list: List[str]) -> 'TensorFluent':
"""Returns the TensorFluent for the exists aggregation function.
Args:
vars_list: The list of variables to be aggregated over.
Returns:
A TensorFluent wrapping the exists aggregation function.
"""
return ... |
def depends(func=None, after=None, before=None, priority=None):
"""Decorator to specify test dependencies
:param after: The test needs to run after this/these tests. String or list of strings.
:param before: The test needs to run before this/these tests. String or list of strings.
"""
if not (func ... | def function[depends, parameter[func, after, before, priority]]:
constant[Decorator to specify test dependencies
:param after: The test needs to run after this/these tests. String or list of strings.
:param before: The test needs to run before this/these tests. String or list of strings.
]
... | keyword[def] identifier[depends] ( identifier[func] = keyword[None] , identifier[after] = keyword[None] , identifier[before] = keyword[None] , identifier[priority] = keyword[None] ):
literal[string]
keyword[if] keyword[not] ( identifier[func] keyword[is] keyword[None] keyword[or] identifier[inspect] .... | def depends(func=None, after=None, before=None, priority=None):
"""Decorator to specify test dependencies
:param after: The test needs to run after this/these tests. String or list of strings.
:param before: The test needs to run before this/these tests. String or list of strings.
"""
if not (func ... |
def add_extruded_obstacles(self, top_polys, make_ccw=True):
"""
Add polyhedras to the Place by giving their top polygon and
applying extrusion along the z axis. The resulting polygon
from the intersection will be declared as a hole in the Surface.
:param top_polys:... | def function[add_extruded_obstacles, parameter[self, top_polys, make_ccw]]:
constant[
Add polyhedras to the Place by giving their top polygon and
applying extrusion along the z axis. The resulting polygon
from the intersection will be declared as a hole in the Surface.
:... | keyword[def] identifier[add_extruded_obstacles] ( identifier[self] , identifier[top_polys] , identifier[make_ccw] = keyword[True] ):
literal[string]
keyword[if] identifier[type] ( identifier[top_polys] )!= identifier[list] : identifier[top_polys] =[ identifier[top_polys] ]
keyword[for]... | def add_extruded_obstacles(self, top_polys, make_ccw=True):
"""
Add polyhedras to the Place by giving their top polygon and
applying extrusion along the z axis. The resulting polygon
from the intersection will be declared as a hole in the Surface.
:param top_polys: Polygons ... |
def _discarded_reads1_out_file_name(self):
"""Checks if file name is set for discarded reads1 output.
Returns absolute path."""
if self.Parameters['-3'].isOn():
discarded_reads1 = self._absolute(str(self.Parameters['-3'].Value))
else:
raise ValueError(
... | def function[_discarded_reads1_out_file_name, parameter[self]]:
constant[Checks if file name is set for discarded reads1 output.
Returns absolute path.]
if call[call[name[self].Parameters][constant[-3]].isOn, parameter[]] begin[:]
variable[discarded_reads1] assign[=] call[name... | keyword[def] identifier[_discarded_reads1_out_file_name] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[Parameters] [ literal[string] ]. identifier[isOn] ():
identifier[discarded_reads1] = identifier[self] . identifier[_absolute] ( identifier[str] ( id... | def _discarded_reads1_out_file_name(self):
"""Checks if file name is set for discarded reads1 output.
Returns absolute path."""
if self.Parameters['-3'].isOn():
discarded_reads1 = self._absolute(str(self.Parameters['-3'].Value)) # depends on [control=['if'], data=[]]
else:
raise ... |
def constraints_stmt(stmt, env=None):
"""
Since a statement may define new names or return an expression ,
the constraints that result are in a
ConstrainedEnv mapping names to types, with constraints, and maybe
having a return type (which is a constrained type)
"""
env = env or {}
... | def function[constraints_stmt, parameter[stmt, env]]:
constant[
Since a statement may define new names or return an expression ,
the constraints that result are in a
ConstrainedEnv mapping names to types, with constraints, and maybe
having a return type (which is a constrained type)
]
... | keyword[def] identifier[constraints_stmt] ( identifier[stmt] , identifier[env] = keyword[None] ):
literal[string]
identifier[env] = identifier[env] keyword[or] {}
keyword[if] identifier[isinstance] ( identifier[stmt] , identifier[ast] . identifier[FunctionDef] ):
identifier[arg_env] = iden... | def constraints_stmt(stmt, env=None):
"""
Since a statement may define new names or return an expression ,
the constraints that result are in a
ConstrainedEnv mapping names to types, with constraints, and maybe
having a return type (which is a constrained type)
"""
env = env or {}
if is... |
def collect(self, order_ref):
"""Collect the progress status of the order with the specified
order reference.
:param order_ref: The UUID string specifying which order to
collect status from.
:type order_ref: str
:return: The CollectResponse parsed to a dictionary.
... | def function[collect, parameter[self, order_ref]]:
constant[Collect the progress status of the order with the specified
order reference.
:param order_ref: The UUID string specifying which order to
collect status from.
:type order_ref: str
:return: The CollectResponse... | keyword[def] identifier[collect] ( identifier[self] , identifier[order_ref] ):
literal[string]
keyword[try] :
identifier[out] = identifier[self] . identifier[client] . identifier[service] . identifier[Collect] ( identifier[order_ref] )
keyword[except] identifier[Error] keywo... | def collect(self, order_ref):
"""Collect the progress status of the order with the specified
order reference.
:param order_ref: The UUID string specifying which order to
collect status from.
:type order_ref: str
:return: The CollectResponse parsed to a dictionary.
... |
def send_alert_to_configured_integration(integration_alert):
"""Send IntegrationAlert to configured integration."""
try:
alert = integration_alert.alert
configured_integration = integration_alert.configured_integration
integration = configured_integration.integration
integration_... | def function[send_alert_to_configured_integration, parameter[integration_alert]]:
constant[Send IntegrationAlert to configured integration.]
<ast.Try object at 0x7da1b12922c0> | keyword[def] identifier[send_alert_to_configured_integration] ( identifier[integration_alert] ):
literal[string]
keyword[try] :
identifier[alert] = identifier[integration_alert] . identifier[alert]
identifier[configured_integration] = identifier[integration_alert] . identifier[configured... | def send_alert_to_configured_integration(integration_alert):
"""Send IntegrationAlert to configured integration."""
try:
alert = integration_alert.alert
configured_integration = integration_alert.configured_integration
integration = configured_integration.integration
integration_... |
def setPermanence(self, columnIndex, permanence):
"""
Sets the permanence values for a given column. ``permanence`` size must
match the number of inputs.
:param columnIndex: (int) column index to set permanence for.
:param permanence: (list) value to set.
"""
assert(columnIndex < self... | def function[setPermanence, parameter[self, columnIndex, permanence]]:
constant[
Sets the permanence values for a given column. ``permanence`` size must
match the number of inputs.
:param columnIndex: (int) column index to set permanence for.
:param permanence: (list) value to set.
]
... | keyword[def] identifier[setPermanence] ( identifier[self] , identifier[columnIndex] , identifier[permanence] ):
literal[string]
keyword[assert] ( identifier[columnIndex] < identifier[self] . identifier[_numColumns] )
identifier[self] . identifier[_updatePermanencesForColumn] ( identifier[permanence] ,... | def setPermanence(self, columnIndex, permanence):
"""
Sets the permanence values for a given column. ``permanence`` size must
match the number of inputs.
:param columnIndex: (int) column index to set permanence for.
:param permanence: (list) value to set.
"""
assert columnIndex < self... |
def exebench(width):
"""
benchorg.jpg is
'http://upload.wikimedia.org/wikipedia/commons/d/df/SAND_LUE.jpg'
"""
height = width * 2 / 3
with Benchmarker(width=30, loop=N) as bm:
for i in bm('kaa.imlib2'):
imlib2_scale('benchorg.jpg', width, height)
for i in bm("PIL"):
... | def function[exebench, parameter[width]]:
constant[
benchorg.jpg is
'http://upload.wikimedia.org/wikipedia/commons/d/df/SAND_LUE.jpg'
]
variable[height] assign[=] binary_operation[binary_operation[name[width] * constant[2]] / constant[3]]
with call[name[Benchmarker], parameter[]] beg... | keyword[def] identifier[exebench] ( identifier[width] ):
literal[string]
identifier[height] = identifier[width] * literal[int] / literal[int]
keyword[with] identifier[Benchmarker] ( identifier[width] = literal[int] , identifier[loop] = identifier[N] ) keyword[as] identifier[bm] :
keyword[f... | def exebench(width):
"""
benchorg.jpg is
'http://upload.wikimedia.org/wikipedia/commons/d/df/SAND_LUE.jpg'
"""
height = width * 2 / 3
with Benchmarker(width=30, loop=N) as bm:
for i in bm('kaa.imlib2'):
imlib2_scale('benchorg.jpg', width, height) # depends on [control=['for'... |
def DeleteInstance(self, InstanceName, **extra):
# pylint: disable=invalid-name
"""
Delete an instance.
This method performs the DeleteInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If t... | def function[DeleteInstance, parameter[self, InstanceName]]:
constant[
Delete an instance.
This method performs the DeleteInstance operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such operations.
If the operation succeeds... | keyword[def] identifier[DeleteInstance] ( identifier[self] , identifier[InstanceName] ,** identifier[extra] ):
literal[string]
identifier[exc] = keyword[None]
identifier[method_name] = literal[string]
keyword[if] identifier[self] . identifier[_operation_recorders] :
... | def DeleteInstance(self, InstanceName, **extra):
# pylint: disable=invalid-name
'\n Delete an instance.\n\n This method performs the DeleteInstance operation\n (see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all\n methods performing such operations.\n\n If the ... |
def in_file(self, filename: str) -> Iterator[FunctionDesc]:
"""
Returns an iterator over all of the functions definitions that are
contained within a given file.
"""
yield from self.__filename_to_functions.get(filename, []) | def function[in_file, parameter[self, filename]]:
constant[
Returns an iterator over all of the functions definitions that are
contained within a given file.
]
<ast.YieldFrom object at 0x7da20c6a9b40> | keyword[def] identifier[in_file] ( identifier[self] , identifier[filename] : identifier[str] )-> identifier[Iterator] [ identifier[FunctionDesc] ]:
literal[string]
keyword[yield] keyword[from] identifier[self] . identifier[__filename_to_functions] . identifier[get] ( identifier[filename] ,[]) | def in_file(self, filename: str) -> Iterator[FunctionDesc]:
"""
Returns an iterator over all of the functions definitions that are
contained within a given file.
"""
yield from self.__filename_to_functions.get(filename, []) |
def get(self, project_name, updatetime=None, md5sum=None):
'''get project data object, return None if not exists'''
if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL:
self._check_projects()
if self._need_update(project_name, updatetime, md5sum):
sel... | def function[get, parameter[self, project_name, updatetime, md5sum]]:
constant[get project data object, return None if not exists]
if compare[binary_operation[call[name[time].time, parameter[]] - name[self].last_check_projects] greater[>] name[self].CHECK_PROJECTS_INTERVAL] begin[:]
call... | keyword[def] identifier[get] ( identifier[self] , identifier[project_name] , identifier[updatetime] = keyword[None] , identifier[md5sum] = keyword[None] ):
literal[string]
keyword[if] identifier[time] . identifier[time] ()- identifier[self] . identifier[last_check_projects] > identifier[self] . id... | def get(self, project_name, updatetime=None, md5sum=None):
"""get project data object, return None if not exists"""
if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL:
self._check_projects() # depends on [control=['if'], data=[]]
if self._need_update(project_name, updatetime, ... |
def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
y = np.dot(self.w, x)
e = d - y
nu = self.mu / (self.eps + np.dot(x, x))
... | def function[adapt, parameter[self, d, x]]:
constant[
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
]
variable[y] assign[=] call[name[np].dot, parameter[name[self].w, n... | keyword[def] identifier[adapt] ( identifier[self] , identifier[d] , identifier[x] ):
literal[string]
identifier[y] = identifier[np] . identifier[dot] ( identifier[self] . identifier[w] , identifier[x] )
identifier[e] = identifier[d] - identifier[y]
identifier[nu] = identifier[sel... | def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
y = np.dot(self.w, x)
e = d - y
nu = self.mu / (self.eps + np.dot(x, x))
self.w += nu *... |
def decls(
self,
name=None,
function=None,
decl_type=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None):
"""returns a set of declarations, that are matched defined criteria"""
return (... | def function[decls, parameter[self, name, function, decl_type, header_dir, header_file, recursive, allow_empty]]:
constant[returns a set of declarations, that are matched defined criteria]
return[call[name[self]._find_multiple, parameter[call[name[self]._impl_matchers][name[scopedef_t].decl]]]] | keyword[def] identifier[decls] (
identifier[self] ,
identifier[name] = keyword[None] ,
identifier[function] = keyword[None] ,
identifier[decl_type] = keyword[None] ,
identifier[header_dir] = keyword[None] ,
identifier[header_file] = keyword[None] ,
identifier[recursive] = keyword[None] ,
identifier[allow_empt... | def decls(self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None, allow_empty=None):
"""returns a set of declarations, that are matched defined criteria"""
return self._find_multiple(self._impl_matchers[scopedef_t.decl], name=name, function=function, decl_type=decl_typ... |
def _prepare_init_params_from_job_description(cls, job_details):
"""Convert the transform job description to init params that can be handled by the class constructor
Args:
job_details (dict): the returned job details from a describe_transform_job API call.
Returns:
dict... | def function[_prepare_init_params_from_job_description, parameter[cls, job_details]]:
constant[Convert the transform job description to init params that can be handled by the class constructor
Args:
job_details (dict): the returned job details from a describe_transform_job API call.
... | keyword[def] identifier[_prepare_init_params_from_job_description] ( identifier[cls] , identifier[job_details] ):
literal[string]
identifier[init_params] = identifier[dict] ()
identifier[init_params] [ literal[string] ]= identifier[job_details] [ literal[string] ]
identifier[init... | def _prepare_init_params_from_job_description(cls, job_details):
"""Convert the transform job description to init params that can be handled by the class constructor
Args:
job_details (dict): the returned job details from a describe_transform_job API call.
Returns:
dict: Th... |
def perspective(fovy, aspect, znear, zfar):
"""Create perspective projection matrix
Parameters
----------
fovy : float
The field of view along the y axis.
aspect : float
Aspect ratio of the view.
znear : float
Near coordinate of the field of view.
zfar : float
... | def function[perspective, parameter[fovy, aspect, znear, zfar]]:
constant[Create perspective projection matrix
Parameters
----------
fovy : float
The field of view along the y axis.
aspect : float
Aspect ratio of the view.
znear : float
Near coordinate of the field o... | keyword[def] identifier[perspective] ( identifier[fovy] , identifier[aspect] , identifier[znear] , identifier[zfar] ):
literal[string]
keyword[assert] ( identifier[znear] != identifier[zfar] )
identifier[h] = identifier[math] . identifier[tan] ( identifier[fovy] / literal[int] * identifier[math] . ide... | def perspective(fovy, aspect, znear, zfar):
"""Create perspective projection matrix
Parameters
----------
fovy : float
The field of view along the y axis.
aspect : float
Aspect ratio of the view.
znear : float
Near coordinate of the field of view.
zfar : float
... |
def start_logging(log_fpath=None, mode='a', appname='default', log_dir=None):
r"""
Overwrites utool print functions to use a logger
CommandLine:
python -m utool.util_logging --test-start_logging:0
python -m utool.util_logging --test-start_logging:1
Example0:
>>> # DISABLE_DOCTE... | def function[start_logging, parameter[log_fpath, mode, appname, log_dir]]:
constant[
Overwrites utool print functions to use a logger
CommandLine:
python -m utool.util_logging --test-start_logging:0
python -m utool.util_logging --test-start_logging:1
Example0:
>>> # DISABLE... | keyword[def] identifier[start_logging] ( identifier[log_fpath] = keyword[None] , identifier[mode] = literal[string] , identifier[appname] = literal[string] , identifier[log_dir] = keyword[None] ):
literal[string]
keyword[global] identifier[__UTOOL_ROOT_LOGGER__]
keyword[global] identifier[__UTOOL_P... | def start_logging(log_fpath=None, mode='a', appname='default', log_dir=None):
"""
Overwrites utool print functions to use a logger
CommandLine:
python -m utool.util_logging --test-start_logging:0
python -m utool.util_logging --test-start_logging:1
Example0:
>>> # DISABLE_DOCTES... |
def _get_ports_list(app_name, port_specs):
""" Returns a list of formatted port mappings for an app """
if app_name not in port_specs['docker_compose']:
return []
return ["{}:{}".format(port_spec['mapped_host_port'], port_spec['in_container_port'])
for port_spec in port_specs['docker_com... | def function[_get_ports_list, parameter[app_name, port_specs]]:
constant[ Returns a list of formatted port mappings for an app ]
if compare[name[app_name] <ast.NotIn object at 0x7da2590d7190> call[name[port_specs]][constant[docker_compose]]] begin[:]
return[list[[]]]
return[<ast.ListComp obj... | keyword[def] identifier[_get_ports_list] ( identifier[app_name] , identifier[port_specs] ):
literal[string]
keyword[if] identifier[app_name] keyword[not] keyword[in] identifier[port_specs] [ literal[string] ]:
keyword[return] []
keyword[return] [ literal[string] . identifier[format] ( ide... | def _get_ports_list(app_name, port_specs):
""" Returns a list of formatted port mappings for an app """
if app_name not in port_specs['docker_compose']:
return [] # depends on [control=['if'], data=[]]
return ['{}:{}'.format(port_spec['mapped_host_port'], port_spec['in_container_port']) for port_sp... |
def vec(data, dtype=float):
""" Makes GLfloat or GLuint vector containing float or uint args.
By default, newtype is 'float', but can be set to 'int' to make
uint list. """
gl_types = {float: gl.GLfloat, int: gl.GLuint}
try:
gl_dtype = gl_types[dtype]
except K... | def function[vec, parameter[data, dtype]]:
constant[ Makes GLfloat or GLuint vector containing float or uint args.
By default, newtype is 'float', but can be set to 'int' to make
uint list. ]
variable[gl_types] assign[=] dictionary[[<ast.Name object at 0x7da1b1c18d90>, <ast.Name object a... | keyword[def] identifier[vec] ( identifier[data] , identifier[dtype] = identifier[float] ):
literal[string]
identifier[gl_types] ={ identifier[float] : identifier[gl] . identifier[GLfloat] , identifier[int] : identifier[gl] . identifier[GLuint] }
keyword[try] :
identifier[gl_dt... | def vec(data, dtype=float):
""" Makes GLfloat or GLuint vector containing float or uint args.
By default, newtype is 'float', but can be set to 'int' to make
uint list. """
gl_types = {float: gl.GLfloat, int: gl.GLuint}
try:
gl_dtype = gl_types[dtype] # depends on [control=['try'], ... |
def Attach(self, pid):
"""Attach to the process with the given pid."""
if self.inferior.is_running:
answer = raw_input('Already attached to process ' +
str(self.inferior.pid) +
'. Detach? [y]/n ')
if answer and answer != 'y' and answer != 'yes':
... | def function[Attach, parameter[self, pid]]:
constant[Attach to the process with the given pid.]
if name[self].inferior.is_running begin[:]
variable[answer] assign[=] call[name[raw_input], parameter[binary_operation[binary_operation[constant[Already attached to process ] + call[name[str],... | keyword[def] identifier[Attach] ( identifier[self] , identifier[pid] ):
literal[string]
keyword[if] identifier[self] . identifier[inferior] . identifier[is_running] :
identifier[answer] = identifier[raw_input] ( literal[string] +
identifier[str] ( identifier[self] . identifier[inferior] . id... | def Attach(self, pid):
"""Attach to the process with the given pid."""
if self.inferior.is_running:
answer = raw_input('Already attached to process ' + str(self.inferior.pid) + '. Detach? [y]/n ')
if answer and answer != 'y' and (answer != 'yes'):
return None # depends on [control=[... |
def load_post(wp_post_id):
"""
Called from load_post_webhook.
This builds a generic WPAPILoader and uses its load_post() to insert/update content for the post.
:param wp_post_id: the WordPress post ID to load
:return: None
"""
# wait a bit to give WordPress REST API a chance to catch up
... | def function[load_post, parameter[wp_post_id]]:
constant[
Called from load_post_webhook.
This builds a generic WPAPILoader and uses its load_post() to insert/update content for the post.
:param wp_post_id: the WordPress post ID to load
:return: None
]
call[name[time].sleep, paramete... | keyword[def] identifier[load_post] ( identifier[wp_post_id] ):
literal[string]
identifier[time] . identifier[sleep] ( literal[int] )
identifier[loader] = identifier[WPAPILoader] ()
identifier[post] = identifier[loader] . identifier[load_post] ( identifier[wp_post_id] )
keyword[if] i... | def load_post(wp_post_id):
"""
Called from load_post_webhook.
This builds a generic WPAPILoader and uses its load_post() to insert/update content for the post.
:param wp_post_id: the WordPress post ID to load
:return: None
"""
# wait a bit to give WordPress REST API a chance to catch up
... |
def acquire_authorization_header(self):
"""Acquire tokens from AAD."""
try:
return self._acquire_authorization_header()
except AdalError as error:
if self._authentication_method is AuthenticationMethod.aad_username_password:
kwargs = {"username": self._use... | def function[acquire_authorization_header, parameter[self]]:
constant[Acquire tokens from AAD.]
<ast.Try object at 0x7da1b1669120> | keyword[def] identifier[acquire_authorization_header] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_acquire_authorization_header] ()
keyword[except] identifier[AdalError] keyword[as] identifier[error] :
key... | def acquire_authorization_header(self):
"""Acquire tokens from AAD."""
try:
return self._acquire_authorization_header() # depends on [control=['try'], data=[]]
except AdalError as error:
if self._authentication_method is AuthenticationMethod.aad_username_password:
kwargs = {'use... |
def make_payment_script(address, blockchain='bitcoin', **blockchain_opts):
"""
High-level API call (meant to be blockchain agnostic)
Make a pay-to-address script.
"""
if blockchain == 'bitcoin':
return btc_make_payment_script(address, **blockchain_opts)
else:
raise ValueErro... | def function[make_payment_script, parameter[address, blockchain]]:
constant[
High-level API call (meant to be blockchain agnostic)
Make a pay-to-address script.
]
if compare[name[blockchain] equal[==] constant[bitcoin]] begin[:]
return[call[name[btc_make_payment_script], parameter[na... | keyword[def] identifier[make_payment_script] ( identifier[address] , identifier[blockchain] = literal[string] ,** identifier[blockchain_opts] ):
literal[string]
keyword[if] identifier[blockchain] == literal[string] :
keyword[return] identifier[btc_make_payment_script] ( identifier[address] ,** ... | def make_payment_script(address, blockchain='bitcoin', **blockchain_opts):
"""
High-level API call (meant to be blockchain agnostic)
Make a pay-to-address script.
"""
if blockchain == 'bitcoin':
return btc_make_payment_script(address, **blockchain_opts) # depends on [control=['if'], data=[]... |
def lifecycle_rules(self):
"""Retrieve or set lifecycle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. note::
The getter for this property returns a list which conta... | def function[lifecycle_rules, parameter[self]]:
constant[Retrieve or set lifecycle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. note::
The getter for this property... | keyword[def] identifier[lifecycle_rules] ( identifier[self] ):
literal[string]
identifier[info] = identifier[self] . identifier[_properties] . identifier[get] ( literal[string] ,{})
keyword[for] identifier[rule] keyword[in] identifier[info] . identifier[get] ( literal[string] ,()):
... | def lifecycle_rules(self):
"""Retrieve or set lifecycle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. note::
The getter for this property returns a list which contains
... |
def get_attachments(self):
"""Return the objects from the UIDs given in the request
"""
# Create a mapping of source ARs for copy
uids = self.request.form.get("attachment_uids", [])
return map(self.get_object_by_uid, uids) | def function[get_attachments, parameter[self]]:
constant[Return the objects from the UIDs given in the request
]
variable[uids] assign[=] call[name[self].request.form.get, parameter[constant[attachment_uids], list[[]]]]
return[call[name[map], parameter[name[self].get_object_by_uid, name[uids... | keyword[def] identifier[get_attachments] ( identifier[self] ):
literal[string]
identifier[uids] = identifier[self] . identifier[request] . identifier[form] . identifier[get] ( literal[string] ,[])
keyword[return] identifier[map] ( identifier[self] . identifier[get_object_by_uid] ... | def get_attachments(self):
"""Return the objects from the UIDs given in the request
"""
# Create a mapping of source ARs for copy
uids = self.request.form.get('attachment_uids', [])
return map(self.get_object_by_uid, uids) |
def update_check(package_name, package_version, bypass_cache=False, url=None,
**extra_data):
"""Convenience method that outputs to stdout if an update is available."""
checker = UpdateChecker(url)
checker.bypass_cache = bypass_cache
result = checker.check(package_name, package_version, ... | def function[update_check, parameter[package_name, package_version, bypass_cache, url]]:
constant[Convenience method that outputs to stdout if an update is available.]
variable[checker] assign[=] call[name[UpdateChecker], parameter[name[url]]]
name[checker].bypass_cache assign[=] name[bypass_cac... | keyword[def] identifier[update_check] ( identifier[package_name] , identifier[package_version] , identifier[bypass_cache] = keyword[False] , identifier[url] = keyword[None] ,
** identifier[extra_data] ):
literal[string]
identifier[checker] = identifier[UpdateChecker] ( identifier[url] )
identifier[che... | def update_check(package_name, package_version, bypass_cache=False, url=None, **extra_data):
"""Convenience method that outputs to stdout if an update is available."""
checker = UpdateChecker(url)
checker.bypass_cache = bypass_cache
result = checker.check(package_name, package_version, **extra_data)
... |
def sync_deps(self, path):
"""
Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each build, before
compili... | def function[sync_deps, parameter[self, path]]:
constant[
Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each bu... | keyword[def] identifier[sync_deps] ( identifier[self] , identifier[path] ):
literal[string]
keyword[if] keyword[not] identifier[exists] ( identifier[path] ):
identifier[os] . identifier[mkdir] ( identifier[path] , literal[int] )
identifier[self] . identifier[_l... | def sync_deps(self, path):
"""
Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each build, before
compiling s... |
def strftime(self, fmt):
"""Format using strftime(). The date part of the timestamp passed
to underlying strftime should not be used.
"""
# The year must be >= 1000 else Python's strftime implementation
# can raise a bogus exception.
timetuple = (1900, 1, 1,
... | def function[strftime, parameter[self, fmt]]:
constant[Format using strftime(). The date part of the timestamp passed
to underlying strftime should not be used.
]
variable[timetuple] assign[=] tuple[[<ast.Constant object at 0x7da18f8117e0>, <ast.Constant object at 0x7da18f813f40>, <ast.... | keyword[def] identifier[strftime] ( identifier[self] , identifier[fmt] ):
literal[string]
identifier[timetuple] =( literal[int] , literal[int] , literal[int] ,
identifier[self] . identifier[_hour] , identifier[self] . identifier[_minute] , identifier[self] . identifier[_s... | def strftime(self, fmt):
"""Format using strftime(). The date part of the timestamp passed
to underlying strftime should not be used.
"""
# The year must be >= 1000 else Python's strftime implementation
# can raise a bogus exception.
timetuple = (1900, 1, 1, self._hour, self._minute, se... |
def get_custom_value(self, field_name):
""" Get a value for a specified custom field
field_name - Name of the custom field you want.
"""
custom_field = self.get_custom_field(field_name)
return CustomFieldValue.objects.get_or_create(
field=custom_field, object_id=self.... | def function[get_custom_value, parameter[self, field_name]]:
constant[ Get a value for a specified custom field
field_name - Name of the custom field you want.
]
variable[custom_field] assign[=] call[name[self].get_custom_field, parameter[name[field_name]]]
return[call[call[name[Cust... | keyword[def] identifier[get_custom_value] ( identifier[self] , identifier[field_name] ):
literal[string]
identifier[custom_field] = identifier[self] . identifier[get_custom_field] ( identifier[field_name] )
keyword[return] identifier[CustomFieldValue] . identifier[objects] . identifier[ge... | def get_custom_value(self, field_name):
""" Get a value for a specified custom field
field_name - Name of the custom field you want.
"""
custom_field = self.get_custom_field(field_name)
return CustomFieldValue.objects.get_or_create(field=custom_field, object_id=self.id)[0].value |
def transformer_base_vq1_16_nb1_packed_nda_b01_scales_dialog():
"""Set of hyperparameters."""
hparams = transformer_base_vq1_16_nb1_packed_nda_b01_scales()
hparams.batch_size = 2048
hparams.max_length = 1024
hparams.filter_size = 3072
return hparams | def function[transformer_base_vq1_16_nb1_packed_nda_b01_scales_dialog, parameter[]]:
constant[Set of hyperparameters.]
variable[hparams] assign[=] call[name[transformer_base_vq1_16_nb1_packed_nda_b01_scales], parameter[]]
name[hparams].batch_size assign[=] constant[2048]
name[hparams].ma... | keyword[def] identifier[transformer_base_vq1_16_nb1_packed_nda_b01_scales_dialog] ():
literal[string]
identifier[hparams] = identifier[transformer_base_vq1_16_nb1_packed_nda_b01_scales] ()
identifier[hparams] . identifier[batch_size] = literal[int]
identifier[hparams] . identifier[max_length] = literal[... | def transformer_base_vq1_16_nb1_packed_nda_b01_scales_dialog():
"""Set of hyperparameters."""
hparams = transformer_base_vq1_16_nb1_packed_nda_b01_scales()
hparams.batch_size = 2048
hparams.max_length = 1024
hparams.filter_size = 3072
return hparams |
def htmlize_list(items):
"""
Turn a python list into an html list.
"""
out = ["<ul>"]
for item in items:
out.append("<li>" + htmlize(item) + "</li>")
out.append("</ul>")
return "\n".join(out) | def function[htmlize_list, parameter[items]]:
constant[
Turn a python list into an html list.
]
variable[out] assign[=] list[[<ast.Constant object at 0x7da1b25857b0>]]
for taget[name[item]] in starred[name[items]] begin[:]
call[name[out].append, parameter[binary_operation... | keyword[def] identifier[htmlize_list] ( identifier[items] ):
literal[string]
identifier[out] =[ literal[string] ]
keyword[for] identifier[item] keyword[in] identifier[items] :
identifier[out] . identifier[append] ( literal[string] + identifier[htmlize] ( identifier[item] )+ literal[string]... | def htmlize_list(items):
"""
Turn a python list into an html list.
"""
out = ['<ul>']
for item in items:
out.append('<li>' + htmlize(item) + '</li>') # depends on [control=['for'], data=['item']]
out.append('</ul>')
return '\n'.join(out) |
def estimate_flux(self):
"""
Estimate the star's flux by summing values in the input cutout
array.
Missing data is filled in by interpolation to better estimate
the total flux.
"""
from .epsf import _interpolate_missing_data
if np.any(self.mask):
... | def function[estimate_flux, parameter[self]]:
constant[
Estimate the star's flux by summing values in the input cutout
array.
Missing data is filled in by interpolation to better estimate
the total flux.
]
from relative_module[epsf] import module[_interpolate_missing... | keyword[def] identifier[estimate_flux] ( identifier[self] ):
literal[string]
keyword[from] . identifier[epsf] keyword[import] identifier[_interpolate_missing_data]
keyword[if] identifier[np] . identifier[any] ( identifier[self] . identifier[mask] ):
identifier[data_inter... | def estimate_flux(self):
"""
Estimate the star's flux by summing values in the input cutout
array.
Missing data is filled in by interpolation to better estimate
the total flux.
"""
from .epsf import _interpolate_missing_data
if np.any(self.mask):
data_interp ... |
def text(self,text):
""" puts text in the entity. Whitespace and newlines are stripped to single spaces. """
if text:
text = utfstr(text)
text = text.strip()
text = re.sub('\s+',' ',text)
if text:
self.dirty = True
self.escp... | def function[text, parameter[self, text]]:
constant[ puts text in the entity. Whitespace and newlines are stripped to single spaces. ]
if name[text] begin[:]
variable[text] assign[=] call[name[utfstr], parameter[name[text]]]
variable[text] assign[=] call[name[text].strip,... | keyword[def] identifier[text] ( identifier[self] , identifier[text] ):
literal[string]
keyword[if] identifier[text] :
identifier[text] = identifier[utfstr] ( identifier[text] )
identifier[text] = identifier[text] . identifier[strip] ()
identifier[text] = iden... | def text(self, text):
""" puts text in the entity. Whitespace and newlines are stripped to single spaces. """
if text:
text = utfstr(text)
text = text.strip()
text = re.sub('\\s+', ' ', text)
if text:
self.dirty = True
self.escpos.text(text) # depends on ... |
def get_show_name(self):
"""
Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name.
"""
div = self.soup.find('div', attrs={'data-hover': True})
data = json.loads... | def function[get_show_name, parameter[self]]:
constant[
Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name.
]
variable[div] assign[=] call[name[self].soup.find, param... | keyword[def] identifier[get_show_name] ( identifier[self] ):
literal[string]
identifier[div] = identifier[self] . identifier[soup] . identifier[find] ( literal[string] , identifier[attrs] ={ literal[string] : keyword[True] })
identifier[data] = identifier[json] . identifier[loads] ( identi... | def get_show_name(self):
"""
Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name.
"""
div = self.soup.find('div', attrs={'data-hover': True})
data = json.loads(div['data-h... |
def _lincomb(self, a, x1, b, x2, out):
"""Implement the linear combination of ``x1`` and ``x2``.
Compute ``out = a*x1 + b*x2`` using optimized
BLAS routines if possible.
This function is part of the subclassing API. Do not
call it directly.
Parameters
---------... | def function[_lincomb, parameter[self, a, x1, b, x2, out]]:
constant[Implement the linear combination of ``x1`` and ``x2``.
Compute ``out = a*x1 + b*x2`` using optimized
BLAS routines if possible.
This function is part of the subclassing API. Do not
call it directly.
P... | keyword[def] identifier[_lincomb] ( identifier[self] , identifier[a] , identifier[x1] , identifier[b] , identifier[x2] , identifier[out] ):
literal[string]
identifier[_lincomb_impl] ( identifier[a] , identifier[x1] , identifier[b] , identifier[x2] , identifier[out] ) | def _lincomb(self, a, x1, b, x2, out):
"""Implement the linear combination of ``x1`` and ``x2``.
Compute ``out = a*x1 + b*x2`` using optimized
BLAS routines if possible.
This function is part of the subclassing API. Do not
call it directly.
Parameters
----------
... |
def defaults_cluster_role_env(cluster_role_env):
"""
if role is not provided, supply userid
if environ is not provided, supply 'default'
"""
if len(cluster_role_env[1]) == 0 and len(cluster_role_env[2]) == 0:
return (cluster_role_env[0], getpass.getuser(), ENVIRON)
return (cluster_role_env[0], cluster_... | def function[defaults_cluster_role_env, parameter[cluster_role_env]]:
constant[
if role is not provided, supply userid
if environ is not provided, supply 'default'
]
if <ast.BoolOp object at 0x7da18f58c0d0> begin[:]
return[tuple[[<ast.Subscript object at 0x7da20c993160>, <ast.Call object a... | keyword[def] identifier[defaults_cluster_role_env] ( identifier[cluster_role_env] ):
literal[string]
keyword[if] identifier[len] ( identifier[cluster_role_env] [ literal[int] ])== literal[int] keyword[and] identifier[len] ( identifier[cluster_role_env] [ literal[int] ])== literal[int] :
keyword[return]... | def defaults_cluster_role_env(cluster_role_env):
"""
if role is not provided, supply userid
if environ is not provided, supply 'default'
"""
if len(cluster_role_env[1]) == 0 and len(cluster_role_env[2]) == 0:
return (cluster_role_env[0], getpass.getuser(), ENVIRON) # depends on [control=['if'], d... |
def align_image_with_openpnm(im):
r"""
Rotates an image to agree with the coordinates used in OpenPNM. It is
unclear why they are not in agreement to start with. This is necessary
for overlaying the image and the network in Paraview.
Parameters
----------
im : ND-array
The image t... | def function[align_image_with_openpnm, parameter[im]]:
constant[
Rotates an image to agree with the coordinates used in OpenPNM. It is
unclear why they are not in agreement to start with. This is necessary
for overlaying the image and the network in Paraview.
Parameters
----------
im ... | keyword[def] identifier[align_image_with_openpnm] ( identifier[im] ):
literal[string]
keyword[if] identifier[im] . identifier[ndim] != identifier[im] . identifier[squeeze] (). identifier[ndim] :
identifier[warnings] . identifier[warn] ( literal[string] + identifier[str] ( identifier[im] . identif... | def align_image_with_openpnm(im):
"""
Rotates an image to agree with the coordinates used in OpenPNM. It is
unclear why they are not in agreement to start with. This is necessary
for overlaying the image and the network in Paraview.
Parameters
----------
im : ND-array
The image to... |
def add_imt(fname, imt):
"""
>>> add_imt('/path/to/hcurve_23.csv', 'SA(0.1)')
'/path/to/hcurve-SA(0.1)_23.csv'
"""
name = os.path.basename(fname)
newname = re.sub(r'(_\d+\.)', '-%s\\1' % imt, name)
return os.path.join(os.path.dirname(fname), newname) | def function[add_imt, parameter[fname, imt]]:
constant[
>>> add_imt('/path/to/hcurve_23.csv', 'SA(0.1)')
'/path/to/hcurve-SA(0.1)_23.csv'
]
variable[name] assign[=] call[name[os].path.basename, parameter[name[fname]]]
variable[newname] assign[=] call[name[re].sub, parameter[constant[... | keyword[def] identifier[add_imt] ( identifier[fname] , identifier[imt] ):
literal[string]
identifier[name] = identifier[os] . identifier[path] . identifier[basename] ( identifier[fname] )
identifier[newname] = identifier[re] . identifier[sub] ( literal[string] , literal[string] % identifier[imt] , ide... | def add_imt(fname, imt):
"""
>>> add_imt('/path/to/hcurve_23.csv', 'SA(0.1)')
'/path/to/hcurve-SA(0.1)_23.csv'
"""
name = os.path.basename(fname)
newname = re.sub('(_\\d+\\.)', '-%s\\1' % imt, name)
return os.path.join(os.path.dirname(fname), newname) |
def validate_layout_display(self, table, display_condition):
"""Check to see if the display condition passes.
Args:
table (str): The name of the DB table which hold the App data.
display_condition (str): The "where" clause of the DB SQL statement.
Returns:
b... | def function[validate_layout_display, parameter[self, table, display_condition]]:
constant[Check to see if the display condition passes.
Args:
table (str): The name of the DB table which hold the App data.
display_condition (str): The "where" clause of the DB SQL statement.
... | keyword[def] identifier[validate_layout_display] ( identifier[self] , identifier[table] , identifier[display_condition] ):
literal[string]
identifier[display] = keyword[False]
keyword[if] identifier[display_condition] keyword[is] keyword[None] :
identifier[display] = keywo... | def validate_layout_display(self, table, display_condition):
"""Check to see if the display condition passes.
Args:
table (str): The name of the DB table which hold the App data.
display_condition (str): The "where" clause of the DB SQL statement.
Returns:
bool:... |
def addItem(self, child, href):
"""Add a new item (a catalogue or resource) as a child of this catalogue."""
assert isinstance(child, Base), "child must be a hypercat Catalogue or Resource"
child.setHref(href)
for item in self.items:
assert item.href != href, "All items in a ... | def function[addItem, parameter[self, child, href]]:
constant[Add a new item (a catalogue or resource) as a child of this catalogue.]
assert[call[name[isinstance], parameter[name[child], name[Base]]]]
call[name[child].setHref, parameter[name[href]]]
for taget[name[item]] in starred[name[self... | keyword[def] identifier[addItem] ( identifier[self] , identifier[child] , identifier[href] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[child] , identifier[Base] ), literal[string]
identifier[child] . identifier[setHref] ( identifier[href] )
keyword[for... | def addItem(self, child, href):
"""Add a new item (a catalogue or resource) as a child of this catalogue."""
assert isinstance(child, Base), 'child must be a hypercat Catalogue or Resource'
child.setHref(href)
for item in self.items:
assert item.href != href, 'All items in a catalogue must have ... |
def pre(*content, sep='\n'):
"""
Make mono-width text block (Markdown)
:param content:
:param sep:
:return:
"""
return _md(_join(*content, sep=sep), symbols=MD_SYMBOLS[3]) | def function[pre, parameter[]]:
constant[
Make mono-width text block (Markdown)
:param content:
:param sep:
:return:
]
return[call[name[_md], parameter[call[name[_join], parameter[<ast.Starred object at 0x7da1b18fe200>]]]]] | keyword[def] identifier[pre] (* identifier[content] , identifier[sep] = literal[string] ):
literal[string]
keyword[return] identifier[_md] ( identifier[_join] (* identifier[content] , identifier[sep] = identifier[sep] ), identifier[symbols] = identifier[MD_SYMBOLS] [ literal[int] ]) | def pre(*content, sep='\n'):
"""
Make mono-width text block (Markdown)
:param content:
:param sep:
:return:
"""
return _md(_join(*content, sep=sep), symbols=MD_SYMBOLS[3]) |
def ansi_format_iter( self, x_start=0, y_start=0, width=None, height=None, frame=0, columns=1, downsample=1, frame_index=None, frame_flip_v=0, frame_flip_h=0 ):
"""Return the ANSI escape sequence to render the image.
x_start
Offset from the left of the image data to render from. Defaults to... | def function[ansi_format_iter, parameter[self, x_start, y_start, width, height, frame, columns, downsample, frame_index, frame_flip_v, frame_flip_h]]:
constant[Return the ANSI escape sequence to render the image.
x_start
Offset from the left of the image data to render from. Defaults to 0.
... | keyword[def] identifier[ansi_format_iter] ( identifier[self] , identifier[x_start] = literal[int] , identifier[y_start] = literal[int] , identifier[width] = keyword[None] , identifier[height] = keyword[None] , identifier[frame] = literal[int] , identifier[columns] = literal[int] , identifier[downsample] = literal[int... | def ansi_format_iter(self, x_start=0, y_start=0, width=None, height=None, frame=0, columns=1, downsample=1, frame_index=None, frame_flip_v=0, frame_flip_h=0):
"""Return the ANSI escape sequence to render the image.
x_start
Offset from the left of the image data to render from. Defaults to 0.
... |
def _output_path(self, input_path, to_format, archive=False):
"""Construct an output path string from an input path string.
:param str input_path: Input path string.
:return: Output path string.
:rtype: :py:class:`str`
"""
indirpath, fname = os.path.split(os.path.abspath(... | def function[_output_path, parameter[self, input_path, to_format, archive]]:
constant[Construct an output path string from an input path string.
:param str input_path: Input path string.
:return: Output path string.
:rtype: :py:class:`str`
]
<ast.Tuple object at 0x7da1b22... | keyword[def] identifier[_output_path] ( identifier[self] , identifier[input_path] , identifier[to_format] , identifier[archive] = keyword[False] ):
literal[string]
identifier[indirpath] , identifier[fname] = identifier[os] . identifier[path] . identifier[split] ( identifier[os] . identifier[path] .... | def _output_path(self, input_path, to_format, archive=False):
"""Construct an output path string from an input path string.
:param str input_path: Input path string.
:return: Output path string.
:rtype: :py:class:`str`
"""
(indirpath, fname) = os.path.split(os.path.abspath(os.pat... |
def get_processes(process_dir, base_source_uri):
"""Find processes in path.
:param str process_dir: Path to the directory where to search for processes
:param str base_source_uri: Base URL of the source code repository with process definitions
:return: Dictionary of processes where keys are URLs pointi... | def function[get_processes, parameter[process_dir, base_source_uri]]:
constant[Find processes in path.
:param str process_dir: Path to the directory where to search for processes
:param str base_source_uri: Base URL of the source code repository with process definitions
:return: Dictionary of proce... | keyword[def] identifier[get_processes] ( identifier[process_dir] , identifier[base_source_uri] ):
literal[string]
keyword[global] identifier[PROCESS_CACHE]
keyword[if] identifier[PROCESS_CACHE] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[PROCESS_CACHE]
id... | def get_processes(process_dir, base_source_uri):
"""Find processes in path.
:param str process_dir: Path to the directory where to search for processes
:param str base_source_uri: Base URL of the source code repository with process definitions
:return: Dictionary of processes where keys are URLs pointi... |
def _ReadUUIDDataTypeDefinition(
self, definitions_registry, definition_values, definition_name,
is_member=False):
"""Reads an UUID data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, obje... | def function[_ReadUUIDDataTypeDefinition, parameter[self, definitions_registry, definition_values, definition_name, is_member]]:
constant[Reads an UUID data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (di... | keyword[def] identifier[_ReadUUIDDataTypeDefinition] (
identifier[self] , identifier[definitions_registry] , identifier[definition_values] , identifier[definition_name] ,
identifier[is_member] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[_ReadFixedSizeDataTypeDefinit... | def _ReadUUIDDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False):
"""Reads an UUID data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definit... |
def ObjectModifiedEventHandler(obj, event):
"""Object has been modified
"""
# only snapshot supported objects
if not supports_snapshots(obj):
return
# take a new snapshot
take_snapshot(obj, action="edit")
# reindex the object in the auditlog catalog
reindex_object(obj) | def function[ObjectModifiedEventHandler, parameter[obj, event]]:
constant[Object has been modified
]
if <ast.UnaryOp object at 0x7da18eb55510> begin[:]
return[None]
call[name[take_snapshot], parameter[name[obj]]]
call[name[reindex_object], parameter[name[obj]]] | keyword[def] identifier[ObjectModifiedEventHandler] ( identifier[obj] , identifier[event] ):
literal[string]
keyword[if] keyword[not] identifier[supports_snapshots] ( identifier[obj] ):
keyword[return]
identifier[take_snapshot] ( identifier[obj] , identifier[action] = liter... | def ObjectModifiedEventHandler(obj, event):
"""Object has been modified
"""
# only snapshot supported objects
if not supports_snapshots(obj):
return # depends on [control=['if'], data=[]]
# take a new snapshot
take_snapshot(obj, action='edit')
# reindex the object in the auditlog ca... |
def convert_values(self, value, field):
"""
Coerce the value returned by the database backend into a consistent
type that is compatible with the field type.
In our case, cater for the fact that SQL Server < 2008 has no
separate Date and Time data types.
TODO: See how we'... | def function[convert_values, parameter[self, value, field]]:
constant[
Coerce the value returned by the database backend into a consistent
type that is compatible with the field type.
In our case, cater for the fact that SQL Server < 2008 has no
separate Date and Time data types... | keyword[def] identifier[convert_values] ( identifier[self] , identifier[value] , identifier[field] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[if] identifier[field] keyword[and] identifier[field] . ... | def convert_values(self, value, field):
"""
Coerce the value returned by the database backend into a consistent
type that is compatible with the field type.
In our case, cater for the fact that SQL Server < 2008 has no
separate Date and Time data types.
TODO: See how we'll h... |
def _update_inplace(self, result, verify_is_copy=True):
"""
Replace self internals with result.
Parameters
----------
verify_is_copy : boolean, default True
provide is_copy checks
"""
# NOTE: This does *not* call __finalize__ and that's an explicit
... | def function[_update_inplace, parameter[self, result, verify_is_copy]]:
constant[
Replace self internals with result.
Parameters
----------
verify_is_copy : boolean, default True
provide is_copy checks
]
call[name[self]._reset_cache, parameter[]]
... | keyword[def] identifier[_update_inplace] ( identifier[self] , identifier[result] , identifier[verify_is_copy] = keyword[True] ):
literal[string]
identifier[self] . identifier[_reset_cache] ()
identifier[self] . identifier[_clear_item_cache] ()
identifier[self] .... | def _update_inplace(self, result, verify_is_copy=True):
"""
Replace self internals with result.
Parameters
----------
verify_is_copy : boolean, default True
provide is_copy checks
"""
# NOTE: This does *not* call __finalize__ and that's an explicit
# dec... |
def getEstTraitCovar(self,term_i=None):
"""
Returns explicitly the estimated trait covariance matrix
Args:
term_i: index of the term we are interested in
"""
assert self.P>1, 'Trait covars not defined for single trait analysis'
if term_i==None:
... | def function[getEstTraitCovar, parameter[self, term_i]]:
constant[
Returns explicitly the estimated trait covariance matrix
Args:
term_i: index of the term we are interested in
]
assert[compare[name[self].P greater[>] constant[1]]]
if compare[name[term_i] equ... | keyword[def] identifier[getEstTraitCovar] ( identifier[self] , identifier[term_i] = keyword[None] ):
literal[string]
keyword[assert] identifier[self] . identifier[P] > literal[int] , literal[string]
keyword[if] identifier[term_i] == keyword[None] :
identifier[RV] = identif... | def getEstTraitCovar(self, term_i=None):
"""
Returns explicitly the estimated trait covariance matrix
Args:
term_i: index of the term we are interested in
"""
assert self.P > 1, 'Trait covars not defined for single trait analysis'
if term_i == None:
RV = SP.z... |
def on(self, val=None):
"""Turns the MixedParameter ON by setting its Value to val
An attempt to turn the parameter on with value 'False' will result
in an error, since this is the same as turning the parameter off.
Turning the MixedParameter ON without a value or with value 'None'... | def function[on, parameter[self, val]]:
constant[Turns the MixedParameter ON by setting its Value to val
An attempt to turn the parameter on with value 'False' will result
in an error, since this is the same as turning the parameter off.
Turning the MixedParameter ON without a valu... | keyword[def] identifier[on] ( identifier[self] , identifier[val] = keyword[None] ):
literal[string]
keyword[if] identifier[val] keyword[is] keyword[False] :
keyword[raise] identifier[ParameterError] ( literal[string]
literal[string]
literal[string] )
... | def on(self, val=None):
"""Turns the MixedParameter ON by setting its Value to val
An attempt to turn the parameter on with value 'False' will result
in an error, since this is the same as turning the parameter off.
Turning the MixedParameter ON without a value or with value 'None'
... |
def inet_ntop(address_family, packed_ip):
""" A platform independent version of inet_ntop """
global __inet_ntop
if __inet_ntop is None:
if hasattr(socket, 'inet_ntop'):
__inet_ntop = socket.inet_ntop
else:
from ospd import win_socket
__inet_ntop = win_soc... | def function[inet_ntop, parameter[address_family, packed_ip]]:
constant[ A platform independent version of inet_ntop ]
<ast.Global object at 0x7da20c7cbdf0>
if compare[name[__inet_ntop] is constant[None]] begin[:]
if call[name[hasattr], parameter[name[socket], constant[inet_ntop]]] b... | keyword[def] identifier[inet_ntop] ( identifier[address_family] , identifier[packed_ip] ):
literal[string]
keyword[global] identifier[__inet_ntop]
keyword[if] identifier[__inet_ntop] keyword[is] keyword[None] :
keyword[if] identifier[hasattr] ( identifier[socket] , literal[string] ):
... | def inet_ntop(address_family, packed_ip):
""" A platform independent version of inet_ntop """
global __inet_ntop
if __inet_ntop is None:
if hasattr(socket, 'inet_ntop'):
__inet_ntop = socket.inet_ntop # depends on [control=['if'], data=[]]
else:
from ospd import win_... |
def create_request_comment(self, issue_id_or_key, body, public=True):
"""
Creating request comment
:param issue_id_or_key: str
:param body: str
:param public: OPTIONAL: bool (default is True)
:return: New comment
"""
log.warning('Creating comment...')
... | def function[create_request_comment, parameter[self, issue_id_or_key, body, public]]:
constant[
Creating request comment
:param issue_id_or_key: str
:param body: str
:param public: OPTIONAL: bool (default is True)
:return: New comment
]
call[name[log].war... | keyword[def] identifier[create_request_comment] ( identifier[self] , identifier[issue_id_or_key] , identifier[body] , identifier[public] = keyword[True] ):
literal[string]
identifier[log] . identifier[warning] ( literal[string] )
identifier[data] ={ literal[string] : identifier[body] , lit... | def create_request_comment(self, issue_id_or_key, body, public=True):
"""
Creating request comment
:param issue_id_or_key: str
:param body: str
:param public: OPTIONAL: bool (default is True)
:return: New comment
"""
log.warning('Creating comment...')
data = ... |
def summarise_file_as_html(fname):
"""
takes a large data file and produces a HTML summary as html
"""
txt = '<H1>' + fname + '</H1>'
num_lines = 0
print('Reading OpenCyc file - ', fname)
with open(ip_folder + os.sep + fname, 'r') as f:
txt += '<PRE>'
for line in f:
... | def function[summarise_file_as_html, parameter[fname]]:
constant[
takes a large data file and produces a HTML summary as html
]
variable[txt] assign[=] binary_operation[binary_operation[constant[<H1>] + name[fname]] + constant[</H1>]]
variable[num_lines] assign[=] constant[0]
ca... | keyword[def] identifier[summarise_file_as_html] ( identifier[fname] ):
literal[string]
identifier[txt] = literal[string] + identifier[fname] + literal[string]
identifier[num_lines] = literal[int]
identifier[print] ( literal[string] , identifier[fname] )
keyword[with] identifier[open] ( id... | def summarise_file_as_html(fname):
"""
takes a large data file and produces a HTML summary as html
"""
txt = '<H1>' + fname + '</H1>'
num_lines = 0
print('Reading OpenCyc file - ', fname)
with open(ip_folder + os.sep + fname, 'r') as f:
txt += '<PRE>'
for line in f:
... |
def query(self, minhash, size):
'''
Giving the MinHash and size of the query set, retrieve
keys that references sets with containment with respect to
the query set greater than the threshold.
Args:
minhash (datasketch.MinHash): The MinHash of the query set.
... | def function[query, parameter[self, minhash, size]]:
constant[
Giving the MinHash and size of the query set, retrieve
keys that references sets with containment with respect to
the query set greater than the threshold.
Args:
minhash (datasketch.MinHash): The MinHash ... | keyword[def] identifier[query] ( identifier[self] , identifier[minhash] , identifier[size] ):
literal[string]
keyword[for] identifier[i] , identifier[index] keyword[in] identifier[enumerate] ( identifier[self] . identifier[indexes] ):
identifier[u] = identifier[self] . identifier[up... | def query(self, minhash, size):
"""
Giving the MinHash and size of the query set, retrieve
keys that references sets with containment with respect to
the query set greater than the threshold.
Args:
minhash (datasketch.MinHash): The MinHash of the query set.
s... |
def trace():
"""Enables and disables request tracing."""
def fget(self):
return self._options.get('trace', None)
def fset(self, value):
self._options['trace'] = value
return locals() | def function[trace, parameter[]]:
constant[Enables and disables request tracing.]
def function[fget, parameter[self]]:
return[call[name[self]._options.get, parameter[constant[trace], constant[None]]]]
def function[fset, parameter[self, value]]:
call[name[self]._options][c... | keyword[def] identifier[trace] ():
literal[string]
keyword[def] identifier[fget] ( identifier[self] ):
keyword[return] identifier[self] . identifier[_options] . identifier[get] ( literal[string] , keyword[None] )
keyword[def] identifier[fset] ( identifier[self] , identifie... | def trace():
"""Enables and disables request tracing."""
def fget(self):
return self._options.get('trace', None)
def fset(self, value):
self._options['trace'] = value
return locals() |
def set_index(self, keys):
"""Set the index of the DataFrame to be the keys columns.
Note this means that the old index is removed.
Parameters
----------
keys : str or list of str
Which column(s) to set as the index.
Returns
-------
DataFram... | def function[set_index, parameter[self, keys]]:
constant[Set the index of the DataFrame to be the keys columns.
Note this means that the old index is removed.
Parameters
----------
keys : str or list of str
Which column(s) to set as the index.
Returns
... | keyword[def] identifier[set_index] ( identifier[self] , identifier[keys] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[keys] , identifier[str] ):
identifier[column] = identifier[self] . identifier[_data] [ identifier[keys] ]
identifier[new_index] = id... | def set_index(self, keys):
"""Set the index of the DataFrame to be the keys columns.
Note this means that the old index is removed.
Parameters
----------
keys : str or list of str
Which column(s) to set as the index.
Returns
-------
DataFrame
... |
def keypoint_random_rotate(image, annos, mask=None, rg=15.):
"""Rotate an image and corresponding keypoints.
Parameters
-----------
image : 3 channel image
The given image for augmentation.
annos : list of list of floats
The keypoints annotation of people.
mask : single channel ... | def function[keypoint_random_rotate, parameter[image, annos, mask, rg]]:
constant[Rotate an image and corresponding keypoints.
Parameters
-----------
image : 3 channel image
The given image for augmentation.
annos : list of list of floats
The keypoints annotation of people.
... | keyword[def] identifier[keypoint_random_rotate] ( identifier[image] , identifier[annos] , identifier[mask] = keyword[None] , identifier[rg] = literal[int] ):
literal[string]
keyword[def] identifier[_rotate_coord] ( identifier[shape] , identifier[newxy] , identifier[point] , identifier[angle] ):
... | def keypoint_random_rotate(image, annos, mask=None, rg=15.0):
"""Rotate an image and corresponding keypoints.
Parameters
-----------
image : 3 channel image
The given image for augmentation.
annos : list of list of floats
The keypoints annotation of people.
mask : single channel... |
def agent(cls, version=None):
"""
Returns:
a connection object to make REST calls to QDS
optionally override the `version` of the REST endpoint for advanced
features available only in the newer version of the API available
for certain resource end points eg: ... | def function[agent, parameter[cls, version]]:
constant[
Returns:
a connection object to make REST calls to QDS
optionally override the `version` of the REST endpoint for advanced
features available only in the newer version of the API available
for certain re... | keyword[def] identifier[agent] ( identifier[cls] , identifier[version] = keyword[None] ):
literal[string]
identifier[reuse_cached_agent] = keyword[True]
keyword[if] identifier[version] :
identifier[log] . identifier[debug] ( literal[string] % identifier[version] )
i... | def agent(cls, version=None):
"""
Returns:
a connection object to make REST calls to QDS
optionally override the `version` of the REST endpoint for advanced
features available only in the newer version of the API available
for certain resource end points eg: /v1.... |
def search_for_devices_by_serial_number(self, sn):
"""
Returns a list of device objects that match the serial number
in param 'sn'.
This will match partial serial numbers.
"""
import re
sn_search = re.compile(sn)
matches = []
for dev... | def function[search_for_devices_by_serial_number, parameter[self, sn]]:
constant[
Returns a list of device objects that match the serial number
in param 'sn'.
This will match partial serial numbers.
]
import module[re]
variable[sn_search] assign[=] call[n... | keyword[def] identifier[search_for_devices_by_serial_number] ( identifier[self] , identifier[sn] ):
literal[string]
keyword[import] identifier[re]
identifier[sn_search] = identifier[re] . identifier[compile] ( identifier[sn] )
identifier[matches] =[]
keyword[for] ide... | def search_for_devices_by_serial_number(self, sn):
"""
Returns a list of device objects that match the serial number
in param 'sn'.
This will match partial serial numbers.
"""
import re
sn_search = re.compile(sn)
matches = []
for dev_o in self.get_all_dev... |
def _get_segment(self, start, request_size, check_response=True):
"""Get a segment of the file from Google Storage.
Args:
start: start offset of the segment. Inclusive. Have to be within the
range of the file.
request_size: number of bytes to request. Have to be small enough
for a s... | def function[_get_segment, parameter[self, start, request_size, check_response]]:
constant[Get a segment of the file from Google Storage.
Args:
start: start offset of the segment. Inclusive. Have to be within the
range of the file.
request_size: number of bytes to request. Have to be sm... | keyword[def] identifier[_get_segment] ( identifier[self] , identifier[start] , identifier[request_size] , identifier[check_response] = keyword[True] ):
literal[string]
identifier[end] = identifier[start] + identifier[request_size] - literal[int]
identifier[content_range] = literal[string] %( identifi... | def _get_segment(self, start, request_size, check_response=True):
"""Get a segment of the file from Google Storage.
Args:
start: start offset of the segment. Inclusive. Have to be within the
range of the file.
request_size: number of bytes to request. Have to be small enough
for a s... |
def set_user_agent_component(self, key, value, sanitize=True):
"""Add or replace new user-agent component strings.
Given strings are formatted along the format agreed upon by Mollie and implementers:
- key and values are separated by a forward slash ("/").
- multiple key/values are sepa... | def function[set_user_agent_component, parameter[self, key, value, sanitize]]:
constant[Add or replace new user-agent component strings.
Given strings are formatted along the format agreed upon by Mollie and implementers:
- key and values are separated by a forward slash ("/").
- multip... | keyword[def] identifier[set_user_agent_component] ( identifier[self] , identifier[key] , identifier[value] , identifier[sanitize] = keyword[True] ):
literal[string]
keyword[if] identifier[sanitize] :
identifier[key] = literal[string] . identifier[join] ( identifier[_x] . identifier[ca... | def set_user_agent_component(self, key, value, sanitize=True):
"""Add or replace new user-agent component strings.
Given strings are formatted along the format agreed upon by Mollie and implementers:
- key and values are separated by a forward slash ("/").
- multiple key/values are separate... |
def add_user_to_groups(self, user_id, body, **kwargs): # noqa: E501
"""Add user to a list of groups. # noqa: E501
An endpoint for adding user to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -d '[0162056a9a1586f30242590700000000,0117056a9a158... | def function[add_user_to_groups, parameter[self, user_id, body]]:
constant[Add user to a list of groups. # noqa: E501
An endpoint for adding user to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -d '[0162056a9a1586f30242590700000000,0117056a9a... | keyword[def] identifier[add_user_to_groups] ( identifier[self] , identifier[user_id] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keywo... | def add_user_to_groups(self, user_id, body, **kwargs): # noqa: E501
"Add user to a list of groups. # noqa: E501\n\n An endpoint for adding user to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f30... |
def gp_rapp():
"""rho in-medium ratios by Rapp (based on protected data)"""
inDir, outDir = getWorkDirs()
# prepare data
yields = {}
for infile in os.listdir(inDir):
energy = re.compile('\d+').search(infile).group()
medium = np.loadtxt(open(os.path.join(inDir, infile), 'rb'))
getMassRangesSums(ene... | def function[gp_rapp, parameter[]]:
constant[rho in-medium ratios by Rapp (based on protected data)]
<ast.Tuple object at 0x7da18f09dbd0> assign[=] call[name[getWorkDirs], parameter[]]
variable[yields] assign[=] dictionary[[], []]
for taget[name[infile]] in starred[call[name[os].listdir,... | keyword[def] identifier[gp_rapp] ():
literal[string]
identifier[inDir] , identifier[outDir] = identifier[getWorkDirs] ()
identifier[yields] ={}
keyword[for] identifier[infile] keyword[in] identifier[os] . identifier[listdir] ( identifier[inDir] ):
identifier[energy] = identifier[re] . identifi... | def gp_rapp():
"""rho in-medium ratios by Rapp (based on protected data)"""
(inDir, outDir) = getWorkDirs()
# prepare data
yields = {}
for infile in os.listdir(inDir):
energy = re.compile('\\d+').search(infile).group()
medium = np.loadtxt(open(os.path.join(inDir, infile), 'rb'))
... |
def last(self, name, value):
"""
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record.
"""
counter = self.get(name, CounterType... | def function[last, parameter[self, name, value]]:
constant[
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record.
]
variable[co... | keyword[def] identifier[last] ( identifier[self] , identifier[name] , identifier[value] ):
literal[string]
identifier[counter] = identifier[self] . identifier[get] ( identifier[name] , identifier[CounterType] . identifier[LastValue] )
identifier[counter] . identifier[last] = identifier[val... | def last(self, name, value):
"""
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
:param name: a counter name of Last type.
:param value: a last value to record.
"""
counter = self.get(name, CounterType.LastVal... |
def to_XML(self, xml_declaration=True, xmlns=True):
"""
Dumps object fields to an XML-formatted string. The 'xml_declaration'
switch enables printing of a leading standard XML line containing XML
version and encoding. The 'xmlns' switch enables printing of qualified
XMLNS prefix... | def function[to_XML, parameter[self, xml_declaration, xmlns]]:
constant[
Dumps object fields to an XML-formatted string. The 'xml_declaration'
switch enables printing of a leading standard XML line containing XML
version and encoding. The 'xmlns' switch enables printing of qualified
... | keyword[def] identifier[to_XML] ( identifier[self] , identifier[xml_declaration] = keyword[True] , identifier[xmlns] = keyword[True] ):
literal[string]
identifier[root_node] = identifier[self] . identifier[_to_DOM] ()
keyword[if] identifier[xmlns] :
identifier[xmlutils] . ide... | def to_XML(self, xml_declaration=True, xmlns=True):
"""
Dumps object fields to an XML-formatted string. The 'xml_declaration'
switch enables printing of a leading standard XML line containing XML
version and encoding. The 'xmlns' switch enables printing of qualified
XMLNS prefixes.
... |
def IsDeletedOrDefault(clean_lines, linenum):
"""Check if current constructor or operator is deleted or default.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if this is a deleted or default constructor.
"""
open_paren = c... | def function[IsDeletedOrDefault, parameter[clean_lines, linenum]]:
constant[Check if current constructor or operator is deleted or default.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if this is a deleted or default co... | keyword[def] identifier[IsDeletedOrDefault] ( identifier[clean_lines] , identifier[linenum] ):
literal[string]
identifier[open_paren] = identifier[clean_lines] . identifier[elided] [ identifier[linenum] ]. identifier[find] ( literal[string] )
keyword[if] identifier[open_paren] < literal[int] :
keyword... | def IsDeletedOrDefault(clean_lines, linenum):
"""Check if current constructor or operator is deleted or default.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if this is a deleted or default constructor.
"""
open_paren... |
def _init_compile_patterns(optional_attrs):
"""Compile search patterns for optional attributes if needed."""
attr2cmp = {}
if optional_attrs is None:
return attr2cmp
# "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
# "blood vessel formation from pre-existing blo... | def function[_init_compile_patterns, parameter[optional_attrs]]:
constant[Compile search patterns for optional attributes if needed.]
variable[attr2cmp] assign[=] dictionary[[], []]
if compare[name[optional_attrs] is constant[None]] begin[:]
return[name[attr2cmp]]
if compare[cons... | keyword[def] identifier[_init_compile_patterns] ( identifier[optional_attrs] ):
literal[string]
identifier[attr2cmp] ={}
keyword[if] identifier[optional_attrs] keyword[is] keyword[None] :
keyword[return] identifier[attr2cmp]
... | def _init_compile_patterns(optional_attrs):
"""Compile search patterns for optional attributes if needed."""
attr2cmp = {}
if optional_attrs is None:
return attr2cmp # depends on [control=['if'], data=[]]
# "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
# "blood vessel formation from ... |
def temporary_file(root_dir=None, cleanup=True, suffix='', permissions=None, binary_mode=True):
"""
A with-context that creates a temporary file and returns a writeable file descriptor to it.
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary fil... | def function[temporary_file, parameter[root_dir, cleanup, suffix, permissions, binary_mode]]:
constant[
A with-context that creates a temporary file and returns a writeable file descriptor to it.
You may specify the following keyword args:
:param str root_dir: The parent directory to create the tem... | keyword[def] identifier[temporary_file] ( identifier[root_dir] = keyword[None] , identifier[cleanup] = keyword[True] , identifier[suffix] = literal[string] , identifier[permissions] = keyword[None] , identifier[binary_mode] = keyword[True] ):
literal[string]
identifier[mode] = literal[string] keyword[if] ide... | def temporary_file(root_dir=None, cleanup=True, suffix='', permissions=None, binary_mode=True):
"""
A with-context that creates a temporary file and returns a writeable file descriptor to it.
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary f... |
def opls_notation(atom_key):
"""Return element for OPLS forcefield atom key."""
# warning for Ne, He, Na types overlap
conflicts = ['ne', 'he', 'na']
if atom_key in conflicts:
raise _AtomKeyConflict((
"One of the OPLS conflicting "
"atom_keys has occured '{0}'. "
... | def function[opls_notation, parameter[atom_key]]:
constant[Return element for OPLS forcefield atom key.]
variable[conflicts] assign[=] list[[<ast.Constant object at 0x7da20e9b18d0>, <ast.Constant object at 0x7da20e9b1ae0>, <ast.Constant object at 0x7da20e9b3160>]]
if compare[name[atom_key] in na... | keyword[def] identifier[opls_notation] ( identifier[atom_key] ):
literal[string]
identifier[conflicts] =[ literal[string] , literal[string] , literal[string] ]
keyword[if] identifier[atom_key] keyword[in] identifier[conflicts] :
keyword[raise] identifier[_AtomKeyConflict] ((
... | def opls_notation(atom_key):
"""Return element for OPLS forcefield atom key."""
# warning for Ne, He, Na types overlap
conflicts = ['ne', 'he', 'na']
if atom_key in conflicts:
raise _AtomKeyConflict("One of the OPLS conflicting atom_keys has occured '{0}'. For how to solve this issue see the man... |
def plot_gos(fout_png, goids, obo_dag, *args, **kws):
"""Given GO ids and the obo_dag, create a plot of paths from GO ids."""
engine = kws['engine'] if 'engine' in kws else 'pydot'
godagsmall = OboToGoDagSmall(goids=goids, obodag=obo_dag).godag
godagplot = GODagSmallPlot(godagsmall, *args, **kws)
go... | def function[plot_gos, parameter[fout_png, goids, obo_dag]]:
constant[Given GO ids and the obo_dag, create a plot of paths from GO ids.]
variable[engine] assign[=] <ast.IfExp object at 0x7da18f811b40>
variable[godagsmall] assign[=] call[name[OboToGoDagSmall], parameter[]].godag
variable[... | keyword[def] identifier[plot_gos] ( identifier[fout_png] , identifier[goids] , identifier[obo_dag] ,* identifier[args] ,** identifier[kws] ):
literal[string]
identifier[engine] = identifier[kws] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[kws] keyword[else] literal[string]
... | def plot_gos(fout_png, goids, obo_dag, *args, **kws):
"""Given GO ids and the obo_dag, create a plot of paths from GO ids."""
engine = kws['engine'] if 'engine' in kws else 'pydot'
godagsmall = OboToGoDagSmall(goids=goids, obodag=obo_dag).godag
godagplot = GODagSmallPlot(godagsmall, *args, **kws)
go... |
def zoning_enabled_configuration_cfg_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
zoning = ET.SubElement(config, "zoning", xmlns="urn:brocade.com:mgmt:brocade-zone")
enabled_configuration = ET.SubElement(zoning, "enabled-configuration")
c... | def function[zoning_enabled_configuration_cfg_name, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[zoning] assign[=] call[name[ET].SubElement, parameter[name[config], constant[zoning]]]
vari... | keyword[def] identifier[zoning_enabled_configuration_cfg_name] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[zoning] = identifier[ET] . identifier[SubElement] ( identifier[config] , lite... | def zoning_enabled_configuration_cfg_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
zoning = ET.SubElement(config, 'zoning', xmlns='urn:brocade.com:mgmt:brocade-zone')
enabled_configuration = ET.SubElement(zoning, 'enabled-configuration')
cfg_name = ET.SubElem... |
def get_AV_infinity(ra,dec,frame='icrs'):
"""
Gets the A_V exctinction at infinity for a given line of sight.
Queries the NED database.
:param ra,dec:
Desired coordinates, in degrees.
:param frame: (optional)
Frame of input coordinates (e.g., ``'icrs', 'galactic'``)
"""
coo... | def function[get_AV_infinity, parameter[ra, dec, frame]]:
constant[
Gets the A_V exctinction at infinity for a given line of sight.
Queries the NED database.
:param ra,dec:
Desired coordinates, in degrees.
:param frame: (optional)
Frame of input coordinates (e.g., ``'icrs', 'ga... | keyword[def] identifier[get_AV_infinity] ( identifier[ra] , identifier[dec] , identifier[frame] = literal[string] ):
literal[string]
identifier[coords] = identifier[SkyCoord] ( identifier[ra] , identifier[dec] , identifier[unit] = literal[string] , identifier[frame] = identifier[frame] ). identifier[transf... | def get_AV_infinity(ra, dec, frame='icrs'):
"""
Gets the A_V exctinction at infinity for a given line of sight.
Queries the NED database.
:param ra,dec:
Desired coordinates, in degrees.
:param frame: (optional)
Frame of input coordinates (e.g., ``'icrs', 'galactic'``)
"""
c... |
def schema_file(self):
""" Gets the full path to the file in which to load configuration schema. """
path = os.getcwd() + '/' + self.lazy_folder
return path + self.schema_filename | def function[schema_file, parameter[self]]:
constant[ Gets the full path to the file in which to load configuration schema. ]
variable[path] assign[=] binary_operation[binary_operation[call[name[os].getcwd, parameter[]] + constant[/]] + name[self].lazy_folder]
return[binary_operation[name[path] + na... | keyword[def] identifier[schema_file] ( identifier[self] ):
literal[string]
identifier[path] = identifier[os] . identifier[getcwd] ()+ literal[string] + identifier[self] . identifier[lazy_folder]
keyword[return] identifier[path] + identifier[self] . identifier[schema_filename] | def schema_file(self):
""" Gets the full path to the file in which to load configuration schema. """
path = os.getcwd() + '/' + self.lazy_folder
return path + self.schema_filename |
def synchronized(cls, obj=None):
""" synchronize on obj if obj is supplied.
:param obj: the obj to lock on. if none, lock to the function
:return: return of the func.
"""
def get_key(f, o):
if o is None:
key = hash(f)
else:
... | def function[synchronized, parameter[cls, obj]]:
constant[ synchronize on obj if obj is supplied.
:param obj: the obj to lock on. if none, lock to the function
:return: return of the func.
]
def function[get_key, parameter[f, o]]:
if compare[name[o] is constant[... | keyword[def] identifier[synchronized] ( identifier[cls] , identifier[obj] = keyword[None] ):
literal[string]
keyword[def] identifier[get_key] ( identifier[f] , identifier[o] ):
keyword[if] identifier[o] keyword[is] keyword[None] :
identifier[key] = identifier[hash... | def synchronized(cls, obj=None):
""" synchronize on obj if obj is supplied.
:param obj: the obj to lock on. if none, lock to the function
:return: return of the func.
"""
def get_key(f, o):
if o is None:
key = hash(f) # depends on [control=['if'], data=[]]
... |
def advance_shards(self):
"""Poll active shards for records and insert them into the buffer. Rotate exhausted shards.
Returns immediately if the buffer isn't empty.
"""
# Don't poll shards when there are pending records.
if self.buffer:
return
# 0) Collect ... | def function[advance_shards, parameter[self]]:
constant[Poll active shards for records and insert them into the buffer. Rotate exhausted shards.
Returns immediately if the buffer isn't empty.
]
if name[self].buffer begin[:]
return[None]
variable[record_shard_pairs] assi... | keyword[def] identifier[advance_shards] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[buffer] :
keyword[return]
identifier[record_shard_pairs] =[]
keyword[for] identifier[shard] keyword[in] identifier[self]... | def advance_shards(self):
"""Poll active shards for records and insert them into the buffer. Rotate exhausted shards.
Returns immediately if the buffer isn't empty.
"""
# Don't poll shards when there are pending records.
if self.buffer:
return # depends on [control=['if'], data=[]... |
def radialrange(self, origin, return_all_global_extrema=False):
"""returns the tuples (d_min, t_min, idx_min), (d_max, t_max, idx_max)
which minimize and maximize, respectively, the distance
d = |self[idx].point(t)-origin|."""
if return_all_global_extrema:
raise NotImplemente... | def function[radialrange, parameter[self, origin, return_all_global_extrema]]:
constant[returns the tuples (d_min, t_min, idx_min), (d_max, t_max, idx_max)
which minimize and maximize, respectively, the distance
d = |self[idx].point(t)-origin|.]
if name[return_all_global_extrema] begin[:... | keyword[def] identifier[radialrange] ( identifier[self] , identifier[origin] , identifier[return_all_global_extrema] = keyword[False] ):
literal[string]
keyword[if] identifier[return_all_global_extrema] :
keyword[raise] identifier[NotImplementedError]
keyword[else] :
... | def radialrange(self, origin, return_all_global_extrema=False):
"""returns the tuples (d_min, t_min, idx_min), (d_max, t_max, idx_max)
which minimize and maximize, respectively, the distance
d = |self[idx].point(t)-origin|."""
if return_all_global_extrema:
raise NotImplementedError # de... |
def upload_files(selected_file, selected_host, only_link, file_name):
"""
Uploads selected file to the host, thanks to the fact that
every pomf.se based site has pretty much the same architecture.
"""
try:
answer = requests.post(
url=selected_host[0]+"upload.php",
fil... | def function[upload_files, parameter[selected_file, selected_host, only_link, file_name]]:
constant[
Uploads selected file to the host, thanks to the fact that
every pomf.se based site has pretty much the same architecture.
]
<ast.Try object at 0x7da1afe6d6c0> | keyword[def] identifier[upload_files] ( identifier[selected_file] , identifier[selected_host] , identifier[only_link] , identifier[file_name] ):
literal[string]
keyword[try] :
identifier[answer] = identifier[requests] . identifier[post] (
identifier[url] = identifier[selected_host] [ lite... | def upload_files(selected_file, selected_host, only_link, file_name):
"""
Uploads selected file to the host, thanks to the fact that
every pomf.se based site has pretty much the same architecture.
"""
try:
answer = requests.post(url=selected_host[0] + 'upload.php', files={'files[]': selected... |
def returns(prices, method='simple', periods=1, fill_method='pad', limit=None, freq=None):
"""
compute the returns for the specified prices.
method: [simple,compound,log], compound is log
"""
if method not in ('simple', 'compound', 'log'):
raise ValueError("Invalid method type. Valid value... | def function[returns, parameter[prices, method, periods, fill_method, limit, freq]]:
constant[
compute the returns for the specified prices.
method: [simple,compound,log], compound is log
]
if compare[name[method] <ast.NotIn object at 0x7da2590d7190> tuple[[<ast.Constant object at 0x7da1b1... | keyword[def] identifier[returns] ( identifier[prices] , identifier[method] = literal[string] , identifier[periods] = literal[int] , identifier[fill_method] = literal[string] , identifier[limit] = keyword[None] , identifier[freq] = keyword[None] ):
literal[string]
keyword[if] identifier[method] keyword[no... | def returns(prices, method='simple', periods=1, fill_method='pad', limit=None, freq=None):
"""
compute the returns for the specified prices.
method: [simple,compound,log], compound is log
"""
if method not in ('simple', 'compound', 'log'):
raise ValueError("Invalid method type. Valid value... |
def set_hash(self, algo, digest):
"""Set algorithm ID and hexadecimal digest for next operation."""
self.algo = algo
self.digest = digest | def function[set_hash, parameter[self, algo, digest]]:
constant[Set algorithm ID and hexadecimal digest for next operation.]
name[self].algo assign[=] name[algo]
name[self].digest assign[=] name[digest] | keyword[def] identifier[set_hash] ( identifier[self] , identifier[algo] , identifier[digest] ):
literal[string]
identifier[self] . identifier[algo] = identifier[algo]
identifier[self] . identifier[digest] = identifier[digest] | def set_hash(self, algo, digest):
"""Set algorithm ID and hexadecimal digest for next operation."""
self.algo = algo
self.digest = digest |
def add_navi_series_from_jsonp(self, data_src=None, data_name='json_data', series_type="line", **kwargs):
"""set series for navigator option in highstocks"""
if not self.jsonp_data_flag:
self.jsonp_data_flag = True
self.jsonp_data_url = json.dumps(data_src)
... | def function[add_navi_series_from_jsonp, parameter[self, data_src, data_name, series_type]]:
constant[set series for navigator option in highstocks]
if <ast.UnaryOp object at 0x7da18bc737f0> begin[:]
name[self].jsonp_data_flag assign[=] constant[True]
name[self].jsonp_dat... | keyword[def] identifier[add_navi_series_from_jsonp] ( identifier[self] , identifier[data_src] = keyword[None] , identifier[data_name] = literal[string] , identifier[series_type] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[jso... | def add_navi_series_from_jsonp(self, data_src=None, data_name='json_data', series_type='line', **kwargs):
"""set series for navigator option in highstocks"""
if not self.jsonp_data_flag:
self.jsonp_data_flag = True
self.jsonp_data_url = json.dumps(data_src)
if data_name == 'data':
... |
def assigned_state(instance):
"""Returns `assigned` or `unassigned` depending on the state of the
analyses the analysisrequest contains. Return `unassigned` if the Analysis
Request has at least one analysis in `unassigned` state.
Otherwise, returns `assigned`
"""
analyses = instance.getAnalyses(... | def function[assigned_state, parameter[instance]]:
constant[Returns `assigned` or `unassigned` depending on the state of the
analyses the analysisrequest contains. Return `unassigned` if the Analysis
Request has at least one analysis in `unassigned` state.
Otherwise, returns `assigned`
]
... | keyword[def] identifier[assigned_state] ( identifier[instance] ):
literal[string]
identifier[analyses] = identifier[instance] . identifier[getAnalyses] ()
keyword[if] keyword[not] identifier[analyses] :
keyword[return] literal[string]
keyword[for] identifier[analysis] keyword[in] ... | def assigned_state(instance):
"""Returns `assigned` or `unassigned` depending on the state of the
analyses the analysisrequest contains. Return `unassigned` if the Analysis
Request has at least one analysis in `unassigned` state.
Otherwise, returns `assigned`
"""
analyses = instance.getAnalyses(... |
def bitpos(self, key, bit, start=None, end=None):
"""
Return the position of the first bit set to 1 or 0 in a string.
``start`` and ``end`` difines search range. The range is interpreted
as a range of bytes and not a range of bits, so start=0 and end=2
means to look at the first ... | def function[bitpos, parameter[self, key, bit, start, end]]:
constant[
Return the position of the first bit set to 1 or 0 in a string.
``start`` and ``end`` difines search range. The range is interpreted
as a range of bytes and not a range of bits, so start=0 and end=2
means to l... | keyword[def] identifier[bitpos] ( identifier[self] , identifier[key] , identifier[bit] , identifier[start] = keyword[None] , identifier[end] = keyword[None] ):
literal[string]
keyword[if] identifier[bit] keyword[not] keyword[in] ( literal[int] , literal[int] ):
keyword[raise] ident... | def bitpos(self, key, bit, start=None, end=None):
"""
Return the position of the first bit set to 1 or 0 in a string.
``start`` and ``end`` difines search range. The range is interpreted
as a range of bytes and not a range of bits, so start=0 and end=2
means to look at the first thre... |
def flatten_tree(tree, nested_attr='replies', depth_first=False):
"""Return a flattened version of the passed in tree.
:param nested_attr: The attribute name that contains the nested items.
Defaults to ``replies`` which is suitable for comments.
:param depth_first: When true, add to the list in a d... | def function[flatten_tree, parameter[tree, nested_attr, depth_first]]:
constant[Return a flattened version of the passed in tree.
:param nested_attr: The attribute name that contains the nested items.
Defaults to ``replies`` which is suitable for comments.
:param depth_first: When true, add to ... | keyword[def] identifier[flatten_tree] ( identifier[tree] , identifier[nested_attr] = literal[string] , identifier[depth_first] = keyword[False] ):
literal[string]
identifier[stack] = identifier[deque] ( identifier[tree] )
identifier[extend] = identifier[stack] . identifier[extend] keyword[if] identi... | def flatten_tree(tree, nested_attr='replies', depth_first=False):
"""Return a flattened version of the passed in tree.
:param nested_attr: The attribute name that contains the nested items.
Defaults to ``replies`` which is suitable for comments.
:param depth_first: When true, add to the list in a d... |
def set_record(self, name, record_id, record):
"""Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model
"""
if name not in self._... | def function[set_record, parameter[self, name, record_id, record]]:
constant[Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model
]
... | keyword[def] identifier[set_record] ( identifier[self] , identifier[name] , identifier[record_id] , identifier[record] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_cache] :
identifier[self] . identifier[_cache] [ identifier... | def set_record(self, name, record_id, record):
"""Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model
"""
if name not in self._cache:
... |
def get_domains(self):
"""
Connect to alignak backend and retrieve all available child endpoints of root
If connection is successful, returns a list of all the resources available in the backend:
Each resource is identified with its title and provides its endpoint relative to backend
... | def function[get_domains, parameter[self]]:
constant[
Connect to alignak backend and retrieve all available child endpoints of root
If connection is successful, returns a list of all the resources available in the backend:
Each resource is identified with its title and provides its endp... | keyword[def] identifier[get_domains] ( identifier[self] ):
literal[string]
identifier[resp] = identifier[self] . identifier[get] ( literal[string] )
keyword[if] literal[string] keyword[in] identifier[resp] :
identifier[_links] = identifier[resp] [ literal[string] ]
... | def get_domains(self):
"""
Connect to alignak backend and retrieve all available child endpoints of root
If connection is successful, returns a list of all the resources available in the backend:
Each resource is identified with its title and provides its endpoint relative to backend
... |
def expected_number_of_transactions_in_first_n_periods(self, n):
r"""
Return expected number of transactions in first n n_periods.
Expected number of transactions occurring across first n transaction
opportunities.
Used by Fader and Hardie to assess in-sample fit.
.. ma... | def function[expected_number_of_transactions_in_first_n_periods, parameter[self, n]]:
constant[
Return expected number of transactions in first n n_periods.
Expected number of transactions occurring across first n transaction
opportunities.
Used by Fader and Hardie to assess in-... | keyword[def] identifier[expected_number_of_transactions_in_first_n_periods] ( identifier[self] , identifier[n] ):
literal[string]
identifier[params] = identifier[self] . identifier[_unload_params] ( literal[string] , literal[string] , literal[string] , literal[string] )
identifier[alpha] ,... | def expected_number_of_transactions_in_first_n_periods(self, n):
"""
Return expected number of transactions in first n n_periods.
Expected number of transactions occurring across first n transaction
opportunities.
Used by Fader and Hardie to assess in-sample fit.
.. math:: ... |
def param_define(self,
param,
default,
unit='',
descr='',
tomatrix=True,
nonzero=False,
mandatory=False,
power=False,
voltage=False... | def function[param_define, parameter[self, param, default, unit, descr, tomatrix, nonzero, mandatory, power, voltage, current, z, y, r, g, dccurrent, dcvoltage, time, event_time]]:
constant[
Define a parameter in the model
:param tomatrix: convert this parameter list to matrix
:param pa... | keyword[def] identifier[param_define] ( identifier[self] ,
identifier[param] ,
identifier[default] ,
identifier[unit] = literal[string] ,
identifier[descr] = literal[string] ,
identifier[tomatrix] = keyword[True] ,
identifier[nonzero] = keyword[False] ,
identifier[mandatory] = keyword[False] ,
identifier[powe... | def param_define(self, param, default, unit='', descr='', tomatrix=True, nonzero=False, mandatory=False, power=False, voltage=False, current=False, z=False, y=False, r=False, g=False, dccurrent=False, dcvoltage=False, time=False, event_time=False, **kwargs):
"""
Define a parameter in the model
:par... |
def structs2records(structs):
"""convert one or more structs and generate dictionaries"""
try:
n = len(structs)
except TypeError:
# no array
yield struct2dict(structs)
# just 1
return
for i in range(n):
struct = structs[i]
yield struct2dict(struct) | def function[structs2records, parameter[structs]]:
constant[convert one or more structs and generate dictionaries]
<ast.Try object at 0x7da1b26a05e0>
for taget[name[i]] in starred[call[name[range], parameter[name[n]]]] begin[:]
variable[struct] assign[=] call[name[structs]][name[i]]
... | keyword[def] identifier[structs2records] ( identifier[structs] ):
literal[string]
keyword[try] :
identifier[n] = identifier[len] ( identifier[structs] )
keyword[except] identifier[TypeError] :
keyword[yield] identifier[struct2dict] ( identifier[structs] )
key... | def structs2records(structs):
"""convert one or more structs and generate dictionaries"""
try:
n = len(structs) # depends on [control=['try'], data=[]]
except TypeError:
# no array
yield struct2dict(structs)
# just 1
return # depends on [control=['except'], data=[]]... |
def get_file_hash(file_path, block_size=1024, hasher=None):
"""
Generate hash for given file
:param file_path: Path to file
:type file_path: str
:param block_size: Size of block to be read at once (default: 1024)
:type block_size: int
:param hasher: Use specific hasher, defaults to md5 (def... | def function[get_file_hash, parameter[file_path, block_size, hasher]]:
constant[
Generate hash for given file
:param file_path: Path to file
:type file_path: str
:param block_size: Size of block to be read at once (default: 1024)
:type block_size: int
:param hasher: Use specific hasher,... | keyword[def] identifier[get_file_hash] ( identifier[file_path] , identifier[block_size] = literal[int] , identifier[hasher] = keyword[None] ):
literal[string]
keyword[if] identifier[hasher] keyword[is] keyword[None] :
identifier[hasher] = identifier[hashlib] . identifier[md5] ()
keyword[wi... | def get_file_hash(file_path, block_size=1024, hasher=None):
"""
Generate hash for given file
:param file_path: Path to file
:type file_path: str
:param block_size: Size of block to be read at once (default: 1024)
:type block_size: int
:param hasher: Use specific hasher, defaults to md5 (def... |
def ensure(self, connection, func, *args, **kwargs):
"""Perform an operation until success
Repeats in the face of connection errors, pursuant to retry policy.
"""
channel = None
while 1:
try:
if channel is None:
channel = connectio... | def function[ensure, parameter[self, connection, func]]:
constant[Perform an operation until success
Repeats in the face of connection errors, pursuant to retry policy.
]
variable[channel] assign[=] constant[None]
while constant[1] begin[:]
<ast.Try object at 0x7da204621... | keyword[def] identifier[ensure] ( identifier[self] , identifier[connection] , identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[channel] = keyword[None]
keyword[while] literal[int] :
keyword[try] :
keyword[if] identif... | def ensure(self, connection, func, *args, **kwargs):
"""Perform an operation until success
Repeats in the face of connection errors, pursuant to retry policy.
"""
channel = None
while 1:
try:
if channel is None:
channel = connection.channel() # depends o... |
def get_access_key(self):
"""
Gets the application secret key.
The value can be stored in parameters "access_key", "client_key" or "secret_key".
:return: the application secret key.
"""
access_key = self.get_as_nullable_string("access_key")
access_key = access_ke... | def function[get_access_key, parameter[self]]:
constant[
Gets the application secret key.
The value can be stored in parameters "access_key", "client_key" or "secret_key".
:return: the application secret key.
]
variable[access_key] assign[=] call[name[self].get_as_nullab... | keyword[def] identifier[get_access_key] ( identifier[self] ):
literal[string]
identifier[access_key] = identifier[self] . identifier[get_as_nullable_string] ( literal[string] )
identifier[access_key] = identifier[access_key] keyword[if] identifier[access_key] != keyword[None] keyword[el... | def get_access_key(self):
"""
Gets the application secret key.
The value can be stored in parameters "access_key", "client_key" or "secret_key".
:return: the application secret key.
"""
access_key = self.get_as_nullable_string('access_key')
access_key = access_key if access_... |
def train(self, record):
"""
Incrementally updates the tree with the given sample record.
"""
assert self.data.class_attribute_name in record, \
"The class attribute must be present in the record."
record = record.copy()
self.sample_count += 1
self.tre... | def function[train, parameter[self, record]]:
constant[
Incrementally updates the tree with the given sample record.
]
assert[compare[name[self].data.class_attribute_name in name[record]]]
variable[record] assign[=] call[name[record].copy, parameter[]]
<ast.AugAssign object at 0x... | keyword[def] identifier[train] ( identifier[self] , identifier[record] ):
literal[string]
keyword[assert] identifier[self] . identifier[data] . identifier[class_attribute_name] keyword[in] identifier[record] , literal[string]
identifier[record] = identifier[record] . identifier[copy] (... | def train(self, record):
"""
Incrementally updates the tree with the given sample record.
"""
assert self.data.class_attribute_name in record, 'The class attribute must be present in the record.'
record = record.copy()
self.sample_count += 1
self.tree.train(record) |
def _handle_ssh_callback(self, submission_id, host, port, password):
""" Handles the creation of a remote ssh server """
if host is not None: # ignore late calls (a bit hacky, but...)
obj = {
"ssh_host": host,
"ssh_port": port,
"ssh_password":... | def function[_handle_ssh_callback, parameter[self, submission_id, host, port, password]]:
constant[ Handles the creation of a remote ssh server ]
if compare[name[host] is_not constant[None]] begin[:]
variable[obj] assign[=] dictionary[[<ast.Constant object at 0x7da1b1736c50>, <ast.Consta... | keyword[def] identifier[_handle_ssh_callback] ( identifier[self] , identifier[submission_id] , identifier[host] , identifier[port] , identifier[password] ):
literal[string]
keyword[if] identifier[host] keyword[is] keyword[not] keyword[None] :
identifier[obj] ={
literal... | def _handle_ssh_callback(self, submission_id, host, port, password):
""" Handles the creation of a remote ssh server """
if host is not None: # ignore late calls (a bit hacky, but...)
obj = {'ssh_host': host, 'ssh_port': port, 'ssh_password': password}
self._database.submissions.update_one({'_i... |
def createRepo(self):
"""
Creates the repository for all the data we've just downloaded.
"""
repo = datarepo.SqlDataRepository(self.repoPath)
repo.open("w")
repo.initialise()
referenceSet = references.HtslibReferenceSet("GRCh37-subset")
referenceSet.popul... | def function[createRepo, parameter[self]]:
constant[
Creates the repository for all the data we've just downloaded.
]
variable[repo] assign[=] call[name[datarepo].SqlDataRepository, parameter[name[self].repoPath]]
call[name[repo].open, parameter[constant[w]]]
call[name[re... | keyword[def] identifier[createRepo] ( identifier[self] ):
literal[string]
identifier[repo] = identifier[datarepo] . identifier[SqlDataRepository] ( identifier[self] . identifier[repoPath] )
identifier[repo] . identifier[open] ( literal[string] )
identifier[repo] . identifier[initi... | def createRepo(self):
"""
Creates the repository for all the data we've just downloaded.
"""
repo = datarepo.SqlDataRepository(self.repoPath)
repo.open('w')
repo.initialise()
referenceSet = references.HtslibReferenceSet('GRCh37-subset')
referenceSet.populateFromFile(self.fastaFil... |
def image_import(cls, image_name, url, target, **kwargs):
"""Import image from remote host to local image repository using scp.
If remote_host not specified, it means the source file exist in local
file system, just copy the image to image repository
"""
source = urlparse.urlpars... | def function[image_import, parameter[cls, image_name, url, target]]:
constant[Import image from remote host to local image repository using scp.
If remote_host not specified, it means the source file exist in local
file system, just copy the image to image repository
]
variable[s... | keyword[def] identifier[image_import] ( identifier[cls] , identifier[image_name] , identifier[url] , identifier[target] ,** identifier[kwargs] ):
literal[string]
identifier[source] = identifier[urlparse] . identifier[urlparse] ( identifier[url] ). identifier[path]
keyword[if] identifier[... | def image_import(cls, image_name, url, target, **kwargs):
"""Import image from remote host to local image repository using scp.
If remote_host not specified, it means the source file exist in local
file system, just copy the image to image repository
"""
source = urlparse.urlparse(url).p... |
def get_diadefs(self, project, linker):
"""Get the diagrams configuration data
:param project:The pyreverse project
:type project: pyreverse.utils.Project
:param linker: The linker
:type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisitor)
:returns: The l... | def function[get_diadefs, parameter[self, project, linker]]:
constant[Get the diagrams configuration data
:param project:The pyreverse project
:type project: pyreverse.utils.Project
:param linker: The linker
:type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisito... | keyword[def] identifier[get_diadefs] ( identifier[self] , identifier[project] , identifier[linker] ):
literal[string]
identifier[diagrams] =[]
identifier[generator] = identifier[ClassDiadefGenerator] ( identifier[linker] , identifier[self] )
keyword[for] identifier[klas... | def get_diadefs(self, project, linker):
"""Get the diagrams configuration data
:param project:The pyreverse project
:type project: pyreverse.utils.Project
:param linker: The linker
:type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisitor)
:returns: The list ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.