code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def self_sign(self, req, receiver='', aud=None):
"""
Sign the extended request.
:param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance
:param receiver: The intended user of this metadata statement
:param aud: The audience, a list of receivers.
:return: ... | def function[self_sign, parameter[self, req, receiver, aud]]:
constant[
Sign the extended request.
:param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance
:param receiver: The intended user of this metadata statement
:param aud: The audience, a list of receivers... | keyword[def] identifier[self_sign] ( identifier[self] , identifier[req] , identifier[receiver] = literal[string] , identifier[aud] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[entity_id] :
identifier[_iss] = identifier[self] . identifier[entity_id]
... | def self_sign(self, req, receiver='', aud=None):
"""
Sign the extended request.
:param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance
:param receiver: The intended user of this metadata statement
:param aud: The audience, a list of receivers.
:return: An a... |
def twostep(script, iterations=3, angle_threshold=60, normal_steps=20, fit_steps=20,
selected=False):
""" Two Step Smoothing, a feature preserving/enhancing fairing filter.
It is based on a Normal Smoothing step where similar normals are averaged
together and a step where the vertexes are fitte... | def function[twostep, parameter[script, iterations, angle_threshold, normal_steps, fit_steps, selected]]:
constant[ Two Step Smoothing, a feature preserving/enhancing fairing filter.
It is based on a Normal Smoothing step where similar normals are averaged
together and a step where the vertexes are fit... | keyword[def] identifier[twostep] ( identifier[script] , identifier[iterations] = literal[int] , identifier[angle_threshold] = literal[int] , identifier[normal_steps] = literal[int] , identifier[fit_steps] = literal[int] ,
identifier[selected] = keyword[False] ):
literal[string]
identifier[filter_xml] = li... | def twostep(script, iterations=3, angle_threshold=60, normal_steps=20, fit_steps=20, selected=False):
""" Two Step Smoothing, a feature preserving/enhancing fairing filter.
It is based on a Normal Smoothing step where similar normals are averaged
together and a step where the vertexes are fitted on the new... |
async def load_remote(
self, email: str, password: str,
skip_existing: bool = True) -> None:
"""Create a local client."""
auth_resp = await self._request(
'post',
'https://my.rainmachine.com/login/auth',
json={'user': {
'email':... | <ast.AsyncFunctionDef object at 0x7da20c6c69e0> | keyword[async] keyword[def] identifier[load_remote] (
identifier[self] , identifier[email] : identifier[str] , identifier[password] : identifier[str] ,
identifier[skip_existing] : identifier[bool] = keyword[True] )-> keyword[None] :
literal[string]
identifier[auth_resp] = keyword[await] identif... | async def load_remote(self, email: str, password: str, skip_existing: bool=True) -> None:
"""Create a local client."""
auth_resp = await self._request('post', 'https://my.rainmachine.com/login/auth', json={'user': {'email': email, 'pwd': password, 'remember': 1}})
access_token = auth_resp['access_token']
... |
def itake_column(list_, colx):
""" iterator version of get_list_column """
if isinstance(colx, list):
# multi select
return ([row[colx_] for colx_ in colx] for row in list_)
else:
return (row[colx] for row in list_) | def function[itake_column, parameter[list_, colx]]:
constant[ iterator version of get_list_column ]
if call[name[isinstance], parameter[name[colx], name[list]]] begin[:]
return[<ast.GeneratorExp object at 0x7da1b24eae90>] | keyword[def] identifier[itake_column] ( identifier[list_] , identifier[colx] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[colx] , identifier[list] ):
keyword[return] ([ identifier[row] [ identifier[colx_] ] keyword[for] identifier[colx_] keyword[in] identifier[colx] ... | def itake_column(list_, colx):
""" iterator version of get_list_column """
if isinstance(colx, list):
# multi select
return ([row[colx_] for colx_ in colx] for row in list_) # depends on [control=['if'], data=[]]
else:
return (row[colx] for row in list_) |
def p_reserved_word(self, p):
"""reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
| DO
... | def function[p_reserved_word, parameter[self, p]]:
constant[reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
... | keyword[def] identifier[p_reserved_word] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[self] . identifier[asttypes] . identifier[Identifier] ( identifier[p] [ literal[int] ])
identifier[p] [ literal[int] ]. identifier[setpos] ( identifier[... | def p_reserved_word(self, p):
"""reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
| DO
... |
def WatchMetadata(
self, handler, metadata_key='', recursive=True, timeout=None):
"""Watch for changes to the contents of the metadata server.
Args:
handler: callable, a function to call with the updated metadata contents.
metadata_key: string, the metadata key to watch for changes.
rec... | def function[WatchMetadata, parameter[self, handler, metadata_key, recursive, timeout]]:
constant[Watch for changes to the contents of the metadata server.
Args:
handler: callable, a function to call with the updated metadata contents.
metadata_key: string, the metadata key to watch for changes... | keyword[def] identifier[WatchMetadata] (
identifier[self] , identifier[handler] , identifier[metadata_key] = literal[string] , identifier[recursive] = keyword[True] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[while] keyword[True] :
identifier[response] = identifier[self] . ide... | def WatchMetadata(self, handler, metadata_key='', recursive=True, timeout=None):
"""Watch for changes to the contents of the metadata server.
Args:
handler: callable, a function to call with the updated metadata contents.
metadata_key: string, the metadata key to watch for changes.
recursive:... |
def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
NTFSFileEntry: file entry or None if not available.
Raises:
BackEndError: if the file entry cannot be opened.
"""
# Openi... | def function[GetFileEntryByPathSpec, parameter[self, path_spec]]:
constant[Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
NTFSFileEntry: file entry or None if not available.
Raises:
BackEndError: if the file entry cannot... | keyword[def] identifier[GetFileEntryByPathSpec] ( identifier[self] , identifier[path_spec] ):
literal[string]
identifier[fsntfs_file_entry] = keyword[None]
identifier[location] = identifier[getattr] ( identifier[path_spec] , literal[string] , keyword[None] )
identifier[mft_attribute] =... | def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
NTFSFileEntry: file entry or None if not available.
Raises:
BackEndError: if the file entry cannot be opened.
"""
# Openi... |
def quickRPCServer(provider, prefix, target,
maxsize=20,
workers=1,
useenv=True, conf=None, isolate=False):
"""Run an RPC server in the current thread
Calls are handled sequentially, and always in the current thread, if workers=1 (the default).
If wo... | def function[quickRPCServer, parameter[provider, prefix, target, maxsize, workers, useenv, conf, isolate]]:
constant[Run an RPC server in the current thread
Calls are handled sequentially, and always in the current thread, if workers=1 (the default).
If workers>1 then calls are handled concurrently by ... | keyword[def] identifier[quickRPCServer] ( identifier[provider] , identifier[prefix] , identifier[target] ,
identifier[maxsize] = literal[int] ,
identifier[workers] = literal[int] ,
identifier[useenv] = keyword[True] , identifier[conf] = keyword[None] , identifier[isolate] = keyword[False] ):
literal[string]
... | def quickRPCServer(provider, prefix, target, maxsize=20, workers=1, useenv=True, conf=None, isolate=False):
"""Run an RPC server in the current thread
Calls are handled sequentially, and always in the current thread, if workers=1 (the default).
If workers>1 then calls are handled concurrently by a pool of ... |
def cv(self, t, structure=None):
"""
Constant volume specific heat C_v at temperature T obtained from the integration of the DOS.
Only positive frequencies will be used.
Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number
of Avogadro times the a... | def function[cv, parameter[self, t, structure]]:
constant[
Constant volume specific heat C_v at temperature T obtained from the integration of the DOS.
Only positive frequencies will be used.
Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number
o... | keyword[def] identifier[cv] ( identifier[self] , identifier[t] , identifier[structure] = keyword[None] ):
literal[string]
keyword[if] identifier[t] == literal[int] :
keyword[return] literal[int]
identifier[freqs] = identifier[self] . identifier[_positive_frequencies]
... | def cv(self, t, structure=None):
"""
Constant volume specific heat C_v at temperature T obtained from the integration of the DOS.
Only positive frequencies will be used.
Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number
of Avogadro times the atoms... |
def update_nodes_published(self):
""" publish or unpublish nodes of current layer """
if self.pk:
self.node_set.all().update(is_published=self.is_published) | def function[update_nodes_published, parameter[self]]:
constant[ publish or unpublish nodes of current layer ]
if name[self].pk begin[:]
call[call[name[self].node_set.all, parameter[]].update, parameter[]] | keyword[def] identifier[update_nodes_published] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[pk] :
identifier[self] . identifier[node_set] . identifier[all] (). identifier[update] ( identifier[is_published] = identifier[self] . identifier[is_publishe... | def update_nodes_published(self):
""" publish or unpublish nodes of current layer """
if self.pk:
self.node_set.all().update(is_published=self.is_published) # depends on [control=['if'], data=[]] |
def check_array(array, accept_sparse=None, dtype=None, order=None, copy=False,
force_all_finite=True, ensure_2d=True, allow_nd=False):
"""Input validation on an array, list, sparse matrix or similar.
By default, the input is converted to an at least 2nd numpy array.
Parameters
--------... | def function[check_array, parameter[array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd]]:
constant[Input validation on an array, list, sparse matrix or similar.
By default, the input is converted to an at least 2nd numpy array.
Parameters
----------
array : object
... | keyword[def] identifier[check_array] ( identifier[array] , identifier[accept_sparse] = keyword[None] , identifier[dtype] = keyword[None] , identifier[order] = keyword[None] , identifier[copy] = keyword[False] ,
identifier[force_all_finite] = keyword[True] , identifier[ensure_2d] = keyword[True] , identifier[allow_nd... | def check_array(array, accept_sparse=None, dtype=None, order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False):
"""Input validation on an array, list, sparse matrix or similar.
By default, the input is converted to an at least 2nd numpy array.
Parameters
----------
array : o... |
def _process_mark_toggle(self, p_todo_id, p_force=None):
"""
Adds p_todo_id to marked_todos attribute and returns True if p_todo_id
is not already marked. Removes p_todo_id from marked_todos and returns
False otherwise.
p_force parameter accepting 'mark' or 'unmark' values, if s... | def function[_process_mark_toggle, parameter[self, p_todo_id, p_force]]:
constant[
Adds p_todo_id to marked_todos attribute and returns True if p_todo_id
is not already marked. Removes p_todo_id from marked_todos and returns
False otherwise.
p_force parameter accepting 'mark' or... | keyword[def] identifier[_process_mark_toggle] ( identifier[self] , identifier[p_todo_id] , identifier[p_force] = keyword[None] ):
literal[string]
keyword[if] identifier[p_force] keyword[in] [ literal[string] , literal[string] ]:
identifier[action] = identifier[p_force]
keyw... | def _process_mark_toggle(self, p_todo_id, p_force=None):
"""
Adds p_todo_id to marked_todos attribute and returns True if p_todo_id
is not already marked. Removes p_todo_id from marked_todos and returns
False otherwise.
p_force parameter accepting 'mark' or 'unmark' values, if set, ... |
def _mark_refunded(self):
''' Marks the invoice as refunded, and updates the attached cart if
necessary. '''
self._release_cart()
self.invoice.status = commerce.Invoice.STATUS_REFUNDED
self.invoice.save() | def function[_mark_refunded, parameter[self]]:
constant[ Marks the invoice as refunded, and updates the attached cart if
necessary. ]
call[name[self]._release_cart, parameter[]]
name[self].invoice.status assign[=] name[commerce].Invoice.STATUS_REFUNDED
call[name[self].invoice.sav... | keyword[def] identifier[_mark_refunded] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_release_cart] ()
identifier[self] . identifier[invoice] . identifier[status] = identifier[commerce] . identifier[Invoice] . identifier[STATUS_REFUNDED]
identifier[self] . ... | def _mark_refunded(self):
""" Marks the invoice as refunded, and updates the attached cart if
necessary. """
self._release_cart()
self.invoice.status = commerce.Invoice.STATUS_REFUNDED
self.invoice.save() |
def get_birthday(code):
"""``get_birthday(code) -> string``
Birthday of the person whose fiscal code is 'code', in the format DD-MM-YY.
Unfortunately it's not possible to guess the four digit birth year, given
that the Italian fiscal code uses only the last two digits (1983 -> 83).
Therefore, thi... | def function[get_birthday, parameter[code]]:
constant[``get_birthday(code) -> string``
Birthday of the person whose fiscal code is 'code', in the format DD-MM-YY.
Unfortunately it's not possible to guess the four digit birth year, given
that the Italian fiscal code uses only the last two digits (... | keyword[def] identifier[get_birthday] ( identifier[code] ):
literal[string]
keyword[assert] identifier[isvalid] ( identifier[code] )
identifier[day] = identifier[int] ( identifier[code] [ literal[int] : literal[int] ])
identifier[day] = identifier[day] < literal[int] keyword[and] identifier[d... | def get_birthday(code):
"""``get_birthday(code) -> string``
Birthday of the person whose fiscal code is 'code', in the format DD-MM-YY.
Unfortunately it's not possible to guess the four digit birth year, given
that the Italian fiscal code uses only the last two digits (1983 -> 83).
Therefore, thi... |
def _generate_data_key(self, algorithm, encryption_context=None):
"""Generates data key and returns plaintext and ciphertext of key.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption... | def function[_generate_data_key, parameter[self, algorithm, encryption_context]]:
constant[Generates data key and returns plaintext and ciphertext of key.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encrypti... | keyword[def] identifier[_generate_data_key] ( identifier[self] , identifier[algorithm] , identifier[encryption_context] = keyword[None] ):
literal[string]
identifier[kms_params] ={ literal[string] : identifier[self] . identifier[_key_id] , literal[string] : identifier[algorithm] . identifier[kdf_in... | def _generate_data_key(self, algorithm, encryption_context=None):
"""Generates data key and returns plaintext and ciphertext of key.
:param algorithm: Algorithm on which to base data key
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param dict encryption_context: Encryption con... |
def _build_env(venv_dir):
"""Create a new virtual environment in `venv_dir`.
This uses the base prefix of any virtual environment that you may be using
when you call this.
"""
# NB: We had to create the because the venv modules wasn't doing what we
# needed. In particular, if we used it create ... | def function[_build_env, parameter[venv_dir]]:
constant[Create a new virtual environment in `venv_dir`.
This uses the base prefix of any virtual environment that you may be using
when you call this.
]
variable[prefix] assign[=] call[name[getattr], parameter[name[sys], constant[real_prefix],... | keyword[def] identifier[_build_env] ( identifier[venv_dir] ):
literal[string]
identifier[prefix] = identifier[getattr] ( identifier[sys] , literal[string] , identifier[sys] . identifier[prefix] )
identifier[python] = identifier[Path] ( identifier[prefix] )/ literal[string... | def _build_env(venv_dir):
"""Create a new virtual environment in `venv_dir`.
This uses the base prefix of any virtual environment that you may be using
when you call this.
"""
# NB: We had to create the because the venv modules wasn't doing what we
# needed. In particular, if we used it create ... |
def unicode_body(self, ignore_errors=True, fix_special_entities=True):
"""
Return response body as unicode string.
"""
if not self._unicode_body:
self._unicode_body = self.convert_body_to_unicode(
body=self.body,
bom=self.bom,
... | def function[unicode_body, parameter[self, ignore_errors, fix_special_entities]]:
constant[
Return response body as unicode string.
]
if <ast.UnaryOp object at 0x7da1b184dd50> begin[:]
name[self]._unicode_body assign[=] call[name[self].convert_body_to_unicode, parameter[]... | keyword[def] identifier[unicode_body] ( identifier[self] , identifier[ignore_errors] = keyword[True] , identifier[fix_special_entities] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_unicode_body] :
identifier[self] . identifier[_unicode_b... | def unicode_body(self, ignore_errors=True, fix_special_entities=True):
"""
Return response body as unicode string.
"""
if not self._unicode_body:
self._unicode_body = self.convert_body_to_unicode(body=self.body, bom=self.bom, charset=self.charset, ignore_errors=ignore_errors, fix_special... |
def _parseDebugDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the C{IMAGE_DEBUG_DIRECTORY} directory.
@see: U{http://msdn.microsoft.com/es-es/library/windows/desktop/ms680307(v=vs.85).aspx}
@type rva: int
@param rva: The RVA where the C{IMAGE_DEBUG_DIRECTOR... | def function[_parseDebugDirectory, parameter[self, rva, size, magic]]:
constant[
Parses the C{IMAGE_DEBUG_DIRECTORY} directory.
@see: U{http://msdn.microsoft.com/es-es/library/windows/desktop/ms680307(v=vs.85).aspx}
@type rva: int
@param rva: The RVA where the C{IMAGE_D... | keyword[def] identifier[_parseDebugDirectory] ( identifier[self] , identifier[rva] , identifier[size] , identifier[magic] = identifier[consts] . identifier[PE32] ):
literal[string]
identifier[debugDirData] = identifier[self] . identifier[getDataAtRva] ( identifier[rva] , identifier[size] )
... | def _parseDebugDirectory(self, rva, size, magic=consts.PE32):
"""
Parses the C{IMAGE_DEBUG_DIRECTORY} directory.
@see: U{http://msdn.microsoft.com/es-es/library/windows/desktop/ms680307(v=vs.85).aspx}
@type rva: int
@param rva: The RVA where the C{IMAGE_DEBUG_DIRECTORY} dir... |
def itemsize(self):
""" Individual item sizes """
return self._items[:self._count, 1] - self._items[:self._count, 0] | def function[itemsize, parameter[self]]:
constant[ Individual item sizes ]
return[binary_operation[call[name[self]._items][tuple[[<ast.Slice object at 0x7da1b0eadcc0>, <ast.Constant object at 0x7da1b0eadf60>]]] - call[name[self]._items][tuple[[<ast.Slice object at 0x7da1b0eadc60>, <ast.Constant object at 0x... | keyword[def] identifier[itemsize] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_items] [: identifier[self] . identifier[_count] , literal[int] ]- identifier[self] . identifier[_items] [: identifier[self] . identifier[_count] , literal[int] ] | def itemsize(self):
""" Individual item sizes """
return self._items[:self._count, 1] - self._items[:self._count, 0] |
def comb_indices(n, k):
"""``n``-dimensional version of itertools.combinations.
Args:
a (np.ndarray): The array from which to get combinations.
k (int): The desired length of the combinations.
Returns:
np.ndarray: Indices that give the ``k``-combinations of ``n`` elements.
Exa... | def function[comb_indices, parameter[n, k]]:
constant[``n``-dimensional version of itertools.combinations.
Args:
a (np.ndarray): The array from which to get combinations.
k (int): The desired length of the combinations.
Returns:
np.ndarray: Indices that give the ``k``-combinati... | keyword[def] identifier[comb_indices] ( identifier[n] , identifier[k] ):
literal[string]
identifier[count] = identifier[comb] ( identifier[n] , identifier[k] , identifier[exact] = keyword[True] )
identifier[indices] = identifier[np] . identifier[fromiter] (
identifier[chain] . identifie... | def comb_indices(n, k):
"""``n``-dimensional version of itertools.combinations.
Args:
a (np.ndarray): The array from which to get combinations.
k (int): The desired length of the combinations.
Returns:
np.ndarray: Indices that give the ``k``-combinations of ``n`` elements.
Exa... |
def ipv6_is_defined(address):
"""
The function for checking if an IPv6 address is defined (does not need to
be resolved).
Args:
address (:obj:`str`): An IPv6 address.
Returns:
namedtuple:
:is_defined (bool): True if given address is defined, otherwise
False
... | def function[ipv6_is_defined, parameter[address]]:
constant[
The function for checking if an IPv6 address is defined (does not need to
be resolved).
Args:
address (:obj:`str`): An IPv6 address.
Returns:
namedtuple:
:is_defined (bool): True if given address is defined, ... | keyword[def] identifier[ipv6_is_defined] ( identifier[address] ):
literal[string]
identifier[query_ip] = identifier[IPv6Address] ( identifier[str] ( identifier[address] ))
identifier[results] = identifier[namedtuple] ( literal[string] , literal[string]
literal[string] )
key... | def ipv6_is_defined(address):
"""
The function for checking if an IPv6 address is defined (does not need to
be resolved).
Args:
address (:obj:`str`): An IPv6 address.
Returns:
namedtuple:
:is_defined (bool): True if given address is defined, otherwise
False
... |
def validate(config):
'''
Validate the beacon configuration
'''
valid = True
messages = []
if not isinstance(config, list):
valid = False
messages.append('[-] Configuration for %s beacon must be a list', config)
else:
_config = {}
list(map(_config.update, con... | def function[validate, parameter[config]]:
constant[
Validate the beacon configuration
]
variable[valid] assign[=] constant[True]
variable[messages] assign[=] list[[]]
if <ast.UnaryOp object at 0x7da1b1c19b10> begin[:]
variable[valid] assign[=] constant[False]
... | keyword[def] identifier[validate] ( identifier[config] ):
literal[string]
identifier[valid] = keyword[True]
identifier[messages] =[]
keyword[if] keyword[not] identifier[isinstance] ( identifier[config] , identifier[list] ):
identifier[valid] = keyword[False]
identifier[mess... | def validate(config):
"""
Validate the beacon configuration
"""
valid = True
messages = []
if not isinstance(config, list):
valid = False
messages.append('[-] Configuration for %s beacon must be a list', config) # depends on [control=['if'], data=[]]
else:
_config = ... |
def save(self):
"""
Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is u... | def function[save, parameter[self]]:
constant[
Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely th... | keyword[def] identifier[save] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[views] :
keyword[if] identifier[self] . identifier[get] ( literal[string] , keyword[None] )!= identifier[QUERY_LANGUAGE] :
keyword[for] identifier[view_name... | def save(self):
"""
Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is updat... |
def retrieve(endpoint='incidents',
api_url=None,
page_id=None,
api_key=None,
api_version=None):
'''
Retrieve a specific endpoint from the Statuspage API.
endpoint: incidents
Request a specific endpoint.
page_id
Page ID. Can also be sp... | def function[retrieve, parameter[endpoint, api_url, page_id, api_key, api_version]]:
constant[
Retrieve a specific endpoint from the Statuspage API.
endpoint: incidents
Request a specific endpoint.
page_id
Page ID. Can also be specified in the config file.
api_key
API ... | keyword[def] identifier[retrieve] ( identifier[endpoint] = literal[string] ,
identifier[api_url] = keyword[None] ,
identifier[page_id] = keyword[None] ,
identifier[api_key] = keyword[None] ,
identifier[api_version] = keyword[None] ):
literal[string]
identifier[params] = identifier[_get_api_params] ( id... | def retrieve(endpoint='incidents', api_url=None, page_id=None, api_key=None, api_version=None):
"""
Retrieve a specific endpoint from the Statuspage API.
endpoint: incidents
Request a specific endpoint.
page_id
Page ID. Can also be specified in the config file.
api_key
API... |
def assignment_source(num_pre, num_post, LISTNAME, ITERNAME):
u"""
Accepts num_pre and num_post, which are counts of values
before and after the starg (not including the starg)
Returns a source fit for Assign() from fixer_util
"""
children = []
pre = unicode(num_pre)
post = unicode(num_p... | def function[assignment_source, parameter[num_pre, num_post, LISTNAME, ITERNAME]]:
constant[
Accepts num_pre and num_post, which are counts of values
before and after the starg (not including the starg)
Returns a source fit for Assign() from fixer_util
]
variable[children] assign[=] list... | keyword[def] identifier[assignment_source] ( identifier[num_pre] , identifier[num_post] , identifier[LISTNAME] , identifier[ITERNAME] ):
literal[string]
identifier[children] =[]
identifier[pre] = identifier[unicode] ( identifier[num_pre] )
identifier[post] = identifier[unicode] ( identifier[num_p... | def assignment_source(num_pre, num_post, LISTNAME, ITERNAME):
u"""
Accepts num_pre and num_post, which are counts of values
before and after the starg (not including the starg)
Returns a source fit for Assign() from fixer_util
"""
children = []
pre = unicode(num_pre)
post = unicode(num_p... |
def clear_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False):
"""Clear DCNM out partition information.
Clear the DCNM OUT partition service node IP address and update
the result
"""
res = fw_const.DCNM_OUT_PART_UPDDEL_SUCCESS
self.update_fw_db_result(tenant_id, dc... | def function[clear_dcnm_out_part, parameter[self, tenant_id, fw_dict, is_fw_virt]]:
constant[Clear DCNM out partition information.
Clear the DCNM OUT partition service node IP address and update
the result
]
variable[res] assign[=] name[fw_const].DCNM_OUT_PART_UPDDEL_SUCCESS
... | keyword[def] identifier[clear_dcnm_out_part] ( identifier[self] , identifier[tenant_id] , identifier[fw_dict] , identifier[is_fw_virt] = keyword[False] ):
literal[string]
identifier[res] = identifier[fw_const] . identifier[DCNM_OUT_PART_UPDDEL_SUCCESS]
identifier[self] . identifier[update... | def clear_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False):
"""Clear DCNM out partition information.
Clear the DCNM OUT partition service node IP address and update
the result
"""
res = fw_const.DCNM_OUT_PART_UPDDEL_SUCCESS
self.update_fw_db_result(tenant_id, dcnm_status=re... |
def wait(self):
"""Waits and returns received messages.
If running in compatibility mode for older uWSGI versions,
it also sends messages that have been queued by send().
A return value of None means that connection was closed.
This must be called repeatedly. For uWSGI < 2.1.x it... | def function[wait, parameter[self]]:
constant[Waits and returns received messages.
If running in compatibility mode for older uWSGI versions,
it also sends messages that have been queued by send().
A return value of None means that connection was closed.
This must be called repea... | keyword[def] identifier[wait] ( identifier[self] ):
literal[string]
keyword[while] keyword[True] :
keyword[if] identifier[self] . identifier[_req_ctx] keyword[is] keyword[not] keyword[None] :
keyword[try] :
identifier[msg] = identifier[uwsgi] ... | def wait(self):
"""Waits and returns received messages.
If running in compatibility mode for older uWSGI versions,
it also sends messages that have been queued by send().
A return value of None means that connection was closed.
This must be called repeatedly. For uWSGI < 2.1.x it mus... |
def __setup(self):
"""
Setup
:return:
"""
if not os.path.exists(self.__local_download_dir_warc):
os.makedirs(self.__local_download_dir_warc)
# make loggers quite
configure_logging({"LOG_LEVEL": "ERROR"})
logging.getLogger('requests').setLevel(... | def function[__setup, parameter[self]]:
constant[
Setup
:return:
]
if <ast.UnaryOp object at 0x7da20cabf250> begin[:]
call[name[os].makedirs, parameter[name[self].__local_download_dir_warc]]
call[name[configure_logging], parameter[dictionary[[<ast.Constant... | keyword[def] identifier[__setup] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[__local_download_dir_warc] ):
identifier[os] . identifier[makedirs] ( identifier[self] . identifier[_... | def __setup(self):
"""
Setup
:return:
"""
if not os.path.exists(self.__local_download_dir_warc):
os.makedirs(self.__local_download_dir_warc) # depends on [control=['if'], data=[]]
# make loggers quite
configure_logging({'LOG_LEVEL': 'ERROR'})
logging.getLogger('reque... |
def setup_neighbors_distances_and_angles(self, indices):
"""
Initializes the angle and distance separations
:param indices: indices of the sites for which the Voronoi is needed
"""
self.neighbors_distances = [None] * len(self.structure)
self.neighbors_normalized_distances... | def function[setup_neighbors_distances_and_angles, parameter[self, indices]]:
constant[
Initializes the angle and distance separations
:param indices: indices of the sites for which the Voronoi is needed
]
name[self].neighbors_distances assign[=] binary_operation[list[[<ast.Const... | keyword[def] identifier[setup_neighbors_distances_and_angles] ( identifier[self] , identifier[indices] ):
literal[string]
identifier[self] . identifier[neighbors_distances] =[ keyword[None] ]* identifier[len] ( identifier[self] . identifier[structure] )
identifier[self] . identifier[neighb... | def setup_neighbors_distances_and_angles(self, indices):
"""
Initializes the angle and distance separations
:param indices: indices of the sites for which the Voronoi is needed
"""
self.neighbors_distances = [None] * len(self.structure)
self.neighbors_normalized_distances = [None] * ... |
def _get_assistants_snippets(path, name):
'''Get Assistants and Snippets for a given DAP name on a given path'''
result = []
subdirs = {'assistants': 2, 'snippets': 1} # Values used for stripping leading path tokens
for loc in subdirs:
for root, dirs, files in os.walk(os.path.join(path, loc)):
... | def function[_get_assistants_snippets, parameter[path, name]]:
constant[Get Assistants and Snippets for a given DAP name on a given path]
variable[result] assign[=] list[[]]
variable[subdirs] assign[=] dictionary[[<ast.Constant object at 0x7da1b1151570>, <ast.Constant object at 0x7da1b1152b30>],... | keyword[def] identifier[_get_assistants_snippets] ( identifier[path] , identifier[name] ):
literal[string]
identifier[result] =[]
identifier[subdirs] ={ literal[string] : literal[int] , literal[string] : literal[int] }
keyword[for] identifier[loc] keyword[in] identifier[subdirs] :
ke... | def _get_assistants_snippets(path, name):
"""Get Assistants and Snippets for a given DAP name on a given path"""
result = []
subdirs = {'assistants': 2, 'snippets': 1} # Values used for stripping leading path tokens
for loc in subdirs:
for (root, dirs, files) in os.walk(os.path.join(path, loc))... |
def psdcompletion(A, reordered = True, **kwargs):
"""
Maximum determinant positive semidefinite matrix completion. The
routine takes a cspmatrix :math:`A` and returns the maximum determinant
positive semidefinite matrix completion :math:`X` as a dense matrix, i.e.,
.. math::
P( X ) = A
... | def function[psdcompletion, parameter[A, reordered]]:
constant[
Maximum determinant positive semidefinite matrix completion. The
routine takes a cspmatrix :math:`A` and returns the maximum determinant
positive semidefinite matrix completion :math:`X` as a dense matrix, i.e.,
.. math::
... | keyword[def] identifier[psdcompletion] ( identifier[A] , identifier[reordered] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[A] , identifier[cspmatrix] ) keyword[and] identifier[A] . identifier[is_factor] keyword[is] keyword[False] , liter... | def psdcompletion(A, reordered=True, **kwargs):
"""
Maximum determinant positive semidefinite matrix completion. The
routine takes a cspmatrix :math:`A` and returns the maximum determinant
positive semidefinite matrix completion :math:`X` as a dense matrix, i.e.,
.. math::
P( X ) = A
... |
def _create_model(self, view_getter=None, source_getters=None,
model_factory=None, officer=None):
"""
Creates a model from the model factory after retrieving
the source and the view. The officer is the IOfficer
FOR THE MODEL TO BE CREATED and NO OFFICER CHECKS ARE P... | def function[_create_model, parameter[self, view_getter, source_getters, model_factory, officer]]:
constant[
Creates a model from the model factory after retrieving
the source and the view. The officer is the IOfficer
FOR THE MODEL TO BE CREATED and NO OFFICER CHECKS ARE PERFORMED.
... | keyword[def] identifier[_create_model] ( identifier[self] , identifier[view_getter] = keyword[None] , identifier[source_getters] = keyword[None] ,
identifier[model_factory] = keyword[None] , identifier[officer] = keyword[None] ):
literal[string]
keyword[if] identifier[view_getter] keyword[is] ... | def _create_model(self, view_getter=None, source_getters=None, model_factory=None, officer=None):
"""
Creates a model from the model factory after retrieving
the source and the view. The officer is the IOfficer
FOR THE MODEL TO BE CREATED and NO OFFICER CHECKS ARE PERFORMED.
"""
... |
def MI_enumInstanceNames(self,
env,
objPath):
# pylint: disable=invalid-name
"""Return instance names of a given CIM class
Implements the WBEM operation EnumerateInstanceNames in terms
of the enum_instances method. A derived cla... | def function[MI_enumInstanceNames, parameter[self, env, objPath]]:
constant[Return instance names of a given CIM class
Implements the WBEM operation EnumerateInstanceNames in terms
of the enum_instances method. A derived class will not normally
override this method.
]
... | keyword[def] identifier[MI_enumInstanceNames] ( identifier[self] ,
identifier[env] ,
identifier[objPath] ):
literal[string]
identifier[logger] = identifier[env] . identifier[get_logger] ()
identifier[logger] . identifier[log_debug] ( literal[string] )
identifier[model] = ident... | def MI_enumInstanceNames(self, env, objPath):
# pylint: disable=invalid-name
'Return instance names of a given CIM class\n\n Implements the WBEM operation EnumerateInstanceNames in terms\n of the enum_instances method. A derived class will not normally\n override this method.\n\n '
... |
def insert(self, docs, *args, **kwargs):
"""Backwards compatibility with insert"""
if isinstance(docs, list):
return self.insert_many(docs, *args, **kwargs)
else:
return self.insert_one(docs, *args, **kwargs) | def function[insert, parameter[self, docs]]:
constant[Backwards compatibility with insert]
if call[name[isinstance], parameter[name[docs], name[list]]] begin[:]
return[call[name[self].insert_many, parameter[name[docs], <ast.Starred object at 0x7da18f58d3c0>]]] | keyword[def] identifier[insert] ( identifier[self] , identifier[docs] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[docs] , identifier[list] ):
keyword[return] identifier[self] . identifier[insert_many] ( identifier[docs... | def insert(self, docs, *args, **kwargs):
"""Backwards compatibility with insert"""
if isinstance(docs, list):
return self.insert_many(docs, *args, **kwargs) # depends on [control=['if'], data=[]]
else:
return self.insert_one(docs, *args, **kwargs) |
def iterate(self, delay=None):
"""See twisted.internet.interfaces.IReactorCore.iterate.
"""
self.runUntilCurrent()
self.doEvents()
self.doIteration(delay) | def function[iterate, parameter[self, delay]]:
constant[See twisted.internet.interfaces.IReactorCore.iterate.
]
call[name[self].runUntilCurrent, parameter[]]
call[name[self].doEvents, parameter[]]
call[name[self].doIteration, parameter[name[delay]]] | keyword[def] identifier[iterate] ( identifier[self] , identifier[delay] = keyword[None] ):
literal[string]
identifier[self] . identifier[runUntilCurrent] ()
identifier[self] . identifier[doEvents] ()
identifier[self] . identifier[doIteration] ( identifier[delay] ) | def iterate(self, delay=None):
"""See twisted.internet.interfaces.IReactorCore.iterate.
"""
self.runUntilCurrent()
self.doEvents()
self.doIteration(delay) |
def starargs(self):
"""The positional arguments that unpack something.
:type: list(Starred)
"""
args = self.args or []
return [arg for arg in args if isinstance(arg, Starred)] | def function[starargs, parameter[self]]:
constant[The positional arguments that unpack something.
:type: list(Starred)
]
variable[args] assign[=] <ast.BoolOp object at 0x7da1b1e78d30>
return[<ast.ListComp object at 0x7da1b1e7b5e0>] | keyword[def] identifier[starargs] ( identifier[self] ):
literal[string]
identifier[args] = identifier[self] . identifier[args] keyword[or] []
keyword[return] [ identifier[arg] keyword[for] identifier[arg] keyword[in] identifier[args] keyword[if] identifier[isinstance] ( identifier[a... | def starargs(self):
"""The positional arguments that unpack something.
:type: list(Starred)
"""
args = self.args or []
return [arg for arg in args if isinstance(arg, Starred)] |
def initdb(self):
"""Create tables and indices as needed."""
if hasattr(self, 'alchemist'):
self.alchemist.meta.create_all(self.engine)
if 'branch' not in self.globl:
self.globl['branch'] = 'trunk'
if 'rev' not in self.globl:
self.globl... | def function[initdb, parameter[self]]:
constant[Create tables and indices as needed.]
if call[name[hasattr], parameter[name[self], constant[alchemist]]] begin[:]
call[name[self].alchemist.meta.create_all, parameter[name[self].engine]]
if compare[constant[branch] <ast.NotI... | keyword[def] identifier[initdb] ( identifier[self] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[alchemist] . identifier[meta] . identifier[create_all] ( identifier[self] . identifier[engine] )
key... | def initdb(self):
"""Create tables and indices as needed."""
if hasattr(self, 'alchemist'):
self.alchemist.meta.create_all(self.engine)
if 'branch' not in self.globl:
self.globl['branch'] = 'trunk' # depends on [control=['if'], data=[]]
if 'rev' not in self.globl:
... |
def stop_consumer(self):
"""Stop the consumer object and allow it to do a clean shutdown if it
has the ability to do so.
"""
try:
LOGGER.info('Shutting down the consumer')
self.consumer.shutdown()
except AttributeError:
LOGGER.debug('Consumer ... | def function[stop_consumer, parameter[self]]:
constant[Stop the consumer object and allow it to do a clean shutdown if it
has the ability to do so.
]
<ast.Try object at 0x7da18dc05f30> | keyword[def] identifier[stop_consumer] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[LOGGER] . identifier[info] ( literal[string] )
identifier[self] . identifier[consumer] . identifier[shutdown] ()
keyword[except] identifier[AttributeError] :
... | def stop_consumer(self):
"""Stop the consumer object and allow it to do a clean shutdown if it
has the ability to do so.
"""
try:
LOGGER.info('Shutting down the consumer')
self.consumer.shutdown() # depends on [control=['try'], data=[]]
except AttributeError:
LOGGER... |
def get_all_user_groups(self, **kwargs): # noqa: E501
"""Get all user groups for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_user_group... | def function[get_all_user_groups, parameter[self]]:
constant[Get all user groups for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_user_gr... | keyword[def] identifier[get_all_user_groups] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self] . identifie... | def get_all_user_groups(self, **kwargs): # noqa: E501
'Get all user groups for a customer # noqa: E501\n\n # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_all_user_groups... |
def get_routes(self, viewset):
"""
DREST routes injection, overrides DRF's get_routes() method, which
gets called for each registered viewset.
"""
routes = super(DynamicRouter, self).get_routes(viewset)
routes += self.get_relation_routes(viewset)
return routes | def function[get_routes, parameter[self, viewset]]:
constant[
DREST routes injection, overrides DRF's get_routes() method, which
gets called for each registered viewset.
]
variable[routes] assign[=] call[call[name[super], parameter[name[DynamicRouter], name[self]]].get_routes, pa... | keyword[def] identifier[get_routes] ( identifier[self] , identifier[viewset] ):
literal[string]
identifier[routes] = identifier[super] ( identifier[DynamicRouter] , identifier[self] ). identifier[get_routes] ( identifier[viewset] )
identifier[routes] += identifier[self] . identifier[get_re... | def get_routes(self, viewset):
"""
DREST routes injection, overrides DRF's get_routes() method, which
gets called for each registered viewset.
"""
routes = super(DynamicRouter, self).get_routes(viewset)
routes += self.get_relation_routes(viewset)
return routes |
def ts_stats_significance_bootstrap(ts, stats_ts, stats_func, B=1000, b=3):
""" Compute the statistical significance of a test statistic at each point
of the time series by using timeseries boootstrap.
"""
pvals = []
for tp in np.arange(0, len(stats_ts)):
pf = partial(stats_func, t=tp)
... | def function[ts_stats_significance_bootstrap, parameter[ts, stats_ts, stats_func, B, b]]:
constant[ Compute the statistical significance of a test statistic at each point
of the time series by using timeseries boootstrap.
]
variable[pvals] assign[=] list[[]]
for taget[name[tp]] in s... | keyword[def] identifier[ts_stats_significance_bootstrap] ( identifier[ts] , identifier[stats_ts] , identifier[stats_func] , identifier[B] = literal[int] , identifier[b] = literal[int] ):
literal[string]
identifier[pvals] =[]
keyword[for] identifier[tp] keyword[in] identifier[np] . identifier[arange... | def ts_stats_significance_bootstrap(ts, stats_ts, stats_func, B=1000, b=3):
""" Compute the statistical significance of a test statistic at each point
of the time series by using timeseries boootstrap.
"""
pvals = []
for tp in np.arange(0, len(stats_ts)):
pf = partial(stats_func, t=tp)
... |
def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts):
"""Return a dict with variables for the 'prepare' action."""
# Add the _SCRIPT_REPR with the repr(script) contents
# Add the _META_YAML_REPR with the repr(meta) contents
# Add variables for directories that need to be created... | def function[_get_prepare_env, parameter[self, script, job_descriptor, inputs, outputs, mounts]]:
constant[Return a dict with variables for the 'prepare' action.]
variable[docker_paths] assign[=] call[name[sorted], parameter[<ast.ListComp object at 0x7da1b012ea70>]]
variable[env] assign[=] dicti... | keyword[def] identifier[_get_prepare_env] ( identifier[self] , identifier[script] , identifier[job_descriptor] , identifier[inputs] , identifier[outputs] , identifier[mounts] ):
literal[string]
identifier[docker_paths] = identifier[sorted... | def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts):
"""Return a dict with variables for the 'prepare' action."""
# Add the _SCRIPT_REPR with the repr(script) contents
# Add the _META_YAML_REPR with the repr(meta) contents
# Add variables for directories that need to be created, ... |
def assign_funds_to_account_pending_invoices(account_id: str) -> Sequence[str]:
"""
Tries to pay pending account invoices (starting from the oldest) with available funds.
:param account_id: the account on which to perform the operation
:return: The ids of the invoices that were paid (possibly empty list... | def function[assign_funds_to_account_pending_invoices, parameter[account_id]]:
constant[
Tries to pay pending account invoices (starting from the oldest) with available funds.
:param account_id: the account on which to perform the operation
:return: The ids of the invoices that were paid (possibly e... | keyword[def] identifier[assign_funds_to_account_pending_invoices] ( identifier[account_id] : identifier[str] )-> identifier[Sequence] [ identifier[str] ]:
literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[account_id] = identifier[str] ( identifier[account_id] ))
ide... | def assign_funds_to_account_pending_invoices(account_id: str) -> Sequence[str]:
"""
Tries to pay pending account invoices (starting from the oldest) with available funds.
:param account_id: the account on which to perform the operation
:return: The ids of the invoices that were paid (possibly empty list... |
def api_user(request, userPk, key=None, hproPk=None):
"""Return information about an user"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
if settings.PIAPI_STANDALONE:
if not settings.PIAPI_REALUSERS:
user = generate_user(pk=userPk)
if us... | def function[api_user, parameter[request, userPk, key, hproPk]]:
constant[Return information about an user]
if <ast.UnaryOp object at 0x7da2041da710> begin[:]
return[name[HttpResponseForbidden]]
if name[settings].PIAPI_STANDALONE begin[:]
if <ast.UnaryOp object at 0x7da20... | keyword[def] identifier[api_user] ( identifier[request] , identifier[userPk] , identifier[key] = keyword[None] , identifier[hproPk] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[check_api_key] ( identifier[request] , identifier[key] , identifier[hproPk] ):
keyword[retur... | def api_user(request, userPk, key=None, hproPk=None):
"""Return information about an user"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden # depends on [control=['if'], data=[]]
if settings.PIAPI_STANDALONE:
if not settings.PIAPI_REALUSERS:
user = gene... |
def deploy_password(username, password, host=None, admin_username=None,
admin_password=None, module=None):
'''
Change the QuickDeploy password, used for switches as well
CLI Example:
.. code-block:: bash
salt dell dracr.deploy_password [USERNAME] [PASSWORD]
hos... | def function[deploy_password, parameter[username, password, host, admin_username, admin_password, module]]:
constant[
Change the QuickDeploy password, used for switches as well
CLI Example:
.. code-block:: bash
salt dell dracr.deploy_password [USERNAME] [PASSWORD]
host=<remote... | keyword[def] identifier[deploy_password] ( identifier[username] , identifier[password] , identifier[host] = keyword[None] , identifier[admin_username] = keyword[None] ,
identifier[admin_password] = keyword[None] , identifier[module] = keyword[None] ):
literal[string]
keyword[return] identifier[__execute_... | def deploy_password(username, password, host=None, admin_username=None, admin_password=None, module=None):
"""
Change the QuickDeploy password, used for switches as well
CLI Example:
.. code-block:: bash
salt dell dracr.deploy_password [USERNAME] [PASSWORD]
host=<remote DRAC> admi... |
def derive_fernet_key(input_key):
"""Derive a 32-bit b64-encoded Fernet key from arbitrary input key."""
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
info=info,
backend=backend,
)
return base64.urlsafe_b64encode(hkdf.derive(force_bytes(input_key))... | def function[derive_fernet_key, parameter[input_key]]:
constant[Derive a 32-bit b64-encoded Fernet key from arbitrary input key.]
variable[hkdf] assign[=] call[name[HKDF], parameter[]]
return[call[name[base64].urlsafe_b64encode, parameter[call[name[hkdf].derive, parameter[call[name[force_bytes], par... | keyword[def] identifier[derive_fernet_key] ( identifier[input_key] ):
literal[string]
identifier[hkdf] = identifier[HKDF] (
identifier[algorithm] = identifier[hashes] . identifier[SHA256] (),
identifier[length] = literal[int] ,
identifier[salt] = identifier[salt] ,
identifier[info] = id... | def derive_fernet_key(input_key):
"""Derive a 32-bit b64-encoded Fernet key from arbitrary input key."""
hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=info, backend=backend)
return base64.urlsafe_b64encode(hkdf.derive(force_bytes(input_key))) |
def name(self, value):
"""Name associated with this email.
:param value: Name associated with this email.
:type value: string
"""
if not (value is None or isinstance(value, str)):
raise TypeError('name must be of type string.')
# Escape common CSV delimiters... | def function[name, parameter[self, value]]:
constant[Name associated with this email.
:param value: Name associated with this email.
:type value: string
]
if <ast.UnaryOp object at 0x7da18f09d720> begin[:]
<ast.Raise object at 0x7da18f09d270>
if <ast.BoolOp objec... | keyword[def] identifier[name] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] keyword[not] ( identifier[value] keyword[is] keyword[None] keyword[or] identifier[isinstance] ( identifier[value] , identifier[str] )):
keyword[raise] identifier[TypeError] ( liter... | def name(self, value):
"""Name associated with this email.
:param value: Name associated with this email.
:type value: string
"""
if not (value is None or isinstance(value, str)):
raise TypeError('name must be of type string.') # depends on [control=['if'], data=[]]
# Escap... |
def encrypt(self, msg, alg='aes_128_cbc', padding='PKCS#7', b64enc=True,
block_size=AES_BLOCK_SIZE):
"""
:param key: The encryption key
:param msg: Message to be encrypted
:param padding: Which padding that should be used
:param b64enc: Whether the result should b... | def function[encrypt, parameter[self, msg, alg, padding, b64enc, block_size]]:
constant[
:param key: The encryption key
:param msg: Message to be encrypted
:param padding: Which padding that should be used
:param b64enc: Whether the result should be base64encoded
:param b... | keyword[def] identifier[encrypt] ( identifier[self] , identifier[msg] , identifier[alg] = literal[string] , identifier[padding] = literal[string] , identifier[b64enc] = keyword[True] ,
identifier[block_size] = identifier[AES_BLOCK_SIZE] ):
literal[string]
identifier[self] . identifier[__class__] .... | def encrypt(self, msg, alg='aes_128_cbc', padding='PKCS#7', b64enc=True, block_size=AES_BLOCK_SIZE):
"""
:param key: The encryption key
:param msg: Message to be encrypted
:param padding: Which padding that should be used
:param b64enc: Whether the result should be base64encoded
... |
def ls_dir(base_dir):
"""List files recursively."""
return [
os.path.join(dirpath.replace(base_dir, '', 1), f)
for (dirpath, dirnames, files) in os.walk(base_dir)
for f in files
] | def function[ls_dir, parameter[base_dir]]:
constant[List files recursively.]
return[<ast.ListComp object at 0x7da18ede7970>] | keyword[def] identifier[ls_dir] ( identifier[base_dir] ):
literal[string]
keyword[return] [
identifier[os] . identifier[path] . identifier[join] ( identifier[dirpath] . identifier[replace] ( identifier[base_dir] , literal[string] , literal[int] ), identifier[f] )
keyword[for] ( identifier[dirpath... | def ls_dir(base_dir):
"""List files recursively."""
return [os.path.join(dirpath.replace(base_dir, '', 1), f) for (dirpath, dirnames, files) in os.walk(base_dir) for f in files] |
def updated(name=None, cyg_arch='x86_64', mirrors=None):
'''
Make sure all packages are up to date.
name : None
No affect, salt fails poorly without the arg available
cyg_arch : x86_64
The cygwin architecture to update.
Current options are x86 and x86_64
mirrors : None
... | def function[updated, parameter[name, cyg_arch, mirrors]]:
constant[
Make sure all packages are up to date.
name : None
No affect, salt fails poorly without the arg available
cyg_arch : x86_64
The cygwin architecture to update.
Current options are x86 and x86_64
mirror... | keyword[def] identifier[updated] ( identifier[name] = keyword[None] , identifier[cyg_arch] = literal[string] , identifier[mirrors] = keyword[None] ):
literal[string]
identifier[ret] ={ literal[string] : literal[string] , literal[string] : keyword[None] , literal[string] : literal[string] , literal[string] ... | def updated(name=None, cyg_arch='x86_64', mirrors=None):
"""
Make sure all packages are up to date.
name : None
No affect, salt fails poorly without the arg available
cyg_arch : x86_64
The cygwin architecture to update.
Current options are x86 and x86_64
mirrors : None
... |
def _set_minimum_links(self, v, load=False):
"""
Setter method for minimum_links, mapped from YANG variable /interface/port_channel/minimum_links (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_minimum_links is considered as a private
method. Backends lookin... | def function[_set_minimum_links, parameter[self, v, load]]:
constant[
Setter method for minimum_links, mapped from YANG variable /interface/port_channel/minimum_links (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_minimum_links is considered as a private
... | keyword[def] identifier[_set_minimum_links] ( 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] :
... | def _set_minimum_links(self, v, load=False):
"""
Setter method for minimum_links, mapped from YANG variable /interface/port_channel/minimum_links (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_minimum_links is considered as a private
method. Backends lookin... |
def do_imports(self):
"""
Import all importable options
"""
self.do_import('worker_class', Worker)
self.do_import('queue_model', self.options.worker_class.queue_model)
self.do_import('error_model', self.options.worker_class.error_model)
self.do_import('callback', ... | def function[do_imports, parameter[self]]:
constant[
Import all importable options
]
call[name[self].do_import, parameter[constant[worker_class], name[Worker]]]
call[name[self].do_import, parameter[constant[queue_model], name[self].options.worker_class.queue_model]]
call[... | keyword[def] identifier[do_imports] ( identifier[self] ):
literal[string]
identifier[self] . identifier[do_import] ( literal[string] , identifier[Worker] )
identifier[self] . identifier[do_import] ( literal[string] , identifier[self] . identifier[options] . identifier[worker_class] . ident... | def do_imports(self):
"""
Import all importable options
"""
self.do_import('worker_class', Worker)
self.do_import('queue_model', self.options.worker_class.queue_model)
self.do_import('error_model', self.options.worker_class.error_model)
self.do_import('callback', self.options.worker_... |
def merge_envs(*args):
"""Union of one or more dictionaries.
In case of duplicate keys, the values in the right-most arguments will
squash (overwrite) the value provided by any dict preceding it.
:param args: Sequence of ``dict`` objects that should be merged.
:return: A ``dict`` containing the un... | def function[merge_envs, parameter[]]:
constant[Union of one or more dictionaries.
In case of duplicate keys, the values in the right-most arguments will
squash (overwrite) the value provided by any dict preceding it.
:param args: Sequence of ``dict`` objects that should be merged.
:return: A ... | keyword[def] identifier[merge_envs] (* identifier[args] ):
literal[string]
identifier[env] ={}
keyword[for] identifier[arg] keyword[in] identifier[args] :
keyword[if] keyword[not] identifier[arg] :
keyword[continue]
identifier[env] . identifier[update] ( identifier... | def merge_envs(*args):
"""Union of one or more dictionaries.
In case of duplicate keys, the values in the right-most arguments will
squash (overwrite) the value provided by any dict preceding it.
:param args: Sequence of ``dict`` objects that should be merged.
:return: A ``dict`` containing the un... |
def g(self, id):
"""
If the given id is known, the numerical representation is returned,
otherwise a new running number is assigned to the id and returned"""
if id not in self._m:
if self.orig_ids:
self._m[id] = id
if self.warn:
... | def function[g, parameter[self, id]]:
constant[
If the given id is known, the numerical representation is returned,
otherwise a new running number is assigned to the id and returned]
if compare[name[id] <ast.NotIn object at 0x7da2590d7190> name[self]._m] begin[:]
if name[... | keyword[def] identifier[g] ( identifier[self] , identifier[id] ):
literal[string]
keyword[if] identifier[id] keyword[not] keyword[in] identifier[self] . identifier[_m] :
keyword[if] identifier[self] . identifier[orig_ids] :
identifier[self] . identifier[_m] [ iden... | def g(self, id):
"""
If the given id is known, the numerical representation is returned,
otherwise a new running number is assigned to the id and returned"""
if id not in self._m:
if self.orig_ids:
self._m[id] = id
if self.warn:
try:
... |
def build_response(self, request, response, from_cache=False):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
if not from_cache and request.method == 'GET':
# apply a... | def function[build_response, parameter[self, request, response, from_cache]]:
constant[
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
]
if <ast.BoolOp object at 0x7da20e961b40> begin[:]
... | keyword[def] identifier[build_response] ( identifier[self] , identifier[request] , identifier[response] , identifier[from_cache] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[from_cache] keyword[and] identifier[request] . identifier[method] == literal[string] :
... | def build_response(self, request, response, from_cache=False):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
if not from_cache and request.method == 'GET':
# apply any expiration... |
def get_average_color(colors):
"""Calculate the average color from the list of colors, where each color
is a 3-tuple of (r, g, b) values.
"""
c = reduce(color_reducer, colors)
total = len(colors)
return tuple(v / total for v in c) | def function[get_average_color, parameter[colors]]:
constant[Calculate the average color from the list of colors, where each color
is a 3-tuple of (r, g, b) values.
]
variable[c] assign[=] call[name[reduce], parameter[name[color_reducer], name[colors]]]
variable[total] assign[=] call[nam... | keyword[def] identifier[get_average_color] ( identifier[colors] ):
literal[string]
identifier[c] = identifier[reduce] ( identifier[color_reducer] , identifier[colors] )
identifier[total] = identifier[len] ( identifier[colors] )
keyword[return] identifier[tuple] ( identifier[v] / identifier[total... | def get_average_color(colors):
"""Calculate the average color from the list of colors, where each color
is a 3-tuple of (r, g, b) values.
"""
c = reduce(color_reducer, colors)
total = len(colors)
return tuple((v / total for v in c)) |
def _save_ack_callback(self, msgid, callback):
"""Keep a reference of the callback on this socket."""
if msgid in self.ack_callbacks:
return False
self.ack_callbacks[msgid] = callback | def function[_save_ack_callback, parameter[self, msgid, callback]]:
constant[Keep a reference of the callback on this socket.]
if compare[name[msgid] in name[self].ack_callbacks] begin[:]
return[constant[False]]
call[name[self].ack_callbacks][name[msgid]] assign[=] name[callback] | keyword[def] identifier[_save_ack_callback] ( identifier[self] , identifier[msgid] , identifier[callback] ):
literal[string]
keyword[if] identifier[msgid] keyword[in] identifier[self] . identifier[ack_callbacks] :
keyword[return] keyword[False]
identifier[self] . identifi... | def _save_ack_callback(self, msgid, callback):
"""Keep a reference of the callback on this socket."""
if msgid in self.ack_callbacks:
return False # depends on [control=['if'], data=[]]
self.ack_callbacks[msgid] = callback |
def register(self, resource, event, trigger, **kwargs):
"""Called in trunk plugin's AFTER_INIT"""
super(AristaTrunkDriver, self).register(resource, event,
trigger, kwargs)
registry.subscribe(self.subport_create,
resources... | def function[register, parameter[self, resource, event, trigger]]:
constant[Called in trunk plugin's AFTER_INIT]
call[call[name[super], parameter[name[AristaTrunkDriver], name[self]]].register, parameter[name[resource], name[event], name[trigger], name[kwargs]]]
call[name[registry].subscribe, pa... | keyword[def] identifier[register] ( identifier[self] , identifier[resource] , identifier[event] , identifier[trigger] ,** identifier[kwargs] ):
literal[string]
identifier[super] ( identifier[AristaTrunkDriver] , identifier[self] ). identifier[register] ( identifier[resource] , identifier[event] ,
... | def register(self, resource, event, trigger, **kwargs):
"""Called in trunk plugin's AFTER_INIT"""
super(AristaTrunkDriver, self).register(resource, event, trigger, kwargs)
registry.subscribe(self.subport_create, resources.SUBPORTS, events.AFTER_CREATE)
registry.subscribe(self.subport_delete, resources.S... |
def delete_items(item_list, reason, login, mediawiki_api_url='https://www.wikidata.org/w/api.php',
user_agent=config['USER_AGENT_DEFAULT']):
"""
Takes a list of items and posts them for deletion by Wikidata moderators, appends at the end of the deletion
request page.
... | def function[delete_items, parameter[item_list, reason, login, mediawiki_api_url, user_agent]]:
constant[
Takes a list of items and posts them for deletion by Wikidata moderators, appends at the end of the deletion
request page.
:param item_list: a list of QIDs which should be deleted
... | keyword[def] identifier[delete_items] ( identifier[item_list] , identifier[reason] , identifier[login] , identifier[mediawiki_api_url] = literal[string] ,
identifier[user_agent] = identifier[config] [ literal[string] ]):
literal[string]
identifier[url] = identifier[mediawiki_api_url]
id... | def delete_items(item_list, reason, login, mediawiki_api_url='https://www.wikidata.org/w/api.php', user_agent=config['USER_AGENT_DEFAULT']):
"""
Takes a list of items and posts them for deletion by Wikidata moderators, appends at the end of the deletion
request page.
:param item_list: a list... |
def _list_result_paths(target_path, log_file_name='log'):
"""list_result_paths."""
result_list = []
for root, _dirs, _files in os.walk(os.path.abspath(target_path)):
for name in _files:
if name == log_file_name:
result_list.append(root)
return result_list | def function[_list_result_paths, parameter[target_path, log_file_name]]:
constant[list_result_paths.]
variable[result_list] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b0dc0550>, <ast.Name object at 0x7da1b0dc0c10>, <ast.Name object at 0x7da1b0dc0fa0>]]] in starred[call[name[os... | keyword[def] identifier[_list_result_paths] ( identifier[target_path] , identifier[log_file_name] = literal[string] ):
literal[string]
identifier[result_list] =[]
keyword[for] identifier[root] , identifier[_dirs] , identifier[_files] keyword[in] identifier[os] . identifier[walk] ( identifier[os] ... | def _list_result_paths(target_path, log_file_name='log'):
"""list_result_paths."""
result_list = []
for (root, _dirs, _files) in os.walk(os.path.abspath(target_path)):
for name in _files:
if name == log_file_name:
result_list.append(root) # depends on [control=['if'], da... |
def server_receives_without_validation(self, *parameters):
"""Receive a message with template defined using `New Message`.
Message template has to be defined with `New Message` before calling
this.
Optional parameters:
- `name` the client name (default is the latest used) examp... | def function[server_receives_without_validation, parameter[self]]:
constant[Receive a message with template defined using `New Message`.
Message template has to be defined with `New Message` before calling
this.
Optional parameters:
- `name` the client name (default is the late... | keyword[def] identifier[server_receives_without_validation] ( identifier[self] ,* identifier[parameters] ):
literal[string]
keyword[with] identifier[self] . identifier[_receive] ( identifier[self] . identifier[_servers] ,* identifier[parameters] ) keyword[as] ( identifier[msg] , identifier[_] , id... | def server_receives_without_validation(self, *parameters):
"""Receive a message with template defined using `New Message`.
Message template has to be defined with `New Message` before calling
this.
Optional parameters:
- `name` the client name (default is the latest used) example: ... |
def find_stacks(node, strict=False):
"""Find pushes and pops to the stack and annotate them as such.
Args:
node: An AST node that might contain stack pushes and pops.
strict: A boolean indicating whether to stringently test whether each
push and pop are matched. This is not always possible when tak... | def function[find_stacks, parameter[node, strict]]:
constant[Find pushes and pops to the stack and annotate them as such.
Args:
node: An AST node that might contain stack pushes and pops.
strict: A boolean indicating whether to stringently test whether each
push and pop are matched. This is n... | keyword[def] identifier[find_stacks] ( identifier[node] , identifier[strict] = keyword[False] ):
literal[string]
identifier[fso] = identifier[FindStackOps] ()
identifier[fso] . identifier[visit] ( identifier[node] )
identifier[AnnotateStacks] ( identifier[fso] . identifier[push_pop_pairs] , identif... | def find_stacks(node, strict=False):
"""Find pushes and pops to the stack and annotate them as such.
Args:
node: An AST node that might contain stack pushes and pops.
strict: A boolean indicating whether to stringently test whether each
push and pop are matched. This is not always possible when t... |
def action_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the action's attribute with specified name.
@param attr_name: the name of an attribute belonging to the action.
@type attr_name: str
"""
def action_attr(_value, context, **_params):
value ... | def function[action_attr, parameter[attr_name]]:
constant[
Creates a getter that will drop the current value
and retrieve the action's attribute with specified name.
@param attr_name: the name of an attribute belonging to the action.
@type attr_name: str
]
def function[action_attr, p... | keyword[def] identifier[action_attr] ( identifier[attr_name] ):
literal[string]
keyword[def] identifier[action_attr] ( identifier[_value] , identifier[context] ,** identifier[_params] ):
identifier[value] = identifier[getattr] ( identifier[context] [ literal[string] ], identifier[attr_name] )
... | def action_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the action's attribute with specified name.
@param attr_name: the name of an attribute belonging to the action.
@type attr_name: str
"""
def action_attr(_value, context, **_params):
value ... |
def seek(self, offset, whence=SEEK_SET):
"""Seek pointer in lob data buffer to requested position.
Might trigger further loading of data from the database if the pointer is beyond currently read data.
"""
# A nice trick is to (ab)use BytesIO.seek() to go to the desired position for easie... | def function[seek, parameter[self, offset, whence]]:
constant[Seek pointer in lob data buffer to requested position.
Might trigger further loading of data from the database if the pointer is beyond currently read data.
]
call[name[self].data.seek, parameter[name[offset], name[whence]]]
... | keyword[def] identifier[seek] ( identifier[self] , identifier[offset] , identifier[whence] = identifier[SEEK_SET] ):
literal[string]
identifier[self] . identifier[data] . identifier[seek] ( identifier[offset] , identifier[whence] )
identifier[new_pos] = identifier[self] .... | def seek(self, offset, whence=SEEK_SET):
"""Seek pointer in lob data buffer to requested position.
Might trigger further loading of data from the database if the pointer is beyond currently read data.
"""
# A nice trick is to (ab)use BytesIO.seek() to go to the desired position for easier calcul... |
def get_opts(opts):
"""
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
"""
defaults = {
'board': None,
'terrain': Opt.random,
'numbers': Opt.pres... | def function[get_opts, parameter[opts]]:
constant[
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
]
variable[defaults] assign[=] dictionary[[<ast.Constant object... | keyword[def] identifier[get_opts] ( identifier[opts] ):
literal[string]
identifier[defaults] ={
literal[string] : keyword[None] ,
literal[string] : identifier[Opt] . identifier[random] ,
literal[string] : identifier[Opt] . identifier[preset] ,
literal[string] : identifier[Opt] . identif... | def get_opts(opts):
"""
Validate options and apply defaults for options not supplied.
:param opts: dictionary mapping str->str.
:return: dictionary mapping str->Opt. All possible keys are present.
"""
defaults = {'board': None, 'terrain': Opt.random, 'numbers': Opt.preset, 'ports': Opt.preset, ... |
def uninstall(pkg,
user=None,
env=None):
'''
Uninstall a cabal package.
pkg
The package to uninstall
user
The user to run ghc-pkg unregister with
env
Environment variables to set when invoking cabal. Uses the
same ``env`` format as the :py... | def function[uninstall, parameter[pkg, user, env]]:
constant[
Uninstall a cabal package.
pkg
The package to uninstall
user
The user to run ghc-pkg unregister with
env
Environment variables to set when invoking cabal. Uses the
same ``env`` format as the :py:func:`... | keyword[def] identifier[uninstall] ( identifier[pkg] ,
identifier[user] = keyword[None] ,
identifier[env] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] ]
identifier[cmd] . identifier[append] ( literal[string] . identifier[format] ( identifier[pkg] ))
identifier[result] ... | def uninstall(pkg, user=None, env=None):
"""
Uninstall a cabal package.
pkg
The package to uninstall
user
The user to run ghc-pkg unregister with
env
Environment variables to set when invoking cabal. Uses the
same ``env`` format as the :py:func:`cmd.run
<salt... |
def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print the output data in JSON
'''
try:
dump_opts = {'indent': 4, 'default': repr}
if 'output_indent' in __opts__:
indent = __opts__.get('output_indent')
sort_keys = False
if indent =... | def function[output, parameter[data]]:
constant[
Print the output data in JSON
]
<ast.Try object at 0x7da20e9570a0>
return[call[name[dson].dumps, parameter[dictionary[[], []]]]] | keyword[def] identifier[output] ( identifier[data] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[dump_opts] ={ literal[string] : literal[int] , literal[string] : identifier[repr] }
keyword[if] literal[string] keyword[in] identifier[__opts__] :
ident... | def output(data, **kwargs): # pylint: disable=unused-argument
'\n Print the output data in JSON\n '
try:
dump_opts = {'indent': 4, 'default': repr}
if 'output_indent' in __opts__:
indent = __opts__.get('output_indent')
sort_keys = False
if indent == 'pr... |
def free(self):
"""Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or
:py:meth:`TornadoSession.callproc <queries.TornadoSession.call... | def function[free, parameter[self]]:
constant[Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or
:py:meth:`TornadoSession.callproc <... | keyword[def] identifier[free] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_freed] = keyword[True]
identifier[self] . identifier[_cleanup] ( identifier[self] . identifier[cursor] , identifier[self] . identifier[_fd] ) | def free(self):
"""Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc... |
def match(self, models, results, relation):
"""
Match the eagerly loaded results to their parents.
:type models: list
:type results: Collection
:type relation: str
"""
foreign = self._foreign_key
other = self._other_key
dictionary = {}
... | def function[match, parameter[self, models, results, relation]]:
constant[
Match the eagerly loaded results to their parents.
:type models: list
:type results: Collection
:type relation: str
]
variable[foreign] assign[=] name[self]._foreign_key
variable[... | keyword[def] identifier[match] ( identifier[self] , identifier[models] , identifier[results] , identifier[relation] ):
literal[string]
identifier[foreign] = identifier[self] . identifier[_foreign_key]
identifier[other] = identifier[self] . identifier[_other_key]
identifier[dic... | def match(self, models, results, relation):
"""
Match the eagerly loaded results to their parents.
:type models: list
:type results: Collection
:type relation: str
"""
foreign = self._foreign_key
other = self._other_key
dictionary = {}
for result in results:... |
def render(self, **kwargs):
""" Make breadcrumbs for a route
:param kwargs: dictionary of named arguments used to construct the view
:type kwargs: dict
:return: List of dict items the view can use to construct the link.
:rtype: {str: list({ "link": str, "title", str, "args", dic... | def function[render, parameter[self]]:
constant[ Make breadcrumbs for a route
:param kwargs: dictionary of named arguments used to construct the view
:type kwargs: dict
:return: List of dict items the view can use to construct the link.
:rtype: {str: list({ "link": str, "title",... | keyword[def] identifier[render] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[breadcrumbs] =[]
identifier[breadcrumbs] =[]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier... | def render(self, **kwargs):
""" Make breadcrumbs for a route
:param kwargs: dictionary of named arguments used to construct the view
:type kwargs: dict
:return: List of dict items the view can use to construct the link.
:rtype: {str: list({ "link": str, "title", str, "args", dict})}... |
def filter_inactive_ports(query):
"""Filter ports that aren't in active status """
port_model = models_v2.Port
query = (query
.filter(port_model.status == n_const.PORT_STATUS_ACTIVE))
return query | def function[filter_inactive_ports, parameter[query]]:
constant[Filter ports that aren't in active status ]
variable[port_model] assign[=] name[models_v2].Port
variable[query] assign[=] call[name[query].filter, parameter[compare[name[port_model].status equal[==] name[n_const].PORT_STATUS_ACTIVE]... | keyword[def] identifier[filter_inactive_ports] ( identifier[query] ):
literal[string]
identifier[port_model] = identifier[models_v2] . identifier[Port]
identifier[query] =( identifier[query]
. identifier[filter] ( identifier[port_model] . identifier[status] == identifier[n_const] . identifier[PO... | def filter_inactive_ports(query):
"""Filter ports that aren't in active status """
port_model = models_v2.Port
query = query.filter(port_model.status == n_const.PORT_STATUS_ACTIVE)
return query |
def _shift_wavelengths(model1, model2):
"""One of the models is either ``RedshiftScaleFactor`` or ``Scale``.
Possible combos::
RedshiftScaleFactor | Model
Scale | Model
Model | Scale
"""
if isinstance(model1, _models.RedshiftScaleFactor):
val = _get_sampleset(model2)
... | def function[_shift_wavelengths, parameter[model1, model2]]:
constant[One of the models is either ``RedshiftScaleFactor`` or ``Scale``.
Possible combos::
RedshiftScaleFactor | Model
Scale | Model
Model | Scale
]
if call[name[isinstance], parameter[name[model1], name[_m... | keyword[def] identifier[_shift_wavelengths] ( identifier[model1] , identifier[model2] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[model1] , identifier[_models] . identifier[RedshiftScaleFactor] ):
identifier[val] = identifier[_get_sampleset] ( identifier[model2] )
... | def _shift_wavelengths(model1, model2):
"""One of the models is either ``RedshiftScaleFactor`` or ``Scale``.
Possible combos::
RedshiftScaleFactor | Model
Scale | Model
Model | Scale
"""
if isinstance(model1, _models.RedshiftScaleFactor):
val = _get_sampleset(model2)
... |
def add_term(set_id, term, access_token):
"""Add the given term to the given set.
:param term: Instance of Term.
"""
api_call('post', 'sets/{}/terms'.format(set_id), term.to_dict(), access_token=access_token) | def function[add_term, parameter[set_id, term, access_token]]:
constant[Add the given term to the given set.
:param term: Instance of Term.
]
call[name[api_call], parameter[constant[post], call[constant[sets/{}/terms].format, parameter[name[set_id]]], call[name[term].to_dict, parameter[]]]] | keyword[def] identifier[add_term] ( identifier[set_id] , identifier[term] , identifier[access_token] ):
literal[string]
identifier[api_call] ( literal[string] , literal[string] . identifier[format] ( identifier[set_id] ), identifier[term] . identifier[to_dict] (), identifier[access_token] = identifier[acce... | def add_term(set_id, term, access_token):
"""Add the given term to the given set.
:param term: Instance of Term.
"""
api_call('post', 'sets/{}/terms'.format(set_id), term.to_dict(), access_token=access_token) |
def __ensure_provisioning_reads(table_name, key_name, num_consec_read_checks):
""" Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type num_consec_read_checks: int
:pa... | def function[__ensure_provisioning_reads, parameter[table_name, key_name, num_consec_read_checks]]:
constant[ Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type num_... | keyword[def] identifier[__ensure_provisioning_reads] ( identifier[table_name] , identifier[key_name] , identifier[num_consec_read_checks] ):
literal[string]
keyword[if] keyword[not] identifier[get_table_option] ( identifier[key_name] , literal[string] ):
identifier[logger] . identifier[info] (
... | def __ensure_provisioning_reads(table_name, key_name, num_consec_read_checks):
""" Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type num_consec_read_checks: int
:pa... |
def get_average_cross_validation_fitness(self): # pragma: no cover
"""Get the per-generation average cross_validation fitness."""
avg_cross_validation_fitness = []
for stats in self.generation_cross_validation_statistics:
scores = []
for fitness in stats.values():
... | def function[get_average_cross_validation_fitness, parameter[self]]:
constant[Get the per-generation average cross_validation fitness.]
variable[avg_cross_validation_fitness] assign[=] list[[]]
for taget[name[stats]] in starred[name[self].generation_cross_validation_statistics] begin[:]
... | keyword[def] identifier[get_average_cross_validation_fitness] ( identifier[self] ):
literal[string]
identifier[avg_cross_validation_fitness] =[]
keyword[for] identifier[stats] keyword[in] identifier[self] . identifier[generation_cross_validation_statistics] :
identifier[sco... | def get_average_cross_validation_fitness(self): # pragma: no cover
'Get the per-generation average cross_validation fitness.'
avg_cross_validation_fitness = []
for stats in self.generation_cross_validation_statistics:
scores = []
for fitness in stats.values():
scores.extend(fitn... |
def send_message(client, message):
"""Send message to client and close the connection."""
print(message)
client.send("HTTP/1.1 200 OK\r\n\r\n{}".format(message).encode("utf-8"))
client.close() | def function[send_message, parameter[client, message]]:
constant[Send message to client and close the connection.]
call[name[print], parameter[name[message]]]
call[name[client].send, parameter[call[call[constant[HTTP/1.1 200 OK
{}].format, parameter[name[message]]].encode, parameter[constant[... | keyword[def] identifier[send_message] ( identifier[client] , identifier[message] ):
literal[string]
identifier[print] ( identifier[message] )
identifier[client] . identifier[send] ( literal[string] . identifier[format] ( identifier[message] ). identifier[encode] ( literal[string] ))
identifier[cl... | def send_message(client, message):
"""Send message to client and close the connection."""
print(message)
client.send('HTTP/1.1 200 OK\r\n\r\n{}'.format(message).encode('utf-8'))
client.close() |
def _insert(self, element, new_element, before):
"""
Insert a element before or after other element.
:param element: The reference element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param new_element: The element that be inserted.
:type new_element... | def function[_insert, parameter[self, element, new_element, before]]:
constant[
Insert a element before or after other element.
:param element: The reference element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param new_element: The element that be inserted... | keyword[def] identifier[_insert] ( identifier[self] , identifier[element] , identifier[new_element] , identifier[before] ):
literal[string]
identifier[tag_name] = identifier[element] . identifier[get_tag_name] ()
identifier[append_tags] =[
literal[string] ,
literal[strin... | def _insert(self, element, new_element, before):
"""
Insert a element before or after other element.
:param element: The reference element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param new_element: The element that be inserted.
:type new_element: ha... |
def downstream_index(dir_value, i, j, alg='taudem'):
"""find downslope coordinate for D8 direction."""
assert alg.lower() in FlowModelConst.d8_deltas
delta = FlowModelConst.d8_deltas.get(alg.lower())
drow, dcol = delta[int(dir_value)]
return i + drow, j + dcol | def function[downstream_index, parameter[dir_value, i, j, alg]]:
constant[find downslope coordinate for D8 direction.]
assert[compare[call[name[alg].lower, parameter[]] in name[FlowModelConst].d8_deltas]]
variable[delta] assign[=] call[name[FlowModelConst].d8_deltas.get, parameter[call[name[alg].low... | keyword[def] identifier[downstream_index] ( identifier[dir_value] , identifier[i] , identifier[j] , identifier[alg] = literal[string] ):
literal[string]
keyword[assert] identifier[alg] . identifier[lower] () keyword[in] identifier[FlowModelConst] . identifier[d8_deltas]
identifier[delta... | def downstream_index(dir_value, i, j, alg='taudem'):
"""find downslope coordinate for D8 direction."""
assert alg.lower() in FlowModelConst.d8_deltas
delta = FlowModelConst.d8_deltas.get(alg.lower())
(drow, dcol) = delta[int(dir_value)]
return (i + drow, j + dcol) |
def _reset_django(settings):
"""
Hackish way to reset the django instance settings and AppConfig
:param settings: django settings module
"""
if settings._wrapped != empty:
clear_url_caches()
from django.apps import apps
apps.clear_cache()
settings._wrapped = empty
... | def function[_reset_django, parameter[settings]]:
constant[
Hackish way to reset the django instance settings and AppConfig
:param settings: django settings module
]
if compare[name[settings]._wrapped not_equal[!=] name[empty]] begin[:]
call[name[clear_url_caches], parameter[... | keyword[def] identifier[_reset_django] ( identifier[settings] ):
literal[string]
keyword[if] identifier[settings] . identifier[_wrapped] != identifier[empty] :
identifier[clear_url_caches] ()
keyword[from] identifier[django] . identifier[apps] keyword[import] identifier[apps]
... | def _reset_django(settings):
"""
Hackish way to reset the django instance settings and AppConfig
:param settings: django settings module
"""
if settings._wrapped != empty:
clear_url_caches()
from django.apps import apps
apps.clear_cache()
settings._wrapped = empty
... |
def remove_binaries(package_dir=False):
"""Remove all binaries for the current platform
Parameters
----------
package_dir: bool
If True, remove all binaries from the `resources`
directory of the qpsphere package. If False,
remove all binaries from the user's cache directory.
... | def function[remove_binaries, parameter[package_dir]]:
constant[Remove all binaries for the current platform
Parameters
----------
package_dir: bool
If True, remove all binaries from the `resources`
directory of the qpsphere package. If False,
remove all binaries from the us... | keyword[def] identifier[remove_binaries] ( identifier[package_dir] = keyword[False] ):
literal[string]
identifier[paths] =[]
keyword[if] identifier[package_dir] :
identifier[pdir] = identifier[RESCR_PATH]
keyword[else] :
identifier[pdir] = identifier[CACHE_PATH]
keywor... | def remove_binaries(package_dir=False):
"""Remove all binaries for the current platform
Parameters
----------
package_dir: bool
If True, remove all binaries from the `resources`
directory of the qpsphere package. If False,
remove all binaries from the user's cache directory.
... |
def get_provisioning_configuration(
self, provisioning_configuration_id, custom_headers=None, raw=False, **operation_config):
"""GetContinuousDeploymentOperation.
:param provisioning_configuration_id:
:type provisioning_configuration_id: str
:param dict custom_headers: heade... | def function[get_provisioning_configuration, parameter[self, provisioning_configuration_id, custom_headers, raw]]:
constant[GetContinuousDeploymentOperation.
:param provisioning_configuration_id:
:type provisioning_configuration_id: str
:param dict custom_headers: headers that will be a... | keyword[def] identifier[get_provisioning_configuration] (
identifier[self] , identifier[provisioning_configuration_id] , identifier[custom_headers] = keyword[None] , identifier[raw] = keyword[False] ,** identifier[operation_config] ):
literal[string]
identifier[url] = literal[string]
... | def get_provisioning_configuration(self, provisioning_configuration_id, custom_headers=None, raw=False, **operation_config):
"""GetContinuousDeploymentOperation.
:param provisioning_configuration_id:
:type provisioning_configuration_id: str
:param dict custom_headers: headers that will be a... |
def set_slug(apps, schema_editor):
"""
Create a slug for each Event already in the DB.
"""
Event = apps.get_model('spectator_events', 'Event')
for e in Event.objects.all():
e.slug = generate_slug(e.pk)
e.save(update_fields=['slug']) | def function[set_slug, parameter[apps, schema_editor]]:
constant[
Create a slug for each Event already in the DB.
]
variable[Event] assign[=] call[name[apps].get_model, parameter[constant[spectator_events], constant[Event]]]
for taget[name[e]] in starred[call[name[Event].objects.all, par... | keyword[def] identifier[set_slug] ( identifier[apps] , identifier[schema_editor] ):
literal[string]
identifier[Event] = identifier[apps] . identifier[get_model] ( literal[string] , literal[string] )
keyword[for] identifier[e] keyword[in] identifier[Event] . identifier[objects] . identifier[all] ()... | def set_slug(apps, schema_editor):
"""
Create a slug for each Event already in the DB.
"""
Event = apps.get_model('spectator_events', 'Event')
for e in Event.objects.all():
e.slug = generate_slug(e.pk)
e.save(update_fields=['slug']) # depends on [control=['for'], data=['e']] |
def execute(self):
"""Output environment name."""
# Disable other runway logging so the only response is the env name
logging.getLogger('runway').setLevel(logging.ERROR)
# This may be invoked from a module directory in an environment;
# account for that here if necessary
... | def function[execute, parameter[self]]:
constant[Output environment name.]
call[call[name[logging].getLogger, parameter[constant[runway]]].setLevel, parameter[name[logging].ERROR]]
if <ast.UnaryOp object at 0x7da1b07ac6a0> begin[:]
name[self].env_root assign[=] call[name[os].path... | keyword[def] identifier[execute] ( identifier[self] ):
literal[string]
identifier[logging] . identifier[getLogger] ( literal[string] ). identifier[setLevel] ( identifier[logging] . identifier[ERROR] )
keyword[if] keyword[not] identifier[os] . identifier[path] ... | def execute(self):
"""Output environment name."""
# Disable other runway logging so the only response is the env name
logging.getLogger('runway').setLevel(logging.ERROR)
# This may be invoked from a module directory in an environment;
# account for that here if necessary
if not os.path.isfile('r... |
def step_impl09(context):
"""Create application list.
:param context: test context.
"""
assert context.table, "ENSURE: table is provided."
context.app_list = [row['application'] for row in context.table.rows] | def function[step_impl09, parameter[context]]:
constant[Create application list.
:param context: test context.
]
assert[name[context].table]
name[context].app_list assign[=] <ast.ListComp object at 0x7da20eb64c70> | keyword[def] identifier[step_impl09] ( identifier[context] ):
literal[string]
keyword[assert] identifier[context] . identifier[table] , literal[string]
identifier[context] . identifier[app_list] =[ identifier[row] [ literal[string] ] keyword[for] identifier[row] keyword[in] identifier[context] . ... | def step_impl09(context):
"""Create application list.
:param context: test context.
"""
assert context.table, 'ENSURE: table is provided.'
context.app_list = [row['application'] for row in context.table.rows] |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ConferenceContext for this ConferenceInstance
:rtype: twilio.rest.api.v2010.account.conference.Co... | def function[_proxy, parameter[self]]:
constant[
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ConferenceContext for this ConferenceInstance
:rtype: twilio.rest.api.... | keyword[def] identifier[_proxy] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_context] keyword[is] keyword[None] :
identifier[self] . identifier[_context] = identifier[ConferenceContext] (
identifier[self] . identifier[_version] ,
... | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ConferenceContext for this ConferenceInstance
:rtype: twilio.rest.api.v2010.account.conference.Confer... |
def download_file_insecure(url, target):
'''
Use Python to download the file, even though it cannot authenticate the
connection.
'''
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
src = dst = None
try:
src = urlopen(url)
... | def function[download_file_insecure, parameter[url, target]]:
constant[
Use Python to download the file, even though it cannot authenticate the
connection.
]
<ast.Try object at 0x7da1b11e04f0>
variable[src] assign[=] constant[None]
<ast.Try object at 0x7da1b11e2e00> | keyword[def] identifier[download_file_insecure] ( identifier[url] , identifier[target] ):
literal[string]
keyword[try] :
keyword[from] identifier[urllib] . identifier[request] keyword[import] identifier[urlopen]
keyword[except] identifier[ImportError] :
keyword[from] identifier... | def download_file_insecure(url, target):
"""
Use Python to download the file, even though it cannot authenticate the
connection.
"""
try:
from urllib.request import urlopen # depends on [control=['try'], data=[]]
except ImportError:
from urllib2 import urlopen # depends on [con... |
def get_attrs_by_path(self, field_path, stop_first=False):
"""
It returns list of values looked up by field path.
Field path is dot-formatted string path: ``parent_field.child_field``.
:param field_path: field path. It allows ``*`` as wildcard.
:type field_path: list or None.
... | def function[get_attrs_by_path, parameter[self, field_path, stop_first]]:
constant[
It returns list of values looked up by field path.
Field path is dot-formatted string path: ``parent_field.child_field``.
:param field_path: field path. It allows ``*`` as wildcard.
:type field_p... | keyword[def] identifier[get_attrs_by_path] ( identifier[self] , identifier[field_path] , identifier[stop_first] = keyword[False] ):
literal[string]
identifier[fields] , identifier[next_field] = identifier[self] . identifier[_get_fields_by_path] ( identifier[field_path] )
identifier[values]... | def get_attrs_by_path(self, field_path, stop_first=False):
"""
It returns list of values looked up by field path.
Field path is dot-formatted string path: ``parent_field.child_field``.
:param field_path: field path. It allows ``*`` as wildcard.
:type field_path: list or None.
... |
def find_this(search, filename=MODULE_PATH):
"""Take a string and a filename path string and return the found value."""
if not search:
return
for line in open(str(filename)).readlines():
if search.lower() in line.lower():
line = line.split("=")[1].strip()
if "'" in li... | def function[find_this, parameter[search, filename]]:
constant[Take a string and a filename path string and return the found value.]
if <ast.UnaryOp object at 0x7da1b0c0d360> begin[:]
return[None]
for taget[name[line]] in starred[call[call[name[open], parameter[call[name[str], parameter[... | keyword[def] identifier[find_this] ( identifier[search] , identifier[filename] = identifier[MODULE_PATH] ):
literal[string]
keyword[if] keyword[not] identifier[search] :
keyword[return]
keyword[for] identifier[line] keyword[in] identifier[open] ( identifier[str] ( identifier[filename] )... | def find_this(search, filename=MODULE_PATH):
"""Take a string and a filename path string and return the found value."""
if not search:
return # depends on [control=['if'], data=[]]
for line in open(str(filename)).readlines():
if search.lower() in line.lower():
line = line.split(... |
def get_upcoming_events(num, days, featured=False):
"""
Get upcoming events.
Allows slicing to a given number,
picking the number of days to hold them after they've started
and whether they should be featured or not.
Usage:
{% get_upcoming_events 5 14 featured as events %}
Would return n... | def function[get_upcoming_events, parameter[num, days, featured]]:
constant[
Get upcoming events.
Allows slicing to a given number,
picking the number of days to hold them after they've started
and whether they should be featured or not.
Usage:
{% get_upcoming_events 5 14 featured as eve... | keyword[def] identifier[get_upcoming_events] ( identifier[num] , identifier[days] , identifier[featured] = keyword[False] ):
literal[string]
keyword[from] identifier[happenings] . identifier[models] keyword[import] identifier[Event]
identifier[start_date] = identifier[today] - identifier[datetime]... | def get_upcoming_events(num, days, featured=False):
"""
Get upcoming events.
Allows slicing to a given number,
picking the number of days to hold them after they've started
and whether they should be featured or not.
Usage:
{% get_upcoming_events 5 14 featured as events %}
Would return n... |
def many_nodes(
lexer: Lexer,
open_kind: TokenKind,
parse_fn: Callable[[Lexer], Node],
close_kind: TokenKind,
) -> List[Node]:
"""Fetch matching nodes, at least one.
Returns a non-empty list of parse nodes, determined by the `parse_fn`.
This list begins with a lex token of `open_kind` and e... | def function[many_nodes, parameter[lexer, open_kind, parse_fn, close_kind]]:
constant[Fetch matching nodes, at least one.
Returns a non-empty list of parse nodes, determined by the `parse_fn`.
This list begins with a lex token of `open_kind` and ends with a lex token of
`close_kind`. Advances the p... | keyword[def] identifier[many_nodes] (
identifier[lexer] : identifier[Lexer] ,
identifier[open_kind] : identifier[TokenKind] ,
identifier[parse_fn] : identifier[Callable] [[ identifier[Lexer] ], identifier[Node] ],
identifier[close_kind] : identifier[TokenKind] ,
)-> identifier[List] [ identifier[Node] ]:
lit... | def many_nodes(lexer: Lexer, open_kind: TokenKind, parse_fn: Callable[[Lexer], Node], close_kind: TokenKind) -> List[Node]:
"""Fetch matching nodes, at least one.
Returns a non-empty list of parse nodes, determined by the `parse_fn`.
This list begins with a lex token of `open_kind` and ends with a lex toke... |
def diff(ctx, branch):
"""
Determine which tests intersect a git diff.
"""
diff = GitDiffReporter(branch)
regions = diff.changed_intervals()
_report_from_regions(regions, ctx.obj, file_factory=diff.old_file) | def function[diff, parameter[ctx, branch]]:
constant[
Determine which tests intersect a git diff.
]
variable[diff] assign[=] call[name[GitDiffReporter], parameter[name[branch]]]
variable[regions] assign[=] call[name[diff].changed_intervals, parameter[]]
call[name[_report_from_reg... | keyword[def] identifier[diff] ( identifier[ctx] , identifier[branch] ):
literal[string]
identifier[diff] = identifier[GitDiffReporter] ( identifier[branch] )
identifier[regions] = identifier[diff] . identifier[changed_intervals] ()
identifier[_report_from_regions] ( identifier[regions] , identifi... | def diff(ctx, branch):
"""
Determine which tests intersect a git diff.
"""
diff = GitDiffReporter(branch)
regions = diff.changed_intervals()
_report_from_regions(regions, ctx.obj, file_factory=diff.old_file) |
def build(self):
"""Builds Discord embed GUI
Returns:
discord.Embed: Built GUI
"""
if self.colour:
embed = discord.Embed(
title=self.title,
type='rich',
description=self.description,
colour=self.col... | def function[build, parameter[self]]:
constant[Builds Discord embed GUI
Returns:
discord.Embed: Built GUI
]
if name[self].colour begin[:]
variable[embed] assign[=] call[name[discord].Embed, parameter[]]
if name[self].thumbnail begin[:]
... | keyword[def] identifier[build] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[colour] :
identifier[embed] = identifier[discord] . identifier[Embed] (
identifier[title] = identifier[self] . identifier[title] ,
identifier[type]... | def build(self):
"""Builds Discord embed GUI
Returns:
discord.Embed: Built GUI
"""
if self.colour:
embed = discord.Embed(title=self.title, type='rich', description=self.description, colour=self.colour) # depends on [control=['if'], data=[]]
else:
embed = discord... |
def forward(ctx, x, dutyCycles, k, boostStrength):
"""
Use the boost strength to compute a boost factor for each unit represented
in x. These factors are used to increase the impact of each unit to improve
their chances of being chosen. This encourages participation of more columns
in the learning p... | def function[forward, parameter[ctx, x, dutyCycles, k, boostStrength]]:
constant[
Use the boost strength to compute a boost factor for each unit represented
in x. These factors are used to increase the impact of each unit to improve
their chances of being chosen. This encourages participation of mor... | keyword[def] identifier[forward] ( identifier[ctx] , identifier[x] , identifier[dutyCycles] , identifier[k] , identifier[boostStrength] ):
literal[string]
identifier[batchSize] = identifier[x] . identifier[shape] [ literal[int] ]
keyword[if] identifier[boostStrength] > literal[int] :
identifie... | def forward(ctx, x, dutyCycles, k, boostStrength):
"""
Use the boost strength to compute a boost factor for each unit represented
in x. These factors are used to increase the impact of each unit to improve
their chances of being chosen. This encourages participation of more columns
in the learning p... |
def _start_instance(self):
"""
Start the instance.
"""
try:
vm_start = self.compute.virtual_machines.start(
self.running_instance_id, self.running_instance_id
)
except Exception as error:
raise AzureCloudException(
... | def function[_start_instance, parameter[self]]:
constant[
Start the instance.
]
<ast.Try object at 0x7da1b1a22da0>
call[name[vm_start].wait, parameter[]] | keyword[def] identifier[_start_instance] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[vm_start] = identifier[self] . identifier[compute] . identifier[virtual_machines] . identifier[start] (
identifier[self] . identifier[running_instance_id] , identifier[... | def _start_instance(self):
"""
Start the instance.
"""
try:
vm_start = self.compute.virtual_machines.start(self.running_instance_id, self.running_instance_id) # depends on [control=['try'], data=[]]
except Exception as error:
raise AzureCloudException('Unable to start instan... |
def barracks_in_middle(self) -> Point2:
""" Barracks position in the middle of the 2 depots """
if len(self.upper2_for_ramp_wall) == 2:
points = self.upper2_for_ramp_wall
p1 = points.pop().offset((self.x_offset, self.y_offset))
p2 = points.pop().offset((self.x_offset,... | def function[barracks_in_middle, parameter[self]]:
constant[ Barracks position in the middle of the 2 depots ]
if compare[call[name[len], parameter[name[self].upper2_for_ramp_wall]] equal[==] constant[2]] begin[:]
variable[points] assign[=] name[self].upper2_for_ramp_wall
... | keyword[def] identifier[barracks_in_middle] ( identifier[self] )-> identifier[Point2] :
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[upper2_for_ramp_wall] )== literal[int] :
identifier[points] = identifier[self] . identifier[upper2_for_ramp_wall]
... | def barracks_in_middle(self) -> Point2:
""" Barracks position in the middle of the 2 depots """
if len(self.upper2_for_ramp_wall) == 2:
points = self.upper2_for_ramp_wall
p1 = points.pop().offset((self.x_offset, self.y_offset))
p2 = points.pop().offset((self.x_offset, self.y_offset))
... |
def get_ref(self, reftype, index):
"""Retrieve a reference."""
try:
got_reftype, data = self.refs[int(index)]
except (IndexError, ValueError):
raise CoconutInternalException("no reference at invalid index", index)
internal_assert(got_reftype == reftype, "wanted " ... | def function[get_ref, parameter[self, reftype, index]]:
constant[Retrieve a reference.]
<ast.Try object at 0x7da1b0912830>
call[name[internal_assert], parameter[compare[name[got_reftype] equal[==] name[reftype]], binary_operation[binary_operation[binary_operation[binary_operation[constant[wanted ] +... | keyword[def] identifier[get_ref] ( identifier[self] , identifier[reftype] , identifier[index] ):
literal[string]
keyword[try] :
identifier[got_reftype] , identifier[data] = identifier[self] . identifier[refs] [ identifier[int] ( identifier[index] )]
keyword[except] ( identifie... | def get_ref(self, reftype, index):
"""Retrieve a reference."""
try:
(got_reftype, data) = self.refs[int(index)] # depends on [control=['try'], data=[]]
except (IndexError, ValueError):
raise CoconutInternalException('no reference at invalid index', index) # depends on [control=['except'], ... |
def _pnpoly(x, y, coords):
"""
the algorithm to judge whether the point is located in polygon
reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation
"""
vert = [[0, 0]]
for coord in coords:
for node in coord:
vert.append(node)
vert.appe... | def function[_pnpoly, parameter[x, y, coords]]:
constant[
the algorithm to judge whether the point is located in polygon
reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation
]
variable[vert] assign[=] list[[<ast.List object at 0x7da1b1019c90>]]
for ta... | keyword[def] identifier[_pnpoly] ( identifier[x] , identifier[y] , identifier[coords] ):
literal[string]
identifier[vert] =[[ literal[int] , literal[int] ]]
keyword[for] identifier[coord] keyword[in] identifier[coords] :
keyword[for] identifier[node] keyword[in] identifier[coord] :
... | def _pnpoly(x, y, coords):
"""
the algorithm to judge whether the point is located in polygon
reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation
"""
vert = [[0, 0]]
for coord in coords:
for node in coord:
vert.append(node) # depends on [con... |
def subdivide(self, points_per_edge):
"""
Adds ``N`` interpolated points with uniform spacing to each edge.
For each edge between points ``A`` and ``B`` this adds points
at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added
point and ``N`` is the number of points... | def function[subdivide, parameter[self, points_per_edge]]:
constant[
Adds ``N`` interpolated points with uniform spacing to each edge.
For each edge between points ``A`` and ``B`` this adds points
at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added
point and ``... | keyword[def] identifier[subdivide] ( identifier[self] , identifier[points_per_edge] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[coords] )<= literal[int] keyword[or] identifier[points_per_edge] < literal[int] :
keyword[return] identifier[self] . id... | def subdivide(self, points_per_edge):
"""
Adds ``N`` interpolated points with uniform spacing to each edge.
For each edge between points ``A`` and ``B`` this adds points
at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added
point and ``N`` is the number of points to ... |
def disambiguate_ip_address(ip, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation of location is localhost)."""
if ip in ('0.0.0.0', '*'):
try:
external_ips = socket.gethostbyname_ex(socket.gethostname())[2]... | def function[disambiguate_ip_address, parameter[ip, location]]:
constant[turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation of location is localhost).]
if compare[name[ip] in tuple[[<ast.Constant object at 0x7da18fe91540>, <ast.Constant ob... | keyword[def] identifier[disambiguate_ip_address] ( identifier[ip] , identifier[location] = keyword[None] ):
literal[string]
keyword[if] identifier[ip] keyword[in] ( literal[string] , literal[string] ):
keyword[try] :
identifier[external_ips] = identifier[socket] . identifier[gethost... | def disambiguate_ip_address(ip, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation of location is localhost)."""
if ip in ('0.0.0.0', '*'):
try:
external_ips = socket.gethostbyname_ex(socket.gethostname())[2]... |
def remove_pod(self, pod, array, **kwargs):
"""Remove arrays from a pod.
:param pod: Name of the pod.
:type pod: str
:param array: Array to remove from pod.
:type array: str
:param \*\*kwargs: See the REST API Guide on your array for the
docume... | def function[remove_pod, parameter[self, pod, array]]:
constant[Remove arrays from a pod.
:param pod: Name of the pod.
:type pod: str
:param array: Array to remove from pod.
:type array: str
:param \*\*kwargs: See the REST API Guide on your array for the
... | keyword[def] identifier[remove_pod] ( identifier[self] , identifier[pod] , identifier[array] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_request] ( literal[string] , literal[string] . identifier[format] ( identifier[pod] , identifier[array] ), identifie... | def remove_pod(self, pod, array, **kwargs):
"""Remove arrays from a pod.
:param pod: Name of the pod.
:type pod: str
:param array: Array to remove from pod.
:type array: str
:param \\*\\*kwargs: See the REST API Guide on your array for the
document... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.