code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _configure_csv_file(self, file_handle, schema):
"""Configure a csv writer with the file_handle and write schema
as headers for the new file.
"""
csv_writer = csv.writer(file_handle, encoding='utf-8',
delimiter=self.field_delimiter)
csv_writer.w... | def function[_configure_csv_file, parameter[self, file_handle, schema]]:
constant[Configure a csv writer with the file_handle and write schema
as headers for the new file.
]
variable[csv_writer] assign[=] call[name[csv].writer, parameter[name[file_handle]]]
call[name[csv_writer].... | keyword[def] identifier[_configure_csv_file] ( identifier[self] , identifier[file_handle] , identifier[schema] ):
literal[string]
identifier[csv_writer] = identifier[csv] . identifier[writer] ( identifier[file_handle] , identifier[encoding] = literal[string] ,
identifier[delimiter] = ident... | def _configure_csv_file(self, file_handle, schema):
"""Configure a csv writer with the file_handle and write schema
as headers for the new file.
"""
csv_writer = csv.writer(file_handle, encoding='utf-8', delimiter=self.field_delimiter)
csv_writer.writerow(schema)
return csv_writer |
def list_prior_model_tuples(self):
"""
Returns
-------
list_prior_model_tuples: [(String, ListPriorModel)]
"""
return list(filter(lambda t: isinstance(t[1], CollectionPriorModel), self.__dict__.items())) | def function[list_prior_model_tuples, parameter[self]]:
constant[
Returns
-------
list_prior_model_tuples: [(String, ListPriorModel)]
]
return[call[name[list], parameter[call[name[filter], parameter[<ast.Lambda object at 0x7da18fe93c40>, call[name[self].__dict__.items, parame... | keyword[def] identifier[list_prior_model_tuples] ( identifier[self] ):
literal[string]
keyword[return] identifier[list] ( identifier[filter] ( keyword[lambda] identifier[t] : identifier[isinstance] ( identifier[t] [ literal[int] ], identifier[CollectionPriorModel] ), identifier[self] . identifier... | def list_prior_model_tuples(self):
"""
Returns
-------
list_prior_model_tuples: [(String, ListPriorModel)]
"""
return list(filter(lambda t: isinstance(t[1], CollectionPriorModel), self.__dict__.items())) |
def get_protein_targets_only(target_chembl_ids):
"""Given list of ChEMBL target ids, return dict of SINGLE PROTEIN targets
Parameters
----------
target_chembl_ids : list
list of chembl_ids as strings
Returns
-------
protein_targets : dict
dictionary keyed to ChEMBL target i... | def function[get_protein_targets_only, parameter[target_chembl_ids]]:
constant[Given list of ChEMBL target ids, return dict of SINGLE PROTEIN targets
Parameters
----------
target_chembl_ids : list
list of chembl_ids as strings
Returns
-------
protein_targets : dict
dict... | keyword[def] identifier[get_protein_targets_only] ( identifier[target_chembl_ids] ):
literal[string]
identifier[protein_targets] ={}
keyword[for] identifier[target_chembl_id] keyword[in] identifier[target_chembl_ids] :
identifier[target] = identifier[query_target] ( identifier[target_chemb... | def get_protein_targets_only(target_chembl_ids):
"""Given list of ChEMBL target ids, return dict of SINGLE PROTEIN targets
Parameters
----------
target_chembl_ids : list
list of chembl_ids as strings
Returns
-------
protein_targets : dict
dictionary keyed to ChEMBL target i... |
def mkdir(directory, exists_okay):
"""
Create a directory on the board.
Mkdir will create the specified directory on the board. One argument is
required, the full path of the directory to create.
Note that you cannot recursively create a hierarchy of directories with one
mkdir command, instea... | def function[mkdir, parameter[directory, exists_okay]]:
constant[
Create a directory on the board.
Mkdir will create the specified directory on the board. One argument is
required, the full path of the directory to create.
Note that you cannot recursively create a hierarchy of directories wit... | keyword[def] identifier[mkdir] ( identifier[directory] , identifier[exists_okay] ):
literal[string]
identifier[board_files] = identifier[files] . identifier[Files] ( identifier[_board] )
identifier[board_files] . identifier[mkdir] ( identifier[directory] , identifier[exists_okay] = identifier[exi... | def mkdir(directory, exists_okay):
"""
Create a directory on the board.
Mkdir will create the specified directory on the board. One argument is
required, the full path of the directory to create.
Note that you cannot recursively create a hierarchy of directories with one
mkdir command, instea... |
def remove_frequencies(self, fmin, fmax):
"""Remove frequencies from the dataset
"""
self.data.query(
'frequency > {0} and frequency < {1}'.format(fmin, fmax),
inplace=True
)
g = self.data.groupby('frequency')
print('Remaining frequencies:')
... | def function[remove_frequencies, parameter[self, fmin, fmax]]:
constant[Remove frequencies from the dataset
]
call[name[self].data.query, parameter[call[constant[frequency > {0} and frequency < {1}].format, parameter[name[fmin], name[fmax]]]]]
variable[g] assign[=] call[name[self].data.g... | keyword[def] identifier[remove_frequencies] ( identifier[self] , identifier[fmin] , identifier[fmax] ):
literal[string]
identifier[self] . identifier[data] . identifier[query] (
literal[string] . identifier[format] ( identifier[fmin] , identifier[fmax] ),
identifier[inplace] = key... | def remove_frequencies(self, fmin, fmax):
"""Remove frequencies from the dataset
"""
self.data.query('frequency > {0} and frequency < {1}'.format(fmin, fmax), inplace=True)
g = self.data.groupby('frequency')
print('Remaining frequencies:')
print(sorted(g.groups.keys())) |
def _check_flag_meanings(self, ds, name):
'''
Check a variable's flag_meanings attribute for compliance under CF
- flag_meanings exists
- flag_meanings is a string
- flag_meanings elements are valid strings
:param netCDF4.Dataset ds: An open netCDF dataset
:para... | def function[_check_flag_meanings, parameter[self, ds, name]]:
constant[
Check a variable's flag_meanings attribute for compliance under CF
- flag_meanings exists
- flag_meanings is a string
- flag_meanings elements are valid strings
:param netCDF4.Dataset ds: An open n... | keyword[def] identifier[_check_flag_meanings] ( identifier[self] , identifier[ds] , identifier[name] ):
literal[string]
identifier[variable] = identifier[ds] . identifier[variables] [ identifier[name] ]
identifier[flag_meanings] = identifier[getattr] ( identifier[variable] , literal[string... | def _check_flag_meanings(self, ds, name):
"""
Check a variable's flag_meanings attribute for compliance under CF
- flag_meanings exists
- flag_meanings is a string
- flag_meanings elements are valid strings
:param netCDF4.Dataset ds: An open netCDF dataset
:param st... |
def init_gl(self):
"""
Perform the magic incantations to create an
OpenGL scene using pyglet.
"""
# default background color is white-ish
background = [.99, .99, .99, 1.0]
# if user passed a background color use it
if 'background' in self.kwargs:
... | def function[init_gl, parameter[self]]:
constant[
Perform the magic incantations to create an
OpenGL scene using pyglet.
]
variable[background] assign[=] list[[<ast.Constant object at 0x7da20c992b00>, <ast.Constant object at 0x7da20c9918d0>, <ast.Constant object at 0x7da20c991c60... | keyword[def] identifier[init_gl] ( identifier[self] ):
literal[string]
identifier[background] =[ literal[int] , literal[int] , literal[int] , literal[int] ]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[kwargs] :
keyword[try] :
... | def init_gl(self):
"""
Perform the magic incantations to create an
OpenGL scene using pyglet.
"""
# default background color is white-ish
background = [0.99, 0.99, 0.99, 1.0]
# if user passed a background color use it
if 'background' in self.kwargs:
try:
#... |
def update_profile_banner(self, filename, **kargs):
""" :reference: https://dev.twitter.com/rest/reference/post/account/update_profile_banner
:allowed_param:'width', 'height', 'offset_left', 'offset_right'
"""
f = kargs.pop('file', None)
headers, post_data = API._pack_image(f... | def function[update_profile_banner, parameter[self, filename]]:
constant[ :reference: https://dev.twitter.com/rest/reference/post/account/update_profile_banner
:allowed_param:'width', 'height', 'offset_left', 'offset_right'
]
variable[f] assign[=] call[name[kargs].pop, parameter[cons... | keyword[def] identifier[update_profile_banner] ( identifier[self] , identifier[filename] ,** identifier[kargs] ):
literal[string]
identifier[f] = identifier[kargs] . identifier[pop] ( literal[string] , keyword[None] )
identifier[headers] , identifier[post_data] = identifier[API] . identifi... | def update_profile_banner(self, filename, **kargs):
""" :reference: https://dev.twitter.com/rest/reference/post/account/update_profile_banner
:allowed_param:'width', 'height', 'offset_left', 'offset_right'
"""
f = kargs.pop('file', None)
(headers, post_data) = API._pack_image(filename, 7... |
def get_file_report(self, this_hash):
""" Get the scan results for a file.
:param this_hash: The md5/sha1/sha256/scan_ids hash of the file whose dynamic behavioural report you want to
retrieve or scan_ids from a previous call to scan_file.
:return:
"""
... | def function[get_file_report, parameter[self, this_hash]]:
constant[ Get the scan results for a file.
:param this_hash: The md5/sha1/sha256/scan_ids hash of the file whose dynamic behavioural report you want to
retrieve or scan_ids from a previous call to scan_file.
... | keyword[def] identifier[get_file_report] ( identifier[self] , identifier[this_hash] ):
literal[string]
identifier[params] ={ literal[string] : identifier[self] . identifier[api_key] , literal[string] : identifier[this_hash] }
keyword[try] :
identifier[response_info] = identif... | def get_file_report(self, this_hash):
""" Get the scan results for a file.
:param this_hash: The md5/sha1/sha256/scan_ids hash of the file whose dynamic behavioural report you want to
retrieve or scan_ids from a previous call to scan_file.
:return:
"""
params... |
def exchange_declare(self, exchange, type, passive=False, durable=False,
auto_delete=True, nowait=False, arguments=None):
"""Declare exchange, create if needed
This method creates an exchange if it does not already exist,
and if the exchange exists, verifies that it is ... | def function[exchange_declare, parameter[self, exchange, type, passive, durable, auto_delete, nowait, arguments]]:
constant[Declare exchange, create if needed
This method creates an exchange if it does not already exist,
and if the exchange exists, verifies that it is of the correct
and... | keyword[def] identifier[exchange_declare] ( identifier[self] , identifier[exchange] , identifier[type] , identifier[passive] = keyword[False] , identifier[durable] = keyword[False] ,
identifier[auto_delete] = keyword[True] , identifier[nowait] = keyword[False] , identifier[arguments] = keyword[None] ):
lite... | def exchange_declare(self, exchange, type, passive=False, durable=False, auto_delete=True, nowait=False, arguments=None):
"""Declare exchange, create if needed
This method creates an exchange if it does not already exist,
and if the exchange exists, verifies that it is of the correct
and ex... |
async def get_offers(self, **params):
"""Receives all users input (by cid) or output offers
Accepts:
- public key
- cid (optional)
- coinid (optional)
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
if not params:
return {"error":400, "reason":"Missed required fi... | <ast.AsyncFunctionDef object at 0x7da1b0a4a9e0> | keyword[async] keyword[def] identifier[get_offers] ( identifier[self] ,** identifier[params] ):
literal[string]
keyword[if] identifier[params] . identifier[get] ( literal[string] ):
identifier[params] = identifier[json] . identifier[loads] ( identifier[params] . identifier[get] ( literal[string] , litera... | async def get_offers(self, **params):
"""Receives all users input (by cid) or output offers
Accepts:
- public key
- cid (optional)
- coinid (optional)
"""
if params.get('message'):
params = json.loads(params.get('message', '{}')) # depends on [control=['if'], data=[]]
if not params:
... |
def to_imgur_format(params):
"""Convert the parameters to the format Imgur expects."""
if params is None:
return None
return dict((k, convert_general(val)) for (k, val) in params.items()) | def function[to_imgur_format, parameter[params]]:
constant[Convert the parameters to the format Imgur expects.]
if compare[name[params] is constant[None]] begin[:]
return[constant[None]]
return[call[name[dict], parameter[<ast.GeneratorExp object at 0x7da1b23445b0>]]] | keyword[def] identifier[to_imgur_format] ( identifier[params] ):
literal[string]
keyword[if] identifier[params] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[return] identifier[dict] (( identifier[k] , identifier[convert_general] ( identifier[val] )) keyword[for] ( i... | def to_imgur_format(params):
"""Convert the parameters to the format Imgur expects."""
if params is None:
return None # depends on [control=['if'], data=[]]
return dict(((k, convert_general(val)) for (k, val) in params.items())) |
def generate_code_challenge(verifier):
"""
source: https://github.com/openstack/deb-python-oauth2client
Creates a 'code_challenge' as described in section 4.2 of RFC 7636
by taking the sha256 hash of the verifier and then urlsafe
base64-encoding it.
Args:
verifier: bytestring, representi... | def function[generate_code_challenge, parameter[verifier]]:
constant[
source: https://github.com/openstack/deb-python-oauth2client
Creates a 'code_challenge' as described in section 4.2 of RFC 7636
by taking the sha256 hash of the verifier and then urlsafe
base64-encoding it.
Args:
v... | keyword[def] identifier[generate_code_challenge] ( identifier[verifier] ):
literal[string]
identifier[digest] = identifier[hashlib] . identifier[sha256] ( identifier[verifier] . identifier[encode] ( literal[string] )). identifier[digest] ()
keyword[return] identifier[base64] . identifier[urlsafe_b64e... | def generate_code_challenge(verifier):
"""
source: https://github.com/openstack/deb-python-oauth2client
Creates a 'code_challenge' as described in section 4.2 of RFC 7636
by taking the sha256 hash of the verifier and then urlsafe
base64-encoding it.
Args:
verifier: bytestring, representi... |
def get_config_window_bounds(self):
"""Reads bounds from config and, if monitor is specified, modify the values to match with the specified monitor
:return: coords X and Y where set the browser window.
"""
bounds_x = int(self.config.get_optional('Driver', 'bounds_x') or 0)
bound... | def function[get_config_window_bounds, parameter[self]]:
constant[Reads bounds from config and, if monitor is specified, modify the values to match with the specified monitor
:return: coords X and Y where set the browser window.
]
variable[bounds_x] assign[=] call[name[int], parameter[<... | keyword[def] identifier[get_config_window_bounds] ( identifier[self] ):
literal[string]
identifier[bounds_x] = identifier[int] ( identifier[self] . identifier[config] . identifier[get_optional] ( literal[string] , literal[string] ) keyword[or] literal[int] )
identifier[bounds_y] = identif... | def get_config_window_bounds(self):
"""Reads bounds from config and, if monitor is specified, modify the values to match with the specified monitor
:return: coords X and Y where set the browser window.
"""
bounds_x = int(self.config.get_optional('Driver', 'bounds_x') or 0)
bounds_y = int(se... |
def get_queryset(self):
"""
This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is ... | def function[get_queryset, parameter[self]]:
constant[
This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
... | keyword[def] identifier[get_queryset] ( identifier[self] ):
literal[string]
identifier[qs] = identifier[super] ( identifier[PrefetchForIncludesHelperMixin] , identifier[self] ). identifier[get_queryset] ()
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ... | def get_queryset(self):
"""
This viewset provides a helper attribute to prefetch related models
based on the include specified in the URL.
__all__ can be used to specify a prefetch which should be done regardless of the include
.. code:: python
# When MyViewSet is call... |
def __stream(self, endpoint, listener, params={}, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Internal streaming API helper.
Returns a handle to the open connection that the user can close if they
... | def function[__stream, parameter[self, endpoint, listener, params, run_async, timeout, reconnect_async, reconnect_async_wait_sec]]:
constant[
Internal streaming API helper.
Returns a handle to the open connection that the user can close if they
wish to terminate it.
]
va... | keyword[def] identifier[__stream] ( identifier[self] , identifier[endpoint] , identifier[listener] , identifier[params] ={}, identifier[run_async] = keyword[False] , identifier[timeout] = identifier[__DEFAULT_STREAM_TIMEOUT] , identifier[reconnect_async] = keyword[False] , identifier[reconnect_async_wait_sec] = ident... | def __stream(self, endpoint, listener, params={}, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Internal streaming API helper.
Returns a handle to the open connection that the user can close if they
... |
def _setup_imports(self):
"""
Ensure the local importer and PushFileService has everything for the
Ansible module before setup() completes, but before detach() is called
in an asynchronous task.
The master automatically streams modules towards us concurrent to the
runner... | def function[_setup_imports, parameter[self]]:
constant[
Ensure the local importer and PushFileService has everything for the
Ansible module before setup() completes, but before detach() is called
in an asynchronous task.
The master automatically streams modules towards us concu... | keyword[def] identifier[_setup_imports] ( identifier[self] ):
literal[string]
keyword[for] identifier[fullname] , identifier[_] , identifier[_] keyword[in] identifier[self] . identifier[module_map] [ literal[string] ]:
identifier[mitogen] . identifier[core] . identifier[import_modul... | def _setup_imports(self):
"""
Ensure the local importer and PushFileService has everything for the
Ansible module before setup() completes, but before detach() is called
in an asynchronous task.
The master automatically streams modules towards us concurrent to the
runner inv... |
def generate_bq_schema(df, default_type="STRING"):
"""DEPRECATED: Given a passed df, generate the associated Google BigQuery
schema.
Parameters
----------
df : DataFrame
default_type : string
The default big query type in case the type of the column
does not exist in the schema.... | def function[generate_bq_schema, parameter[df, default_type]]:
constant[DEPRECATED: Given a passed df, generate the associated Google BigQuery
schema.
Parameters
----------
df : DataFrame
default_type : string
The default big query type in case the type of the column
does no... | keyword[def] identifier[generate_bq_schema] ( identifier[df] , identifier[default_type] = literal[string] ):
literal[string]
identifier[warnings] . identifier[warn] (
literal[string]
literal[string] ,
identifier[FutureWarning] ,
identifier[stacklevel] = literal[int] ,
)
... | def generate_bq_schema(df, default_type='STRING'):
"""DEPRECATED: Given a passed df, generate the associated Google BigQuery
schema.
Parameters
----------
df : DataFrame
default_type : string
The default big query type in case the type of the column
does not exist in the schema.... |
def remove_from_parent(self):
'''
Removes this frame from its parent, and nulls the parent link
'''
if self.parent:
self.parent._children.remove(self)
self.parent._invalidate_time_caches()
self.parent = None | def function[remove_from_parent, parameter[self]]:
constant[
Removes this frame from its parent, and nulls the parent link
]
if name[self].parent begin[:]
call[name[self].parent._children.remove, parameter[name[self]]]
call[name[self].parent._invalidate_ti... | keyword[def] identifier[remove_from_parent] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[parent] :
identifier[self] . identifier[parent] . identifier[_children] . identifier[remove] ( identifier[self] )
identifier[self] . identifier[pare... | def remove_from_parent(self):
"""
Removes this frame from its parent, and nulls the parent link
"""
if self.parent:
self.parent._children.remove(self)
self.parent._invalidate_time_caches()
self.parent = None # depends on [control=['if'], data=[]] |
def list_config_map_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind ConfigMap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_config_map_for_all_namespaces(async_... | def function[list_config_map_for_all_namespaces, parameter[self]]:
constant[
list or watch objects of kind ConfigMap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_config_map_for_all_... | keyword[def] identifier[list_config_map_for_all_namespaces] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[se... | def list_config_map_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind ConfigMap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_config_map_for_all_namespaces(async_req=... |
def _validate_importers(importers):
"""Validates the importers and decorates the callables with our output
formatter.
"""
# They could have no importers, that's chill
if importers is None:
return None
def _to_importer(priority, func):
assert isinstance(priority, int), priority
... | def function[_validate_importers, parameter[importers]]:
constant[Validates the importers and decorates the callables with our output
formatter.
]
if compare[name[importers] is constant[None]] begin[:]
return[constant[None]]
def function[_to_importer, parameter[priority, func]]:
... | keyword[def] identifier[_validate_importers] ( identifier[importers] ):
literal[string]
keyword[if] identifier[importers] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[def] identifier[_to_importer] ( identifier[priority] , identifier[func] ):
keyword[a... | def _validate_importers(importers):
"""Validates the importers and decorates the callables with our output
formatter.
"""
# They could have no importers, that's chill
if importers is None:
return None # depends on [control=['if'], data=[]]
def _to_importer(priority, func):
asse... |
def getIndexForValue(self, value):
"""
Return the ramp index for the given value
:param value: Lookup value
:rtype: int
"""
return math.trunc(self.slope * float(value) + self.intercept) | def function[getIndexForValue, parameter[self, value]]:
constant[
Return the ramp index for the given value
:param value: Lookup value
:rtype: int
]
return[call[name[math].trunc, parameter[binary_operation[binary_operation[name[self].slope * call[name[float], parameter[name[v... | keyword[def] identifier[getIndexForValue] ( identifier[self] , identifier[value] ):
literal[string]
keyword[return] identifier[math] . identifier[trunc] ( identifier[self] . identifier[slope] * identifier[float] ( identifier[value] )+ identifier[self] . identifier[intercept] ) | def getIndexForValue(self, value):
"""
Return the ramp index for the given value
:param value: Lookup value
:rtype: int
"""
return math.trunc(self.slope * float(value) + self.intercept) |
def map_navigation(self):
"""
This is a wrapper for depth-first recursive analysis of the article
"""
#All articles should have titles
title_id = 'titlepage-{0}'.format(self.article_doi)
title_label = self.article.publisher.nav_title()
title_source = 'main.{0}.xht... | def function[map_navigation, parameter[self]]:
constant[
This is a wrapper for depth-first recursive analysis of the article
]
variable[title_id] assign[=] call[constant[titlepage-{0}].format, parameter[name[self].article_doi]]
variable[title_label] assign[=] call[name[self].arti... | keyword[def] identifier[map_navigation] ( identifier[self] ):
literal[string]
identifier[title_id] = literal[string] . identifier[format] ( identifier[self] . identifier[article_doi] )
identifier[title_label] = identifier[self] . identifier[article] . identifier[publisher] . ident... | def map_navigation(self):
"""
This is a wrapper for depth-first recursive analysis of the article
"""
#All articles should have titles
title_id = 'titlepage-{0}'.format(self.article_doi)
title_label = self.article.publisher.nav_title()
title_source = 'main.{0}.xhtml#title'.format(sel... |
def lang_match_rdf(triple, accepted_languages):
'''Find if the RDF triple contains acceptable language data'''
if not accepted_languages:
return True
languages = set([n.language for n in triple if isinstance(n, Literal)])
return (not languages) or (languages & accepted_languages) | def function[lang_match_rdf, parameter[triple, accepted_languages]]:
constant[Find if the RDF triple contains acceptable language data]
if <ast.UnaryOp object at 0x7da18f09edd0> begin[:]
return[constant[True]]
variable[languages] assign[=] call[name[set], parameter[<ast.ListComp object a... | keyword[def] identifier[lang_match_rdf] ( identifier[triple] , identifier[accepted_languages] ):
literal[string]
keyword[if] keyword[not] identifier[accepted_languages] :
keyword[return] keyword[True]
identifier[languages] = identifier[set] ([ identifier[n] . identifier[language] keyword... | def lang_match_rdf(triple, accepted_languages):
"""Find if the RDF triple contains acceptable language data"""
if not accepted_languages:
return True # depends on [control=['if'], data=[]]
languages = set([n.language for n in triple if isinstance(n, Literal)])
return not languages or languages ... |
def Rx(rads: Union[float, sympy.Basic]) -> XPowGate:
"""Returns a gate with the matrix e^{-i X rads / 2}."""
pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
return XPowGate(exponent=rads / pi, global_shift=-0.5) | def function[Rx, parameter[rads]]:
constant[Returns a gate with the matrix e^{-i X rads / 2}.]
variable[pi] assign[=] <ast.IfExp object at 0x7da1b1c62770>
return[call[name[XPowGate], parameter[]]] | keyword[def] identifier[Rx] ( identifier[rads] : identifier[Union] [ identifier[float] , identifier[sympy] . identifier[Basic] ])-> identifier[XPowGate] :
literal[string]
identifier[pi] = identifier[sympy] . identifier[pi] keyword[if] identifier[protocols] . identifier[is_parameterized] ( identifier[rads... | def Rx(rads: Union[float, sympy.Basic]) -> XPowGate:
"""Returns a gate with the matrix e^{-i X rads / 2}."""
pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
return XPowGate(exponent=rads / pi, global_shift=-0.5) |
def publish_synchronous(self, *args, **kwargs):
'''
Helper for publishing a message using transactions. If 'cb' keyword
arg is supplied, will be called when the transaction is committed.
'''
cb = kwargs.pop('cb', None)
self.tx.select()
self.basic.publish(*args, *... | def function[publish_synchronous, parameter[self]]:
constant[
Helper for publishing a message using transactions. If 'cb' keyword
arg is supplied, will be called when the transaction is committed.
]
variable[cb] assign[=] call[name[kwargs].pop, parameter[constant[cb], constant[N... | keyword[def] identifier[publish_synchronous] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[cb] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
identifier[self] . identifier[tx] . identifier[select] ()
identif... | def publish_synchronous(self, *args, **kwargs):
"""
Helper for publishing a message using transactions. If 'cb' keyword
arg is supplied, will be called when the transaction is committed.
"""
cb = kwargs.pop('cb', None)
self.tx.select()
self.basic.publish(*args, **kwargs)
sel... |
def use_openssl(libcrypto_path, libssl_path, trust_list_path=None):
"""
Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll),
or using a specific dynamic library on Linux/BSD (.so).
This can also be used to configure oscrypto to use LibreSSL dynamic
libraries.
This method ... | def function[use_openssl, parameter[libcrypto_path, libssl_path, trust_list_path]]:
constant[
Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll),
or using a specific dynamic library on Linux/BSD (.so).
This can also be used to configure oscrypto to use LibreSSL dynamic
li... | keyword[def] identifier[use_openssl] ( identifier[libcrypto_path] , identifier[libssl_path] , identifier[trust_list_path] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[libcrypto_path] , identifier[str_cls] ):
keyword[raise] identifier[ValueErro... | def use_openssl(libcrypto_path, libssl_path, trust_list_path=None):
"""
Forces using OpenSSL dynamic libraries on OS X (.dylib) or Windows (.dll),
or using a specific dynamic library on Linux/BSD (.so).
This can also be used to configure oscrypto to use LibreSSL dynamic
libraries.
This method ... |
def setup_rate_limit_handler(self, sleep_for_rate=False, min_rate_to_sleep=MIN_RATE_LIMIT,
rate_limit_header=RATE_LIMIT_HEADER,
rate_limit_reset_header=RATE_LIMIT_RESET_HEADER):
"""Setup the rate limit handler.
:param sleep_for_rate: sle... | def function[setup_rate_limit_handler, parameter[self, sleep_for_rate, min_rate_to_sleep, rate_limit_header, rate_limit_reset_header]]:
constant[Setup the rate limit handler.
:param sleep_for_rate: sleep until rate limit is reset
:param min_rate_to_sleep: minimun rate needed to make the fecthin... | keyword[def] identifier[setup_rate_limit_handler] ( identifier[self] , identifier[sleep_for_rate] = keyword[False] , identifier[min_rate_to_sleep] = identifier[MIN_RATE_LIMIT] ,
identifier[rate_limit_header] = identifier[RATE_LIMIT_HEADER] ,
identifier[rate_limit_reset_header] = identifier[RATE_LIMIT_RESET_HEADER] ... | def setup_rate_limit_handler(self, sleep_for_rate=False, min_rate_to_sleep=MIN_RATE_LIMIT, rate_limit_header=RATE_LIMIT_HEADER, rate_limit_reset_header=RATE_LIMIT_RESET_HEADER):
"""Setup the rate limit handler.
:param sleep_for_rate: sleep until rate limit is reset
:param min_rate_to_sleep: minimun... |
def dedent(string, indent_str=' ', max_levels=None):
"""Revert the effect of indentation.
Examples
--------
Remove a simple one-level indentation:
>>> text = '''<->This is line 1.
... <->Next line.
... <->And another one.'''
>>> print(text)
<->This is line 1.
<->Next line.
... | def function[dedent, parameter[string, indent_str, max_levels]]:
constant[Revert the effect of indentation.
Examples
--------
Remove a simple one-level indentation:
>>> text = '''<->This is line 1.
... <->Next line.
... <->And another one.'''
>>> print(text)
<->This is line 1.
... | keyword[def] identifier[dedent] ( identifier[string] , identifier[indent_str] = literal[string] , identifier[max_levels] = keyword[None] ):
literal[string]
keyword[if] identifier[len] ( identifier[indent_str] )== literal[int] :
keyword[return] identifier[string]
identifier[lines] = identi... | def dedent(string, indent_str=' ', max_levels=None):
"""Revert the effect of indentation.
Examples
--------
Remove a simple one-level indentation:
>>> text = '''<->This is line 1.
... <->Next line.
... <->And another one.'''
>>> print(text)
<->This is line 1.
<->Next line.
... |
def dragEnterEvent(self, event):
"""Allow user to drag files"""
if mimedata2url(event.mimeData()):
event.accept()
else:
event.ignore() | def function[dragEnterEvent, parameter[self, event]]:
constant[Allow user to drag files]
if call[name[mimedata2url], parameter[call[name[event].mimeData, parameter[]]]] begin[:]
call[name[event].accept, parameter[]] | keyword[def] identifier[dragEnterEvent] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[mimedata2url] ( identifier[event] . identifier[mimeData] ()):
identifier[event] . identifier[accept] ()
keyword[else] :
identifier[event]... | def dragEnterEvent(self, event):
"""Allow user to drag files"""
if mimedata2url(event.mimeData()):
event.accept() # depends on [control=['if'], data=[]]
else:
event.ignore() |
def _execute_wakeup_tasks(self):
"""Executes wakeup tasks, should only be called from loop()"""
# Check the length of wakeup tasks first to avoid concurrent issues
size = len(self.wakeup_tasks)
for i in range(size):
self.wakeup_tasks[i]() | def function[_execute_wakeup_tasks, parameter[self]]:
constant[Executes wakeup tasks, should only be called from loop()]
variable[size] assign[=] call[name[len], parameter[name[self].wakeup_tasks]]
for taget[name[i]] in starred[call[name[range], parameter[name[size]]]] begin[:]
c... | keyword[def] identifier[_execute_wakeup_tasks] ( identifier[self] ):
literal[string]
identifier[size] = identifier[len] ( identifier[self] . identifier[wakeup_tasks] )
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[size] ):
identifier[self] . identifier[wakeup_tas... | def _execute_wakeup_tasks(self):
"""Executes wakeup tasks, should only be called from loop()"""
# Check the length of wakeup tasks first to avoid concurrent issues
size = len(self.wakeup_tasks)
for i in range(size):
self.wakeup_tasks[i]() # depends on [control=['for'], data=['i']] |
def write(self, filepath, skip_unknown=False):
"""Write the metadata fields to filepath."""
fp = codecs.open(filepath, 'w', encoding='utf-8')
try:
self.write_file(fp, skip_unknown)
finally:
fp.close() | def function[write, parameter[self, filepath, skip_unknown]]:
constant[Write the metadata fields to filepath.]
variable[fp] assign[=] call[name[codecs].open, parameter[name[filepath], constant[w]]]
<ast.Try object at 0x7da1b1de1c60> | keyword[def] identifier[write] ( identifier[self] , identifier[filepath] , identifier[skip_unknown] = keyword[False] ):
literal[string]
identifier[fp] = identifier[codecs] . identifier[open] ( identifier[filepath] , literal[string] , identifier[encoding] = literal[string] )
keyword[try] :
... | def write(self, filepath, skip_unknown=False):
"""Write the metadata fields to filepath."""
fp = codecs.open(filepath, 'w', encoding='utf-8')
try:
self.write_file(fp, skip_unknown) # depends on [control=['try'], data=[]]
finally:
fp.close() |
def getLinkProperties(self, wanInterfaceId=1, timeout=1):
"""Execute GetCommonLinkProperties action to get WAN link properties.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN link properties
... | def function[getLinkProperties, parameter[self, wanInterfaceId, timeout]]:
constant[Execute GetCommonLinkProperties action to get WAN link properties.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN... | keyword[def] identifier[getLinkProperties] ( identifier[self] , identifier[wanInterfaceId] = literal[int] , identifier[timeout] = literal[int] ):
literal[string]
identifier[namespace] = identifier[Wan] . identifier[getServiceType] ( literal[string] )+ identifier[str] ( identifier[wanInterfaceId] )
... | def getLinkProperties(self, wanInterfaceId=1, timeout=1):
"""Execute GetCommonLinkProperties action to get WAN link properties.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN link properties
:r... |
def patch_namespaced_service_status(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_service_status # noqa: E501
partially update status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP... | def function[patch_namespaced_service_status, parameter[self, name, namespace, body]]:
constant[patch_namespaced_service_status # noqa: E501
partially update status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous H... | keyword[def] identifier[patch_namespaced_service_status] ( identifier[self] , identifier[name] , identifier[namespace] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( lit... | def patch_namespaced_service_status(self, name, namespace, body, **kwargs): # noqa: E501
"patch_namespaced_service_status # noqa: E501\n\n partially update status of the specified Service # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP r... |
def save_task(self, task):
"""Save a task into TaskWarrior database using add/modify call"""
args = [task['uuid'], 'modify'] if task.saved else ['add']
args.extend(self._get_modified_task_fields_as_args(task))
output = self.execute_command(args)
# Parse out the new ID, if the t... | def function[save_task, parameter[self, task]]:
constant[Save a task into TaskWarrior database using add/modify call]
variable[args] assign[=] <ast.IfExp object at 0x7da1b05481f0>
call[name[args].extend, parameter[call[name[self]._get_modified_task_fields_as_args, parameter[name[task]]]]]
... | keyword[def] identifier[save_task] ( identifier[self] , identifier[task] ):
literal[string]
identifier[args] =[ identifier[task] [ literal[string] ], literal[string] ] keyword[if] identifier[task] . identifier[saved] keyword[else] [ literal[string] ]
identifier[args] . identifier[extend... | def save_task(self, task):
"""Save a task into TaskWarrior database using add/modify call"""
args = [task['uuid'], 'modify'] if task.saved else ['add']
args.extend(self._get_modified_task_fields_as_args(task))
output = self.execute_command(args)
# Parse out the new ID, if the task is being added for... |
def prepare_rsem_reference(gtf, multifasta, build):
"""
gtf: path to GTF file (must have gene_id and transcript_id)
multifasta: path to multifasta file
build: name of organism build (e.g. hg19)
"""
if not utils.which("rsem-prepare-reference"):
logger.info("Skipping prepping RSEM referenc... | def function[prepare_rsem_reference, parameter[gtf, multifasta, build]]:
constant[
gtf: path to GTF file (must have gene_id and transcript_id)
multifasta: path to multifasta file
build: name of organism build (e.g. hg19)
]
if <ast.UnaryOp object at 0x7da1b1881540> begin[:]
... | keyword[def] identifier[prepare_rsem_reference] ( identifier[gtf] , identifier[multifasta] , identifier[build] ):
literal[string]
keyword[if] keyword[not] identifier[utils] . identifier[which] ( literal[string] ):
identifier[logger] . identifier[info] ( literal[string]
literal[string] ... | def prepare_rsem_reference(gtf, multifasta, build):
"""
gtf: path to GTF file (must have gene_id and transcript_id)
multifasta: path to multifasta file
build: name of organism build (e.g. hg19)
"""
if not utils.which('rsem-prepare-reference'):
logger.info('Skipping prepping RSEM referenc... |
def _par_vector2dict(v, pars, dims, starts=None):
"""Turn a vector of samples into an OrderedDict according to param dims.
Parameters
----------
y : list of int or float
pars : list of str
parameter names
dims : list of list of int
list of dimensions of parameters
Returns
... | def function[_par_vector2dict, parameter[v, pars, dims, starts]]:
constant[Turn a vector of samples into an OrderedDict according to param dims.
Parameters
----------
y : list of int or float
pars : list of str
parameter names
dims : list of list of int
list of dimensions of... | keyword[def] identifier[_par_vector2dict] ( identifier[v] , identifier[pars] , identifier[dims] , identifier[starts] = keyword[None] ):
literal[string]
keyword[if] identifier[starts] keyword[is] keyword[None] :
identifier[starts] = identifier[_calc_starts] ( identifier[dims] )
identifier[d... | def _par_vector2dict(v, pars, dims, starts=None):
"""Turn a vector of samples into an OrderedDict according to param dims.
Parameters
----------
y : list of int or float
pars : list of str
parameter names
dims : list of list of int
list of dimensions of parameters
Returns
... |
def returnOneIndex(self, last=False):
'''Return the first origin index (integer) of the current list. That
index refers to it's placement in the original list of dictionaries.
This is very useful when one wants to reference the original entry by
index.
Example of use:
... | def function[returnOneIndex, parameter[self, last]]:
constant[Return the first origin index (integer) of the current list. That
index refers to it's placement in the original list of dictionaries.
This is very useful when one wants to reference the original entry by
index.
... | keyword[def] identifier[returnOneIndex] ( identifier[self] , identifier[last] = keyword[False] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[table] )== literal[int] :
keyword[return] keyword[None]
keyword[else] :
keyword[if] id... | def returnOneIndex(self, last=False):
"""Return the first origin index (integer) of the current list. That
index refers to it's placement in the original list of dictionaries.
This is very useful when one wants to reference the original entry by
index.
Example of use:
... |
def autoscale(self):
"""
Sets the view limits to the nearest multiples of base that contain the
data.
"""
# requires matplotlib >= 0.98.0
(vmin, vmax) = self.axis.get_data_interval()
locs = self._get_default_locs(vmin, vmax)
(vmin, vmax) = locs[[0, -1]]
... | def function[autoscale, parameter[self]]:
constant[
Sets the view limits to the nearest multiples of base that contain the
data.
]
<ast.Tuple object at 0x7da18ede5330> assign[=] call[name[self].axis.get_data_interval, parameter[]]
variable[locs] assign[=] call[name[self].... | keyword[def] identifier[autoscale] ( identifier[self] ):
literal[string]
( identifier[vmin] , identifier[vmax] )= identifier[self] . identifier[axis] . identifier[get_data_interval] ()
identifier[locs] = identifier[self] . identifier[_get_default_locs] ( identifier[vmin] , identif... | def autoscale(self):
"""
Sets the view limits to the nearest multiples of base that contain the
data.
"""
# requires matplotlib >= 0.98.0
(vmin, vmax) = self.axis.get_data_interval()
locs = self._get_default_locs(vmin, vmax)
(vmin, vmax) = locs[[0, -1]]
if vmin == vmax:
... |
def edit_dataset_metadata(request, dataset_id=None):
"""Renders a template to upload or edit a Dataset.
Most of the heavy lifting is done by add_dataset(...).
"""
if request.method == 'POST':
return add_dataset(request, dataset_id)
elif request.method == 'GET':
# create a blank fo... | def function[edit_dataset_metadata, parameter[request, dataset_id]]:
constant[Renders a template to upload or edit a Dataset.
Most of the heavy lifting is done by add_dataset(...).
]
if compare[name[request].method equal[==] constant[POST]] begin[:]
return[call[name[add_dataset], param... | keyword[def] identifier[edit_dataset_metadata] ( identifier[request] , identifier[dataset_id] = keyword[None] ):
literal[string]
keyword[if] identifier[request] . identifier[method] == literal[string] :
keyword[return] identifier[add_dataset] ( identifier[request] , identifier[dataset_id] )
... | def edit_dataset_metadata(request, dataset_id=None):
"""Renders a template to upload or edit a Dataset.
Most of the heavy lifting is done by add_dataset(...).
"""
if request.method == 'POST':
return add_dataset(request, dataset_id) # depends on [control=['if'], data=[]]
elif request.metho... |
def create(self, name, plugin_data_dir, gzip=False):
"""
Create a new plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
plugin_data_dir (string): Path to the plugin dat... | def function[create, parameter[self, name, plugin_data_dir, gzip]]:
constant[
Create a new plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
plugin_data_dir (string): P... | keyword[def] identifier[create] ( identifier[self] , identifier[name] , identifier[plugin_data_dir] , identifier[gzip] = keyword[False] ):
literal[string]
identifier[self] . identifier[client] . identifier[api] . identifier[create_plugin] ( identifier[name] , identifier[plugin_data_dir] , identifie... | def create(self, name, plugin_data_dir, gzip=False):
"""
Create a new plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
plugin_data_dir (string): Path to the plugin data di... |
def project(self, term, **kwargs):
"""Search for a project by id.
Args:
term (str): Term to search for.
kwargs (dict): additional keywords passed into
requests.session.get params keyword.
"""
params = kwargs
baseuri = self._BASE_URI + 'projects/' ... | def function[project, parameter[self, term]]:
constant[Search for a project by id.
Args:
term (str): Term to search for.
kwargs (dict): additional keywords passed into
requests.session.get params keyword.
]
variable[params] assign[=] name[kwargs]
... | keyword[def] identifier[project] ( identifier[self] , identifier[term] ,** identifier[kwargs] ):
literal[string]
identifier[params] = identifier[kwargs]
identifier[baseuri] = identifier[self] . identifier[_BASE_URI] + literal[string] + identifier[term]
identifier[res] = identifi... | def project(self, term, **kwargs):
"""Search for a project by id.
Args:
term (str): Term to search for.
kwargs (dict): additional keywords passed into
requests.session.get params keyword.
"""
params = kwargs
baseuri = self._BASE_URI + 'projects/' + term
r... |
def get_bytes_to_image_callback(image_dims=(224, 224)):
"""Return a callback to process image bytes for ImageNet."""
from keras.preprocessing import image
import numpy as np
from PIL import Image
from io import BytesIO
def preprocess_image_bytes(data_bytes):
"""Process image bytes for I... | def function[get_bytes_to_image_callback, parameter[image_dims]]:
constant[Return a callback to process image bytes for ImageNet.]
from relative_module[keras.preprocessing] import module[image]
import module[numpy] as alias[np]
from relative_module[PIL] import module[Image]
from relative_module[... | keyword[def] identifier[get_bytes_to_image_callback] ( identifier[image_dims] =( literal[int] , literal[int] )):
literal[string]
keyword[from] identifier[keras] . identifier[preprocessing] keyword[import] identifier[image]
keyword[import] identifier[numpy] keyword[as] identifier[np]
keywo... | def get_bytes_to_image_callback(image_dims=(224, 224)):
"""Return a callback to process image bytes for ImageNet."""
from keras.preprocessing import image
import numpy as np
from PIL import Image
from io import BytesIO
def preprocess_image_bytes(data_bytes):
"""Process image bytes for I... |
def get_memberdef_nodes_and_signatures(self, node, kind):
"""Collects the memberdef nodes and corresponding signatures that
correspond to public function entries that are at most depth 2 deeper
than the current (compounddef) node. Returns a dictionary with
function signatures (what swig... | def function[get_memberdef_nodes_and_signatures, parameter[self, node, kind]]:
constant[Collects the memberdef nodes and corresponding signatures that
correspond to public function entries that are at most depth 2 deeper
than the current (compounddef) node. Returns a dictionary with
fun... | keyword[def] identifier[get_memberdef_nodes_and_signatures] ( identifier[self] , identifier[node] , identifier[kind] ):
literal[string]
identifier[sig_dict] ={}
identifier[sig_prefix] = literal[string]
keyword[if] identifier[kind] keyword[in] ( literal[string] , literal[string]... | def get_memberdef_nodes_and_signatures(self, node, kind):
"""Collects the memberdef nodes and corresponding signatures that
correspond to public function entries that are at most depth 2 deeper
than the current (compounddef) node. Returns a dictionary with
function signatures (what swig exp... |
def factory_reset(self, ids, except_ids=False, except_baudrate_and_ids=False):
""" Reset all motors on the bus to their factory default settings. """
mode = (0x02 if except_baudrate_and_ids else
0x01 if except_ids else 0xFF)
for id in ids:
try:
self.... | def function[factory_reset, parameter[self, ids, except_ids, except_baudrate_and_ids]]:
constant[ Reset all motors on the bus to their factory default settings. ]
variable[mode] assign[=] <ast.IfExp object at 0x7da1b1304ee0>
for taget[name[id]] in starred[name[ids]] begin[:]
<ast.Try obj... | keyword[def] identifier[factory_reset] ( identifier[self] , identifier[ids] , identifier[except_ids] = keyword[False] , identifier[except_baudrate_and_ids] = keyword[False] ):
literal[string]
identifier[mode] =( literal[int] keyword[if] identifier[except_baudrate_and_ids] keyword[else]
... | def factory_reset(self, ids, except_ids=False, except_baudrate_and_ids=False):
""" Reset all motors on the bus to their factory default settings. """
mode = 2 if except_baudrate_and_ids else 1 if except_ids else 255
for id in ids:
try:
self._send_packet(self._protocol.DxlResetPacket(id, ... |
def get_event(self, name, default=_sentinel):
"""
Lookup an event by name.
:param str item: Event name
:return Event: Event instance under key
"""
if name not in self.events:
if self.create_events_on_access:
self.add_event(name)
el... | def function[get_event, parameter[self, name, default]]:
constant[
Lookup an event by name.
:param str item: Event name
:return Event: Event instance under key
]
if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[self].events] begin[:]
if nam... | keyword[def] identifier[get_event] ( identifier[self] , identifier[name] , identifier[default] = identifier[_sentinel] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[events] :
keyword[if] identifier[self] . identifier[create_... | def get_event(self, name, default=_sentinel):
"""
Lookup an event by name.
:param str item: Event name
:return Event: Event instance under key
"""
if name not in self.events:
if self.create_events_on_access:
self.add_event(name) # depends on [control=['if'],... |
def materials(self):
"""
Property for accessing :class:`MaterialManager` instance, which is used to manage materials.
:rtype: yagocd.resources.material.MaterialManager
"""
if self._material_manager is None:
self._material_manager = MaterialManager(session=self._sessi... | def function[materials, parameter[self]]:
constant[
Property for accessing :class:`MaterialManager` instance, which is used to manage materials.
:rtype: yagocd.resources.material.MaterialManager
]
if compare[name[self]._material_manager is constant[None]] begin[:]
... | keyword[def] identifier[materials] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_material_manager] keyword[is] keyword[None] :
identifier[self] . identifier[_material_manager] = identifier[MaterialManager] ( identifier[session] = identifier[self] .... | def materials(self):
"""
Property for accessing :class:`MaterialManager` instance, which is used to manage materials.
:rtype: yagocd.resources.material.MaterialManager
"""
if self._material_manager is None:
self._material_manager = MaterialManager(session=self._session) # depen... |
def index_objects(mapping_type, ids, chunk_size=100, es=None, index=None):
"""Index documents of a specified mapping type.
This allows for asynchronous indexing.
If a mapping_type extends Indexable, you can add a ``post_save``
hook for the model that it's based on like this::
@receiver(dbsign... | def function[index_objects, parameter[mapping_type, ids, chunk_size, es, index]]:
constant[Index documents of a specified mapping type.
This allows for asynchronous indexing.
If a mapping_type extends Indexable, you can add a ``post_save``
hook for the model that it's based on like this::
... | keyword[def] identifier[index_objects] ( identifier[mapping_type] , identifier[ids] , identifier[chunk_size] = literal[int] , identifier[es] = keyword[None] , identifier[index] = keyword[None] ):
literal[string]
keyword[if] identifier[settings] . identifier[ES_DISABLED] :
keyword[return]
i... | def index_objects(mapping_type, ids, chunk_size=100, es=None, index=None):
"""Index documents of a specified mapping type.
This allows for asynchronous indexing.
If a mapping_type extends Indexable, you can add a ``post_save``
hook for the model that it's based on like this::
@receiver(dbsign... |
def params(self):
""" Return a *copy* (we hope) of the parameters.
DANGER: Altering properties directly doesn't call model._cache
"""
params = odict([])
for key,model in self.models.items():
params.update(model.params)
return params | def function[params, parameter[self]]:
constant[ Return a *copy* (we hope) of the parameters.
DANGER: Altering properties directly doesn't call model._cache
]
variable[params] assign[=] call[name[odict], parameter[list[[]]]]
for taget[tuple[[<ast.Name object at 0x7da1b232f970>, <... | keyword[def] identifier[params] ( identifier[self] ):
literal[string]
identifier[params] = identifier[odict] ([])
keyword[for] identifier[key] , identifier[model] keyword[in] identifier[self] . identifier[models] . identifier[items] ():
identifier[params] . identifier[updat... | def params(self):
""" Return a *copy* (we hope) of the parameters.
DANGER: Altering properties directly doesn't call model._cache
"""
params = odict([])
for (key, model) in self.models.items():
params.update(model.params) # depends on [control=['for'], data=[]]
return params |
def create(cls, name, ipv4_network=None, ipv6_network=None,
comment=None):
"""
Create the network element
:param str name: Name of element
:param str ipv4_network: network cidr (optional if ipv6)
:param str ipv6_network: network cidr (optional if ipv4)
:pa... | def function[create, parameter[cls, name, ipv4_network, ipv6_network, comment]]:
constant[
Create the network element
:param str name: Name of element
:param str ipv4_network: network cidr (optional if ipv6)
:param str ipv6_network: network cidr (optional if ipv4)
:param... | keyword[def] identifier[create] ( identifier[cls] , identifier[name] , identifier[ipv4_network] = keyword[None] , identifier[ipv6_network] = keyword[None] ,
identifier[comment] = keyword[None] ):
literal[string]
identifier[ipv4_network] = identifier[ipv4_network] keyword[if] identifier[ipv4_netw... | def create(cls, name, ipv4_network=None, ipv6_network=None, comment=None):
"""
Create the network element
:param str name: Name of element
:param str ipv4_network: network cidr (optional if ipv6)
:param str ipv6_network: network cidr (optional if ipv4)
:param str comment: co... |
def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False,
with_superuser=True, accept_global_perms=True, perms_filter='pk__in'):
"""Return queryset with required permissions."""
if isinstance(perms, str):
perms = [perms]
ctype = None
app_label =... | def function[get_objects_for_user, parameter[user, perms, klass, use_groups, any_perm, with_superuser, accept_global_perms, perms_filter]]:
constant[Return queryset with required permissions.]
if call[name[isinstance], parameter[name[perms], name[str]]] begin[:]
variable[perms] assign[=]... | keyword[def] identifier[get_objects_for_user] ( identifier[user] , identifier[perms] , identifier[klass] = keyword[None] , identifier[use_groups] = keyword[True] , identifier[any_perm] = keyword[False] ,
identifier[with_superuser] = keyword[True] , identifier[accept_global_perms] = keyword[True] , identifier[perms_f... | def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False, with_superuser=True, accept_global_perms=True, perms_filter='pk__in'):
"""Return queryset with required permissions."""
if isinstance(perms, str):
perms = [perms] # depends on [control=['if'], data=[]]
ctype = None
... |
def _refine_upcheck(merge, min_goodness):
"""Remove from the merge any entries which would be covered by entries
between their current position and the merge insertion position.
For example, the third entry of::
0011 -> N
0100 -> N
1000 -> N
X000 -> NE
Cannot be merged... | def function[_refine_upcheck, parameter[merge, min_goodness]]:
constant[Remove from the merge any entries which would be covered by entries
between their current position and the merge insertion position.
For example, the third entry of::
0011 -> N
0100 -> N
1000 -> N
X... | keyword[def] identifier[_refine_upcheck] ( identifier[merge] , identifier[min_goodness] ):
literal[string]
identifier[changed] = keyword[False]
keyword[for] identifier[i] keyword[in] identifier[sorted] ( identifier[merge] . identifier[entries] , identifier[reverse] = keyword[True] ):
... | def _refine_upcheck(merge, min_goodness):
"""Remove from the merge any entries which would be covered by entries
between their current position and the merge insertion position.
For example, the third entry of::
0011 -> N
0100 -> N
1000 -> N
X000 -> NE
Cannot be merged... |
def __get_activity_by_name(self, name, category_id = None, resurrect = True):
"""get most recent, preferably not deleted activity by it's name"""
if category_id:
query = """
SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category
FROM ... | def function[__get_activity_by_name, parameter[self, name, category_id, resurrect]]:
constant[get most recent, preferably not deleted activity by it's name]
if name[category_id] begin[:]
variable[query] assign[=] constant[
SELECT a.id, a.name, a.deleted, coalesce(b... | keyword[def] identifier[__get_activity_by_name] ( identifier[self] , identifier[name] , identifier[category_id] = keyword[None] , identifier[resurrect] = keyword[True] ):
literal[string]
keyword[if] identifier[category_id] :
identifier[query] = literal[string]
identifi... | def __get_activity_by_name(self, name, category_id=None, resurrect=True):
"""get most recent, preferably not deleted activity by it's name"""
if category_id:
query = '\n SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category\n FROM activities a\n ... |
def path(self):
"""Node's relative path from the root node"""
if self.parent:
try:
parent_path = self.parent.path.encode()
except AttributeError:
parent_path = self.parent.path
return os.path.join(parent_path, self.name)
return... | def function[path, parameter[self]]:
constant[Node's relative path from the root node]
if name[self].parent begin[:]
<ast.Try object at 0x7da1b053acb0>
return[call[name[os].path.join, parameter[name[parent_path], name[self].name]]]
return[constant[b'/']] | keyword[def] identifier[path] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[parent] :
keyword[try] :
identifier[parent_path] = identifier[self] . identifier[parent] . identifier[path] . identifier[encode] ()
keyword[exce... | def path(self):
"""Node's relative path from the root node"""
if self.parent:
try:
parent_path = self.parent.path.encode() # depends on [control=['try'], data=[]]
except AttributeError:
parent_path = self.parent.path # depends on [control=['except'], data=[]]
re... |
def db_import(self, urls=None, force_download=False):
"""Updates the CTD database
1. downloads all files from CTD
2. drops all tables in database
3. creates all tables in database
4. import all data from CTD files
:param iter[str] urls: An iterable of UR... | def function[db_import, parameter[self, urls, force_download]]:
constant[Updates the CTD database
1. downloads all files from CTD
2. drops all tables in database
3. creates all tables in database
4. import all data from CTD files
:param iter[str] urls: A... | keyword[def] identifier[db_import] ( identifier[self] , identifier[urls] = keyword[None] , identifier[force_download] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[urls] :
identifier[urls] =[
identifier[defaults] . identifier[url_base] + identif... | def db_import(self, urls=None, force_download=False):
"""Updates the CTD database
1. downloads all files from CTD
2. drops all tables in database
3. creates all tables in database
4. import all data from CTD files
:param iter[str] urls: An iterable of URL st... |
def set_href_prefix(self, prefix):
"""
Set the prefix of any hrefs associated with this thing.
prefix -- the prefix
"""
self.href_prefix = prefix
for property_ in self.properties.values():
property_.set_href_prefix(prefix)
for action_name in self.ac... | def function[set_href_prefix, parameter[self, prefix]]:
constant[
Set the prefix of any hrefs associated with this thing.
prefix -- the prefix
]
name[self].href_prefix assign[=] name[prefix]
for taget[name[property_]] in starred[call[name[self].properties.values, paramet... | keyword[def] identifier[set_href_prefix] ( identifier[self] , identifier[prefix] ):
literal[string]
identifier[self] . identifier[href_prefix] = identifier[prefix]
keyword[for] identifier[property_] keyword[in] identifier[self] . identifier[properties] . identifier[values] ():
... | def set_href_prefix(self, prefix):
"""
Set the prefix of any hrefs associated with this thing.
prefix -- the prefix
"""
self.href_prefix = prefix
for property_ in self.properties.values():
property_.set_href_prefix(prefix) # depends on [control=['for'], data=['property_']]
... |
def find_global(self, pattern):
"""
Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive!
"""
pos_s = self.reader.search(pattern)
if len(pos_s) == 0:
return -1
return pos_s[0] | def function[find_global, parameter[self, pattern]]:
constant[
Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive!
]
variable[pos_s] assign[=] call[name[self].reader.search, parameter[name[pattern]]]
if compare[call[name[len], pa... | keyword[def] identifier[find_global] ( identifier[self] , identifier[pattern] ):
literal[string]
identifier[pos_s] = identifier[self] . identifier[reader] . identifier[search] ( identifier[pattern] )
keyword[if] identifier[len] ( identifier[pos_s] )== literal[int] :
keyword[return] - literal[int]
... | def find_global(self, pattern):
"""
Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive!
"""
pos_s = self.reader.search(pattern)
if len(pos_s) == 0:
return -1 # depends on [control=['if'], data=[]]
return pos_s[0] |
def _query_init(k, oracle, query, method='all'):
"""A helper function for query-matching function initialization."""
if method == 'all':
a = np.subtract(query, [oracle.f_array[t] for t in oracle.latent[oracle.data[k]]])
dvec = (a * a).sum(axis=1) # Could skip the sqrt
_d = dvec.argmin()... | def function[_query_init, parameter[k, oracle, query, method]]:
constant[A helper function for query-matching function initialization.]
if compare[name[method] equal[==] constant[all]] begin[:]
variable[a] assign[=] call[name[np].subtract, parameter[name[query], <ast.ListComp object at 0... | keyword[def] identifier[_query_init] ( identifier[k] , identifier[oracle] , identifier[query] , identifier[method] = literal[string] ):
literal[string]
keyword[if] identifier[method] == literal[string] :
identifier[a] = identifier[np] . identifier[subtract] ( identifier[query] ,[ identifier[oracl... | def _query_init(k, oracle, query, method='all'):
"""A helper function for query-matching function initialization."""
if method == 'all':
a = np.subtract(query, [oracle.f_array[t] for t in oracle.latent[oracle.data[k]]])
dvec = (a * a).sum(axis=1) # Could skip the sqrt
_d = dvec.argmin()... |
def pack_found_items(self, s_text, target):
""" pack up found items for search ctrl
:param target: treectrl obj
:param s_text: text to search, lower case
return list of found items
"""
all_children = self.all_children
all_text = [target.GetItemText(i).... | def function[pack_found_items, parameter[self, s_text, target]]:
constant[ pack up found items for search ctrl
:param target: treectrl obj
:param s_text: text to search, lower case
return list of found items
]
variable[all_children] assign[=] name[self].all_ch... | keyword[def] identifier[pack_found_items] ( identifier[self] , identifier[s_text] , identifier[target] ):
literal[string]
identifier[all_children] = identifier[self] . identifier[all_children]
identifier[all_text] =[ identifier[target] . identifier[GetItemText] ( identifier[i] ). identifi... | def pack_found_items(self, s_text, target):
""" pack up found items for search ctrl
:param target: treectrl obj
:param s_text: text to search, lower case
return list of found items
"""
all_children = self.all_children
all_text = [target.GetItemText(i).lower() for ... |
def _api_on_write_error(self, status_code, **kwargs):
"""
Catches errors and renders it as a JSON message. Adds the traceback if
debug is enabled.
"""
return_error = { "code": self.get_status() }
exc_info = kwargs.get("exc_info")
if exc_info and isinstance(exc_i... | def function[_api_on_write_error, parameter[self, status_code]]:
constant[
Catches errors and renders it as a JSON message. Adds the traceback if
debug is enabled.
]
variable[return_error] assign[=] dictionary[[<ast.Constant object at 0x7da1b0a31570>], [<ast.Call object at 0x7da1... | keyword[def] identifier[_api_on_write_error] ( identifier[self] , identifier[status_code] ,** identifier[kwargs] ):
literal[string]
identifier[return_error] ={ literal[string] : identifier[self] . identifier[get_status] ()}
identifier[exc_info] = identifier[kwargs] . identifier[get] ( lit... | def _api_on_write_error(self, status_code, **kwargs):
"""
Catches errors and renders it as a JSON message. Adds the traceback if
debug is enabled.
"""
return_error = {'code': self.get_status()}
exc_info = kwargs.get('exc_info')
if exc_info and isinstance(exc_info[1], oz.json_api.... |
def start_capture(self, slot_number, port_number, output_file, data_link_type="DLT_EN10MB"):
"""
Starts a packet capture.
:param slot_number: slot number
:param port_number: port number
:param output_file: PCAP destination file for the capture
:param data_link_type: PCAP... | def function[start_capture, parameter[self, slot_number, port_number, output_file, data_link_type]]:
constant[
Starts a packet capture.
:param slot_number: slot number
:param port_number: port number
:param output_file: PCAP destination file for the capture
:param data_l... | keyword[def] identifier[start_capture] ( identifier[self] , identifier[slot_number] , identifier[port_number] , identifier[output_file] , identifier[data_link_type] = literal[string] ):
literal[string]
keyword[try] :
identifier[open] ( identifier[output_file] , literal[string] ). iden... | def start_capture(self, slot_number, port_number, output_file, data_link_type='DLT_EN10MB'):
"""
Starts a packet capture.
:param slot_number: slot number
:param port_number: port number
:param output_file: PCAP destination file for the capture
:param data_link_type: PCAP dat... |
def task_date(self, task_re):
""" Get a datetime.date object for the last task that matches a regex.
:param task_re: regex, eg re.compile('Development Freeze').
See txproductpages.milestones for some useful regex
constants to pass in here.
:return... | def function[task_date, parameter[self, task_re]]:
constant[ Get a datetime.date object for the last task that matches a regex.
:param task_re: regex, eg re.compile('Development Freeze').
See txproductpages.milestones for some useful regex
constants to pa... | keyword[def] identifier[task_date] ( identifier[self] , identifier[task_re] ):
literal[string]
identifier[tasks] = keyword[yield] identifier[self] . identifier[schedule_tasks] ()
identifier[task_date] = keyword[None]
keyword[for] identifier[task] keyword[in] identifier[tasks]... | def task_date(self, task_re):
""" Get a datetime.date object for the last task that matches a regex.
:param task_re: regex, eg re.compile('Development Freeze').
See txproductpages.milestones for some useful regex
constants to pass in here.
:returns: d... |
def renumber(args):
"""
%prog renumber Mt35.consolidated.bed > tagged.bed
Renumber genes for annotation updates.
"""
from jcvi.algorithms.lis import longest_increasing_subsequence
from jcvi.utils.grouper import Grouper
p = OptionParser(renumber.__doc__)
p.set_annot_reformat_opts()
... | def function[renumber, parameter[args]]:
constant[
%prog renumber Mt35.consolidated.bed > tagged.bed
Renumber genes for annotation updates.
]
from relative_module[jcvi.algorithms.lis] import module[longest_increasing_subsequence]
from relative_module[jcvi.utils.grouper] import module[Groupe... | keyword[def] identifier[renumber] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[algorithms] . identifier[lis] keyword[import] identifier[longest_increasing_subsequence]
keyword[from] identifier[jcvi] . identifier[utils] . identifier[grouper] keyword[import] i... | def renumber(args):
"""
%prog renumber Mt35.consolidated.bed > tagged.bed
Renumber genes for annotation updates.
"""
from jcvi.algorithms.lis import longest_increasing_subsequence
from jcvi.utils.grouper import Grouper
p = OptionParser(renumber.__doc__)
p.set_annot_reformat_opts()
(... |
def _parseExportDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the C{IMAGE_EXPORT_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_EXPORT_DIRECTORY} directory starts.
@type size: int
@param size: The size of the C{... | def function[_parseExportDirectory, parameter[self, rva, size, magic]]:
constant[
Parses the C{IMAGE_EXPORT_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_EXPORT_DIRECTORY} directory starts.
@type size: int
@param size: The s... | keyword[def] identifier[_parseExportDirectory] ( identifier[self] , identifier[rva] , identifier[size] , identifier[magic] = identifier[consts] . identifier[PE32] ):
literal[string]
identifier[data] = identifier[self] . identifier[getDataAtRva] ( identifier[rva] , identifier[size] )
identi... | def _parseExportDirectory(self, rva, size, magic=consts.PE32):
"""
Parses the C{IMAGE_EXPORT_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_EXPORT_DIRECTORY} directory starts.
@type size: int
@param size: The size of the C{IMAGE_... |
def cmd_xor(k, i, o):
"""XOR cipher.
Note: XOR is not a 'secure cipher'. If you need strong crypto you must use
algorithms like AES. You can use habu.fernet for that.
Example:
\b
$ habu.xor -k mysecretkey -i /bin/ls > xored
$ habu.xor -k mysecretkey -i xored > uxored
$ sha1sum /bin/ls... | def function[cmd_xor, parameter[k, i, o]]:
constant[XOR cipher.
Note: XOR is not a 'secure cipher'. If you need strong crypto you must use
algorithms like AES. You can use habu.fernet for that.
Example:
$ habu.xor -k mysecretkey -i /bin/ls > xored
$ habu.xor -k mysecretkey -i xored ... | keyword[def] identifier[cmd_xor] ( identifier[k] , identifier[i] , identifier[o] ):
literal[string]
identifier[o] . identifier[write] ( identifier[xor] ( identifier[i] . identifier[read] (), identifier[k] . identifier[encode] ())) | def cmd_xor(k, i, o):
"""XOR cipher.
Note: XOR is not a 'secure cipher'. If you need strong crypto you must use
algorithms like AES. You can use habu.fernet for that.
Example:
\x08
$ habu.xor -k mysecretkey -i /bin/ls > xored
$ habu.xor -k mysecretkey -i xored > uxored
$ sha1sum /bin/... |
def get_for(self, historics_id, with_estimate=None):
""" Get the historic query for the given ID
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: playback id of the query
:type historics_id: str
:return... | def function[get_for, parameter[self, historics_id, with_estimate]]:
constant[ Get the historic query for the given ID
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: playback id of the query
:type historics_id: s... | keyword[def] identifier[get_for] ( identifier[self] , identifier[historics_id] , identifier[with_estimate] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( identifier[historics_id] , identifier[maximum] = keyword[None] , identifier[page] = keyword[None] , ide... | def get_for(self, historics_id, with_estimate=None):
""" Get the historic query for the given ID
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: playback id of the query
:type historics_id: str
:return: di... |
def put_target_state():
"""SDP target State.
Sets the target state
"""
sdp_state = SDPState()
errval, errdict = _check_status(sdp_state)
if errval == "error":
LOG.debug(errdict['reason'])
rdict = dict(
current_state="unknown",
last_updated="unknown",
... | def function[put_target_state, parameter[]]:
constant[SDP target State.
Sets the target state
]
variable[sdp_state] assign[=] call[name[SDPState], parameter[]]
<ast.Tuple object at 0x7da20c7962f0> assign[=] call[name[_check_status], parameter[name[sdp_state]]]
if compare[name[er... | keyword[def] identifier[put_target_state] ():
literal[string]
identifier[sdp_state] = identifier[SDPState] ()
identifier[errval] , identifier[errdict] = identifier[_check_status] ( identifier[sdp_state] )
keyword[if] identifier[errval] == literal[string] :
identifier[LOG] . identifier[d... | def put_target_state():
"""SDP target State.
Sets the target state
"""
sdp_state = SDPState()
(errval, errdict) = _check_status(sdp_state)
if errval == 'error':
LOG.debug(errdict['reason'])
rdict = dict(current_state='unknown', last_updated='unknown', reason=errdict['reason']) ... |
def number_aware_alphabetical_cmp(str1, str2):
""" cmp function for sorting a list of strings by alphabetical order, but with
numbers sorted numerically.
i.e., foo1, foo2, foo10, foo11
instead of foo1, foo10
"""
def flatten_tokens(tokens):
l = []
for token in tokens... | def function[number_aware_alphabetical_cmp, parameter[str1, str2]]:
constant[ cmp function for sorting a list of strings by alphabetical order, but with
numbers sorted numerically.
i.e., foo1, foo2, foo10, foo11
instead of foo1, foo10
]
def function[flatten_tokens, parameter... | keyword[def] identifier[number_aware_alphabetical_cmp] ( identifier[str1] , identifier[str2] ):
literal[string]
keyword[def] identifier[flatten_tokens] ( identifier[tokens] ):
identifier[l] =[]
keyword[for] identifier[token] keyword[in] identifier[tokens] :
keyword[if] ... | def number_aware_alphabetical_cmp(str1, str2):
""" cmp function for sorting a list of strings by alphabetical order, but with
numbers sorted numerically.
i.e., foo1, foo2, foo10, foo11
instead of foo1, foo10
"""
def flatten_tokens(tokens):
l = []
for token in tokens... |
def zk_client(host, scheme, credential):
""" returns a connected (and possibly authenticated) ZK client """
if not re.match(r".*:\d+$", host):
host = "%s:%d" % (host, DEFAULT_ZK_PORT)
client = KazooClient(hosts=host)
client.start()
if scheme != "":
client.add_auth(scheme, credenti... | def function[zk_client, parameter[host, scheme, credential]]:
constant[ returns a connected (and possibly authenticated) ZK client ]
if <ast.UnaryOp object at 0x7da18f00ee60> begin[:]
variable[host] assign[=] binary_operation[constant[%s:%d] <ast.Mod object at 0x7da2590d6920> tuple[[<ast... | keyword[def] identifier[zk_client] ( identifier[host] , identifier[scheme] , identifier[credential] ):
literal[string]
keyword[if] keyword[not] identifier[re] . identifier[match] ( literal[string] , identifier[host] ):
identifier[host] = literal[string] %( identifier[host] , identifier[DEFAULT_... | def zk_client(host, scheme, credential):
""" returns a connected (and possibly authenticated) ZK client """
if not re.match('.*:\\d+$', host):
host = '%s:%d' % (host, DEFAULT_ZK_PORT) # depends on [control=['if'], data=[]]
client = KazooClient(hosts=host)
client.start()
if scheme != '':
... |
def get_release_id_data(self, release_id: bytes) -> Tuple[str, str, str]:
"""
Returns ``(package_name, version, manifest_uri)`` associated with the given
release id, *if* it is available on the current registry.
* Parameters:
* ``release_id``: 32 byte release identifier
... | def function[get_release_id_data, parameter[self, release_id]]:
constant[
Returns ``(package_name, version, manifest_uri)`` associated with the given
release id, *if* it is available on the current registry.
* Parameters:
* ``release_id``: 32 byte release identifier
... | keyword[def] identifier[get_release_id_data] ( identifier[self] , identifier[release_id] : identifier[bytes] )-> identifier[Tuple] [ identifier[str] , identifier[str] , identifier[str] ]:
literal[string]
identifier[self] . identifier[_validate_set_registry] ()
keyword[return] identifier[s... | def get_release_id_data(self, release_id: bytes) -> Tuple[str, str, str]:
"""
Returns ``(package_name, version, manifest_uri)`` associated with the given
release id, *if* it is available on the current registry.
* Parameters:
* ``release_id``: 32 byte release identifier
... |
def build(self, **kw):
"""A null "builder" for directories."""
global MkdirBuilder
if self.builder is not MkdirBuilder:
SCons.Node.Node.build(self, **kw) | def function[build, parameter[self]]:
constant[A null "builder" for directories.]
<ast.Global object at 0x7da204347f10>
if compare[name[self].builder is_not name[MkdirBuilder]] begin[:]
call[name[SCons].Node.Node.build, parameter[name[self]]] | keyword[def] identifier[build] ( identifier[self] ,** identifier[kw] ):
literal[string]
keyword[global] identifier[MkdirBuilder]
keyword[if] identifier[self] . identifier[builder] keyword[is] keyword[not] identifier[MkdirBuilder] :
identifier[SCons] . identifier[Node] . ... | def build(self, **kw):
"""A null "builder" for directories."""
global MkdirBuilder
if self.builder is not MkdirBuilder:
SCons.Node.Node.build(self, **kw) # depends on [control=['if'], data=[]] |
def _repeat_length(cls, part):
"""
The length of the repeated portions of ``part``.
:param part: a number
:type part: list of int
:returns: the first index at which part repeats
:rtype: int
If part does not repeat, result is the length of part.
Complexi... | def function[_repeat_length, parameter[cls, part]]:
constant[
The length of the repeated portions of ``part``.
:param part: a number
:type part: list of int
:returns: the first index at which part repeats
:rtype: int
If part does not repeat, result is the length... | keyword[def] identifier[_repeat_length] ( identifier[cls] , identifier[part] ):
literal[string]
identifier[repeat_len] = identifier[len] ( identifier[part] )
keyword[if] identifier[repeat_len] == literal[int] :
keyword[return] identifier[repeat_len]
identifier[fir... | def _repeat_length(cls, part):
"""
The length of the repeated portions of ``part``.
:param part: a number
:type part: list of int
:returns: the first index at which part repeats
:rtype: int
If part does not repeat, result is the length of part.
Complexity: ... |
def parents(self, id, level=None, featuretype=None, order_by=None,
reverse=False, completely_within=False, limit=None):
"""
Return parents of feature `id`.
{_relation_docstring}
"""
return self._relation(
id, join_on='parent', join_to='child', level=le... | def function[parents, parameter[self, id, level, featuretype, order_by, reverse, completely_within, limit]]:
constant[
Return parents of feature `id`.
{_relation_docstring}
]
return[call[name[self]._relation, parameter[name[id]]]] | keyword[def] identifier[parents] ( identifier[self] , identifier[id] , identifier[level] = keyword[None] , identifier[featuretype] = keyword[None] , identifier[order_by] = keyword[None] ,
identifier[reverse] = keyword[False] , identifier[completely_within] = keyword[False] , identifier[limit] = keyword[None] ):
... | def parents(self, id, level=None, featuretype=None, order_by=None, reverse=False, completely_within=False, limit=None):
"""
Return parents of feature `id`.
{_relation_docstring}
"""
return self._relation(id, join_on='parent', join_to='child', level=level, featuretype=featuretype, order_b... |
def _get_plsr_dac_charge(self, plsr_dac_array, no_offset=False):
'''Takes the PlsrDAC calibration and the stored C-high/C-low mask to calculate the charge from the PlsrDAC array on a pixel basis
'''
charge = np.zeros_like(self.c_low_mask, dtype=np.float16) # charge in electrons
if self.... | def function[_get_plsr_dac_charge, parameter[self, plsr_dac_array, no_offset]]:
constant[Takes the PlsrDAC calibration and the stored C-high/C-low mask to calculate the charge from the PlsrDAC array on a pixel basis
]
variable[charge] assign[=] call[name[np].zeros_like, parameter[name[self].c_lo... | keyword[def] identifier[_get_plsr_dac_charge] ( identifier[self] , identifier[plsr_dac_array] , identifier[no_offset] = keyword[False] ):
literal[string]
identifier[charge] = identifier[np] . identifier[zeros_like] ( identifier[self] . identifier[c_low_mask] , identifier[dtype] = identifier[np] . i... | def _get_plsr_dac_charge(self, plsr_dac_array, no_offset=False):
"""Takes the PlsrDAC calibration and the stored C-high/C-low mask to calculate the charge from the PlsrDAC array on a pixel basis
"""
charge = np.zeros_like(self.c_low_mask, dtype=np.float16) # charge in electrons
if self.vcal_c0 is n... |
def inference(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the inference towers.
"""
handles = [h for h in self._handles if not h.is_training]
return TowerTensorHandles(handles) | def function[inference, parameter[self]]:
constant[
Returns:
A :class:`TowerTensorHandles`, containing only the inference towers.
]
variable[handles] assign[=] <ast.ListComp object at 0x7da2041d8f40>
return[call[name[TowerTensorHandles], parameter[name[handles]]]] | keyword[def] identifier[inference] ( identifier[self] ):
literal[string]
identifier[handles] =[ identifier[h] keyword[for] identifier[h] keyword[in] identifier[self] . identifier[_handles] keyword[if] keyword[not] identifier[h] . identifier[is_training] ]
keyword[return] identifier... | def inference(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the inference towers.
"""
handles = [h for h in self._handles if not h.is_training]
return TowerTensorHandles(handles) |
def _get_source_sum(source_hash, file_path, saltenv):
'''
Extract the hash sum, whether it is in a remote hash file, or just a string.
'''
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = ("Source hash '{0}' format is invalid. It must be in "
... | def function[_get_source_sum, parameter[source_hash, file_path, saltenv]]:
constant[
Extract the hash sum, whether it is in a remote hash file, or just a string.
]
variable[ret] assign[=] call[name[dict], parameter[]]
variable[schemes] assign[=] tuple[[<ast.Constant object at 0x7da2044c0... | keyword[def] identifier[_get_source_sum] ( identifier[source_hash] , identifier[file_path] , identifier[saltenv] ):
literal[string]
identifier[ret] = identifier[dict] ()
identifier[schemes] =( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , l... | def _get_source_sum(source_hash, file_path, saltenv):
"""
Extract the hash sum, whether it is in a remote hash file, or just a string.
"""
ret = dict()
schemes = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')
invalid_hash_msg = "Source hash '{0}' format is invalid. It must be in the for... |
def filePostProcess(self):
'''
The real name of this method should be ``reparentFiles``, but to avoid confusion
with what stage this must happen at it is called this instead. After the
:func:`~exhale.graph.ExhaleRoot.fileRefDiscovery` method has been called, each
file will have ... | def function[filePostProcess, parameter[self]]:
constant[
The real name of this method should be ``reparentFiles``, but to avoid confusion
with what stage this must happen at it is called this instead. After the
:func:`~exhale.graph.ExhaleRoot.fileRefDiscovery` method has been called, e... | keyword[def] identifier[filePostProcess] ( identifier[self] ):
literal[string]
identifier[nodes_remaining] =[ identifier[d] keyword[for] identifier[d] keyword[in] identifier[self] . identifier[dirs] ]
identifier[all_directories] =[]
keyword[while] i... | def filePostProcess(self):
"""
The real name of this method should be ``reparentFiles``, but to avoid confusion
with what stage this must happen at it is called this instead. After the
:func:`~exhale.graph.ExhaleRoot.fileRefDiscovery` method has been called, each
file will have its ... |
def argparser(self):
"""
Argparser option with search functionality specific for ranges.
"""
core_parser = self.core_parser
core_parser.add_argument('-r', '--range', type=str, help="The range to search for use")
return core_parser | def function[argparser, parameter[self]]:
constant[
Argparser option with search functionality specific for ranges.
]
variable[core_parser] assign[=] name[self].core_parser
call[name[core_parser].add_argument, parameter[constant[-r], constant[--range]]]
return[name[core_p... | keyword[def] identifier[argparser] ( identifier[self] ):
literal[string]
identifier[core_parser] = identifier[self] . identifier[core_parser]
identifier[core_parser] . identifier[add_argument] ( literal[string] , literal[string] , identifier[type] = identifier[str] , identifier[help] = li... | def argparser(self):
"""
Argparser option with search functionality specific for ranges.
"""
core_parser = self.core_parser
core_parser.add_argument('-r', '--range', type=str, help='The range to search for use')
return core_parser |
def createTemporaryCredentials(clientId, accessToken, start, expiry, scopes, name=None):
""" Create a set of temporary credentials
Callers should not apply any clock skew; clock drift is accounted for by
auth service.
clientId: the issuing clientId
accessToken: the issuer's accessToken
start: ... | def function[createTemporaryCredentials, parameter[clientId, accessToken, start, expiry, scopes, name]]:
constant[ Create a set of temporary credentials
Callers should not apply any clock skew; clock drift is accounted for by
auth service.
clientId: the issuing clientId
accessToken: the issuer... | keyword[def] identifier[createTemporaryCredentials] ( identifier[clientId] , identifier[accessToken] , identifier[start] , identifier[expiry] , identifier[scopes] , identifier[name] = keyword[None] ):
literal[string]
keyword[for] identifier[scope] keyword[in] identifier[scopes] :
keyword[if] ... | def createTemporaryCredentials(clientId, accessToken, start, expiry, scopes, name=None):
""" Create a set of temporary credentials
Callers should not apply any clock skew; clock drift is accounted for by
auth service.
clientId: the issuing clientId
accessToken: the issuer's accessToken
start: ... |
def clean(self, tol=None):
"""
Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large.
If ``tol=None`` only removes coincident points.
:param tol: defines how far should be the points from each other in terms of fraction
of the bounding box length.
... | def function[clean, parameter[self, tol]]:
constant[
Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large.
If ``tol=None`` only removes coincident points.
:param tol: defines how far should be the points from each other in terms of fraction
of the ... | keyword[def] identifier[clean] ( identifier[self] , identifier[tol] = keyword[None] ):
literal[string]
identifier[poly] = identifier[self] . identifier[polydata] ( keyword[False] )
identifier[cleanPolyData] = identifier[vtk] . identifier[vtkCleanPolyData] ()
identifier[cleanPolyDa... | def clean(self, tol=None):
"""
Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large.
If ``tol=None`` only removes coincident points.
:param tol: defines how far should be the points from each other in terms of fraction
of the bounding box length.
... |
def parse_scwrl_out(scwrl_std_out, scwrl_pdb):
"""Parses SCWRL output and returns PDB and SCWRL score.
Parameters
----------
scwrl_std_out : str
Std out from SCWRL.
scwrl_pdb : str
String of packed SCWRL PDB.
Returns
-------
fixed_scwrl_str : str
String of packe... | def function[parse_scwrl_out, parameter[scwrl_std_out, scwrl_pdb]]:
constant[Parses SCWRL output and returns PDB and SCWRL score.
Parameters
----------
scwrl_std_out : str
Std out from SCWRL.
scwrl_pdb : str
String of packed SCWRL PDB.
Returns
-------
fixed_scwrl_st... | keyword[def] identifier[parse_scwrl_out] ( identifier[scwrl_std_out] , identifier[scwrl_pdb] ):
literal[string]
identifier[score] = identifier[re] . identifier[findall] (
literal[string] , identifier[scwrl_std_out] )[ literal[int] ]
identifier[split_scwrl] = identifier[scwrl_pdb] . identifie... | def parse_scwrl_out(scwrl_std_out, scwrl_pdb):
"""Parses SCWRL output and returns PDB and SCWRL score.
Parameters
----------
scwrl_std_out : str
Std out from SCWRL.
scwrl_pdb : str
String of packed SCWRL PDB.
Returns
-------
fixed_scwrl_str : str
String of packe... |
def add_commands(parser, functions, namespace=None, namespace_kwargs=None,
func_kwargs=None,
# deprecated args:
title=None, description=None, help=None):
"""
Adds given functions as commands to given parser.
:param parser:
an :class:`argparse.Argu... | def function[add_commands, parameter[parser, functions, namespace, namespace_kwargs, func_kwargs, title, description, help]]:
constant[
Adds given functions as commands to given parser.
:param parser:
an :class:`argparse.ArgumentParser` instance.
:param functions:
a list of funct... | keyword[def] identifier[add_commands] ( identifier[parser] , identifier[functions] , identifier[namespace] = keyword[None] , identifier[namespace_kwargs] = keyword[None] ,
identifier[func_kwargs] = keyword[None] ,
identifier[title] = keyword[None] , identifier[description] = keyword[None] , identifier[help] = keyw... | def add_commands(parser, functions, namespace=None, namespace_kwargs=None, func_kwargs=None, title=None, description=None, help=None):
# deprecated args:
'\n Adds given functions as commands to given parser.\n\n :param parser:\n\n an :class:`argparse.ArgumentParser` instance.\n\n :param function... |
def add(self, text, name, field, type='term', size=None, params=None):
"""
Set the suggester of given type.
:param text: text
:param name: name of suggest
:param field: field to be used
:param type: type of suggester to add, available types are: completion,
... | def function[add, parameter[self, text, name, field, type, size, params]]:
constant[
Set the suggester of given type.
:param text: text
:param name: name of suggest
:param field: field to be used
:param type: type of suggester to add, available types are: completion,
... | keyword[def] identifier[add] ( identifier[self] , identifier[text] , identifier[name] , identifier[field] , identifier[type] = literal[string] , identifier[size] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
identifier[func] = keyword[None]
keyword[if] identifi... | def add(self, text, name, field, type='term', size=None, params=None):
"""
Set the suggester of given type.
:param text: text
:param name: name of suggest
:param field: field to be used
:param type: type of suggester to add, available types are: completion,
... |
def synctree(src, dst, onexist=None):
"""Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
... | def function[synctree, parameter[src, dst, onexist]]:
constant[Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an ... | keyword[def] identifier[synctree] ( identifier[src] , identifier[dst] , identifier[onexist] = keyword[None] ):
literal[string]
identifier[src] = identifier[pathlib] . identifier[Path] ( identifier[src] ). identifier[resolve] ()
identifier[dst] = identifier[pathlib] . identifier[Path] ( identifier[dst]... | def synctree(src, dst, onexist=None):
"""Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
... |
def export_flow_process_data(params, process):
"""
Creates a new SequenceFlow XML element for given edge parameters and adds it to 'process' element.
:param params: dictionary with edge parameters,
:param process: object of Element class, representing BPMN XML 'process' element (root fo... | def function[export_flow_process_data, parameter[params, process]]:
constant[
Creates a new SequenceFlow XML element for given edge parameters and adds it to 'process' element.
:param params: dictionary with edge parameters,
:param process: object of Element class, representing BPMN XML... | keyword[def] identifier[export_flow_process_data] ( identifier[params] , identifier[process] ):
literal[string]
identifier[output_flow] = identifier[eTree] . identifier[SubElement] ( identifier[process] , identifier[consts] . identifier[Consts] . identifier[sequence_flow] )
identifier[outp... | def export_flow_process_data(params, process):
"""
Creates a new SequenceFlow XML element for given edge parameters and adds it to 'process' element.
:param params: dictionary with edge parameters,
:param process: object of Element class, representing BPMN XML 'process' element (root for se... |
def depersist(self, key):
"""
Remove ``key`` from dictionary.
:param key: Key to remove from Zookeeper.
:type key: string
"""
self.connection.retry(self.connection.delete, self.__path_of(key))
self.__increment_last_updated() | def function[depersist, parameter[self, key]]:
constant[
Remove ``key`` from dictionary.
:param key: Key to remove from Zookeeper.
:type key: string
]
call[name[self].connection.retry, parameter[name[self].connection.delete, call[name[self].__path_of, parameter[name[key]... | keyword[def] identifier[depersist] ( identifier[self] , identifier[key] ):
literal[string]
identifier[self] . identifier[connection] . identifier[retry] ( identifier[self] . identifier[connection] . identifier[delete] , identifier[self] . identifier[__path_of] ( identifier[key] ))
identifi... | def depersist(self, key):
"""
Remove ``key`` from dictionary.
:param key: Key to remove from Zookeeper.
:type key: string
"""
self.connection.retry(self.connection.delete, self.__path_of(key))
self.__increment_last_updated() |
def values(cls, dataset, dim, expanded=True, flat=True, compute=True):
"""
The set of samples available along a particular dimension.
"""
dim_idx = dataset.get_dimension_index(dim)
if dim_idx in [0, 1]:
l, b, r, t = dataset.bounds.lbrt()
dim2, dim1 = datas... | def function[values, parameter[cls, dataset, dim, expanded, flat, compute]]:
constant[
The set of samples available along a particular dimension.
]
variable[dim_idx] assign[=] call[name[dataset].get_dimension_index, parameter[name[dim]]]
if compare[name[dim_idx] in list[[<ast.Con... | keyword[def] identifier[values] ( identifier[cls] , identifier[dataset] , identifier[dim] , identifier[expanded] = keyword[True] , identifier[flat] = keyword[True] , identifier[compute] = keyword[True] ):
literal[string]
identifier[dim_idx] = identifier[dataset] . identifier[get_dimension_index] ( ... | def values(cls, dataset, dim, expanded=True, flat=True, compute=True):
"""
The set of samples available along a particular dimension.
"""
dim_idx = dataset.get_dimension_index(dim)
if dim_idx in [0, 1]:
(l, b, r, t) = dataset.bounds.lbrt()
(dim2, dim1) = dataset.data.shape[:2... |
def _set_get_mac_address_table(self, v, load=False):
"""
Setter method for get_mac_address_table, mapped from YANG variable /brocade_mac_address_table_rpc/get_mac_address_table (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_mac_address_table is considered as a... | def function[_set_get_mac_address_table, parameter[self, v, load]]:
constant[
Setter method for get_mac_address_table, mapped from YANG variable /brocade_mac_address_table_rpc/get_mac_address_table (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_mac_address... | keyword[def] identifier[_set_get_mac_address_table] ( 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_get_mac_address_table(self, v, load=False):
"""
Setter method for get_mac_address_table, mapped from YANG variable /brocade_mac_address_table_rpc/get_mac_address_table (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_mac_address_table is considered as a... |
def _set_root(self, request):
"""Sets the root of the merkle tree, returning any head id used.
Note:
This method will fail if `_tree` has not been set
Args:
request (object): The parsed protobuf request object
Returns:
str: the state root of the hea... | def function[_set_root, parameter[self, request]]:
constant[Sets the root of the merkle tree, returning any head id used.
Note:
This method will fail if `_tree` has not been set
Args:
request (object): The parsed protobuf request object
Returns:
str... | keyword[def] identifier[_set_root] ( identifier[self] , identifier[request] ):
literal[string]
keyword[if] identifier[request] . identifier[state_root] :
identifier[root] = identifier[request] . identifier[state_root]
keyword[else] :
identifier[head] = identifie... | def _set_root(self, request):
"""Sets the root of the merkle tree, returning any head id used.
Note:
This method will fail if `_tree` has not been set
Args:
request (object): The parsed protobuf request object
Returns:
str: the state root of the head bl... |
def run_once(function, state={}, errors={}):
"""A memoization decorator, whose purpose is to cache calls."""
@six.wraps(function)
def _wrapper(*args, **kwargs):
if function in errors:
# Deliberate use of LBYL.
six.reraise(*errors[function])
try:
return st... | def function[run_once, parameter[function, state, errors]]:
constant[A memoization decorator, whose purpose is to cache calls.]
def function[_wrapper, parameter[]]:
if compare[name[function] in name[errors]] begin[:]
call[name[six].reraise, parameter[<ast.Starred ... | keyword[def] identifier[run_once] ( identifier[function] , identifier[state] ={}, identifier[errors] ={}):
literal[string]
@ identifier[six] . identifier[wraps] ( identifier[function] )
keyword[def] identifier[_wrapper] (* identifier[args] ,** identifier[kwargs] ):
keyword[if] identifier[fun... | def run_once(function, state={}, errors={}):
"""A memoization decorator, whose purpose is to cache calls."""
@six.wraps(function)
def _wrapper(*args, **kwargs):
if function in errors:
# Deliberate use of LBYL.
six.reraise(*errors[function]) # depends on [control=['if'], dat... |
def format_mentions(text, format_callback=format_mention):
"""Searches the given text for mentions generated by `expand_mention()` and returns a human-readable form.
For example:
"@<bob http://example.org/twtxt.txt>" will result in "@bob"
If you follow a source: source.nick will be bold
If you are... | def function[format_mentions, parameter[text, format_callback]]:
constant[Searches the given text for mentions generated by `expand_mention()` and returns a human-readable form.
For example:
"@<bob http://example.org/twtxt.txt>" will result in "@bob"
If you follow a source: source.nick will be bol... | keyword[def] identifier[format_mentions] ( identifier[text] , identifier[format_callback] = identifier[format_mention] ):
literal[string]
keyword[def] identifier[handle_mention] ( identifier[match] ):
identifier[name] , identifier[url] = identifier[match] . identifier[groups] ()
keyword... | def format_mentions(text, format_callback=format_mention):
"""Searches the given text for mentions generated by `expand_mention()` and returns a human-readable form.
For example:
"@<bob http://example.org/twtxt.txt>" will result in "@bob"
If you follow a source: source.nick will be bold
If you are... |
def eth_getTransactionByBlockHashAndIndex(self, bhash, index=0):
"""https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyblockhashandindex
:param bhash: Block hash
:type bhash: str
:param index: Index position (optional)
:type index: int
"""
result... | def function[eth_getTransactionByBlockHashAndIndex, parameter[self, bhash, index]]:
constant[https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyblockhashandindex
:param bhash: Block hash
:type bhash: str
:param index: Index position (optional)
:type index: int
... | keyword[def] identifier[eth_getTransactionByBlockHashAndIndex] ( identifier[self] , identifier[bhash] , identifier[index] = literal[int] ):
literal[string]
identifier[result] = keyword[yield] keyword[from] identifier[self] . identifier[rpc_call] ( literal[string] ,
[ identifier[bhash] , i... | def eth_getTransactionByBlockHashAndIndex(self, bhash, index=0):
"""https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyblockhashandindex
:param bhash: Block hash
:type bhash: str
:param index: Index position (optional)
:type index: int
"""
result = (yiel... |
def cancel_id(cls, id):
"""
Cancels command denoted by this id
Args:
`id`: command id
"""
conn = Qubole.agent()
data = {"status": "kill"}
return conn.put(cls.element_path(id), data) | def function[cancel_id, parameter[cls, id]]:
constant[
Cancels command denoted by this id
Args:
`id`: command id
]
variable[conn] assign[=] call[name[Qubole].agent, parameter[]]
variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da1b101a830>], [<... | keyword[def] identifier[cancel_id] ( identifier[cls] , identifier[id] ):
literal[string]
identifier[conn] = identifier[Qubole] . identifier[agent] ()
identifier[data] ={ literal[string] : literal[string] }
keyword[return] identifier[conn] . identifier[put] ( identifier[cls] . ide... | def cancel_id(cls, id):
"""
Cancels command denoted by this id
Args:
`id`: command id
"""
conn = Qubole.agent()
data = {'status': 'kill'}
return conn.put(cls.element_path(id), data) |
def has(self, key: str) -> bool:
"""
Returns True is set() has been called for a key. The cached value may be of type 'None'.
:param key:
:return:
"""
if key in self._services:
return True
return False | def function[has, parameter[self, key]]:
constant[
Returns True is set() has been called for a key. The cached value may be of type 'None'.
:param key:
:return:
]
if compare[name[key] in name[self]._services] begin[:]
return[constant[True]]
return[constant[Fal... | keyword[def] identifier[has] ( identifier[self] , identifier[key] : identifier[str] )-> identifier[bool] :
literal[string]
keyword[if] identifier[key] keyword[in] identifier[self] . identifier[_services] :
keyword[return] keyword[True]
keyword[return] keyword[False] | def has(self, key: str) -> bool:
"""
Returns True is set() has been called for a key. The cached value may be of type 'None'.
:param key:
:return:
"""
if key in self._services:
return True # depends on [control=['if'], data=[]]
return False |
def get_visible_scopes(self):
"""Get list of non-internal scopes for token.
:returns: A list of scopes.
"""
return [k for k, s in current_oauth2server.scope_choices()
if k in self.scopes] | def function[get_visible_scopes, parameter[self]]:
constant[Get list of non-internal scopes for token.
:returns: A list of scopes.
]
return[<ast.ListComp object at 0x7da1b2524040>] | keyword[def] identifier[get_visible_scopes] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[k] keyword[for] identifier[k] , identifier[s] keyword[in] identifier[current_oauth2server] . identifier[scope_choices] ()
keyword[if] identifier[k] keyword[in] identifier[s... | def get_visible_scopes(self):
"""Get list of non-internal scopes for token.
:returns: A list of scopes.
"""
return [k for (k, s) in current_oauth2server.scope_choices() if k in self.scopes] |
def toggle_codecompletion(self, checked):
"""Toggle automatic code completion"""
self.shell.set_codecompletion_auto(checked)
self.set_option('codecompletion/auto', checked) | def function[toggle_codecompletion, parameter[self, checked]]:
constant[Toggle automatic code completion]
call[name[self].shell.set_codecompletion_auto, parameter[name[checked]]]
call[name[self].set_option, parameter[constant[codecompletion/auto], name[checked]]] | keyword[def] identifier[toggle_codecompletion] ( identifier[self] , identifier[checked] ):
literal[string]
identifier[self] . identifier[shell] . identifier[set_codecompletion_auto] ( identifier[checked] )
identifier[self] . identifier[set_option] ( literal[string] , identifier[checked]... | def toggle_codecompletion(self, checked):
"""Toggle automatic code completion"""
self.shell.set_codecompletion_auto(checked)
self.set_option('codecompletion/auto', checked) |
def distance(self, channel=1):
"""
Returns distance (0, 100) to the beacon on the given channel.
Returns None when beacon is not found.
"""
self._ensure_mode(self.MODE_IR_SEEK)
channel = self._normalize_channel(channel)
ret_value = self.value((channel * 2) + 1)
... | def function[distance, parameter[self, channel]]:
constant[
Returns distance (0, 100) to the beacon on the given channel.
Returns None when beacon is not found.
]
call[name[self]._ensure_mode, parameter[name[self].MODE_IR_SEEK]]
variable[channel] assign[=] call[name[self]... | keyword[def] identifier[distance] ( identifier[self] , identifier[channel] = literal[int] ):
literal[string]
identifier[self] . identifier[_ensure_mode] ( identifier[self] . identifier[MODE_IR_SEEK] )
identifier[channel] = identifier[self] . identifier[_normalize_channel] ( identifier[chan... | def distance(self, channel=1):
"""
Returns distance (0, 100) to the beacon on the given channel.
Returns None when beacon is not found.
"""
self._ensure_mode(self.MODE_IR_SEEK)
channel = self._normalize_channel(channel)
ret_value = self.value(channel * 2 + 1)
# The value will... |
def on_connected(self, headers, body):
"""
Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real
heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats
are not 0, we start up the heartbeat l... | def function[on_connected, parameter[self, headers, body]]:
constant[
Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real
heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats
are not 0, ... | keyword[def] identifier[on_connected] ( identifier[self] , identifier[headers] , identifier[body] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[headers] :
identifier[self] . identifier[heartbeats] = identifier[utils] . identifier[calculate_heartbeats] (
... | def on_connected(self, headers, body):
"""
Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real
heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats
are not 0, we start up the heartbeat loop ... |
def select(self, *cluster_ids):
"""Select a list of clusters."""
# HACK: allow for `select(1, 2, 3)` in addition to `select([1, 2, 3])`
# This makes it more convenient to select multiple clusters with
# the snippet: `:c 1 2 3` instead of `:c 1,2,3`.
if cluster_ids and isinstance(... | def function[select, parameter[self]]:
constant[Select a list of clusters.]
if <ast.BoolOp object at 0x7da1b12f2c20> begin[:]
variable[cluster_ids] assign[=] binary_operation[call[name[list], parameter[call[name[cluster_ids]][constant[0]]]] + call[name[list], parameter[call[name[cluster_... | keyword[def] identifier[select] ( identifier[self] ,* identifier[cluster_ids] ):
literal[string]
keyword[if] identifier[cluster_ids] keyword[and] identifier[isinstance] ( identifier[cluster_ids] [ literal[int] ],( identifier[tuple] , identifier[list] )):
i... | def select(self, *cluster_ids):
"""Select a list of clusters."""
# HACK: allow for `select(1, 2, 3)` in addition to `select([1, 2, 3])`
# This makes it more convenient to select multiple clusters with
# the snippet: `:c 1 2 3` instead of `:c 1,2,3`.
if cluster_ids and isinstance(cluster_ids[0], (tup... |
def parse_message(message, validation_level=None, find_groups=True, message_profile=None, report_file=None,
force_validation=False):
"""
Parse the given ER7-encoded message and return an instance of :class:`Message <hl7apy.core.Message>`.
:type message: ``str``
:param message: the ER7... | def function[parse_message, parameter[message, validation_level, find_groups, message_profile, report_file, force_validation]]:
constant[
Parse the given ER7-encoded message and return an instance of :class:`Message <hl7apy.core.Message>`.
:type message: ``str``
:param message: the ER7-encoded mess... | keyword[def] identifier[parse_message] ( identifier[message] , identifier[validation_level] = keyword[None] , identifier[find_groups] = keyword[True] , identifier[message_profile] = keyword[None] , identifier[report_file] = keyword[None] ,
identifier[force_validation] = keyword[False] ):
literal[string]
i... | def parse_message(message, validation_level=None, find_groups=True, message_profile=None, report_file=None, force_validation=False):
"""
Parse the given ER7-encoded message and return an instance of :class:`Message <hl7apy.core.Message>`.
:type message: ``str``
:param message: the ER7-encoded message t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.