code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def asyncPipeSubstr(context=None, _INPUT=None, conf=None, **kwargs):
"""A string module that asynchronously returns a substring. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items or strings
conf : {
'from': {'type': 'number', va... | def function[asyncPipeSubstr, parameter[context, _INPUT, conf]]:
constant[A string module that asynchronously returns a substring. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items or strings
conf : {
'from': {'type': 'numbe... | keyword[def] identifier[asyncPipeSubstr] ( identifier[context] = keyword[None] , identifier[_INPUT] = keyword[None] , identifier[conf] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[conf] [ literal[string] ]= identifier[conf] . identifier[pop] ( literal[string] , identifier[dict] . id... | def asyncPipeSubstr(context=None, _INPUT=None, conf=None, **kwargs):
"""A string module that asynchronously returns a substring. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items or strings
conf : {
'from': {'type': 'number', va... |
def error(self, *args):
"""Log an error. By default this will also raise an exception."""
if _canShortcutLogging(self.logCategory, ERROR):
return
errorObject(self.logObjectName(), self.logCategory,
*self.logFunction(*args)) | def function[error, parameter[self]]:
constant[Log an error. By default this will also raise an exception.]
if call[name[_canShortcutLogging], parameter[name[self].logCategory, name[ERROR]]] begin[:]
return[None]
call[name[errorObject], parameter[call[name[self].logObjectName, parameter... | keyword[def] identifier[error] ( identifier[self] ,* identifier[args] ):
literal[string]
keyword[if] identifier[_canShortcutLogging] ( identifier[self] . identifier[logCategory] , identifier[ERROR] ):
keyword[return]
identifier[errorObject] ( identifier[self] . identifier[lo... | def error(self, *args):
"""Log an error. By default this will also raise an exception."""
if _canShortcutLogging(self.logCategory, ERROR):
return # depends on [control=['if'], data=[]]
errorObject(self.logObjectName(), self.logCategory, *self.logFunction(*args)) |
def _validate_unique(self, create=True):
""" Validate the unique constraints for the entity """
# Build the filters from the unique constraints
filters, excludes = {}, {}
for field_name, field_obj in self.meta_.unique_fields:
lookup_value = getattr(self, field_name, None)
... | def function[_validate_unique, parameter[self, create]]:
constant[ Validate the unique constraints for the entity ]
<ast.Tuple object at 0x7da1b195c790> assign[=] tuple[[<ast.Dict object at 0x7da1b195c610>, <ast.Dict object at 0x7da1b195ea70>]]
for taget[tuple[[<ast.Name object at 0x7da1b195c460... | keyword[def] identifier[_validate_unique] ( identifier[self] , identifier[create] = keyword[True] ):
literal[string]
identifier[filters] , identifier[excludes] ={},{}
keyword[for] identifier[field_name] , identifier[field_obj] keyword[in] identifier[self] . identifier[meta_] .... | def _validate_unique(self, create=True):
""" Validate the unique constraints for the entity """
# Build the filters from the unique constraints
(filters, excludes) = ({}, {})
for (field_name, field_obj) in self.meta_.unique_fields:
lookup_value = getattr(self, field_name, None)
# Ignore ... |
def url(self):
"""
We will always check if this song file exists in local library,
if true, we return the url of the local file.
.. note::
As netease song url will be expired after a period of time,
we can not use static url here. Currently, we assume that the
... | def function[url, parameter[self]]:
constant[
We will always check if this song file exists in local library,
if true, we return the url of the local file.
.. note::
As netease song url will be expired after a period of time,
we can not use static url here. Curr... | keyword[def] identifier[url] ( identifier[self] ):
literal[string]
identifier[local_path] = identifier[self] . identifier[_find_in_local] ()
keyword[if] identifier[local_path] :
keyword[return] identifier[local_path]
keyword[if] keyword[not] identifier[self] . i... | def url(self):
"""
We will always check if this song file exists in local library,
if true, we return the url of the local file.
.. note::
As netease song url will be expired after a period of time,
we can not use static url here. Currently, we assume that the
... |
def get_by_oid(self, *oid):
"""SNMP simple request (list of OID).
One request per OID list.
* oid: oid list
> Return a dict
"""
if self.version == '3':
errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd(
cmdgen.UsmUserDat... | def function[get_by_oid, parameter[self]]:
constant[SNMP simple request (list of OID).
One request per OID list.
* oid: oid list
> Return a dict
]
if compare[name[self].version equal[==] constant[3]] begin[:]
<ast.Tuple object at 0x7da18f09ece0> assign[=... | keyword[def] identifier[get_by_oid] ( identifier[self] ,* identifier[oid] ):
literal[string]
keyword[if] identifier[self] . identifier[version] == literal[string] :
identifier[errorIndication] , identifier[errorStatus] , identifier[errorIndex] , identifier[varBinds] = identifier[self]... | def get_by_oid(self, *oid):
"""SNMP simple request (list of OID).
One request per OID list.
* oid: oid list
> Return a dict
"""
if self.version == '3':
(errorIndication, errorStatus, errorIndex, varBinds) = self.cmdGen.getCmd(cmdgen.UsmUserData(self.user, self.auth), cm... |
def load_file(self):
"""
Loads SAR format logfile in ASCII format (sarXX).
:return: ``True`` if loading and parsing of file went fine, \
``False`` if it failed (at any point)
"""
# We first split file into pieces
searchunks = self._split_file()
i... | def function[load_file, parameter[self]]:
constant[
Loads SAR format logfile in ASCII format (sarXX).
:return: ``True`` if loading and parsing of file went fine, ``False`` if it failed (at any point)
]
variable[searchunks] assign[=] call[name[self]._split_file, pa... | keyword[def] identifier[load_file] ( identifier[self] ):
literal[string]
identifier[searchunks] = identifier[self] . identifier[_split_file] ()
keyword[if] identifier[searchunks] :
identifier[usage] = identifier[self] . identifier[_parse_file] ( identifie... | def load_file(self):
"""
Loads SAR format logfile in ASCII format (sarXX).
:return: ``True`` if loading and parsing of file went fine, ``False`` if it failed (at any point)
"""
# We first split file into pieces
searchunks = self._split_file()
if searchunks:
... |
def parse(md, model, encoding='utf-8', config=None):
"""
Translate the Versa Markdown syntax into Versa model relationships
md -- markdown source text
model -- Versa model to take the output relationship
encoding -- character encoding (defaults to UTF-8)
Returns: The overall base URI (`@base`)... | def function[parse, parameter[md, model, encoding, config]]:
constant[
Translate the Versa Markdown syntax into Versa model relationships
md -- markdown source text
model -- Versa model to take the output relationship
encoding -- character encoding (defaults to UTF-8)
Returns: The overall ... | keyword[def] identifier[parse] ( identifier[md] , identifier[model] , identifier[encoding] = literal[string] , identifier[config] = keyword[None] ):
literal[string]
identifier[config] = identifier[config] keyword[or] {}
identifier[syntaxtypemap] ={}
keyword[if] identifier[config] . id... | def parse(md, model, encoding='utf-8', config=None):
"""
Translate the Versa Markdown syntax into Versa model relationships
md -- markdown source text
model -- Versa model to take the output relationship
encoding -- character encoding (defaults to UTF-8)
Returns: The overall base URI (`@base`)... |
def parse(self, xml_data):
""" Parse XML data """
# parse tree
if isinstance(xml_data, string_types):
# Presumably, this is textual xml data.
try:
root = ET.fromstring(xml_data)
except StdlibParseError as e:
raise ParseError(st... | def function[parse, parameter[self, xml_data]]:
constant[ Parse XML data ]
if call[name[isinstance], parameter[name[xml_data], name[string_types]]] begin[:]
<ast.Try object at 0x7da1b1da2ef0>
if compare[constant[type] in name[root].attrib] begin[:]
name[self].kind assign[... | keyword[def] identifier[parse] ( identifier[self] , identifier[xml_data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[xml_data] , identifier[string_types] ):
keyword[try] :
identifier[root] = identifier[ET] . identifier[fromstr... | def parse(self, xml_data):
""" Parse XML data """
# parse tree
if isinstance(xml_data, string_types):
# Presumably, this is textual xml data.
try:
root = ET.fromstring(xml_data) # depends on [control=['try'], data=[]]
except StdlibParseError as e:
raise Parse... |
def u(d):
"""
convert string, string container or unicode
:param d:
:return:
"""
if six.PY2:
if isinstance(d, six.binary_type):
return d.decode("utf8", "ignore")
elif isinstance(d, list):
return [u(x) for x in d]
elif isinstance(d, tuple):
... | def function[u, parameter[d]]:
constant[
convert string, string container or unicode
:param d:
:return:
]
if name[six].PY2 begin[:]
if call[name[isinstance], parameter[name[d], name[six].binary_type]] begin[:]
return[call[name[d].decode, parameter[constant[utf... | keyword[def] identifier[u] ( identifier[d] ):
literal[string]
keyword[if] identifier[six] . identifier[PY2] :
keyword[if] identifier[isinstance] ( identifier[d] , identifier[six] . identifier[binary_type] ):
keyword[return] identifier[d] . identifier[decode] ( literal[string] , lit... | def u(d):
"""
convert string, string container or unicode
:param d:
:return:
"""
if six.PY2:
if isinstance(d, six.binary_type):
return d.decode('utf8', 'ignore') # depends on [control=['if'], data=[]]
elif isinstance(d, list):
return [u(x) for x in d] # ... |
def _set_flow_id(self, v, load=False):
"""
Setter method for flow_id, mapped from YANG variable /openflow_state/flow_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_flow_id is considered as a private
method. Backends looking to populate this variable s... | def function[_set_flow_id, parameter[self, v, load]]:
constant[
Setter method for flow_id, mapped from YANG variable /openflow_state/flow_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_flow_id is considered as a private
method. Backends looking to... | keyword[def] identifier[_set_flow_id] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identi... | def _set_flow_id(self, v, load=False):
"""
Setter method for flow_id, mapped from YANG variable /openflow_state/flow_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_flow_id is considered as a private
method. Backends looking to populate this variable s... |
def _do_create_list_action(act, kw):
"""A factory for list actions. Convert the input list into Actions
and then wrap them in a ListAction."""
acts = []
for a in act:
aa = _do_create_action(a, kw)
if aa is not None: acts.append(aa)
if not acts:
return ListAction([])
elif... | def function[_do_create_list_action, parameter[act, kw]]:
constant[A factory for list actions. Convert the input list into Actions
and then wrap them in a ListAction.]
variable[acts] assign[=] list[[]]
for taget[name[a]] in starred[name[act]] begin[:]
variable[aa] assign[=] ... | keyword[def] identifier[_do_create_list_action] ( identifier[act] , identifier[kw] ):
literal[string]
identifier[acts] =[]
keyword[for] identifier[a] keyword[in] identifier[act] :
identifier[aa] = identifier[_do_create_action] ( identifier[a] , identifier[kw] )
keyword[if] identi... | def _do_create_list_action(act, kw):
"""A factory for list actions. Convert the input list into Actions
and then wrap them in a ListAction."""
acts = []
for a in act:
aa = _do_create_action(a, kw)
if aa is not None:
acts.append(aa) # depends on [control=['if'], data=['aa']]... |
def declare_directory(self, value): # type: (MutableMapping) -> ProvEntity
"""Register any nested files/directories."""
# FIXME: Calculate a hash-like identifier for directory
# so we get same value if it's the same filenames/hashes
# in a different location.
# For now, mint a n... | def function[declare_directory, parameter[self, value]]:
constant[Register any nested files/directories.]
variable[dir_id] assign[=] call[name[value].setdefault, parameter[constant[@id], call[name[uuid].uuid4, parameter[]].urn]]
variable[ore_doc_fn] assign[=] binary_operation[call[name[dir_id].r... | keyword[def] identifier[declare_directory] ( identifier[self] , identifier[value] ):
literal[string]
identifier[dir_id] = identifier[value] . identifier[setdefault] ( literal[string] , identifier[uuid] . identifier[uuid4] (). identifier[urn] )
... | def declare_directory(self, value): # type: (MutableMapping) -> ProvEntity
'Register any nested files/directories.'
# FIXME: Calculate a hash-like identifier for directory
# so we get same value if it's the same filenames/hashes
# in a different location.
# For now, mint a new UUID to identify this... |
def _set_scroll_v(self, *args):
"""Scroll both categories Canvas and scrolling container"""
self._canvas_categories.yview(*args)
self._canvas_scroll.yview(*args) | def function[_set_scroll_v, parameter[self]]:
constant[Scroll both categories Canvas and scrolling container]
call[name[self]._canvas_categories.yview, parameter[<ast.Starred object at 0x7da1b23c6e90>]]
call[name[self]._canvas_scroll.yview, parameter[<ast.Starred object at 0x7da1b1d4b1c0>]] | keyword[def] identifier[_set_scroll_v] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[self] . identifier[_canvas_categories] . identifier[yview] (* identifier[args] )
identifier[self] . identifier[_canvas_scroll] . identifier[yview] (* identifier[args] ) | def _set_scroll_v(self, *args):
"""Scroll both categories Canvas and scrolling container"""
self._canvas_categories.yview(*args)
self._canvas_scroll.yview(*args) |
def MOVS(cpu, dest, src):
"""
Moves data from string to string.
Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified
with the first operand (destination operand). Both the source and destination operands are located in memory. ... | def function[MOVS, parameter[cpu, dest, src]]:
constant[
Moves data from string to string.
Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified
with the first operand (destination operand). Both the source and destination opera... | keyword[def] identifier[MOVS] ( identifier[cpu] , identifier[dest] , identifier[src] ):
literal[string]
identifier[base] , identifier[size] , identifier[ty] = identifier[cpu] . identifier[get_descriptor] ( identifier[cpu] . identifier[DS] )
identifier[src_addr] = identifier[src] . identifi... | def MOVS(cpu, dest, src):
"""
Moves data from string to string.
Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified
with the first operand (destination operand). Both the source and destination operands are located in memory. The
... |
def add_bpmn_files(self, filenames):
"""
Add all filenames in the given list to the parser's set.
"""
for filename in filenames:
f = open(filename, 'r')
try:
self.add_bpmn_xml(ET.parse(f), filename=filename)
finally:
f.c... | def function[add_bpmn_files, parameter[self, filenames]]:
constant[
Add all filenames in the given list to the parser's set.
]
for taget[name[filename]] in starred[name[filenames]] begin[:]
variable[f] assign[=] call[name[open], parameter[name[filename], constant[r]]]
... | keyword[def] identifier[add_bpmn_files] ( identifier[self] , identifier[filenames] ):
literal[string]
keyword[for] identifier[filename] keyword[in] identifier[filenames] :
identifier[f] = identifier[open] ( identifier[filename] , literal[string] )
keyword[try] :
... | def add_bpmn_files(self, filenames):
"""
Add all filenames in the given list to the parser's set.
"""
for filename in filenames:
f = open(filename, 'r')
try:
self.add_bpmn_xml(ET.parse(f), filename=filename) # depends on [control=['try'], data=[]]
finally:
... |
def add_pattern(self, pattern, category=SourceRootCategories.UNKNOWN):
"""Add a pattern to the trie."""
self._do_add_pattern(pattern, tuple(), category) | def function[add_pattern, parameter[self, pattern, category]]:
constant[Add a pattern to the trie.]
call[name[self]._do_add_pattern, parameter[name[pattern], call[name[tuple], parameter[]], name[category]]] | keyword[def] identifier[add_pattern] ( identifier[self] , identifier[pattern] , identifier[category] = identifier[SourceRootCategories] . identifier[UNKNOWN] ):
literal[string]
identifier[self] . identifier[_do_add_pattern] ( identifier[pattern] , identifier[tuple] (), identifier[category] ) | def add_pattern(self, pattern, category=SourceRootCategories.UNKNOWN):
"""Add a pattern to the trie."""
self._do_add_pattern(pattern, tuple(), category) |
def create_item(self, **kwargs):
"""
Return a model instance created from kwargs.
"""
item, created = self.queryset.model.objects.get_or_create(**kwargs)
return item | def function[create_item, parameter[self]]:
constant[
Return a model instance created from kwargs.
]
<ast.Tuple object at 0x7da18c4cf250> assign[=] call[name[self].queryset.model.objects.get_or_create, parameter[]]
return[name[item]] | keyword[def] identifier[create_item] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[item] , identifier[created] = identifier[self] . identifier[queryset] . identifier[model] . identifier[objects] . identifier[get_or_create] (** identifier[kwargs] )
keyword[return] ... | def create_item(self, **kwargs):
"""
Return a model instance created from kwargs.
"""
(item, created) = self.queryset.model.objects.get_or_create(**kwargs)
return item |
def _get_role_arn():
"""
Return role arn from X-Role-ARN header,
lookup role arn from source IP,
or fall back to command line default.
"""
role_arn = bottle.request.headers.get('X-Role-ARN')
if not role_arn:
role_arn = _lookup_ip_role_arn(bottle.request.environ.get('REMOTE_ADDR'))
... | def function[_get_role_arn, parameter[]]:
constant[
Return role arn from X-Role-ARN header,
lookup role arn from source IP,
or fall back to command line default.
]
variable[role_arn] assign[=] call[name[bottle].request.headers.get, parameter[constant[X-Role-ARN]]]
if <ast.UnaryOp... | keyword[def] identifier[_get_role_arn] ():
literal[string]
identifier[role_arn] = identifier[bottle] . identifier[request] . identifier[headers] . identifier[get] ( literal[string] )
keyword[if] keyword[not] identifier[role_arn] :
identifier[role_arn] = identifier[_lookup_ip_role_arn] ( ide... | def _get_role_arn():
"""
Return role arn from X-Role-ARN header,
lookup role arn from source IP,
or fall back to command line default.
"""
role_arn = bottle.request.headers.get('X-Role-ARN')
if not role_arn:
role_arn = _lookup_ip_role_arn(bottle.request.environ.get('REMOTE_ADDR')) #... |
def adet(z, x):
"""d|A|/dA = adj(A).T
See Jacobi's formula: https://en.wikipedia.org/wiki/Jacobi%27s_formula
"""
adjugate = numpy.linalg.det(x) * numpy.linalg.pinv(x)
d[x] = d[z] * numpy.transpose(adjugate) | def function[adet, parameter[z, x]]:
constant[d|A|/dA = adj(A).T
See Jacobi's formula: https://en.wikipedia.org/wiki/Jacobi%27s_formula
]
variable[adjugate] assign[=] binary_operation[call[name[numpy].linalg.det, parameter[name[x]]] * call[name[numpy].linalg.pinv, parameter[name[x]]]]
call... | keyword[def] identifier[adet] ( identifier[z] , identifier[x] ):
literal[string]
identifier[adjugate] = identifier[numpy] . identifier[linalg] . identifier[det] ( identifier[x] )* identifier[numpy] . identifier[linalg] . identifier[pinv] ( identifier[x] )
identifier[d] [ identifier[x] ]= identifier[d] [ ide... | def adet(z, x):
"""d|A|/dA = adj(A).T
See Jacobi's formula: https://en.wikipedia.org/wiki/Jacobi%27s_formula
"""
adjugate = numpy.linalg.det(x) * numpy.linalg.pinv(x)
d[x] = d[z] * numpy.transpose(adjugate) |
def set_points(self, pt1, pt2):
"""Reset the rectangle coordinates."""
(x1, y1) = pt1.as_tuple()
(x2, y2) = pt2.as_tuple()
self.left = min(x1, x2)
self.top = min(y1, y2)
self.right = max(x1, x2)
self.bottom = max(y1, y2) | def function[set_points, parameter[self, pt1, pt2]]:
constant[Reset the rectangle coordinates.]
<ast.Tuple object at 0x7da18fe93340> assign[=] call[name[pt1].as_tuple, parameter[]]
<ast.Tuple object at 0x7da18fe913c0> assign[=] call[name[pt2].as_tuple, parameter[]]
name[self].left assign... | keyword[def] identifier[set_points] ( identifier[self] , identifier[pt1] , identifier[pt2] ):
literal[string]
( identifier[x1] , identifier[y1] )= identifier[pt1] . identifier[as_tuple] ()
( identifier[x2] , identifier[y2] )= identifier[pt2] . identifier[as_tuple] ()
identifier[self... | def set_points(self, pt1, pt2):
"""Reset the rectangle coordinates."""
(x1, y1) = pt1.as_tuple()
(x2, y2) = pt2.as_tuple()
self.left = min(x1, x2)
self.top = min(y1, y2)
self.right = max(x1, x2)
self.bottom = max(y1, y2) |
def download(self, source, target, mpi=None, pos=0, chunk=0, part=0):
'''Thread worker for download operation.'''
s3url = S3URL(source)
obj = self.lookup(s3url)
if obj is None:
raise Failure('The obj "%s" does not exists.' % (s3url.path,))
# Initialization: Set up multithreaded downloads.
... | def function[download, parameter[self, source, target, mpi, pos, chunk, part]]:
constant[Thread worker for download operation.]
variable[s3url] assign[=] call[name[S3URL], parameter[name[source]]]
variable[obj] assign[=] call[name[self].lookup, parameter[name[s3url]]]
if compare[name[obj... | keyword[def] identifier[download] ( identifier[self] , identifier[source] , identifier[target] , identifier[mpi] = keyword[None] , identifier[pos] = literal[int] , identifier[chunk] = literal[int] , identifier[part] = literal[int] ):
literal[string]
identifier[s3url] = identifier[S3URL] ( identifier[source... | def download(self, source, target, mpi=None, pos=0, chunk=0, part=0):
"""Thread worker for download operation."""
s3url = S3URL(source)
obj = self.lookup(s3url)
if obj is None:
raise Failure('The obj "%s" does not exists.' % (s3url.path,)) # depends on [control=['if'], data=[]]
# Initializa... |
def _extract_mask_distance(image, mask = slice(None), voxelspacing = None):
"""
Internal, single-image version of `mask_distance`.
"""
if isinstance(mask, slice):
mask = numpy.ones(image.shape, numpy.bool)
distance_map = distance_transform_edt(mask, sampling=voxelspacing)
retur... | def function[_extract_mask_distance, parameter[image, mask, voxelspacing]]:
constant[
Internal, single-image version of `mask_distance`.
]
if call[name[isinstance], parameter[name[mask], name[slice]]] begin[:]
variable[mask] assign[=] call[name[numpy].ones, parameter[name[image].... | keyword[def] identifier[_extract_mask_distance] ( identifier[image] , identifier[mask] = identifier[slice] ( keyword[None] ), identifier[voxelspacing] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[mask] , identifier[slice] ):
identifier[mask] = identifier[nump... | def _extract_mask_distance(image, mask=slice(None), voxelspacing=None):
"""
Internal, single-image version of `mask_distance`.
"""
if isinstance(mask, slice):
mask = numpy.ones(image.shape, numpy.bool) # depends on [control=['if'], data=[]]
distance_map = distance_transform_edt(mask, sampli... |
def parse(file_path, content=None):
"""
Create a PythonFile object with specified file_path and content.
If content is None then, it is loaded from the file_path method.
Otherwise, file_path is only used for reporting errors.
"""
try:
if content is None:
... | def function[parse, parameter[file_path, content]]:
constant[
Create a PythonFile object with specified file_path and content.
If content is None then, it is loaded from the file_path method.
Otherwise, file_path is only used for reporting errors.
]
<ast.Try object at 0x7da1b... | keyword[def] identifier[parse] ( identifier[file_path] , identifier[content] = keyword[None] ):
literal[string]
keyword[try] :
keyword[if] identifier[content] keyword[is] keyword[None] :
keyword[with] identifier[open] ( identifier[file_path] ) keyword[as] identifi... | def parse(file_path, content=None):
"""
Create a PythonFile object with specified file_path and content.
If content is None then, it is loaded from the file_path method.
Otherwise, file_path is only used for reporting errors.
"""
try:
if content is None:
with ... |
def accounts_frontiers(self, accounts):
"""
Returns a list of pairs of account and block hash representing the
head block for **accounts** list
:param accounts: Accounts to return frontier blocks for
:type accounts: list of str
:raises: :py:exc:`nano.rpc.RPCException`
... | def function[accounts_frontiers, parameter[self, accounts]]:
constant[
Returns a list of pairs of account and block hash representing the
head block for **accounts** list
:param accounts: Accounts to return frontier blocks for
:type accounts: list of str
:raises: :py:ex... | keyword[def] identifier[accounts_frontiers] ( identifier[self] , identifier[accounts] ):
literal[string]
identifier[accounts] = identifier[self] . identifier[_process_value] ( identifier[accounts] , literal[string] )
identifier[payload] ={ literal[string] : identifier[accounts] }
... | def accounts_frontiers(self, accounts):
"""
Returns a list of pairs of account and block hash representing the
head block for **accounts** list
:param accounts: Accounts to return frontier blocks for
:type accounts: list of str
:raises: :py:exc:`nano.rpc.RPCException`
... |
def checkIfEmailWasHacked(email=None, sleepSeconds=1):
"""
Method that checks if the given email is stored in the HIBP website.
This function automatically waits a second to avoid problems with the API
rate limit. An example of the json received:
```
[{"Title":"Adobe","Name":"Adobe","Domain... | def function[checkIfEmailWasHacked, parameter[email, sleepSeconds]]:
constant[
Method that checks if the given email is stored in the HIBP website.
This function automatically waits a second to avoid problems with the API
rate limit. An example of the json received:
```
[{"Title":"Adobe... | keyword[def] identifier[checkIfEmailWasHacked] ( identifier[email] = keyword[None] , identifier[sleepSeconds] = literal[int] ):
literal[string]
identifier[time] . identifier[sleep] ( identifier[sleepSeconds] )
identifier[print] ( literal[string] )
identifier[ua] = literal[string]
iden... | def checkIfEmailWasHacked(email=None, sleepSeconds=1):
"""
Method that checks if the given email is stored in the HIBP website.
This function automatically waits a second to avoid problems with the API
rate limit. An example of the json received:
```
[{"Title":"Adobe","Name":"Adobe","Domain... |
def _extract_axes_for_slice(self, axes):
"""
Return the slice dictionary for these axes.
"""
return {self._AXIS_SLICEMAP[i]: a for i, a in
zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)} | def function[_extract_axes_for_slice, parameter[self, axes]]:
constant[
Return the slice dictionary for these axes.
]
return[<ast.DictComp object at 0x7da1b2346da0>] | keyword[def] identifier[_extract_axes_for_slice] ( identifier[self] , identifier[axes] ):
literal[string]
keyword[return] { identifier[self] . identifier[_AXIS_SLICEMAP] [ identifier[i] ]: identifier[a] keyword[for] identifier[i] , identifier[a] keyword[in]
identifier[zip] ( identifier... | def _extract_axes_for_slice(self, axes):
"""
Return the slice dictionary for these axes.
"""
return {self._AXIS_SLICEMAP[i]: a for (i, a) in zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)} |
def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = (not ... | def function[_add_assert, parameter[self]]:
constant[
if screenshot is None, only failed case will take screenshot
]
variable[screenshot] assign[=] call[name[kwargs].get, parameter[constant[screenshot]]]
variable[is_success] assign[=] call[name[kwargs].get, parameter[constant[suc... | keyword[def] identifier[_add_assert] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[screenshot] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[is_success] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier... | def _add_assert(self, **kwargs):
"""
if screenshot is None, only failed case will take screenshot
"""
# convert screenshot to relative path from <None|True|False|PIL.Image>
screenshot = kwargs.get('screenshot')
is_success = kwargs.get('success')
screenshot = not is_success if screens... |
def update(self, portfolio, date, perfs=None):
'''
Actualizes the portfolio universe with the alog state
'''
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date | def function[update, parameter[self, portfolio, date, perfs]]:
constant[
Actualizes the portfolio universe with the alog state
]
name[self].portfolio assign[=] name[portfolio]
name[self].perfs assign[=] name[perfs]
name[self].date assign[=] name[date] | keyword[def] identifier[update] ( identifier[self] , identifier[portfolio] , identifier[date] , identifier[perfs] = keyword[None] ):
literal[string]
identifier[self] . identifier[portfolio] = identifier[portfolio]
identifier[self] . identifier[perfs] = identifier[perfs]
... | def update(self, portfolio, date, perfs=None):
"""
Actualizes the portfolio universe with the alog state
"""
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date |
def rpc(ctx, call, arguments, api):
""" Construct RPC call directly
\b
You can specify which API to send the call to:
peerplays rpc --api bookie get_matched_bets_for_bettor 1.2.0
You can also specify lists using
peerplays rpc get_objects "['2.0.0', '2.1.0']"
"... | def function[rpc, parameter[ctx, call, arguments, api]]:
constant[ Construct RPC call directly
You can specify which API to send the call to:
peerplays rpc --api bookie get_matched_bets_for_bettor 1.2.0
You can also specify lists using
peerplays rpc get_objec... | keyword[def] identifier[rpc] ( identifier[ctx] , identifier[call] , identifier[arguments] , identifier[api] ):
literal[string]
keyword[try] :
identifier[data] = identifier[list] ( identifier[eval] ( identifier[d] ) keyword[for] identifier[d] keyword[in] identifier[arguments] )
keyword[exce... | def rpc(ctx, call, arguments, api):
""" Construct RPC call directly
\x08
You can specify which API to send the call to:
peerplays rpc --api bookie get_matched_bets_for_bettor 1.2.0
You can also specify lists using
peerplays rpc get_objects "['2.0.0', '2.1.0']"
... |
def clear_lock(self, abspath=True):
"""Clean any conda lock in the system."""
cmd_list = ['clean', '--lock', '--json']
return self._call_and_parse(cmd_list, abspath=abspath) | def function[clear_lock, parameter[self, abspath]]:
constant[Clean any conda lock in the system.]
variable[cmd_list] assign[=] list[[<ast.Constant object at 0x7da1b272f760>, <ast.Constant object at 0x7da1b2845660>, <ast.Constant object at 0x7da1b2844880>]]
return[call[name[self]._call_and_parse, par... | keyword[def] identifier[clear_lock] ( identifier[self] , identifier[abspath] = keyword[True] ):
literal[string]
identifier[cmd_list] =[ literal[string] , literal[string] , literal[string] ]
keyword[return] identifier[self] . identifier[_call_and_parse] ( identifier[cmd_list] , identifier[... | def clear_lock(self, abspath=True):
"""Clean any conda lock in the system."""
cmd_list = ['clean', '--lock', '--json']
return self._call_and_parse(cmd_list, abspath=abspath) |
def argmaxMulti(a, groupKeys, assumeSorted=False):
"""
This is like numpy's argmax, but it returns multiple maximums.
It gets the indices of the max values of each group in 'a', grouping the
elements by their corresponding value in 'groupKeys'.
@param a (numpy array)
An array of values that will be compar... | def function[argmaxMulti, parameter[a, groupKeys, assumeSorted]]:
constant[
This is like numpy's argmax, but it returns multiple maximums.
It gets the indices of the max values of each group in 'a', grouping the
elements by their corresponding value in 'groupKeys'.
@param a (numpy array)
An array of... | keyword[def] identifier[argmaxMulti] ( identifier[a] , identifier[groupKeys] , identifier[assumeSorted] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[assumeSorted] :
identifier[sorter] = identifier[np] . identifier[argsort] ( identifier[groupKeys] , identifier[kind] = liter... | def argmaxMulti(a, groupKeys, assumeSorted=False):
"""
This is like numpy's argmax, but it returns multiple maximums.
It gets the indices of the max values of each group in 'a', grouping the
elements by their corresponding value in 'groupKeys'.
@param a (numpy array)
An array of values that will be comp... |
def clamp(value, lower=0, upper=sys.maxsize):
"""Clamp float between given range"""
return max(lower, min(upper, value)) | def function[clamp, parameter[value, lower, upper]]:
constant[Clamp float between given range]
return[call[name[max], parameter[name[lower], call[name[min], parameter[name[upper], name[value]]]]]] | keyword[def] identifier[clamp] ( identifier[value] , identifier[lower] = literal[int] , identifier[upper] = identifier[sys] . identifier[maxsize] ):
literal[string]
keyword[return] identifier[max] ( identifier[lower] , identifier[min] ( identifier[upper] , identifier[value] )) | def clamp(value, lower=0, upper=sys.maxsize):
"""Clamp float between given range"""
return max(lower, min(upper, value)) |
def put(self, storagemodel:object, modeldefinition = None) -> StorageQueueModel:
""" insert queue message into storage """
try:
message = modeldefinition['queueservice'].put_message(storagemodel._queuename, storagemodel.getmessage())
storagemodel.mergemessage(message)
ex... | def function[put, parameter[self, storagemodel, modeldefinition]]:
constant[ insert queue message into storage ]
<ast.Try object at 0x7da20e954550> | keyword[def] identifier[put] ( identifier[self] , identifier[storagemodel] : identifier[object] , identifier[modeldefinition] = keyword[None] )-> identifier[StorageQueueModel] :
literal[string]
keyword[try] :
identifier[message] = identifier[modeldefinition] [ literal[string] ]. identi... | def put(self, storagemodel: object, modeldefinition=None) -> StorageQueueModel:
""" insert queue message into storage """
try:
message = modeldefinition['queueservice'].put_message(storagemodel._queuename, storagemodel.getmessage())
storagemodel.mergemessage(message) # depends on [control=['try... |
def _clone_properties(self):
"""Internal helper to clone self._properties if necessary."""
cls = self.__class__
if self._properties is cls._properties:
self._properties = dict(cls._properties) | def function[_clone_properties, parameter[self]]:
constant[Internal helper to clone self._properties if necessary.]
variable[cls] assign[=] name[self].__class__
if compare[name[self]._properties is name[cls]._properties] begin[:]
name[self]._properties assign[=] call[name[dict], ... | keyword[def] identifier[_clone_properties] ( identifier[self] ):
literal[string]
identifier[cls] = identifier[self] . identifier[__class__]
keyword[if] identifier[self] . identifier[_properties] keyword[is] identifier[cls] . identifier[_properties] :
identifier[self] . identifier[_propertie... | def _clone_properties(self):
"""Internal helper to clone self._properties if necessary."""
cls = self.__class__
if self._properties is cls._properties:
self._properties = dict(cls._properties) # depends on [control=['if'], data=[]] |
def landweber(op, x, rhs, niter, omega=None, projection=None, callback=None):
r"""Optimized implementation of Landweber's method.
Solves the inverse problem::
A(x) = rhs
Parameters
----------
op : `Operator`
Operator in the inverse problem. ``op.derivative(x).adjoint`` must be
... | def function[landweber, parameter[op, x, rhs, niter, omega, projection, callback]]:
constant[Optimized implementation of Landweber's method.
Solves the inverse problem::
A(x) = rhs
Parameters
----------
op : `Operator`
Operator in the inverse problem. ``op.derivative(x).adjoin... | keyword[def] identifier[landweber] ( identifier[op] , identifier[x] , identifier[rhs] , identifier[niter] , identifier[omega] = keyword[None] , identifier[projection] = keyword[None] , identifier[callback] = keyword[None] ):
literal[string]
keyword[if] identifier[x] keyword[not] keyword[in] ident... | def landweber(op, x, rhs, niter, omega=None, projection=None, callback=None):
"""Optimized implementation of Landweber's method.
Solves the inverse problem::
A(x) = rhs
Parameters
----------
op : `Operator`
Operator in the inverse problem. ``op.derivative(x).adjoint`` must be
... |
def _validate_message_type(self):
"""Check to see if the current message's AMQP type property is
supported and if not, raise either a :exc:`DropMessage` or
:exc:`MessageException`.
:raises: DropMessage
:raises: MessageException
"""
if self._unsupported_message_t... | def function[_validate_message_type, parameter[self]]:
constant[Check to see if the current message's AMQP type property is
supported and if not, raise either a :exc:`DropMessage` or
:exc:`MessageException`.
:raises: DropMessage
:raises: MessageException
]
if ca... | keyword[def] identifier[_validate_message_type] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_unsupported_message_type] ():
identifier[self] . identifier[logger] . identifier[warning] (
literal[string] , identifier[self] . identifier[mes... | def _validate_message_type(self):
"""Check to see if the current message's AMQP type property is
supported and if not, raise either a :exc:`DropMessage` or
:exc:`MessageException`.
:raises: DropMessage
:raises: MessageException
"""
if self._unsupported_message_type():
... |
def ismount(self, path):
"""Return true if the given path is a mount point.
Args:
path: Path to filesystem object to be checked
Returns:
`True` if path is a mount point added to the fake file system.
Under Windows also returns True for drive and UNC roots
... | def function[ismount, parameter[self, path]]:
constant[Return true if the given path is a mount point.
Args:
path: Path to filesystem object to be checked
Returns:
`True` if path is a mount point added to the fake file system.
Under Windows also returns True... | keyword[def] identifier[ismount] ( identifier[self] , identifier[path] ):
literal[string]
identifier[path] = identifier[make_string_path] ( identifier[path] )
keyword[if] keyword[not] identifier[path] :
keyword[return] keyword[False]
identifier[normed_path] = iden... | def ismount(self, path):
"""Return true if the given path is a mount point.
Args:
path: Path to filesystem object to be checked
Returns:
`True` if path is a mount point added to the fake file system.
Under Windows also returns True for drive and UNC roots
... |
def __cancel(self, subscription_id, **kwargs):
"""Call documentation: `/subscription/cancel
<https://www.wepay.com/developer/reference/subscription#cancel>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``... | def function[__cancel, parameter[self, subscription_id]]:
constant[Call documentation: `/subscription/cancel
<https://www.wepay.com/developer/reference/subscription#cancel>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
... | keyword[def] identifier[__cancel] ( identifier[self] , identifier[subscription_id] ,** identifier[kwargs] ):
literal[string]
identifier[params] ={
literal[string] : identifier[subscription_id]
}
keyword[return] identifier[self] . identifier[make_call] ( identifier[self] ... | def __cancel(self, subscription_id, **kwargs):
"""Call documentation: `/subscription/cancel
<https://www.wepay.com/developer/reference/subscription#cancel>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, wi... |
def get_called_sequence(self, section=None, fastq=False):
""" Return either the called sequence data, if present.
:param section: ['template', 'complement' or '2D']
:param fastq: If True, return a single, multiline fastq string. If
False, return a tuple of (name, sequence, qstring).
... | def function[get_called_sequence, parameter[self, section, fastq]]:
constant[ Return either the called sequence data, if present.
:param section: ['template', 'complement' or '2D']
:param fastq: If True, return a single, multiline fastq string. If
False, return a tuple of (name, sequ... | keyword[def] identifier[get_called_sequence] ( identifier[self] , identifier[section] = keyword[None] , identifier[fastq] = keyword[False] ):
literal[string]
keyword[if] identifier[section] != literal[string] :
identifier[warnings] . identifier[warn] ( literal[string] , identifier[Dep... | def get_called_sequence(self, section=None, fastq=False):
""" Return either the called sequence data, if present.
:param section: ['template', 'complement' or '2D']
:param fastq: If True, return a single, multiline fastq string. If
False, return a tuple of (name, sequence, qstring).
... |
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 get_weather(self):
"""
Returns an instance of the Weather Service.
"""
import predix.data.weather
weather = predix.data.weather.WeatherForecast()
return weather | def function[get_weather, parameter[self]]:
constant[
Returns an instance of the Weather Service.
]
import module[predix.data.weather]
variable[weather] assign[=] call[name[predix].data.weather.WeatherForecast, parameter[]]
return[name[weather]] | keyword[def] identifier[get_weather] ( identifier[self] ):
literal[string]
keyword[import] identifier[predix] . identifier[data] . identifier[weather]
identifier[weather] = identifier[predix] . identifier[data] . identifier[weather] . identifier[WeatherForecast] ()
keyword[retur... | def get_weather(self):
"""
Returns an instance of the Weather Service.
"""
import predix.data.weather
weather = predix.data.weather.WeatherForecast()
return weather |
def createPopulationFile(inputFiles, labels, outputFileName):
"""Creates a population file.
:param inputFiles: the list of input files.
:param labels: the list of labels (corresponding to the input files).
:param outputFileName: the name of the output file.
:type inputFiles: list
:type labels:... | def function[createPopulationFile, parameter[inputFiles, labels, outputFileName]]:
constant[Creates a population file.
:param inputFiles: the list of input files.
:param labels: the list of labels (corresponding to the input files).
:param outputFileName: the name of the output file.
:type inp... | keyword[def] identifier[createPopulationFile] ( identifier[inputFiles] , identifier[labels] , identifier[outputFileName] ):
literal[string]
identifier[outputFile] = keyword[None]
keyword[try] :
identifier[outputFile] = identifier[open] ( identifier[outputFileName] , literal[string] )
ke... | def createPopulationFile(inputFiles, labels, outputFileName):
"""Creates a population file.
:param inputFiles: the list of input files.
:param labels: the list of labels (corresponding to the input files).
:param outputFileName: the name of the output file.
:type inputFiles: list
:type labels:... |
def transaction_stop(self):
"""stop/commit a transaction if ready"""
if self.transaction_count > 0:
logger.debug("{}. Stop transaction".format(self.transaction_count))
if self.transaction_count == 1:
self._transaction_stop()
self.transaction_count -= ... | def function[transaction_stop, parameter[self]]:
constant[stop/commit a transaction if ready]
if compare[name[self].transaction_count greater[>] constant[0]] begin[:]
call[name[logger].debug, parameter[call[constant[{}. Stop transaction].format, parameter[name[self].transaction_count]]]]... | keyword[def] identifier[transaction_stop] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[transaction_count] > literal[int] :
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[self] . identifier[transaction_count... | def transaction_stop(self):
"""stop/commit a transaction if ready"""
if self.transaction_count > 0:
logger.debug('{}. Stop transaction'.format(self.transaction_count))
if self.transaction_count == 1:
self._transaction_stop() # depends on [control=['if'], data=[]]
self.transa... |
def _get_consent_id(self, requester, user_id, filtered_attr):
"""
Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling requester
:param user_... | def function[_get_consent_id, parameter[self, requester, user_id, filtered_attr]]:
constant[
Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling req... | keyword[def] identifier[_get_consent_id] ( identifier[self] , identifier[requester] , identifier[user_id] , identifier[filtered_attr] ):
literal[string]
identifier[filtered_attr_key_list] = identifier[sorted] ( identifier[filtered_attr] . identifier[keys] ())
identifier[hash_str] = litera... | def _get_consent_id(self, requester, user_id, filtered_attr):
"""
Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling requester
:param user_id: ... |
def read_array(self, key, start=None, stop=None):
""" read an array for the specified node (off of group """
import tables
node = getattr(self.group, key)
attrs = node._v_attrs
transposed = getattr(attrs, 'transposed', False)
if isinstance(node, tables.VLArray):
... | def function[read_array, parameter[self, key, start, stop]]:
constant[ read an array for the specified node (off of group ]
import module[tables]
variable[node] assign[=] call[name[getattr], parameter[name[self].group, name[key]]]
variable[attrs] assign[=] name[node]._v_attrs
variabl... | keyword[def] identifier[read_array] ( identifier[self] , identifier[key] , identifier[start] = keyword[None] , identifier[stop] = keyword[None] ):
literal[string]
keyword[import] identifier[tables]
identifier[node] = identifier[getattr] ( identifier[self] . identifier[group] , identifier... | def read_array(self, key, start=None, stop=None):
""" read an array for the specified node (off of group """
import tables
node = getattr(self.group, key)
attrs = node._v_attrs
transposed = getattr(attrs, 'transposed', False)
if isinstance(node, tables.VLArray):
ret = node[0][start:stop]... |
def _folder_item_method(self, analysis_brain, item):
"""Fills the analysis' method to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
is_editable = self.is_analysis_edition_allo... | def function[_folder_item_method, parameter[self, analysis_brain, item]]:
constant[Fills the analysis' method to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
]
variable[is_editabl... | keyword[def] identifier[_folder_item_method] ( identifier[self] , identifier[analysis_brain] , identifier[item] ):
literal[string]
identifier[is_editable] = identifier[self] . identifier[is_analysis_edition_allowed] ( identifier[analysis_brain] )
identifier[method_title] = identifier[anal... | def _folder_item_method(self, analysis_brain, item):
"""Fills the analysis' method to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
is_editable = self.is_analysis_edition_allowed(analy... |
def get_dsl_by_hash(self, node_hash: str) -> Optional[BaseEntity]:
"""Look up a node by the hash and returns the corresponding PyBEL node tuple."""
node = self.get_node_by_hash(node_hash)
if node is not None:
return node.as_bel() | def function[get_dsl_by_hash, parameter[self, node_hash]]:
constant[Look up a node by the hash and returns the corresponding PyBEL node tuple.]
variable[node] assign[=] call[name[self].get_node_by_hash, parameter[name[node_hash]]]
if compare[name[node] is_not constant[None]] begin[:]
ret... | keyword[def] identifier[get_dsl_by_hash] ( identifier[self] , identifier[node_hash] : identifier[str] )-> identifier[Optional] [ identifier[BaseEntity] ]:
literal[string]
identifier[node] = identifier[self] . identifier[get_node_by_hash] ( identifier[node_hash] )
keyword[if] identifier[no... | def get_dsl_by_hash(self, node_hash: str) -> Optional[BaseEntity]:
"""Look up a node by the hash and returns the corresponding PyBEL node tuple."""
node = self.get_node_by_hash(node_hash)
if node is not None:
return node.as_bel() # depends on [control=['if'], data=['node']] |
def last_seen_utc(self) -> Optional[datetime]:
"""Timestamp when the story has last been watched or None (UTC)."""
if self._node['seen']:
return datetime.utcfromtimestamp(self._node['seen']) | def function[last_seen_utc, parameter[self]]:
constant[Timestamp when the story has last been watched or None (UTC).]
if call[name[self]._node][constant[seen]] begin[:]
return[call[name[datetime].utcfromtimestamp, parameter[call[name[self]._node][constant[seen]]]]] | keyword[def] identifier[last_seen_utc] ( identifier[self] )-> identifier[Optional] [ identifier[datetime] ]:
literal[string]
keyword[if] identifier[self] . identifier[_node] [ literal[string] ]:
keyword[return] identifier[datetime] . identifier[utcfromtimestamp] ( identifier[self] . ... | def last_seen_utc(self) -> Optional[datetime]:
"""Timestamp when the story has last been watched or None (UTC)."""
if self._node['seen']:
return datetime.utcfromtimestamp(self._node['seen']) # depends on [control=['if'], data=[]] |
def try_wrapper(fxn):
"""Wraps a function, returning (True, fxn(val)) if successful, (False, val) if not."""
def wrapper(val):
"""Try to call fxn with the given value. If successful, return (True, fxn(val)), otherwise
returns (False, val).
"""
try:
return (True, fxn(val))
except Exception:... | def function[try_wrapper, parameter[fxn]]:
constant[Wraps a function, returning (True, fxn(val)) if successful, (False, val) if not.]
def function[wrapper, parameter[val]]:
constant[Try to call fxn with the given value. If successful, return (True, fxn(val)), otherwise
returns (False... | keyword[def] identifier[try_wrapper] ( identifier[fxn] ):
literal[string]
keyword[def] identifier[wrapper] ( identifier[val] ):
literal[string]
keyword[try] :
keyword[return] ( keyword[True] , identifier[fxn] ( identifier[val] ))
keyword[except] identifier[Exception] :
keyword[r... | def try_wrapper(fxn):
"""Wraps a function, returning (True, fxn(val)) if successful, (False, val) if not."""
def wrapper(val):
"""Try to call fxn with the given value. If successful, return (True, fxn(val)), otherwise
returns (False, val).
"""
try:
return (True, fxn(val)) #... |
def legacy_notes_view(request):
"""
View to see legacy notes.
"""
notes = TeacherNote.objects.all()
note_count = notes.count()
paginator = Paginator(notes, 100)
page = request.GET.get('page')
try:
notes = paginator.page(page)
except PageNotAnInteger:
notes = paginato... | def function[legacy_notes_view, parameter[request]]:
constant[
View to see legacy notes.
]
variable[notes] assign[=] call[name[TeacherNote].objects.all, parameter[]]
variable[note_count] assign[=] call[name[notes].count, parameter[]]
variable[paginator] assign[=] call[name[Pagina... | keyword[def] identifier[legacy_notes_view] ( identifier[request] ):
literal[string]
identifier[notes] = identifier[TeacherNote] . identifier[objects] . identifier[all] ()
identifier[note_count] = identifier[notes] . identifier[count] ()
identifier[paginator] = identifier[Paginator] ( identifier[n... | def legacy_notes_view(request):
"""
View to see legacy notes.
"""
notes = TeacherNote.objects.all()
note_count = notes.count()
paginator = Paginator(notes, 100)
page = request.GET.get('page')
try:
notes = paginator.page(page) # depends on [control=['try'], data=[]]
except Pa... |
def match(column, term, match_type=None, options=None):
"""Generates match predicate for fulltext search
:param column: A reference to a column or an index, or a subcolumn, or a
dictionary of subcolumns with boost values.
:param term: The term to match against. This string is analyzed and the
re... | def function[match, parameter[column, term, match_type, options]]:
constant[Generates match predicate for fulltext search
:param column: A reference to a column or an index, or a subcolumn, or a
dictionary of subcolumns with boost values.
:param term: The term to match against. This string is ana... | keyword[def] identifier[match] ( identifier[column] , identifier[term] , identifier[match_type] = keyword[None] , identifier[options] = keyword[None] ):
literal[string]
keyword[return] identifier[Match] ( identifier[column] , identifier[term] , identifier[match_type] , identifier[options] ) | def match(column, term, match_type=None, options=None):
"""Generates match predicate for fulltext search
:param column: A reference to a column or an index, or a subcolumn, or a
dictionary of subcolumns with boost values.
:param term: The term to match against. This string is analyzed and the
re... |
def decode(encoded_histogram, b64_wrap=True):
'''Decode a wire histogram encoding into a read-only Hdr Payload instance
Args:
encoded_histogram a string containing the wire encoding of a histogram
such as one returned from encode()
Returns:
a... | def function[decode, parameter[encoded_histogram, b64_wrap]]:
constant[Decode a wire histogram encoding into a read-only Hdr Payload instance
Args:
encoded_histogram a string containing the wire encoding of a histogram
such as one returned from encode()
... | keyword[def] identifier[decode] ( identifier[encoded_histogram] , identifier[b64_wrap] = keyword[True] ):
literal[string]
keyword[if] identifier[b64_wrap] :
identifier[b64decode] = identifier[base64] . identifier[b64decode] ( identifier[encoded_histogram] )
i... | def decode(encoded_histogram, b64_wrap=True):
"""Decode a wire histogram encoding into a read-only Hdr Payload instance
Args:
encoded_histogram a string containing the wire encoding of a histogram
such as one returned from encode()
Returns:
an hd... |
def download_file(self, remote_filename, local_filename=None):
"""Download file from github.
Args:
remote_filename (str): The name of the file as defined in git repository.
local_filename (str, optional): Defaults to None. The name of the file as it should be
be ... | def function[download_file, parameter[self, remote_filename, local_filename]]:
constant[Download file from github.
Args:
remote_filename (str): The name of the file as defined in git repository.
local_filename (str, optional): Defaults to None. The name of the file as it should ... | keyword[def] identifier[download_file] ( identifier[self] , identifier[remote_filename] , identifier[local_filename] = keyword[None] ):
literal[string]
identifier[status] = literal[string]
keyword[if] identifier[local_filename] keyword[is] keyword[None] :
identifier[local_... | def download_file(self, remote_filename, local_filename=None):
"""Download file from github.
Args:
remote_filename (str): The name of the file as defined in git repository.
local_filename (str, optional): Defaults to None. The name of the file as it should be
be writ... |
def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True):
"""
Return True if file f is image (types type) and set its correct content_type and filename extension.
Example:
if is_image(request.FILES['file']):
print 'File is image'
if is_image(open('/tmp/image.jpeg', '... | def function[is_image, parameter[f, types, set_content_type]]:
constant[
Return True if file f is image (types type) and set its correct content_type and filename extension.
Example:
if is_image(request.FILES['file']):
print 'File is image'
if is_image(open('/tmp/image.jpeg'... | keyword[def] identifier[is_image] ( identifier[f] , identifier[types] =( literal[string] , literal[string] , literal[string] ), identifier[set_content_type] = keyword[True] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[types] ,( identifier[list] , identifier[tuple] ))
identif... | def is_image(f, types=('png', 'jpeg', 'gif'), set_content_type=True):
"""
Return True if file f is image (types type) and set its correct content_type and filename extension.
Example:
if is_image(request.FILES['file']):
print 'File is image'
if is_image(open('/tmp/image.jpeg', '... |
def quit_all(editor, force=False):
"""
Quit all.
"""
quit(editor, all_=True, force=force) | def function[quit_all, parameter[editor, force]]:
constant[
Quit all.
]
call[name[quit], parameter[name[editor]]] | keyword[def] identifier[quit_all] ( identifier[editor] , identifier[force] = keyword[False] ):
literal[string]
identifier[quit] ( identifier[editor] , identifier[all_] = keyword[True] , identifier[force] = identifier[force] ) | def quit_all(editor, force=False):
"""
Quit all.
"""
quit(editor, all_=True, force=force) |
def call_cmd(cmdlist, stdin=None):
"""
get a shell commands output, error message and return value and immediately
return.
.. warning::
This returns with the first screen content for interactive commands.
:param cmdlist: shellcommand to call, already splitted into a list accepted
... | def function[call_cmd, parameter[cmdlist, stdin]]:
constant[
get a shell commands output, error message and return value and immediately
return.
.. warning::
This returns with the first screen content for interactive commands.
:param cmdlist: shellcommand to call, already splitted int... | keyword[def] identifier[call_cmd] ( identifier[cmdlist] , identifier[stdin] = keyword[None] ):
literal[string]
identifier[termenc] = identifier[urwid] . identifier[util] . identifier[detected_encoding]
keyword[if] identifier[isinstance] ( identifier[stdin] , identifier[str] ):
identifier[st... | def call_cmd(cmdlist, stdin=None):
"""
get a shell commands output, error message and return value and immediately
return.
.. warning::
This returns with the first screen content for interactive commands.
:param cmdlist: shellcommand to call, already splitted into a list accepted
... |
def check(self, solution):
"""Check that a solution satisfies the constraint.
Args:
solution (container):
An assignment for the variables in the constraint.
Returns:
bool: True if the solution satisfies the constraint; otherwise False.
Examples:... | def function[check, parameter[self, solution]]:
constant[Check that a solution satisfies the constraint.
Args:
solution (container):
An assignment for the variables in the constraint.
Returns:
bool: True if the solution satisfies the constraint; otherwis... | keyword[def] identifier[check] ( identifier[self] , identifier[solution] ):
literal[string]
keyword[return] identifier[self] . identifier[func] (*( identifier[solution] [ identifier[v] ] keyword[for] identifier[v] keyword[in] identifier[self] . identifier[variables] )) | def check(self, solution):
"""Check that a solution satisfies the constraint.
Args:
solution (container):
An assignment for the variables in the constraint.
Returns:
bool: True if the solution satisfies the constraint; otherwise False.
Examples:
... |
async def parseResults(self, api_data):
""" See CoverSource.parseResults. """
results = []
# parse page
parser = lxml.etree.HTMLParser()
html = lxml.etree.XML(api_data.decode("utf-8", "ignore"), parser)
for page_struct_version, result_selector in enumerate(__class__.RESULTS_SELECTORS):
r... | <ast.AsyncFunctionDef object at 0x7da1b0666d10> | keyword[async] keyword[def] identifier[parseResults] ( identifier[self] , identifier[api_data] ):
literal[string]
identifier[results] =[]
identifier[parser] = identifier[lxml] . identifier[etree] . identifier[HTMLParser] ()
identifier[html] = identifier[lxml] . identifier[etree] . identifi... | async def parseResults(self, api_data):
""" See CoverSource.parseResults. """
results = []
# parse page
parser = lxml.etree.HTMLParser()
html = lxml.etree.XML(api_data.decode('utf-8', 'ignore'), parser)
for (page_struct_version, result_selector) in enumerate(__class__.RESULTS_SELECTORS):
... |
def get_slot_offsets(self):
"""
col_offset
- from bottom left corner of 1 to bottom corner of 2
row_offset
- from bottom left corner of 1 to bottom corner of 4
TODO: figure out actual X and Y offsets (from origin)
"""
SLOT_OFFSETS = {
'slots'... | def function[get_slot_offsets, parameter[self]]:
constant[
col_offset
- from bottom left corner of 1 to bottom corner of 2
row_offset
- from bottom left corner of 1 to bottom corner of 4
TODO: figure out actual X and Y offsets (from origin)
]
variable[SL... | keyword[def] identifier[get_slot_offsets] ( identifier[self] ):
literal[string]
identifier[SLOT_OFFSETS] ={
literal[string] :{
literal[string] : literal[int] ,
literal[string] : literal[int]
}
}
identifier[slot_settings] = identifier[SLOT_OFFSETS... | def get_slot_offsets(self):
"""
col_offset
- from bottom left corner of 1 to bottom corner of 2
row_offset
- from bottom left corner of 1 to bottom corner of 4
TODO: figure out actual X and Y offsets (from origin)
"""
SLOT_OFFSETS = {'slots': {'col_offset': 132.... |
def get_c_extension(support_legacy=False, system_zstd=False, name='zstd',
warnings_as_errors=False, root=None):
"""Obtain a distutils.extension.Extension for the C extension.
``support_legacy`` controls whether to compile in legacy zstd format support.
``system_zstd`` controls whether ... | def function[get_c_extension, parameter[support_legacy, system_zstd, name, warnings_as_errors, root]]:
constant[Obtain a distutils.extension.Extension for the C extension.
``support_legacy`` controls whether to compile in legacy zstd format support.
``system_zstd`` controls whether to compile against ... | keyword[def] identifier[get_c_extension] ( identifier[support_legacy] = keyword[False] , identifier[system_zstd] = keyword[False] , identifier[name] = literal[string] ,
identifier[warnings_as_errors] = keyword[False] , identifier[root] = keyword[None] ):
literal[string]
identifier[actual_root] = identifie... | def get_c_extension(support_legacy=False, system_zstd=False, name='zstd', warnings_as_errors=False, root=None):
"""Obtain a distutils.extension.Extension for the C extension.
``support_legacy`` controls whether to compile in legacy zstd format support.
``system_zstd`` controls whether to compile against t... |
def population_analysis_summary_report(feature, parent):
"""Retrieve an HTML population analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_population['key'])
if analysis_dir:
return get_impact_report_as_string(an... | def function[population_analysis_summary_report, parameter[feature, parent]]:
constant[Retrieve an HTML population analysis table report from a multi exposure
analysis.
]
variable[_] assign[=] tuple[[<ast.Name object at 0x7da1b0c516f0>, <ast.Name object at 0x7da1b0c520e0>]]
variable[anal... | keyword[def] identifier[population_analysis_summary_report] ( identifier[feature] , identifier[parent] ):
literal[string]
identifier[_] = identifier[feature] , identifier[parent]
identifier[analysis_dir] = identifier[get_analysis_dir] ( identifier[exposure_population] [ literal[string] ])
keywor... | def population_analysis_summary_report(feature, parent):
"""Retrieve an HTML population analysis table report from a multi exposure
analysis.
"""
_ = (feature, parent) # NOQA
analysis_dir = get_analysis_dir(exposure_population['key'])
if analysis_dir:
return get_impact_report_as_string(... |
def link_or_copy(src, dst, verbosity=0):
"""Try to make a hard link from src to dst and if that fails
copy the file. Hard links save some disk space and linking
should fail fast since no copying is involved.
"""
if verbosity > 0:
log_info("Copying %s -> %s" % (src, dst))
try:
os.... | def function[link_or_copy, parameter[src, dst, verbosity]]:
constant[Try to make a hard link from src to dst and if that fails
copy the file. Hard links save some disk space and linking
should fail fast since no copying is involved.
]
if compare[name[verbosity] greater[>] constant[0]] begin[... | keyword[def] identifier[link_or_copy] ( identifier[src] , identifier[dst] , identifier[verbosity] = literal[int] ):
literal[string]
keyword[if] identifier[verbosity] > literal[int] :
identifier[log_info] ( literal[string] %( identifier[src] , identifier[dst] ))
keyword[try] :
identi... | def link_or_copy(src, dst, verbosity=0):
"""Try to make a hard link from src to dst and if that fails
copy the file. Hard links save some disk space and linking
should fail fast since no copying is involved.
"""
if verbosity > 0:
log_info('Copying %s -> %s' % (src, dst)) # depends on [contr... |
def from_defaults(clz, defaults):
""" Given a dictionary of defaults, ie {attribute: value},
this classmethod constructs a new instance of the class and
merges the defaults"""
if isinstance(defaults, (str, unicode)):
defaults = json.loads(defaults)
c = clz()
... | def function[from_defaults, parameter[clz, defaults]]:
constant[ Given a dictionary of defaults, ie {attribute: value},
this classmethod constructs a new instance of the class and
merges the defaults]
if call[name[isinstance], parameter[name[defaults], tuple[[<ast.Name object at 0x7da1b1... | keyword[def] identifier[from_defaults] ( identifier[clz] , identifier[defaults] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[defaults] ,( identifier[str] , identifier[unicode] )):
identifier[defaults] = identifier[json] . identifier[loads] ( identifier[defaults] ... | def from_defaults(clz, defaults):
""" Given a dictionary of defaults, ie {attribute: value},
this classmethod constructs a new instance of the class and
merges the defaults"""
if isinstance(defaults, (str, unicode)):
defaults = json.loads(defaults) # depends on [control=['if'], data=[]]... |
def a2s_rules(server_addr, timeout=2, challenge=0):
"""Get rules from server
:param server_addr: (ip, port) for the server
:type server_addr: tuple
:param timeout: (optional) timeout in seconds
:type timeout: float
:param challenge: (optional) challenge number
:type challenge: int
:r... | def function[a2s_rules, parameter[server_addr, timeout, challenge]]:
constant[Get rules from server
:param server_addr: (ip, port) for the server
:type server_addr: tuple
:param timeout: (optional) timeout in seconds
:type timeout: float
:param challenge: (optional) challenge number
:... | keyword[def] identifier[a2s_rules] ( identifier[server_addr] , identifier[timeout] = literal[int] , identifier[challenge] = literal[int] ):
literal[string]
identifier[ss] = identifier[socket] . identifier[socket] ( identifier[socket] . identifier[AF_INET] , identifier[socket] . identifier[SOCK_DGRAM] )
... | def a2s_rules(server_addr, timeout=2, challenge=0):
"""Get rules from server
:param server_addr: (ip, port) for the server
:type server_addr: tuple
:param timeout: (optional) timeout in seconds
:type timeout: float
:param challenge: (optional) challenge number
:type challenge: int
:r... |
def get_google_playlist_songs(self, playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):
"""Create song list from a user-generated Google Music playlist.
Parameters:
playlist (str): Name or ID of Google Music playlist. Names are case-sensitive.
Google allows multipl... | def function[get_google_playlist_songs, parameter[self, playlist, include_filters, exclude_filters, all_includes, all_excludes]]:
constant[Create song list from a user-generated Google Music playlist.
Parameters:
playlist (str): Name or ID of Google Music playlist. Names are case-sensitive.
Google all... | keyword[def] identifier[get_google_playlist_songs] ( identifier[self] , identifier[playlist] , identifier[include_filters] = keyword[None] , identifier[exclude_filters] = keyword[None] , identifier[all_includes] = keyword[False] , identifier[all_excludes] = keyword[False] ):
literal[string]
identifier[logger]... | def get_google_playlist_songs(self, playlist, include_filters=None, exclude_filters=None, all_includes=False, all_excludes=False):
"""Create song list from a user-generated Google Music playlist.
Parameters:
playlist (str): Name or ID of Google Music playlist. Names are case-sensitive.
Google allows multi... |
def set_url(self, url):
"""Sets the url.
arg: url (string): the new copyright
raise: InvalidArgument - ``url`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``url`` is ``null``
*compliance: mandatory -- This method must be... | def function[set_url, parameter[self, url]]:
constant[Sets the url.
arg: url (string): the new copyright
raise: InvalidArgument - ``url`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``url`` is ``null``
*compliance: manda... | keyword[def] identifier[set_url] ( identifier[self] , identifier[url] ):
literal[string]
keyword[if] identifier[self] . identifier[get_url_metadata] (). identifier[is_read_only] ():
keyword[raise] identifier[errors] . identifier[NoAccess] ()
keyword[if] keyword[not... | def set_url(self, url):
"""Sets the url.
arg: url (string): the new copyright
raise: InvalidArgument - ``url`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``url`` is ``null``
*compliance: mandatory -- This method must be imp... |
async def save(self, fp, *, seek_begin=True, use_cached=False):
"""|coro|
Saves this attachment into a file-like object.
Parameters
-----------
fp: Union[BinaryIO, :class:`os.PathLike`]
The file-like object to save this attachment to or the filename
to u... | <ast.AsyncFunctionDef object at 0x7da1b1ea3fd0> | keyword[async] keyword[def] identifier[save] ( identifier[self] , identifier[fp] ,*, identifier[seek_begin] = keyword[True] , identifier[use_cached] = keyword[False] ):
literal[string]
identifier[url] = identifier[self] . identifier[proxy_url] keyword[if] identifier[use_cached] keyword[else] i... | async def save(self, fp, *, seek_begin=True, use_cached=False):
"""|coro|
Saves this attachment into a file-like object.
Parameters
-----------
fp: Union[BinaryIO, :class:`os.PathLike`]
The file-like object to save this attachment to or the filename
to use. ... |
def check_sub_path_create(sub_path):
"""
检查当前路径下的某个子路径是否存在, 不存在则创建;
:param:
* sub_path: (string) 下一级的某路径名称
:return:
* 返回类型 (tuple),有两个值
* True: 路径存在,False: 不需要创建
* False: 路径不存在,True: 创建成功
举例如下::
print('--- check_sub_path_create demo ---')
#... | def function[check_sub_path_create, parameter[sub_path]]:
constant[
检查当前路径下的某个子路径是否存在, 不存在则创建;
:param:
* sub_path: (string) 下一级的某路径名称
:return:
* 返回类型 (tuple),有两个值
* True: 路径存在,False: 不需要创建
* False: 路径不存在,True: 创建成功
举例如下::
print('--- check_sub_pa... | keyword[def] identifier[check_sub_path_create] ( identifier[sub_path] ):
literal[string]
identifier[temp_path] = identifier[pathlib] . identifier[Path] ()
identifier[cur_path] = identifier[temp_path] . identifier[resolve] ()
identifier[path] = identifier[cur_path] / identifier[pathli... | def check_sub_path_create(sub_path):
"""
检查当前路径下的某个子路径是否存在, 不存在则创建;
:param:
* sub_path: (string) 下一级的某路径名称
:return:
* 返回类型 (tuple),有两个值
* True: 路径存在,False: 不需要创建
* False: 路径不存在,True: 创建成功
举例如下::
print('--- check_sub_path_create demo ---')
# ... |
def project_search(auth=None, **kwargs):
'''
Search projects
CLI Example:
.. code-block:: bash
salt '*' keystoneng.project_search
salt '*' keystoneng.project_search name=project1
salt '*' keystoneng.project_search domain_id=b62e76fbeeff4e8fb77073f591cf211e
'''
cloud = ... | def function[project_search, parameter[auth]]:
constant[
Search projects
CLI Example:
.. code-block:: bash
salt '*' keystoneng.project_search
salt '*' keystoneng.project_search name=project1
salt '*' keystoneng.project_search domain_id=b62e76fbeeff4e8fb77073f591cf211e
... | keyword[def] identifier[project_search] ( identifier[auth] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[cloud] = identifier[get_openstack_cloud] ( identifier[auth] )
identifier[kwargs] = identifier[_clean_kwargs] (** identifier[kwargs] )
keyword[return] identifier[cloud] ... | def project_search(auth=None, **kwargs):
"""
Search projects
CLI Example:
.. code-block:: bash
salt '*' keystoneng.project_search
salt '*' keystoneng.project_search name=project1
salt '*' keystoneng.project_search domain_id=b62e76fbeeff4e8fb77073f591cf211e
"""
cloud = ... |
def rolling_percentileofscore(series, window, min_periods=None):
"""Computue the score percentile for the specified window."""
import scipy.stats as stats
def _percentile(arr):
score = arr[-1]
vals = arr[:-1]
return stats.percentileofscore(vals, score)
notnull = series.dropna()... | def function[rolling_percentileofscore, parameter[series, window, min_periods]]:
constant[Computue the score percentile for the specified window.]
import module[scipy.stats] as alias[stats]
def function[_percentile, parameter[arr]]:
variable[score] assign[=] call[name[arr]][<ast.Unar... | keyword[def] identifier[rolling_percentileofscore] ( identifier[series] , identifier[window] , identifier[min_periods] = keyword[None] ):
literal[string]
keyword[import] identifier[scipy] . identifier[stats] keyword[as] identifier[stats]
keyword[def] identifier[_percentile] ( identifier[arr] ):
... | def rolling_percentileofscore(series, window, min_periods=None):
"""Computue the score percentile for the specified window."""
import scipy.stats as stats
def _percentile(arr):
score = arr[-1]
vals = arr[:-1]
return stats.percentileofscore(vals, score)
notnull = series.dropna()
... |
def extract_objects(self, fname, type_filter=None):
'''Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file.
'''
objects = []
if fname in se... | def function[extract_objects, parameter[self, fname, type_filter]]:
constant[Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file.
]
var... | keyword[def] identifier[extract_objects] ( identifier[self] , identifier[fname] , identifier[type_filter] = keyword[None] ):
literal[string]
identifier[objects] =[]
keyword[if] identifier[fname] keyword[in] identifier[self] . identifier[object_cache] :
identifier[objects] = identifier[self] ... | def extract_objects(self, fname, type_filter=None):
"""Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file.
"""
objects = []
if fname in se... |
def src_new(converter_type, channels):
"""Initialise a new sample rate converter.
Parameters
----------
converter_type : int
Converter to be used.
channels : int
Number of channels.
Returns
-------
state
An anonymous pointer to the internal state of the converte... | def function[src_new, parameter[converter_type, channels]]:
constant[Initialise a new sample rate converter.
Parameters
----------
converter_type : int
Converter to be used.
channels : int
Number of channels.
Returns
-------
state
An anonymous pointer to the... | keyword[def] identifier[src_new] ( identifier[converter_type] , identifier[channels] ):
literal[string]
identifier[error] = identifier[ffi] . identifier[new] ( literal[string] )
identifier[state] = identifier[_lib] . identifier[src_new] ( identifier[converter_type] , identifier[channels] , identifier[... | def src_new(converter_type, channels):
"""Initialise a new sample rate converter.
Parameters
----------
converter_type : int
Converter to be used.
channels : int
Number of channels.
Returns
-------
state
An anonymous pointer to the internal state of the converte... |
def difference(self, *others):
"""Return the difference of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.difference(b))
['eggs']
"""
return self.copy(super(NGram, self)... | def function[difference, parameter[self]]:
constant[Return the difference of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.difference(b))
['eggs']
]
return[call[name[self].... | keyword[def] identifier[difference] ( identifier[self] ,* identifier[others] ):
literal[string]
keyword[return] identifier[self] . identifier[copy] ( identifier[super] ( identifier[NGram] , identifier[self] ). identifier[difference] (* identifier[others] )) | def difference(self, *others):
"""Return the difference of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.difference(b))
['eggs']
"""
return self.copy(super(NGram, self).differe... |
def restore_definition(self, project, definition_id, deleted):
"""RestoreDefinition.
Restores a deleted definition
:param str project: Project ID or project name
:param int definition_id: The identifier of the definition to restore.
:param bool deleted: When false, restores a del... | def function[restore_definition, parameter[self, project, definition_id, deleted]]:
constant[RestoreDefinition.
Restores a deleted definition
:param str project: Project ID or project name
:param int definition_id: The identifier of the definition to restore.
:param bool deleted:... | keyword[def] identifier[restore_definition] ( identifier[self] , identifier[project] , identifier[definition_id] , identifier[deleted] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[project] keyword[is] keyword[not] keyword[None] :
identifier[route_... | def restore_definition(self, project, definition_id, deleted):
"""RestoreDefinition.
Restores a deleted definition
:param str project: Project ID or project name
:param int definition_id: The identifier of the definition to restore.
:param bool deleted: When false, restores a deleted... |
def create_serving_logger() -> Logger:
"""Create a logger for serving.
This creates a logger named quart.serving.
"""
logger = getLogger('quart.serving')
if logger.level == NOTSET:
logger.setLevel(INFO)
logger.addHandler(serving_handler)
return logger | def function[create_serving_logger, parameter[]]:
constant[Create a logger for serving.
This creates a logger named quart.serving.
]
variable[logger] assign[=] call[name[getLogger], parameter[constant[quart.serving]]]
if compare[name[logger].level equal[==] name[NOTSET]] begin[:]
... | keyword[def] identifier[create_serving_logger] ()-> identifier[Logger] :
literal[string]
identifier[logger] = identifier[getLogger] ( literal[string] )
keyword[if] identifier[logger] . identifier[level] == identifier[NOTSET] :
identifier[logger] . identifier[setLevel] ( identifier[INFO] )
... | def create_serving_logger() -> Logger:
"""Create a logger for serving.
This creates a logger named quart.serving.
"""
logger = getLogger('quart.serving')
if logger.level == NOTSET:
logger.setLevel(INFO) # depends on [control=['if'], data=[]]
logger.addHandler(serving_handler)
retur... |
def unpack_data(data):
"""Unpack data returned by the net's iterator into a 2-tuple.
If the wrong number of items is returned, raise a helpful error
message.
"""
# Note: This function cannot detect it when a user only returns 1
# item that is exactly of length 2 (e.g. because the batch size is... | def function[unpack_data, parameter[data]]:
constant[Unpack data returned by the net's iterator into a 2-tuple.
If the wrong number of items is returned, raise a helpful error
message.
]
<ast.Try object at 0x7da18dc07ac0> | keyword[def] identifier[unpack_data] ( identifier[data] ):
literal[string]
keyword[try] :
identifier[X] , identifier[y] = identifier[data]
keyword[return] identifier[X] , identifier[y]
keyword[except] identifier[ValueError] :
keyword[if] keyword... | def unpack_data(data):
"""Unpack data returned by the net's iterator into a 2-tuple.
If the wrong number of items is returned, raise a helpful error
message.
"""
# Note: This function cannot detect it when a user only returns 1
# item that is exactly of length 2 (e.g. because the batch size is... |
def from_external(external=H2OFrame):
"""
Creates new H2OWord2vecEstimator based on an external model.
:param external: H2OFrame with an external model
:return: H2OWord2vecEstimator instance representing the external model
"""
w2v_model = H2OWord2vecEstimator(pre_trained=... | def function[from_external, parameter[external]]:
constant[
Creates new H2OWord2vecEstimator based on an external model.
:param external: H2OFrame with an external model
:return: H2OWord2vecEstimator instance representing the external model
]
variable[w2v_model] assign[=]... | keyword[def] identifier[from_external] ( identifier[external] = identifier[H2OFrame] ):
literal[string]
identifier[w2v_model] = identifier[H2OWord2vecEstimator] ( identifier[pre_trained] = identifier[external] )
identifier[w2v_model] . identifier[train] ()
keyword[return] identif... | def from_external(external=H2OFrame):
"""
Creates new H2OWord2vecEstimator based on an external model.
:param external: H2OFrame with an external model
:return: H2OWord2vecEstimator instance representing the external model
"""
w2v_model = H2OWord2vecEstimator(pre_trained=external... |
def skip_whitespace(self, newlines=0):
"""Moves the position forwards to the next non newline space character.
If newlines >= 1 include newlines as spaces.
"""
if newlines:
while not self.eos:
if self.get_char().isspace():
self.eat_length(1... | def function[skip_whitespace, parameter[self, newlines]]:
constant[Moves the position forwards to the next non newline space character.
If newlines >= 1 include newlines as spaces.
]
if name[newlines] begin[:]
while <ast.UnaryOp object at 0x7da1b27e0850> begin[:]
... | keyword[def] identifier[skip_whitespace] ( identifier[self] , identifier[newlines] = literal[int] ):
literal[string]
keyword[if] identifier[newlines] :
keyword[while] keyword[not] identifier[self] . identifier[eos] :
keyword[if] identifier[self] . identifier[get_ch... | def skip_whitespace(self, newlines=0):
"""Moves the position forwards to the next non newline space character.
If newlines >= 1 include newlines as spaces.
"""
if newlines:
while not self.eos:
if self.get_char().isspace():
self.eat_length(1) # depends on [con... |
def _inject_function_into_js(context, name, func):
"""
Inject a Python function into the global scope of a dukpy JavaScript interpreter context.
:type context: dukpy.JSInterpreter
:param name: Name to give the function in JavaScript.
:param func: Python function.
"""
context.export_function... | def function[_inject_function_into_js, parameter[context, name, func]]:
constant[
Inject a Python function into the global scope of a dukpy JavaScript interpreter context.
:type context: dukpy.JSInterpreter
:param name: Name to give the function in JavaScript.
:param func: Python function.
... | keyword[def] identifier[_inject_function_into_js] ( identifier[context] , identifier[name] , identifier[func] ):
literal[string]
identifier[context] . identifier[export_function] ( identifier[name] , identifier[func] )
identifier[context] . identifier[evaljs] ( literal[string] . identifier[format] ( i... | def _inject_function_into_js(context, name, func):
"""
Inject a Python function into the global scope of a dukpy JavaScript interpreter context.
:type context: dukpy.JSInterpreter
:param name: Name to give the function in JavaScript.
:param func: Python function.
"""
context.export_function... |
def raw_broadcast(self, destination, message, **kwargs):
"""Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param *... | def function[raw_broadcast, parameter[self, destination, message]]:
constant[Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent... | keyword[def] identifier[raw_broadcast] ( identifier[self] , identifier[destination] , identifier[message] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_broadcast] ( identifier[destination] , identifier[message] ,** identifier[kwargs] ) | def raw_broadcast(self, destination, message, **kwargs):
"""Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param **kwa... |
def fetch_file(self, in_path, out_path):
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
''' fetch a file from local to local -- for copatibility '''
self.put_file(in_path, out_path) | def function[fetch_file, parameter[self, in_path, out_path]]:
call[name[vvv], parameter[binary_operation[constant[FETCH %s TO %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b15b1ea0>, <ast.Name object at 0x7da1b15b23e0>]]]]]
constant[ fetch a file from local to local -- for copa... | keyword[def] identifier[fetch_file] ( identifier[self] , identifier[in_path] , identifier[out_path] ):
identifier[vvv] ( literal[string] %( identifier[in_path] , identifier[out_path] ), identifier[host] = identifier[self] . identifier[host] )
literal[string]
identifier[self] . identifier[p... | def fetch_file(self, in_path, out_path):
vvv('FETCH %s TO %s' % (in_path, out_path), host=self.host)
' fetch a file from local to local -- for copatibility '
self.put_file(in_path, out_path) |
def plot_somas(somas):
'''Plot set of somas on same figure as spheres, each with different color'''
_, ax = common.get_figure(new_fig=True, subplot=111,
params={'projection': '3d', 'aspect': 'equal'})
for s in somas:
common.plot_sphere(ax, s.center, s.radius, color=rand... | def function[plot_somas, parameter[somas]]:
constant[Plot set of somas on same figure as spheres, each with different color]
<ast.Tuple object at 0x7da2047e9990> assign[=] call[name[common].get_figure, parameter[]]
for taget[name[s]] in starred[name[somas]] begin[:]
call[name[com... | keyword[def] identifier[plot_somas] ( identifier[somas] ):
literal[string]
identifier[_] , identifier[ax] = identifier[common] . identifier[get_figure] ( identifier[new_fig] = keyword[True] , identifier[subplot] = literal[int] ,
identifier[params] ={ literal[string] : literal[string] , literal[string]... | def plot_somas(somas):
"""Plot set of somas on same figure as spheres, each with different color"""
(_, ax) = common.get_figure(new_fig=True, subplot=111, params={'projection': '3d', 'aspect': 'equal'})
for s in somas:
common.plot_sphere(ax, s.center, s.radius, color=random_color(), alpha=1) # depe... |
def propagate(self, token, channel):
"""
Kick off the propagate function on the remote server.
Arguments:
token (str): The token to propagate
channel (str): The channel to propagate
Returns:
boolean: Success
"""
if self.get_propagate_... | def function[propagate, parameter[self, token, channel]]:
constant[
Kick off the propagate function on the remote server.
Arguments:
token (str): The token to propagate
channel (str): The channel to propagate
Returns:
boolean: Success
]
... | keyword[def] identifier[propagate] ( identifier[self] , identifier[token] , identifier[channel] ):
literal[string]
keyword[if] identifier[self] . identifier[get_propagate_status] ( identifier[token] , identifier[channel] )!= literal[string] :
keyword[return]
identifier[url] ... | def propagate(self, token, channel):
"""
Kick off the propagate function on the remote server.
Arguments:
token (str): The token to propagate
channel (str): The channel to propagate
Returns:
boolean: Success
"""
if self.get_propagate_status(t... |
def _countEXT(self,extname="SCI"):
""" Count the number of extensions in the file with the given name
(``EXTNAME``).
"""
count=0 #simple fits image
if (self._image['PRIMARY'].header["EXTEND"]):
for i,hdu in enumerate(self._image):
if i > 0:
... | def function[_countEXT, parameter[self, extname]]:
constant[ Count the number of extensions in the file with the given name
(``EXTNAME``).
]
variable[count] assign[=] constant[0]
if call[call[name[self]._image][constant[PRIMARY]].header][constant[EXTEND]] begin[:]
... | keyword[def] identifier[_countEXT] ( identifier[self] , identifier[extname] = literal[string] ):
literal[string]
identifier[count] = literal[int]
keyword[if] ( identifier[self] . identifier[_image] [ literal[string] ]. identifier[header] [ literal[string] ]):
keyword[for] i... | def _countEXT(self, extname='SCI'):
""" Count the number of extensions in the file with the given name
(``EXTNAME``).
"""
count = 0 #simple fits image
if self._image['PRIMARY'].header['EXTEND']:
for (i, hdu) in enumerate(self._image):
if i > 0:
hduExtnam... |
def close_fds(keep_fds): # pragma: no cover
"""Close all the file descriptors except those in keep_fds."""
# Make sure to keep stdout and stderr open for logging purpose
keep_fds = set(keep_fds).union([1, 2])
# We try to retrieve all the open fds
try:
open_fds = set(int(fd) for fd in os.l... | def function[close_fds, parameter[keep_fds]]:
constant[Close all the file descriptors except those in keep_fds.]
variable[keep_fds] assign[=] call[call[name[set], parameter[name[keep_fds]]].union, parameter[list[[<ast.Constant object at 0x7da1b05bfeb0>, <ast.Constant object at 0x7da1b05bfaf0>]]]]
<a... | keyword[def] identifier[close_fds] ( identifier[keep_fds] ):
literal[string]
identifier[keep_fds] = identifier[set] ( identifier[keep_fds] ). identifier[union] ([ literal[int] , literal[int] ])
keyword[try] :
identifier[open_fds] = identifier[set] ( identifier[int] ( identifier[fd... | def close_fds(keep_fds): # pragma: no cover
'Close all the file descriptors except those in keep_fds.'
# Make sure to keep stdout and stderr open for logging purpose
keep_fds = set(keep_fds).union([1, 2])
# We try to retrieve all the open fds
try:
open_fds = set((int(fd) for fd in os.listdi... |
def get_default_wrapper(cls):
"""Returns the default (first) driver wrapper
:returns: default driver wrapper
:rtype: toolium.driver_wrapper.DriverWrapper
"""
if cls.is_empty():
# Create a new driver wrapper if the pool is empty
from toolium.driver_wrapper... | def function[get_default_wrapper, parameter[cls]]:
constant[Returns the default (first) driver wrapper
:returns: default driver wrapper
:rtype: toolium.driver_wrapper.DriverWrapper
]
if call[name[cls].is_empty, parameter[]] begin[:]
from relative_module[toolium.driver_wr... | keyword[def] identifier[get_default_wrapper] ( identifier[cls] ):
literal[string]
keyword[if] identifier[cls] . identifier[is_empty] ():
keyword[from] identifier[toolium] . identifier[driver_wrapper] keyword[import] identifier[DriverWrapper]
identifier[Driver... | def get_default_wrapper(cls):
"""Returns the default (first) driver wrapper
:returns: default driver wrapper
:rtype: toolium.driver_wrapper.DriverWrapper
"""
if cls.is_empty():
# Create a new driver wrapper if the pool is empty
from toolium.driver_wrapper import DriverWr... |
def get_all_plus_and_delete(self):
"""
Get all self.plus items of list. We copy it, delete the original and return the copy list
:return: list of self.plus
:rtype: list
"""
res = {}
props = list(self.plus.keys()) # we delete entries, so no for ... in ...
... | def function[get_all_plus_and_delete, parameter[self]]:
constant[
Get all self.plus items of list. We copy it, delete the original and return the copy list
:return: list of self.plus
:rtype: list
]
variable[res] assign[=] dictionary[[], []]
variable[props] assign... | keyword[def] identifier[get_all_plus_and_delete] ( identifier[self] ):
literal[string]
identifier[res] ={}
identifier[props] = identifier[list] ( identifier[self] . identifier[plus] . identifier[keys] ())
keyword[for] identifier[prop] keyword[in] identifier[props] :
... | def get_all_plus_and_delete(self):
"""
Get all self.plus items of list. We copy it, delete the original and return the copy list
:return: list of self.plus
:rtype: list
"""
res = {}
props = list(self.plus.keys()) # we delete entries, so no for ... in ...
for prop in pro... |
def start(self):
"""
Start the patch
"""
self._patcher = mock.patch(target=self.target)
MockClient = self._patcher.start()
instance = MockClient.return_value
instance.model.side_effect = mock.Mock(
side_effect=self.model
) | def function[start, parameter[self]]:
constant[
Start the patch
]
name[self]._patcher assign[=] call[name[mock].patch, parameter[]]
variable[MockClient] assign[=] call[name[self]._patcher.start, parameter[]]
variable[instance] assign[=] name[MockClient].return_value
... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_patcher] = identifier[mock] . identifier[patch] ( identifier[target] = identifier[self] . identifier[target] )
identifier[MockClient] = identifier[self] . identifier[_patcher] . identifier[s... | def start(self):
"""
Start the patch
"""
self._patcher = mock.patch(target=self.target)
MockClient = self._patcher.start()
instance = MockClient.return_value
instance.model.side_effect = mock.Mock(side_effect=self.model) |
def _transform_result(typ, result):
"""Convert the result back into the input type.
"""
if issubclass(typ, bytes):
return tostring(result, encoding='utf-8')
elif issubclass(typ, unicode):
return tostring(result, encoding='unicode')
else:
return result | def function[_transform_result, parameter[typ, result]]:
constant[Convert the result back into the input type.
]
if call[name[issubclass], parameter[name[typ], name[bytes]]] begin[:]
return[call[name[tostring], parameter[name[result]]]] | keyword[def] identifier[_transform_result] ( identifier[typ] , identifier[result] ):
literal[string]
keyword[if] identifier[issubclass] ( identifier[typ] , identifier[bytes] ):
keyword[return] identifier[tostring] ( identifier[result] , identifier[encoding] = literal[string] )
keyword[elif]... | def _transform_result(typ, result):
"""Convert the result back into the input type.
"""
if issubclass(typ, bytes):
return tostring(result, encoding='utf-8') # depends on [control=['if'], data=[]]
elif issubclass(typ, unicode):
return tostring(result, encoding='unicode') # depends on [c... |
def validate(self, form_cls, obj=None):
'''Validate a form from the request and handle errors'''
if 'application/json' not in request.headers.get('Content-Type'):
errors = {'Content-Type': 'expecting application/json'}
self.abort(400, errors=errors)
form = form_cls.from_j... | def function[validate, parameter[self, form_cls, obj]]:
constant[Validate a form from the request and handle errors]
if compare[constant[application/json] <ast.NotIn object at 0x7da2590d7190> call[name[request].headers.get, parameter[constant[Content-Type]]]] begin[:]
variable[errors] as... | keyword[def] identifier[validate] ( identifier[self] , identifier[form_cls] , identifier[obj] = keyword[None] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[request] . identifier[headers] . identifier[get] ( literal[string] ):
identifier[errors] ... | def validate(self, form_cls, obj=None):
"""Validate a form from the request and handle errors"""
if 'application/json' not in request.headers.get('Content-Type'):
errors = {'Content-Type': 'expecting application/json'}
self.abort(400, errors=errors) # depends on [control=['if'], data=[]]
fo... |
def get_sequence(self):
"""Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
"""
if not self.address:
raise StellarAddressInvalidError('No address provided.')
address = self.horizon.... | def function[get_sequence, parameter[self]]:
constant[Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
]
if <ast.UnaryOp object at 0x7da1b16c20b0> begin[:]
<ast.Raise object at 0x7da1b16c3340>
... | keyword[def] identifier[get_sequence] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[address] :
keyword[raise] identifier[StellarAddressInvalidError] ( literal[string] )
identifier[address] = identifier[self] . identifier[horiz... | def get_sequence(self):
"""Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
"""
if not self.address:
raise StellarAddressInvalidError('No address provided.') # depends on [control=['if'], data=[]]
... |
def rm_dup_args_safe(self, tag: str = None) -> None:
"""Remove duplicate arguments in a safe manner.
Remove the duplicate arguments only in the following situations:
1. Both arguments have the same name AND value. (Remove one of
them.)
2. Arguments have the same ... | def function[rm_dup_args_safe, parameter[self, tag]]:
constant[Remove duplicate arguments in a safe manner.
Remove the duplicate arguments only in the following situations:
1. Both arguments have the same name AND value. (Remove one of
them.)
2. Arguments have th... | keyword[def] identifier[rm_dup_args_safe] ( identifier[self] , identifier[tag] : identifier[str] = keyword[None] )-> keyword[None] :
literal[string]
identifier[name_to_lastarg_vals] ={}
keyword[for] identifier[arg] keyword[in] identifier[reversed] ( identifier[self] . ... | def rm_dup_args_safe(self, tag: str=None) -> None:
"""Remove duplicate arguments in a safe manner.
Remove the duplicate arguments only in the following situations:
1. Both arguments have the same name AND value. (Remove one of
them.)
2. Arguments have the same name a... |
def takewhile(self, func=None):
"""
Return a new Collection with the last few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
at and after the first item where bool(func(item)) == False
... | def function[takewhile, parameter[self, func]]:
constant[
Return a new Collection with the last few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
at and after the first item where bool(func... | keyword[def] identifier[takewhile] ( identifier[self] , identifier[func] = keyword[None] ):
literal[string]
identifier[func] = identifier[_make_callable] ( identifier[func] )
keyword[return] identifier[Collection] ( identifier[takewhile] ( identifier[func] , identifier[self] . identifier[... | def takewhile(self, func=None):
"""
Return a new Collection with the last few items removed.
Parameters:
func : function(Node) -> Node
Returns:
A new Collection, discarding all items
at and after the first item where bool(func(item)) == False
... |
def summary_plot(shap_values, features=None, feature_names=None, max_display=None, plot_type="dot",
color=None, axis_color="#333333", title=None, alpha=1, show=True, sort=True,
color_bar=True, auto_size_plot=True, layered_violin_max_num_bins=20, class_names=None):
"""Create a SHAP ... | def function[summary_plot, parameter[shap_values, features, feature_names, max_display, plot_type, color, axis_color, title, alpha, show, sort, color_bar, auto_size_plot, layered_violin_max_num_bins, class_names]]:
constant[Create a SHAP summary plot, colored by feature values when they are provided.
Param... | keyword[def] identifier[summary_plot] ( identifier[shap_values] , identifier[features] = keyword[None] , identifier[feature_names] = keyword[None] , identifier[max_display] = keyword[None] , identifier[plot_type] = literal[string] ,
identifier[color] = keyword[None] , identifier[axis_color] = literal[string] , ident... | def summary_plot(shap_values, features=None, feature_names=None, max_display=None, plot_type='dot', color=None, axis_color='#333333', title=None, alpha=1, show=True, sort=True, color_bar=True, auto_size_plot=True, layered_violin_max_num_bins=20, class_names=None):
"""Create a SHAP summary plot, colored by feature v... |
def to_nifti(obj, like=None, header=None, affine=None, extensions=Ellipsis, version=1):
'''
to_nifti(obj) yields a Nifti2Image object that is as equivalent as possible to the given object
obj. If obj is a Nifti2Image already, then it is returned unmolested; other deduction rules
are described below.... | def function[to_nifti, parameter[obj, like, header, affine, extensions, version]]:
constant[
to_nifti(obj) yields a Nifti2Image object that is as equivalent as possible to the given object
obj. If obj is a Nifti2Image already, then it is returned unmolested; other deduction rules
are described b... | keyword[def] identifier[to_nifti] ( identifier[obj] , identifier[like] = keyword[None] , identifier[header] = keyword[None] , identifier[affine] = keyword[None] , identifier[extensions] = identifier[Ellipsis] , identifier[version] = literal[int] ):
literal[string]
keyword[from] identifier[neuropythy] . id... | def to_nifti(obj, like=None, header=None, affine=None, extensions=Ellipsis, version=1):
"""
to_nifti(obj) yields a Nifti2Image object that is as equivalent as possible to the given object
obj. If obj is a Nifti2Image already, then it is returned unmolested; other deduction rules
are described below.... |
def save_file(client, bucket, data_file, items, dry_run=None):
"""Tries to write JSON data to data file in S3."""
logger.debug('Writing {number_items} items to s3. Bucket: {bucket} Key: {key}'.format(
number_items=len(items),
bucket=bucket,
key=data_file
))
if not dry_run:
... | def function[save_file, parameter[client, bucket, data_file, items, dry_run]]:
constant[Tries to write JSON data to data file in S3.]
call[name[logger].debug, parameter[call[constant[Writing {number_items} items to s3. Bucket: {bucket} Key: {key}].format, parameter[]]]]
if <ast.UnaryOp object at... | keyword[def] identifier[save_file] ( identifier[client] , identifier[bucket] , identifier[data_file] , identifier[items] , identifier[dry_run] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] (
identifier[number_items] = identifier[len] (... | def save_file(client, bucket, data_file, items, dry_run=None):
"""Tries to write JSON data to data file in S3."""
logger.debug('Writing {number_items} items to s3. Bucket: {bucket} Key: {key}'.format(number_items=len(items), bucket=bucket, key=data_file))
if not dry_run:
return _put_to_s3(client, bu... |
def JC69 (mu=1.0, alphabet="nuc", **kwargs):
"""
Jukes-Cantor 1969 model. This model assumes equal concentrations
of the nucleotides and equal transition rates between nucleotide states.
For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules.
New York: Academ... | def function[JC69, parameter[mu, alphabet]]:
constant[
Jukes-Cantor 1969 model. This model assumes equal concentrations
of the nucleotides and equal transition rates between nucleotide states.
For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules.
New Yo... | keyword[def] identifier[JC69] ( identifier[mu] = literal[int] , identifier[alphabet] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[num_chars] = identifier[len] ( identifier[alphabets] [ identifier[alphabet] ])
identifier[W] , identifier[pi] = identifier[np] . identifier[ones] ... | def JC69(mu=1.0, alphabet='nuc', **kwargs):
"""
Jukes-Cantor 1969 model. This model assumes equal concentrations
of the nucleotides and equal transition rates between nucleotide states.
For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules.
New York: Academi... |
def build_block(self, format_string):
"""
Parse the format string into blocks containing Literals, Placeholders
etc that we can cache and reuse.
"""
first_block = Block(None, py3_wrapper=self.py3_wrapper)
block = first_block
# Tokenize the format string and proce... | def function[build_block, parameter[self, format_string]]:
constant[
Parse the format string into blocks containing Literals, Placeholders
etc that we can cache and reuse.
]
variable[first_block] assign[=] call[name[Block], parameter[constant[None]]]
variable[block] assig... | keyword[def] identifier[build_block] ( identifier[self] , identifier[format_string] ):
literal[string]
identifier[first_block] = identifier[Block] ( keyword[None] , identifier[py3_wrapper] = identifier[self] . identifier[py3_wrapper] )
identifier[block] = identifier[first_block]
... | def build_block(self, format_string):
"""
Parse the format string into blocks containing Literals, Placeholders
etc that we can cache and reuse.
"""
first_block = Block(None, py3_wrapper=self.py3_wrapper)
block = first_block
# Tokenize the format string and process them
for t... |
def reformat_schema(model):
""" Reformat schema to be in a more displayable format. """
if not hasattr(model, 'schema'):
return "Model '{}' does not have a schema".format(model)
if 'properties' not in model.schema:
return "Schema in unexpected format."
ret = copy.deepcopy(model.schema[... | def function[reformat_schema, parameter[model]]:
constant[ Reformat schema to be in a more displayable format. ]
if <ast.UnaryOp object at 0x7da1b1f26e90> begin[:]
return[call[constant[Model '{}' does not have a schema].format, parameter[name[model]]]]
if compare[constant[properties] <as... | keyword[def] identifier[reformat_schema] ( identifier[model] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[model] , literal[string] ):
keyword[return] literal[string] . identifier[format] ( identifier[model] )
keyword[if] literal[string] keyword[not] keyw... | def reformat_schema(model):
""" Reformat schema to be in a more displayable format. """
if not hasattr(model, 'schema'):
return "Model '{}' does not have a schema".format(model) # depends on [control=['if'], data=[]]
if 'properties' not in model.schema:
return 'Schema in unexpected format.'... |
def load_module(self, fullname):
"""import a notebook as a module"""
path = find_notebook(fullname, self.path)
print ("importing Jupyter notebook from %s" % path)
# load the notebook object
with io.open(path, 'r', encoding='utf-8') as f:
nb = read(f, 4)
# ... | def function[load_module, parameter[self, fullname]]:
constant[import a notebook as a module]
variable[path] assign[=] call[name[find_notebook], parameter[name[fullname], name[self].path]]
call[name[print], parameter[binary_operation[constant[importing Jupyter notebook from %s] <ast.Mod object a... | keyword[def] identifier[load_module] ( identifier[self] , identifier[fullname] ):
literal[string]
identifier[path] = identifier[find_notebook] ( identifier[fullname] , identifier[self] . identifier[path] )
identifier[print] ( literal[string] % identifier[path] )
keyword... | def load_module(self, fullname):
"""import a notebook as a module"""
path = find_notebook(fullname, self.path)
print('importing Jupyter notebook from %s' % path)
# load the notebook object
with io.open(path, 'r', encoding='utf-8') as f:
nb = read(f, 4) # depends on [control=['with'], data=[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.