code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def run(self):
"""Start the exchange"""
self.started_queue.put('STARTED')
while True:
event = self.publisher_queue.get()
if event == POISON_PILL:
return
else:
self.dispatch(event) | def function[run, parameter[self]]:
constant[Start the exchange]
call[name[self].started_queue.put, parameter[constant[STARTED]]]
while constant[True] begin[:]
variable[event] assign[=] call[name[self].publisher_queue.get, parameter[]]
if compare[name[event] equal... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[self] . identifier[started_queue] . identifier[put] ( literal[string] )
keyword[while] keyword[True] :
identifier[event] = identifier[self] . identifier[publisher_queue] . identifier[get] ()
... | def run(self):
"""Start the exchange"""
self.started_queue.put('STARTED')
while True:
event = self.publisher_queue.get()
if event == POISON_PILL:
return # depends on [control=['if'], data=[]]
else:
self.dispatch(event) # depends on [control=['while'], data=[... |
def get_msg_login(self, username):
"""message for welcome.
"""
account = self.get_account(username)
if account:
account.update_last_login()
account.save()
return 'welcome.' | def function[get_msg_login, parameter[self, username]]:
constant[message for welcome.
]
variable[account] assign[=] call[name[self].get_account, parameter[name[username]]]
if name[account] begin[:]
call[name[account].update_last_login, parameter[]]
call[na... | keyword[def] identifier[get_msg_login] ( identifier[self] , identifier[username] ):
literal[string]
identifier[account] = identifier[self] . identifier[get_account] ( identifier[username] )
keyword[if] identifier[account] :
identifier[account] . identifier[update_last_login] ... | def get_msg_login(self, username):
"""message for welcome.
"""
account = self.get_account(username)
if account:
account.update_last_login()
account.save() # depends on [control=['if'], data=[]]
return 'welcome.' |
def remove_start_NaN(self, data, var=None):
""" Remove start NaN.
CHECK: Note issue with multi-column df.
Parameters
----------
data : pd.DataFrame()
Input dataframe.
var : list(str)
List that specifies specific columns of ... | def function[remove_start_NaN, parameter[self, data, var]]:
constant[ Remove start NaN.
CHECK: Note issue with multi-column df.
Parameters
----------
data : pd.DataFrame()
Input dataframe.
var : list(str)
List that specifie... | keyword[def] identifier[remove_start_NaN] ( identifier[self] , identifier[data] , identifier[var] = keyword[None] ):
literal[string]
keyword[if] identifier[var] :
identifier[start_ok_data] = identifier[data] [ identifier[var] ]. identifier[first_valid_index] ()
keyw... | def remove_start_NaN(self, data, var=None):
""" Remove start NaN.
CHECK: Note issue with multi-column df.
Parameters
----------
data : pd.DataFrame()
Input dataframe.
var : list(str)
List that specifies specific columns of data... |
def _readable_part_size(num_bytes):
"Returns the file size in readable form."
B = num_bytes
KB = float(1024)
MB = float(KB * 1024)
GB = float(MB * 1024)
TB = float(GB * 1024)
if B < KB:
return '{0} {1}'.format(B, 'bytes' if B != 1 else 'byte')
elif KB <= B < MB:
return '... | def function[_readable_part_size, parameter[num_bytes]]:
constant[Returns the file size in readable form.]
variable[B] assign[=] name[num_bytes]
variable[KB] assign[=] call[name[float], parameter[constant[1024]]]
variable[MB] assign[=] call[name[float], parameter[binary_operation[name[KB... | keyword[def] identifier[_readable_part_size] ( identifier[num_bytes] ):
literal[string]
identifier[B] = identifier[num_bytes]
identifier[KB] = identifier[float] ( literal[int] )
identifier[MB] = identifier[float] ( identifier[KB] * literal[int] )
identifier[GB] = identifier[float] ( identif... | def _readable_part_size(num_bytes):
"""Returns the file size in readable form."""
B = num_bytes
KB = float(1024)
MB = float(KB * 1024)
GB = float(MB * 1024)
TB = float(GB * 1024)
if B < KB:
return '{0} {1}'.format(B, 'bytes' if B != 1 else 'byte') # depends on [control=['if'], data=... |
def run_subprocess(command: str, verbose: bool = True, blocking: bool = True) \
-> Optional[subprocess.Popen]:
"""Execute the given command in a new process.
Only when both `verbose` and `blocking` are |True|, |run_subprocess|
prints all responses to the current value of |sys.stdout|:
>>> from... | def function[run_subprocess, parameter[command, verbose, blocking]]:
constant[Execute the given command in a new process.
Only when both `verbose` and `blocking` are |True|, |run_subprocess|
prints all responses to the current value of |sys.stdout|:
>>> from hydpy import run_subprocess
>>> imp... | keyword[def] identifier[run_subprocess] ( identifier[command] : identifier[str] , identifier[verbose] : identifier[bool] = keyword[True] , identifier[blocking] : identifier[bool] = keyword[True] )-> identifier[Optional] [ identifier[subprocess] . identifier[Popen] ]:
literal[string]
keyword[if] identifier... | def run_subprocess(command: str, verbose: bool=True, blocking: bool=True) -> Optional[subprocess.Popen]:
"""Execute the given command in a new process.
Only when both `verbose` and `blocking` are |True|, |run_subprocess|
prints all responses to the current value of |sys.stdout|:
>>> from hydpy import ... |
def _load_items_from_file(keychain, path):
"""
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
"""
certificates = []
identities = []
result_array = Non... | def function[_load_items_from_file, parameter[keychain, path]]:
constant[
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
]
variable[certificates] assi... | keyword[def] identifier[_load_items_from_file] ( identifier[keychain] , identifier[path] ):
literal[string]
identifier[certificates] =[]
identifier[identities] =[]
identifier[result_array] = keyword[None]
keyword[with] identifier[open] ( identifier[path] , literal[string] ) keyword[as] i... | def _load_items_from_file(keychain, path):
"""
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
"""
certificates = []
identities = []
result_array = Non... |
def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path,
verbose):
"""
Runs the program. Takes a list of postcodes or coordinates and
returns various information about them. If using the cli, make
sure to update the bikes database with t... | def function[run, parameter[locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path, verbose]]:
constant[
Runs the program. Takes a list of postcodes or coordinates and
returns various information about them. If using the cli, make
sure to update th... | keyword[def] identifier[run] ( identifier[locations] , identifier[random] , identifier[bikes] , identifier[crime] , identifier[nearby] , identifier[json] , identifier[update_bikes] , identifier[api_server] , identifier[cross_origin] , identifier[host] , identifier[port] , identifier[db_path] ,
identifier[verbose] ):... | def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path, verbose):
"""
Runs the program. Takes a list of postcodes or coordinates and
returns various information about them. If using the cli, make
sure to update the bikes database with the -u co... |
def parse_end_date(self, request, start_date):
"""
Return period in days after the start date to show event occurrences,
which is one of the following in order of priority:
- `end_date` GET parameter value, if given and valid. The filtering
will be *inclusive* of the end date... | def function[parse_end_date, parameter[self, request, start_date]]:
constant[
Return period in days after the start date to show event occurrences,
which is one of the following in order of priority:
- `end_date` GET parameter value, if given and valid. The filtering
will be ... | keyword[def] identifier[parse_end_date] ( identifier[self] , identifier[request] , identifier[start_date] ):
literal[string]
keyword[if] identifier[request] . identifier[GET] . identifier[get] ( literal[string] ):
keyword[try] :
keyword[return] identifier[djtz] . ide... | def parse_end_date(self, request, start_date):
"""
Return period in days after the start date to show event occurrences,
which is one of the following in order of priority:
- `end_date` GET parameter value, if given and valid. The filtering
will be *inclusive* of the end date: un... |
def _get_current_minute(self):
"""
Internal utility method to get the current simulation time.
Possible answers are:
- whatever the algorithm's get_datetime() method returns (this is what
`self.simulation_dt_func()` points to)
- sometimes we're knowingly not in a mar... | def function[_get_current_minute, parameter[self]]:
constant[
Internal utility method to get the current simulation time.
Possible answers are:
- whatever the algorithm's get_datetime() method returns (this is what
`self.simulation_dt_func()` points to)
- sometimes w... | keyword[def] identifier[_get_current_minute] ( identifier[self] ):
literal[string]
identifier[dt] = identifier[self] . identifier[datetime]
keyword[if] identifier[self] . identifier[_adjust_minutes] :
identifier[dt] = identifier[self] . identifier[data_portal] . identifier... | def _get_current_minute(self):
"""
Internal utility method to get the current simulation time.
Possible answers are:
- whatever the algorithm's get_datetime() method returns (this is what
`self.simulation_dt_func()` points to)
- sometimes we're knowingly not in a market ... |
def doc_metadata(doc):
"""Create a metadata dict from a MetatabDoc, for Document conversion"""
r = doc['Root'].as_dict()
r.update(doc['Contacts'].as_dict())
r['author'] = r.get('author', r.get('creator', r.get('wrangler')))
return r | def function[doc_metadata, parameter[doc]]:
constant[Create a metadata dict from a MetatabDoc, for Document conversion]
variable[r] assign[=] call[call[name[doc]][constant[Root]].as_dict, parameter[]]
call[name[r].update, parameter[call[call[name[doc]][constant[Contacts]].as_dict, parameter[]]]]... | keyword[def] identifier[doc_metadata] ( identifier[doc] ):
literal[string]
identifier[r] = identifier[doc] [ literal[string] ]. identifier[as_dict] ()
identifier[r] . identifier[update] ( identifier[doc] [ literal[string] ]. identifier[as_dict] ())
identifier[r] [ literal[string] ]= identifier[r... | def doc_metadata(doc):
"""Create a metadata dict from a MetatabDoc, for Document conversion"""
r = doc['Root'].as_dict()
r.update(doc['Contacts'].as_dict())
r['author'] = r.get('author', r.get('creator', r.get('wrangler')))
return r |
def get_input_grads(self, merge_multi_context=True):
"""Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
will be collected fro... | def function[get_input_grads, parameter[self, merge_multi_context]]:
constant[Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
... | keyword[def] identifier[get_input_grads] ( identifier[self] , identifier[merge_multi_context] = keyword[True] ):
literal[string]
keyword[assert] identifier[self] . identifier[inputs_need_grad]
keyword[if] identifier[merge_multi_context] :
keyword[return] identifier[_merge_... | def get_input_grads(self, merge_multi_context=True):
"""Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
will be collected from mu... |
def fit_predict(training_data, fitting_data, tau=1, samples_per_job=0, save_results=True, show=False):
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
from disco.core import Disco
"""
training_data - training samples
fitting_data - dataset to b... | def function[fit_predict, parameter[training_data, fitting_data, tau, samples_per_job, save_results, show]]:
from relative_module[disco.worker.pipeline.worker] import module[Worker], module[Stage]
from relative_module[disco.core] import module[Job], module[result_iterator]
from relative_module[disco.core] i... | keyword[def] identifier[fit_predict] ( identifier[training_data] , identifier[fitting_data] , identifier[tau] = literal[int] , identifier[samples_per_job] = literal[int] , identifier[save_results] = keyword[True] , identifier[show] = keyword[False] ):
keyword[from] identifier[disco] . identifier[worker] . ident... | def fit_predict(training_data, fitting_data, tau=1, samples_per_job=0, save_results=True, show=False):
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
from disco.core import Disco
'\n training_data - training samples\n fitting_data - dataset to be... |
def unpack_rows(self, parameters_metadata, connection):
"""Unpack output or input/output parameters from the stored procedure call result
:parameters_metadata: a stored procedure parameters metadata
:returns: parameter values
"""
values = []
for param in parameters_metada... | def function[unpack_rows, parameter[self, parameters_metadata, connection]]:
constant[Unpack output or input/output parameters from the stored procedure call result
:parameters_metadata: a stored procedure parameters metadata
:returns: parameter values
]
variable[values] assign[=... | keyword[def] identifier[unpack_rows] ( identifier[self] , identifier[parameters_metadata] , identifier[connection] ):
literal[string]
identifier[values] =[]
keyword[for] identifier[param] keyword[in] identifier[parameters_metadata] :
keyword[if] identifier[param] ... | def unpack_rows(self, parameters_metadata, connection):
"""Unpack output or input/output parameters from the stored procedure call result
:parameters_metadata: a stored procedure parameters metadata
:returns: parameter values
"""
values = []
for param in parameters_metadata:
... |
def create(self, product_type, attribute_set_id, sku, data):
"""
Create Product and return ID
:param product_type: String type of product
:param attribute_set_id: ID of attribute set
:param sku: SKU of the product
:param data: Dictionary of data
:return: INT id o... | def function[create, parameter[self, product_type, attribute_set_id, sku, data]]:
constant[
Create Product and return ID
:param product_type: String type of product
:param attribute_set_id: ID of attribute set
:param sku: SKU of the product
:param data: Dictionary of dat... | keyword[def] identifier[create] ( identifier[self] , identifier[product_type] , identifier[attribute_set_id] , identifier[sku] , identifier[data] ):
literal[string]
keyword[return] identifier[int] ( identifier[self] . identifier[call] (
literal[string] ,
[ identifier[product_type]... | def create(self, product_type, attribute_set_id, sku, data):
"""
Create Product and return ID
:param product_type: String type of product
:param attribute_set_id: ID of attribute set
:param sku: SKU of the product
:param data: Dictionary of data
:return: INT id of pr... |
def clear_queue(self, trans_id=None):
''' Clear the queue of database operations without executing any of
the pending operations'''
if not self.queue:
return
if trans_id is None:
self.queue = []
return
for index, op in enumerate(self.queue):
if op.trans_id == trans_id:
break
self.queue = ... | def function[clear_queue, parameter[self, trans_id]]:
constant[ Clear the queue of database operations without executing any of
the pending operations]
if <ast.UnaryOp object at 0x7da207f9ac80> begin[:]
return[None]
if compare[name[trans_id] is constant[None]] begin[:]
... | keyword[def] identifier[clear_queue] ( identifier[self] , identifier[trans_id] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[queue] :
keyword[return]
keyword[if] identifier[trans_id] keyword[is] keyword[None] :
identifier[self] . identifier[queue] =[... | def clear_queue(self, trans_id=None):
""" Clear the queue of database operations without executing any of
the pending operations"""
if not self.queue:
return # depends on [control=['if'], data=[]]
if trans_id is None:
self.queue = []
return # depends on [control=['if'], data=[]... |
def cdx_limit(cdx_iter, limit):
"""
limit cdx to at most `limit`.
"""
# for cdx, _ in itertools.izip(cdx_iter, xrange(limit)):
# yield cdx
return (cdx for cdx, _ in zip(cdx_iter, range(limit))) | def function[cdx_limit, parameter[cdx_iter, limit]]:
constant[
limit cdx to at most `limit`.
]
return[<ast.GeneratorExp object at 0x7da20c9931f0>] | keyword[def] identifier[cdx_limit] ( identifier[cdx_iter] , identifier[limit] ):
literal[string]
keyword[return] ( identifier[cdx] keyword[for] identifier[cdx] , identifier[_] keyword[in] identifier[zip] ( identifier[cdx_iter] , identifier[range] ( identifier[limit] ))) | def cdx_limit(cdx_iter, limit):
"""
limit cdx to at most `limit`.
"""
# for cdx, _ in itertools.izip(cdx_iter, xrange(limit)):
# yield cdx
return (cdx for (cdx, _) in zip(cdx_iter, range(limit))) |
def get_user_config_dir(app_name, app_author, roaming=True, force_xdg=True):
"""Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
For an example application called ``"My App"`` by ``"Acme"``,
something like the follo... | def function[get_user_config_dir, parameter[app_name, app_author, roaming, force_xdg]]:
constant[Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
For an example application called ``"My App"`` by ``"Acme"``,
som... | keyword[def] identifier[get_user_config_dir] ( identifier[app_name] , identifier[app_author] , identifier[roaming] = keyword[True] , identifier[force_xdg] = keyword[True] ):
literal[string]
keyword[if] identifier[WIN] :
identifier[key] = literal[string] keyword[if] identifier[roaming] keyword[... | def get_user_config_dir(app_name, app_author, roaming=True, force_xdg=True):
"""Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
For an example application called ``"My App"`` by ``"Acme"``,
something like the follo... |
def __create_profile_from_identities(self, identities, uuid, verbose):
"""Create a profile using the data from the identities"""
import re
EMAIL_ADDRESS_REGEX = r"^(?P<email>[^\s@]+@[^\s@.]+\.[^\s@]+)$"
NAME_REGEX = r"^\w+\s\w+"
name = None
email = None
usernam... | def function[__create_profile_from_identities, parameter[self, identities, uuid, verbose]]:
constant[Create a profile using the data from the identities]
import module[re]
variable[EMAIL_ADDRESS_REGEX] assign[=] constant[^(?P<email>[^\s@]+@[^\s@.]+\.[^\s@]+)$]
variable[NAME_REGEX] assign[=] ... | keyword[def] identifier[__create_profile_from_identities] ( identifier[self] , identifier[identities] , identifier[uuid] , identifier[verbose] ):
literal[string]
keyword[import] identifier[re]
identifier[EMAIL_ADDRESS_REGEX] = literal[string]
identifier[NAME_REGEX] = literal[... | def __create_profile_from_identities(self, identities, uuid, verbose):
"""Create a profile using the data from the identities"""
import re
EMAIL_ADDRESS_REGEX = '^(?P<email>[^\\s@]+@[^\\s@.]+\\.[^\\s@]+)$'
NAME_REGEX = '^\\w+\\s\\w+'
name = None
email = None
username = None
for identity ... |
def is_clockwise(vertices):
""" Evaluate whether vertices are in clockwise order.
Args:
vertices: list of vertices (x, y) in polygon.
Returns:
True: clockwise, False: counter-clockwise
Raises:
ValueError: the polygon is complex or overlapped.
"""
it = iterator.consecutive(cycle... | def function[is_clockwise, parameter[vertices]]:
constant[ Evaluate whether vertices are in clockwise order.
Args:
vertices: list of vertices (x, y) in polygon.
Returns:
True: clockwise, False: counter-clockwise
Raises:
ValueError: the polygon is complex or overlapped.
]
... | keyword[def] identifier[is_clockwise] ( identifier[vertices] ):
literal[string]
identifier[it] = identifier[iterator] . identifier[consecutive] ( identifier[cycle] ( identifier[vertices] ), literal[int] )
identifier[clockwise] = literal[int]
identifier[counter] = literal[int]
keyword[for] ... | def is_clockwise(vertices):
""" Evaluate whether vertices are in clockwise order.
Args:
vertices: list of vertices (x, y) in polygon.
Returns:
True: clockwise, False: counter-clockwise
Raises:
ValueError: the polygon is complex or overlapped.
"""
it = iterator.consecutive(cycle... |
def candidate_subclass(
class_name, args, table_name=None, cardinality=None, values=None
):
"""
Creates and returns a Candidate subclass with provided argument names,
which are Context type. Creates the table in DB if does not exist yet.
Import using:
.. code-block:: python
from fondu... | def function[candidate_subclass, parameter[class_name, args, table_name, cardinality, values]]:
constant[
Creates and returns a Candidate subclass with provided argument names,
which are Context type. Creates the table in DB if does not exist yet.
Import using:
.. code-block:: python
... | keyword[def] identifier[candidate_subclass] (
identifier[class_name] , identifier[args] , identifier[table_name] = keyword[None] , identifier[cardinality] = keyword[None] , identifier[values] = keyword[None]
):
literal[string]
keyword[if] identifier[table_name] keyword[is] keyword[None] :
ide... | def candidate_subclass(class_name, args, table_name=None, cardinality=None, values=None):
"""
Creates and returns a Candidate subclass with provided argument names,
which are Context type. Creates the table in DB if does not exist yet.
Import using:
.. code-block:: python
from fonduer.can... |
def __get_query_agg_ts(cls, field, time_field, interval=None,
time_zone=None, start=None, end=None,
agg_type='count', offset=None):
"""
Create an es_dsl aggregation object for getting the time series values for a field.
:param field: field t... | def function[__get_query_agg_ts, parameter[cls, field, time_field, interval, time_zone, start, end, agg_type, offset]]:
constant[
Create an es_dsl aggregation object for getting the time series values for a field.
:param field: field to get the time series values
:param time_field: fiel... | keyword[def] identifier[__get_query_agg_ts] ( identifier[cls] , identifier[field] , identifier[time_field] , identifier[interval] = keyword[None] ,
identifier[time_zone] = keyword[None] , identifier[start] = keyword[None] , identifier[end] = keyword[None] ,
identifier[agg_type] = literal[string] , identifier[offset... | def __get_query_agg_ts(cls, field, time_field, interval=None, time_zone=None, start=None, end=None, agg_type='count', offset=None):
"""
Create an es_dsl aggregation object for getting the time series values for a field.
:param field: field to get the time series values
:param time_field: fi... |
def show_vcs_output_vcs_nodes_vcs_node_info_node_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_nodes = ET.SubElement(output, "... | def function[show_vcs_output_vcs_nodes_vcs_node_info_node_rbridge_id, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[show_vcs] assign[=] call[name[ET].Element, parameter[constant[show_vcs]]]
... | keyword[def] identifier[show_vcs_output_vcs_nodes_vcs_node_info_node_rbridge_id] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[show_vcs] = identifier[ET] . identifier[Element] ( literal[... | def show_vcs_output_vcs_nodes_vcs_node_info_node_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
show_vcs = ET.Element('show_vcs')
config = show_vcs
output = ET.SubElement(show_vcs, 'output')
vcs_nodes = ET.SubElement(output, 'vcs-nodes')
vcs_node... |
def _get_unpatched(cls):
"""Protect against re-patching the distutils if reloaded
Also ensures that no other distutils extension monkeypatched the distutils
first.
"""
while cls.__module__.startswith('setuptools'):
cls, = cls.__bases__
if not cls.__module__.startswith('distutils'):
... | def function[_get_unpatched, parameter[cls]]:
constant[Protect against re-patching the distutils if reloaded
Also ensures that no other distutils extension monkeypatched the distutils
first.
]
while call[name[cls].__module__.startswith, parameter[constant[setuptools]]] begin[:]
... | keyword[def] identifier[_get_unpatched] ( identifier[cls] ):
literal[string]
keyword[while] identifier[cls] . identifier[__module__] . identifier[startswith] ( literal[string] ):
identifier[cls] ,= identifier[cls] . identifier[__bases__]
keyword[if] keyword[not] identifier[cls] . identifi... | def _get_unpatched(cls):
"""Protect against re-patching the distutils if reloaded
Also ensures that no other distutils extension monkeypatched the distutils
first.
"""
while cls.__module__.startswith('setuptools'):
(cls,) = cls.__bases__ # depends on [control=['while'], data=[]]
if not... |
def get_category_aliases_under(parent_alias=None):
"""Returns a list of category aliases under the given parent.
Could be useful to pass to `ModelWithCategory.enable_category_lists_editor`
in `additional_parents_aliases` parameter.
:param str|None parent_alias: Parent alias or None to categories under... | def function[get_category_aliases_under, parameter[parent_alias]]:
constant[Returns a list of category aliases under the given parent.
Could be useful to pass to `ModelWithCategory.enable_category_lists_editor`
in `additional_parents_aliases` parameter.
:param str|None parent_alias: Parent alias o... | keyword[def] identifier[get_category_aliases_under] ( identifier[parent_alias] = keyword[None] ):
literal[string]
keyword[return] [ identifier[ch] . identifier[alias] keyword[for] identifier[ch] keyword[in] identifier[get_cache] (). identifier[get_children_for] ( identifier[parent_alias] , identifier[o... | def get_category_aliases_under(parent_alias=None):
"""Returns a list of category aliases under the given parent.
Could be useful to pass to `ModelWithCategory.enable_category_lists_editor`
in `additional_parents_aliases` parameter.
:param str|None parent_alias: Parent alias or None to categories under... |
def quit(self):
""" Quits the application (called when the last window is closed)
"""
logger.debug("ArgosApplication.quit called")
assert len(self.mainWindows) == 0, \
"Bug: still {} windows present at application quit!".format(len(self.mainWindows))
self.qApplication... | def function[quit, parameter[self]]:
constant[ Quits the application (called when the last window is closed)
]
call[name[logger].debug, parameter[constant[ArgosApplication.quit called]]]
assert[compare[call[name[len], parameter[name[self].mainWindows]] equal[==] constant[0]]]
call[na... | keyword[def] identifier[quit] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
keyword[assert] identifier[len] ( identifier[self] . identifier[mainWindows] )== literal[int] , literal[string] . identifier[format] ( identifier[len] ( identifie... | def quit(self):
""" Quits the application (called when the last window is closed)
"""
logger.debug('ArgosApplication.quit called')
assert len(self.mainWindows) == 0, 'Bug: still {} windows present at application quit!'.format(len(self.mainWindows))
self.qApplication.quit() |
def remove_account(self, id):
"""Add Account from config (does not save)"""
if self.parser.has_section(id):
self.parser.remove_section(id)
return True
return False | def function[remove_account, parameter[self, id]]:
constant[Add Account from config (does not save)]
if call[name[self].parser.has_section, parameter[name[id]]] begin[:]
call[name[self].parser.remove_section, parameter[name[id]]]
return[constant[True]]
return[constant[False]] | keyword[def] identifier[remove_account] ( identifier[self] , identifier[id] ):
literal[string]
keyword[if] identifier[self] . identifier[parser] . identifier[has_section] ( identifier[id] ):
identifier[self] . identifier[parser] . identifier[remove_section] ( identifier[id] )
... | def remove_account(self, id):
"""Add Account from config (does not save)"""
if self.parser.has_section(id):
self.parser.remove_section(id)
return True # depends on [control=['if'], data=[]]
return False |
def _extract_when(body):
"""Extract the generated datetime from the notification."""
# NOTE: I am keeping the logic the same as it was in openstack
# code, However, *ALL* notifications should have a 'timestamp'
# field, it's part of the notification envelope spec. If this was
# ... | def function[_extract_when, parameter[body]]:
constant[Extract the generated datetime from the notification.]
variable[when] assign[=] call[name[body].get, parameter[constant[timestamp], call[name[body].get, parameter[constant[_context_timestamp]]]]]
if name[when] begin[:]
return[call[na... | keyword[def] identifier[_extract_when] ( identifier[body] ):
literal[string]
identifier[when] = identifier[body] . identifier[get] ( literal[string] , identifier[body] . identifier[get] ( literal[string] ))
keyword[if] identifier[when... | def _extract_when(body):
"""Extract the generated datetime from the notification."""
# NOTE: I am keeping the logic the same as it was in openstack
# code, However, *ALL* notifications should have a 'timestamp'
# field, it's part of the notification envelope spec. If this was
# put here because some... |
def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer):
"""Return a dict that can be JSONify using json.dump.
Advanced usage might optionaly use a callback as parameter:
.. code::python
def my_key_transformer(key, attr_desc, value):
return key... | def function[as_dict, parameter[self, keep_readonly, key_transformer]]:
constant[Return a dict that can be JSONify using json.dump.
Advanced usage might optionaly use a callback as parameter:
.. code::python
def my_key_transformer(key, attr_desc, value):
return key... | keyword[def] identifier[as_dict] ( identifier[self] , identifier[keep_readonly] = keyword[True] , identifier[key_transformer] = identifier[attribute_transformer] ):
literal[string]
identifier[serializer] = identifier[Serializer] ( identifier[self] . identifier[_infer_class_models] ())
keyw... | def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer):
"""Return a dict that can be JSONify using json.dump.
Advanced usage might optionaly use a callback as parameter:
.. code::python
def my_key_transformer(key, attr_desc, value):
return key
... |
def match_published_date(self, start, end, match):
"""Match assets that are published between the specified time period.
arg: start (osid.calendaring.DateTime): start time of the
query
arg: end (osid.calendaring.DateTime): end time of the query
arg: match (boole... | def function[match_published_date, parameter[self, start, end, match]]:
constant[Match assets that are published between the specified time period.
arg: start (osid.calendaring.DateTime): start time of the
query
arg: end (osid.calendaring.DateTime): end time of the query
... | keyword[def] identifier[match_published_date] ( identifier[self] , identifier[start] , identifier[end] , identifier[match] ):
literal[string]
identifier[self] . identifier[_match_minimum_date_time] ( literal[string] , identifier[start] , identifier[match] )
identifier[self] . identifier[_m... | def match_published_date(self, start, end, match):
"""Match assets that are published between the specified time period.
arg: start (osid.calendaring.DateTime): start time of the
query
arg: end (osid.calendaring.DateTime): end time of the query
arg: match (boolean):... |
def Entry(self, name, directory=None, create=1):
""" Create `SCons.Node.FS.Entry` """
return self._create_node(name, self.env.fs.Entry, directory, create) | def function[Entry, parameter[self, name, directory, create]]:
constant[ Create `SCons.Node.FS.Entry` ]
return[call[name[self]._create_node, parameter[name[name], name[self].env.fs.Entry, name[directory], name[create]]]] | keyword[def] identifier[Entry] ( identifier[self] , identifier[name] , identifier[directory] = keyword[None] , identifier[create] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[_create_node] ( identifier[name] , identifier[self] . identifier[env] . identifier[fs] .... | def Entry(self, name, directory=None, create=1):
""" Create `SCons.Node.FS.Entry` """
return self._create_node(name, self.env.fs.Entry, directory, create) |
def device_query_create(self, device, **kwargs): # noqa: E501
"""Create a device query # noqa: E501
Create a new device query. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread ... | def function[device_query_create, parameter[self, device]]:
constant[Create a device query # noqa: E501
Create a new device query. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thre... | keyword[def] identifier[device_query_create] ( identifier[self] , identifier[device] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identif... | def device_query_create(self, device, **kwargs): # noqa: E501
'Create a device query # noqa: E501\n\n Create a new device query. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass asynchronous=True\n >>> thread =... |
def CheckSupportedFormat(cls, path, check_readable_only=False):
"""Checks if the storage file format is supported.
Args:
path (str): path to the storage file.
check_readable_only (Optional[bool]): whether the store should only be
checked to see if it can be read. If False, the store will ... | def function[CheckSupportedFormat, parameter[cls, path, check_readable_only]]:
constant[Checks if the storage file format is supported.
Args:
path (str): path to the storage file.
check_readable_only (Optional[bool]): whether the store should only be
checked to see if it can be read. ... | keyword[def] identifier[CheckSupportedFormat] ( identifier[cls] , identifier[path] , identifier[check_readable_only] = keyword[False] ):
literal[string]
keyword[try] :
identifier[connection] = identifier[sqlite3] . identifier[connect] (
identifier[path] , identifier[detect_types] = identifier... | def CheckSupportedFormat(cls, path, check_readable_only=False):
"""Checks if the storage file format is supported.
Args:
path (str): path to the storage file.
check_readable_only (Optional[bool]): whether the store should only be
checked to see if it can be read. If False, the store will ... |
def detect_scheme(filename):
"""Detects partitioning scheme of the source
Args:
filename (str): path to file or device for detection of \
partitioning scheme.
Returns:
SCHEME_MBR, SCHEME_GPT or SCHEME_UNKNOWN
Raises:
IOError: The file doesn't exist or cannot be opened ... | def function[detect_scheme, parameter[filename]]:
constant[Detects partitioning scheme of the source
Args:
filename (str): path to file or device for detection of partitioning scheme.
Returns:
SCHEME_MBR, SCHEME_GPT or SCHEME_UNKNOWN
Raises:
IOError: The file doesn... | keyword[def] identifier[detect_scheme] ( identifier[filename] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( identifier[__name__] )
identifier[logger] . identifier[info] ( literal[string] )
keyword[with] identifier[open] ( identifier[filename] , literal[s... | def detect_scheme(filename):
"""Detects partitioning scheme of the source
Args:
filename (str): path to file or device for detection of partitioning scheme.
Returns:
SCHEME_MBR, SCHEME_GPT or SCHEME_UNKNOWN
Raises:
IOError: The file doesn't exist or cannot be opened fo... |
def _to_utc(self, dt):
"""Takes a naive timezone with an localized value and return it formatted
as utc."""
tz = self._get_tz()
loc_dt = tz.localize(dt)
return loc_dt.astimezone(pytz.utc) | def function[_to_utc, parameter[self, dt]]:
constant[Takes a naive timezone with an localized value and return it formatted
as utc.]
variable[tz] assign[=] call[name[self]._get_tz, parameter[]]
variable[loc_dt] assign[=] call[name[tz].localize, parameter[name[dt]]]
return[call[name[l... | keyword[def] identifier[_to_utc] ( identifier[self] , identifier[dt] ):
literal[string]
identifier[tz] = identifier[self] . identifier[_get_tz] ()
identifier[loc_dt] = identifier[tz] . identifier[localize] ( identifier[dt] )
keyword[return] identifier[loc_dt] . identifier[astimez... | def _to_utc(self, dt):
"""Takes a naive timezone with an localized value and return it formatted
as utc."""
tz = self._get_tz()
loc_dt = tz.localize(dt)
return loc_dt.astimezone(pytz.utc) |
def _parse_signal_lines(signal_lines):
"""
Extract fields from a list of signal line strings into a dictionary.
"""
n_sig = len(signal_lines)
# Dictionary for signal fields
signal_fields = {}
# Each dictionary field is a list
for field in SIGNAL_SPECS.index:
signal_fields[field... | def function[_parse_signal_lines, parameter[signal_lines]]:
constant[
Extract fields from a list of signal line strings into a dictionary.
]
variable[n_sig] assign[=] call[name[len], parameter[name[signal_lines]]]
variable[signal_fields] assign[=] dictionary[[], []]
for taget[na... | keyword[def] identifier[_parse_signal_lines] ( identifier[signal_lines] ):
literal[string]
identifier[n_sig] = identifier[len] ( identifier[signal_lines] )
identifier[signal_fields] ={}
keyword[for] identifier[field] keyword[in] identifier[SIGNAL_SPECS] . identifier[index] :
... | def _parse_signal_lines(signal_lines):
"""
Extract fields from a list of signal line strings into a dictionary.
"""
n_sig = len(signal_lines)
# Dictionary for signal fields
signal_fields = {}
# Each dictionary field is a list
for field in SIGNAL_SPECS.index:
signal_fields[field]... |
def write_catalog(filename, catalog, fmt=None, meta=None, prefix=None):
"""
Write a catalog (list of sources) to a file with format determined by extension.
Sources must be of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSo... | def function[write_catalog, parameter[filename, catalog, fmt, meta, prefix]]:
constant[
Write a catalog (list of sources) to a file with format determined by extension.
Sources must be of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools... | keyword[def] identifier[write_catalog] ( identifier[filename] , identifier[catalog] , identifier[fmt] = keyword[None] , identifier[meta] = keyword[None] , identifier[prefix] = keyword[None] ):
literal[string]
keyword[if] identifier[meta] keyword[is] keyword[None] :
identifier[meta] ={}
ke... | def write_catalog(filename, catalog, fmt=None, meta=None, prefix=None):
"""
Write a catalog (list of sources) to a file with format determined by extension.
Sources must be of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSo... |
def load_xml(self, xmlfile, **kwargs):
"""Load sources from an XML file."""
extdir = kwargs.get('extdir', self.extdir)
coordsys = kwargs.get('coordsys', 'CEL')
if not os.path.isfile(xmlfile):
xmlfile = os.path.join(fermipy.PACKAGE_DATA, 'catalogs', xmlfile)
root = E... | def function[load_xml, parameter[self, xmlfile]]:
constant[Load sources from an XML file.]
variable[extdir] assign[=] call[name[kwargs].get, parameter[constant[extdir], name[self].extdir]]
variable[coordsys] assign[=] call[name[kwargs].get, parameter[constant[coordsys], constant[CEL]]]
i... | keyword[def] identifier[load_xml] ( identifier[self] , identifier[xmlfile] ,** identifier[kwargs] ):
literal[string]
identifier[extdir] = identifier[kwargs] . identifier[get] ( literal[string] , identifier[self] . identifier[extdir] )
identifier[coordsys] = identifier[kwargs] . identifier... | def load_xml(self, xmlfile, **kwargs):
"""Load sources from an XML file."""
extdir = kwargs.get('extdir', self.extdir)
coordsys = kwargs.get('coordsys', 'CEL')
if not os.path.isfile(xmlfile):
xmlfile = os.path.join(fermipy.PACKAGE_DATA, 'catalogs', xmlfile) # depends on [control=['if'], data=[]... |
def dual_obj_grad(alpha, beta, a, b, C, regul):
"""
Compute objective value and gradients of dual objective.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Current iterate of dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
... | def function[dual_obj_grad, parameter[alpha, beta, a, b, C, regul]]:
constant[
Compute objective value and gradients of dual objective.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Current iterate of dual potentials.
a: array, shape = len(a)
... | keyword[def] identifier[dual_obj_grad] ( identifier[alpha] , identifier[beta] , identifier[a] , identifier[b] , identifier[C] , identifier[regul] ):
literal[string]
identifier[obj] = identifier[np] . identifier[dot] ( identifier[alpha] , identifier[a] )+ identifier[np] . identifier[dot] ( identifier[beta] ... | def dual_obj_grad(alpha, beta, a, b, C, regul):
"""
Compute objective value and gradients of dual objective.
Parameters
----------
alpha: array, shape = len(a)
beta: array, shape = len(b)
Current iterate of dual potentials.
a: array, shape = len(a)
b: array, shape = len(b)
... |
def service_restart(name):
'''
Restart a "service" on the ssh server
.. versionadded:: 2015.8.2
'''
cmd = 'restart ' + name
# Send the command to execute
out, err = DETAILS['server'].sendline(cmd)
# "scrape" the output and return the right fields as a dict
return parse(out) | def function[service_restart, parameter[name]]:
constant[
Restart a "service" on the ssh server
.. versionadded:: 2015.8.2
]
variable[cmd] assign[=] binary_operation[constant[restart ] + name[name]]
<ast.Tuple object at 0x7da20c6c74c0> assign[=] call[call[name[DETAILS]][constant[ser... | keyword[def] identifier[service_restart] ( identifier[name] ):
literal[string]
identifier[cmd] = literal[string] + identifier[name]
identifier[out] , identifier[err] = identifier[DETAILS] [ literal[string] ]. identifier[sendline] ( identifier[cmd] )
keyword[return] identifier[parse]... | def service_restart(name):
"""
Restart a "service" on the ssh server
.. versionadded:: 2015.8.2
"""
cmd = 'restart ' + name
# Send the command to execute
(out, err) = DETAILS['server'].sendline(cmd)
# "scrape" the output and return the right fields as a dict
return parse(out) |
def get_time_remaining_estimate(self):
"""
In Mac OS X 10.7+
Uses IOPSGetTimeRemainingEstimate to get time remaining estimate.
In Mac OS X 10.6
IOPSGetTimeRemainingEstimate is not available.
If providing power source type is AC, returns TIME_REMAINING_UNLIMITED.
... | def function[get_time_remaining_estimate, parameter[self]]:
constant[
In Mac OS X 10.7+
Uses IOPSGetTimeRemainingEstimate to get time remaining estimate.
In Mac OS X 10.6
IOPSGetTimeRemainingEstimate is not available.
If providing power source type is AC, returns TIME_RE... | keyword[def] identifier[get_time_remaining_estimate] ( identifier[self] ):
literal[string]
keyword[if] identifier[IOPSGetTimeRemainingEstimate] keyword[is] keyword[not] keyword[None] :
identifier[estimate] = identifier[float] ( identifier[IOPSGetTimeRemainingEstimate] ())
... | def get_time_remaining_estimate(self):
"""
In Mac OS X 10.7+
Uses IOPSGetTimeRemainingEstimate to get time remaining estimate.
In Mac OS X 10.6
IOPSGetTimeRemainingEstimate is not available.
If providing power source type is AC, returns TIME_REMAINING_UNLIMITED.
Othe... |
def tweak_message(message):
"""We piggyback on jinja2's babel_extract() (really, Babel's extract_*
functions) but they don't support some things we need so this function will
tweak the message. Specifically:
1) We strip whitespace from the msgid. Jinja2 will only strip
whitespace from... | def function[tweak_message, parameter[message]]:
constant[We piggyback on jinja2's babel_extract() (really, Babel's extract_*
functions) but they don't support some things we need so this function will
tweak the message. Specifically:
1) We strip whitespace from the msgid. Jinja2 will only st... | keyword[def] identifier[tweak_message] ( identifier[message] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[message] , identifier[basestring] ):
identifier[message] = identifier[strip_whitespace] ( identifier[message] )
keyword[elif] identifier[isinstance] ( identifier[m... | def tweak_message(message):
"""We piggyback on jinja2's babel_extract() (really, Babel's extract_*
functions) but they don't support some things we need so this function will
tweak the message. Specifically:
1) We strip whitespace from the msgid. Jinja2 will only strip
whitespace from... |
def download_data(job, master_ip, inputs, known_snps, bam, hdfs_snps, hdfs_bam):
"""
Downloads input data files from S3.
:type masterIP: MasterAddress
"""
log.info("Downloading known sites file %s to %s.", known_snps, hdfs_snps)
call_conductor(job, master_ip, known_snps, hdfs_snps, memory=inpu... | def function[download_data, parameter[job, master_ip, inputs, known_snps, bam, hdfs_snps, hdfs_bam]]:
constant[
Downloads input data files from S3.
:type masterIP: MasterAddress
]
call[name[log].info, parameter[constant[Downloading known sites file %s to %s.], name[known_snps], name[hdfs_sn... | keyword[def] identifier[download_data] ( identifier[job] , identifier[master_ip] , identifier[inputs] , identifier[known_snps] , identifier[bam] , identifier[hdfs_snps] , identifier[hdfs_bam] ):
literal[string]
identifier[log] . identifier[info] ( literal[string] , identifier[known_snps] , identifier[hdfs... | def download_data(job, master_ip, inputs, known_snps, bam, hdfs_snps, hdfs_bam):
"""
Downloads input data files from S3.
:type masterIP: MasterAddress
"""
log.info('Downloading known sites file %s to %s.', known_snps, hdfs_snps)
call_conductor(job, master_ip, known_snps, hdfs_snps, memory=input... |
def perform_oauth(email, master_token, android_id, service, app, client_sig,
device_country='us', operatorCountry='us', lang='en',
sdk_version=17):
"""
Use a master token from master_login to perform OAuth to a specific Google
service.
Return a dict, eg::
{
... | def function[perform_oauth, parameter[email, master_token, android_id, service, app, client_sig, device_country, operatorCountry, lang, sdk_version]]:
constant[
Use a master token from master_login to perform OAuth to a specific Google
service.
Return a dict, eg::
{
'Auth': '..... | keyword[def] identifier[perform_oauth] ( identifier[email] , identifier[master_token] , identifier[android_id] , identifier[service] , identifier[app] , identifier[client_sig] ,
identifier[device_country] = literal[string] , identifier[operatorCountry] = literal[string] , identifier[lang] = literal[string] ,
identi... | def perform_oauth(email, master_token, android_id, service, app, client_sig, device_country='us', operatorCountry='us', lang='en', sdk_version=17):
"""
Use a master token from master_login to perform OAuth to a specific Google
service.
Return a dict, eg::
{
'Auth': '...',
... |
def validate_offset(reference_event, estimated_event, t_collar=0.200, percentage_of_length=0.5):
"""Validate estimated event based on event offset
Parameters
----------
reference_event : dict
Reference event.
estimated_event : dict
Estimated event.
... | def function[validate_offset, parameter[reference_event, estimated_event, t_collar, percentage_of_length]]:
constant[Validate estimated event based on event offset
Parameters
----------
reference_event : dict
Reference event.
estimated_event : dict
Estim... | keyword[def] identifier[validate_offset] ( identifier[reference_event] , identifier[estimated_event] , identifier[t_collar] = literal[int] , identifier[percentage_of_length] = literal[int] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[reference_event] keyword[a... | def validate_offset(reference_event, estimated_event, t_collar=0.2, percentage_of_length=0.5):
"""Validate estimated event based on event offset
Parameters
----------
reference_event : dict
Reference event.
estimated_event : dict
Estimated event.
t_... |
def start_api_and_rpc_workers(self):
"""Initializes eventlet and starts wait for workers to exit.
Spawns the workers returned from serve_rpc
"""
pool = eventlet.GreenPool()
quark_rpc = self.serve_rpc()
pool.spawn(quark_rpc.wait)
pool.waitall() | def function[start_api_and_rpc_workers, parameter[self]]:
constant[Initializes eventlet and starts wait for workers to exit.
Spawns the workers returned from serve_rpc
]
variable[pool] assign[=] call[name[eventlet].GreenPool, parameter[]]
variable[quark_rpc] assign[=] call[name[... | keyword[def] identifier[start_api_and_rpc_workers] ( identifier[self] ):
literal[string]
identifier[pool] = identifier[eventlet] . identifier[GreenPool] ()
identifier[quark_rpc] = identifier[self] . identifier[serve_rpc] ()
identifier[pool] . identifier[spawn] ( identifier[quark_... | def start_api_and_rpc_workers(self):
"""Initializes eventlet and starts wait for workers to exit.
Spawns the workers returned from serve_rpc
"""
pool = eventlet.GreenPool()
quark_rpc = self.serve_rpc()
pool.spawn(quark_rpc.wait)
pool.waitall() |
def list(self, search_opts=None):
"""Get a list of Plugins."""
query = base.get_query_string(search_opts)
return self._list('/plugins%s' % query, 'plugins') | def function[list, parameter[self, search_opts]]:
constant[Get a list of Plugins.]
variable[query] assign[=] call[name[base].get_query_string, parameter[name[search_opts]]]
return[call[name[self]._list, parameter[binary_operation[constant[/plugins%s] <ast.Mod object at 0x7da2590d6920> name[query]], ... | keyword[def] identifier[list] ( identifier[self] , identifier[search_opts] = keyword[None] ):
literal[string]
identifier[query] = identifier[base] . identifier[get_query_string] ( identifier[search_opts] )
keyword[return] identifier[self] . identifier[_list] ( literal[string] % identifier... | def list(self, search_opts=None):
"""Get a list of Plugins."""
query = base.get_query_string(search_opts)
return self._list('/plugins%s' % query, 'plugins') |
def _format(self, method="sparql", dt_format="turtle"):
"""
Rormats the value in various formats
args:
method: ['sparql', 'json', 'pyuri']
dt_format: ['turtle','uri'] used in conjuction with the 'sparql'
method
"""
try:
... | def function[_format, parameter[self, method, dt_format]]:
constant[
Rormats the value in various formats
args:
method: ['sparql', 'json', 'pyuri']
dt_format: ['turtle','uri'] used in conjuction with the 'sparql'
method
]
<ast.Try obje... | keyword[def] identifier[_format] ( identifier[self] , identifier[method] = literal[string] , identifier[dt_format] = literal[string] ):
literal[string]
keyword[try] :
keyword[return] identifier[__FORMAT_OPTIONS__] [ identifier[method] ]( identifier[self] , identifier[dt_format] = ide... | def _format(self, method='sparql', dt_format='turtle'):
"""
Rormats the value in various formats
args:
method: ['sparql', 'json', 'pyuri']
dt_format: ['turtle','uri'] used in conjuction with the 'sparql'
method
"""
try:
return __FO... |
def get_chassis_datacenter(host=None,
admin_username=None,
admin_password=None):
'''
Get the datacenter of the chassis.
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
The passw... | def function[get_chassis_datacenter, parameter[host, admin_username, admin_password]]:
constant[
Get the datacenter of the chassis.
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
The password used to access the chassis.
... | keyword[def] identifier[get_chassis_datacenter] ( identifier[host] = keyword[None] ,
identifier[admin_username] = keyword[None] ,
identifier[admin_password] = keyword[None] ):
literal[string]
keyword[return] identifier[get_general] ( literal[string] , literal[string] , identifier[host] = identifier[host... | def get_chassis_datacenter(host=None, admin_username=None, admin_password=None):
"""
Get the datacenter of the chassis.
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
The password used to access the chassis.
CLI Example:
... |
def extend(self, items):
""" extend items and print them to stdout
using the new line separator
"""
print('\n'.join(items))
super(MyList, self).extend(items) | def function[extend, parameter[self, items]]:
constant[ extend items and print them to stdout
using the new line separator
]
call[name[print], parameter[call[constant[
].join, parameter[name[items]]]]]
call[call[name[super], parameter[name[MyList], name[self]]].extend, parameter[... | keyword[def] identifier[extend] ( identifier[self] , identifier[items] ):
literal[string]
identifier[print] ( literal[string] . identifier[join] ( identifier[items] ))
identifier[super] ( identifier[MyList] , identifier[self] ). identifier[extend] ( identifier[items] ) | def extend(self, items):
""" extend items and print them to stdout
using the new line separator
"""
print('\n'.join(items))
super(MyList, self).extend(items) |
def print_event(attributes=[]):
"""
Function that returns a Python callback to pretty print the events.
"""
def python_callback(event):
cls_name = event.__class__.__name__
attrs = ', '.join(['{attr}={val}'.format(attr=attr, val=event.__dict__[attr])
for attr in att... | def function[print_event, parameter[attributes]]:
constant[
Function that returns a Python callback to pretty print the events.
]
def function[python_callback, parameter[event]]:
variable[cls_name] assign[=] name[event].__class__.__name__
variable[attrs] assign[=]... | keyword[def] identifier[print_event] ( identifier[attributes] =[]):
literal[string]
keyword[def] identifier[python_callback] ( identifier[event] ):
identifier[cls_name] = identifier[event] . identifier[__class__] . identifier[__name__]
identifier[attrs] = literal[string] . identifier[jo... | def print_event(attributes=[]):
"""
Function that returns a Python callback to pretty print the events.
"""
def python_callback(event):
cls_name = event.__class__.__name__
attrs = ', '.join(['{attr}={val}'.format(attr=attr, val=event.__dict__[attr]) for attr in attributes])
prin... |
def search(self, source, destination = None, display = None,
component = None, q = None,
algo = 'DFS', reverse = False, **kargs):
'''
API: search(self, source, destination = None, display = None,
component = None, q = Stack(),
algo = 'DFS', rev... | def function[search, parameter[self, source, destination, display, component, q, algo, reverse]]:
constant[
API: search(self, source, destination = None, display = None,
component = None, q = Stack(),
algo = 'DFS', reverse = False, **kargs)
Description:
Gene... | keyword[def] identifier[search] ( identifier[self] , identifier[source] , identifier[destination] = keyword[None] , identifier[display] = keyword[None] ,
identifier[component] = keyword[None] , identifier[q] = keyword[None] ,
identifier[algo] = literal[string] , identifier[reverse] = keyword[False] ,** identifier[k... | def search(self, source, destination=None, display=None, component=None, q=None, algo='DFS', reverse=False, **kargs):
"""
API: search(self, source, destination = None, display = None,
component = None, q = Stack(),
algo = 'DFS', reverse = False, **kargs)
Description:
... |
def to_url(self):
""" special function for handling 'multi',
refer to Swagger 2.0, Parameter Object, collectionFormat
"""
if self.__collection_format == 'multi':
return [str(s) for s in self]
else:
return [str(self)] | def function[to_url, parameter[self]]:
constant[ special function for handling 'multi',
refer to Swagger 2.0, Parameter Object, collectionFormat
]
if compare[name[self].__collection_format equal[==] constant[multi]] begin[:]
return[<ast.ListComp object at 0x7da2044c1000>] | keyword[def] identifier[to_url] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__collection_format] == literal[string] :
keyword[return] [ identifier[str] ( identifier[s] ) keyword[for] identifier[s] keyword[in] identifier[self] ]
keyword[e... | def to_url(self):
""" special function for handling 'multi',
refer to Swagger 2.0, Parameter Object, collectionFormat
"""
if self.__collection_format == 'multi':
return [str(s) for s in self] # depends on [control=['if'], data=[]]
else:
return [str(self)] |
def update(self, friendly_name=values.unset, unique_name=values.unset,
email=values.unset, cc_emails=values.unset, status=values.unset,
verification_code=values.unset, verification_type=values.unset,
verification_document_sid=values.unset, extension=values.unset,
... | def function[update, parameter[self, friendly_name, unique_name, email, cc_emails, status, verification_code, verification_type, verification_document_sid, extension, call_delay]]:
constant[
Update the HostedNumberOrderInstance
:param unicode friendly_name: A human readable description of this ... | keyword[def] identifier[update] ( identifier[self] , identifier[friendly_name] = identifier[values] . identifier[unset] , identifier[unique_name] = identifier[values] . identifier[unset] ,
identifier[email] = identifier[values] . identifier[unset] , identifier[cc_emails] = identifier[values] . identifier[unset] , id... | def update(self, friendly_name=values.unset, unique_name=values.unset, email=values.unset, cc_emails=values.unset, status=values.unset, verification_code=values.unset, verification_type=values.unset, verification_document_sid=values.unset, extension=values.unset, call_delay=values.unset):
"""
Update the Hos... |
def scan_temperature(self, measure, temperature, rate, delay=1):
"""Performs a temperature scan.
Measures until the target temperature is reached.
:param measure: A callable called repeatedly until stability at target
temperature is reached.
:param temperature: The target t... | def function[scan_temperature, parameter[self, measure, temperature, rate, delay]]:
constant[Performs a temperature scan.
Measures until the target temperature is reached.
:param measure: A callable called repeatedly until stability at target
temperature is reached.
:param ... | keyword[def] identifier[scan_temperature] ( identifier[self] , identifier[measure] , identifier[temperature] , identifier[rate] , identifier[delay] = literal[int] ):
literal[string]
identifier[self] . identifier[target_temperature] = identifier[Tset] = identifier[self] . identifier[control... | def scan_temperature(self, measure, temperature, rate, delay=1):
"""Performs a temperature scan.
Measures until the target temperature is reached.
:param measure: A callable called repeatedly until stability at target
temperature is reached.
:param temperature: The target tempe... |
def compound(clr, flip=False):
"""
Roughly the complement and some far analogs.
"""
def _wrap(x, min, threshold, plus):
if x - min < threshold:
return x + plus
else:
return x - min
d = 1
if flip: d = -1
clr = color(clr)
colors = colorlist(clr)
... | def function[compound, parameter[clr, flip]]:
constant[
Roughly the complement and some far analogs.
]
def function[_wrap, parameter[x, min, threshold, plus]]:
if compare[binary_operation[name[x] - name[min]] less[<] name[threshold]] begin[:]
return[binary_operation[n... | keyword[def] identifier[compound] ( identifier[clr] , identifier[flip] = keyword[False] ):
literal[string]
keyword[def] identifier[_wrap] ( identifier[x] , identifier[min] , identifier[threshold] , identifier[plus] ):
keyword[if] identifier[x] - identifier[min] < identifier[threshold] :
... | def compound(clr, flip=False):
"""
Roughly the complement and some far analogs.
"""
def _wrap(x, min, threshold, plus):
if x - min < threshold:
return x + plus # depends on [control=['if'], data=[]]
else:
return x - min
d = 1
if flip:
d = -1 # d... |
def get_config(self, section=None):
""" Return the merged end-user configuration for this command or a
specific section if set in `section`. """
config = self.session.config
section = self.config_section() if section is None else section
try:
return config[section]
... | def function[get_config, parameter[self, section]]:
constant[ Return the merged end-user configuration for this command or a
specific section if set in `section`. ]
variable[config] assign[=] name[self].session.config
variable[section] assign[=] <ast.IfExp object at 0x7da18eb56f80>
<... | keyword[def] identifier[get_config] ( identifier[self] , identifier[section] = keyword[None] ):
literal[string]
identifier[config] = identifier[self] . identifier[session] . identifier[config]
identifier[section] = identifier[self] . identifier[config_section] () keyword[if] identifier[s... | def get_config(self, section=None):
""" Return the merged end-user configuration for this command or a
specific section if set in `section`. """
config = self.session.config
section = self.config_section() if section is None else section
try:
return config[section] # depends on [control... |
def vehicle_type_string(self, hb):
'''return vehicle type string from a heartbeat'''
if hb.type == mavutil.mavlink.MAV_TYPE_FIXED_WING:
return 'Plane'
if hb.type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER:
return 'Rover'
if hb.type == mavutil.mavlink.MAV_TYPE_SURFAC... | def function[vehicle_type_string, parameter[self, hb]]:
constant[return vehicle type string from a heartbeat]
if compare[name[hb].type equal[==] name[mavutil].mavlink.MAV_TYPE_FIXED_WING] begin[:]
return[constant[Plane]]
if compare[name[hb].type equal[==] name[mavutil].mavlink.MAV_TYPE_G... | keyword[def] identifier[vehicle_type_string] ( identifier[self] , identifier[hb] ):
literal[string]
keyword[if] identifier[hb] . identifier[type] == identifier[mavutil] . identifier[mavlink] . identifier[MAV_TYPE_FIXED_WING] :
keyword[return] literal[string]
keyword[if] id... | def vehicle_type_string(self, hb):
"""return vehicle type string from a heartbeat"""
if hb.type == mavutil.mavlink.MAV_TYPE_FIXED_WING:
return 'Plane' # depends on [control=['if'], data=[]]
if hb.type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER:
return 'Rover' # depends on [control=['if'], da... |
def headers_present(self, headers):
"""
Defines a list of headers that must be present in the
outgoing request in order to satisfy the matcher, no matter what value
the headers hosts.
Header keys are case insensitive.
Arguments:
headers (list|tuple): header ... | def function[headers_present, parameter[self, headers]]:
constant[
Defines a list of headers that must be present in the
outgoing request in order to satisfy the matcher, no matter what value
the headers hosts.
Header keys are case insensitive.
Arguments:
he... | keyword[def] identifier[headers_present] ( identifier[self] , identifier[headers] ):
literal[string]
identifier[headers] ={ identifier[name] : identifier[re] . identifier[compile] ( literal[string] ) keyword[for] identifier[name] keyword[in] identifier[headers] }
identifier[self] . iden... | def headers_present(self, headers):
"""
Defines a list of headers that must be present in the
outgoing request in order to satisfy the matcher, no matter what value
the headers hosts.
Header keys are case insensitive.
Arguments:
headers (list|tuple): header keys... |
def scan_band(self, band, **kwargs):
"""Run Kalibrate for a band.
Supported keyword arguments:
gain -- Gain in dB
device -- Index of device to be used
error -- Initial frequency error in ppm
"""
kal_run_line = fn.build_kal_scan_band_string(self.kal_bin,
... | def function[scan_band, parameter[self, band]]:
constant[Run Kalibrate for a band.
Supported keyword arguments:
gain -- Gain in dB
device -- Index of device to be used
error -- Initial frequency error in ppm
]
variable[kal_run_line] assign[=] call[name[fn]... | keyword[def] identifier[scan_band] ( identifier[self] , identifier[band] ,** identifier[kwargs] ):
literal[string]
identifier[kal_run_line] = identifier[fn] . identifier[build_kal_scan_band_string] ( identifier[self] . identifier[kal_bin] ,
identifier[band] , identifier[kwargs] )
... | def scan_band(self, band, **kwargs):
"""Run Kalibrate for a band.
Supported keyword arguments:
gain -- Gain in dB
device -- Index of device to be used
error -- Initial frequency error in ppm
"""
kal_run_line = fn.build_kal_scan_band_string(self.kal_bin, band, kwar... |
def shared_prefix(args):
"""
Find the shared prefix between the strings.
For instance:
sharedPrefix(['blahblah', 'blahwhat'])
returns 'blah'.
"""
i = 0
while i < min(map(len, args)):
if len(set(map(operator.itemgetter(i), args))) != 1:
break
i += 1
... | def function[shared_prefix, parameter[args]]:
constant[
Find the shared prefix between the strings.
For instance:
sharedPrefix(['blahblah', 'blahwhat'])
returns 'blah'.
]
variable[i] assign[=] constant[0]
while compare[name[i] less[<] call[name[min], parameter[call[nam... | keyword[def] identifier[shared_prefix] ( identifier[args] ):
literal[string]
identifier[i] = literal[int]
keyword[while] identifier[i] < identifier[min] ( identifier[map] ( identifier[len] , identifier[args] )):
keyword[if] identifier[len] ( identifier[set] ( identifier[map] ( identifier[o... | def shared_prefix(args):
"""
Find the shared prefix between the strings.
For instance:
sharedPrefix(['blahblah', 'blahwhat'])
returns 'blah'.
"""
i = 0
while i < min(map(len, args)):
if len(set(map(operator.itemgetter(i), args))) != 1:
break # depends on [cont... |
def write(self, more):
"""Append the Unicode representation of `s` to our output."""
if more:
self.output += str(more).upper()
self.output += '\n' | def function[write, parameter[self, more]]:
constant[Append the Unicode representation of `s` to our output.]
if name[more] begin[:]
<ast.AugAssign object at 0x7da1b1a943d0>
<ast.AugAssign object at 0x7da1b1a94910> | keyword[def] identifier[write] ( identifier[self] , identifier[more] ):
literal[string]
keyword[if] identifier[more] :
identifier[self] . identifier[output] += identifier[str] ( identifier[more] ). identifier[upper] ()
identifier[self] . identifier[output] += literal[stri... | def write(self, more):
"""Append the Unicode representation of `s` to our output."""
if more:
self.output += str(more).upper()
self.output += '\n' # depends on [control=['if'], data=[]] |
def layout_circle(self):
'''Position vertices evenly around a circle.'''
n = self.num_vertices()
t = np.linspace(0, 2*np.pi, n+1)[:n]
return np.column_stack((np.cos(t), np.sin(t))) | def function[layout_circle, parameter[self]]:
constant[Position vertices evenly around a circle.]
variable[n] assign[=] call[name[self].num_vertices, parameter[]]
variable[t] assign[=] call[call[name[np].linspace, parameter[constant[0], binary_operation[constant[2] * name[np].pi], binary_operati... | keyword[def] identifier[layout_circle] ( identifier[self] ):
literal[string]
identifier[n] = identifier[self] . identifier[num_vertices] ()
identifier[t] = identifier[np] . identifier[linspace] ( literal[int] , literal[int] * identifier[np] . identifier[pi] , identifier[n] + literal[int] )[: identifie... | def layout_circle(self):
"""Position vertices evenly around a circle."""
n = self.num_vertices()
t = np.linspace(0, 2 * np.pi, n + 1)[:n]
return np.column_stack((np.cos(t), np.sin(t))) |
def merge(self):
"""
Merge contained schemas into one.
@return: The merged schema.
@rtype: L{Schema}
"""
if self.children:
schema = self.children[0]
for s in self.children[1:]:
schema.merge(s)
return schema | def function[merge, parameter[self]]:
constant[
Merge contained schemas into one.
@return: The merged schema.
@rtype: L{Schema}
]
if name[self].children begin[:]
variable[schema] assign[=] call[name[self].children][constant[0]]
for taget[... | keyword[def] identifier[merge] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[children] :
identifier[schema] = identifier[self] . identifier[children] [ literal[int] ]
keyword[for] identifier[s] keyword[in] identifier[self] . identifier... | def merge(self):
"""
Merge contained schemas into one.
@return: The merged schema.
@rtype: L{Schema}
"""
if self.children:
schema = self.children[0]
for s in self.children[1:]:
schema.merge(s) # depends on [control=['for'], data=['s']]
retur... |
def get_cached_parent_for_taxon(self, child_taxon):
"""If the taxa are being cached, this call will create a the lineage "spike" for taxon child_taxon
Expecting child_taxon to have a non-empty _taxonomic_lineage with response dicts that can create
an ancestral TaxonWrapper.
"""
... | def function[get_cached_parent_for_taxon, parameter[self, child_taxon]]:
constant[If the taxa are being cached, this call will create a the lineage "spike" for taxon child_taxon
Expecting child_taxon to have a non-empty _taxonomic_lineage with response dicts that can create
an ancestral Tax... | keyword[def] identifier[get_cached_parent_for_taxon] ( identifier[self] , identifier[child_taxon] ):
literal[string]
keyword[if] identifier[self] . identifier[_ott_id2taxon] keyword[is] keyword[None] :
identifier[resp] = identifier[child_taxon] . identifier[_taxonomic_lineage] [ lit... | def get_cached_parent_for_taxon(self, child_taxon):
"""If the taxa are being cached, this call will create a the lineage "spike" for taxon child_taxon
Expecting child_taxon to have a non-empty _taxonomic_lineage with response dicts that can create
an ancestral TaxonWrapper.
"""
if s... |
def _unwrap(variable_parts: VariablePartsType):
"""
Yield URL parts. The given parts are usually in reverse order.
"""
curr_parts = variable_parts
var_any = []
while curr_parts:
curr_parts, (var_type, part) = curr_parts
if var_type == Routes._VAR_ANY_NODE:
var_any.a... | def function[_unwrap, parameter[variable_parts]]:
constant[
Yield URL parts. The given parts are usually in reverse order.
]
variable[curr_parts] assign[=] name[variable_parts]
variable[var_any] assign[=] list[[]]
while name[curr_parts] begin[:]
<ast.Tuple object ... | keyword[def] identifier[_unwrap] ( identifier[variable_parts] : identifier[VariablePartsType] ):
literal[string]
identifier[curr_parts] = identifier[variable_parts]
identifier[var_any] =[]
keyword[while] identifier[curr_parts] :
identifier[curr_parts] ,( identifier[var_type] , identif... | def _unwrap(variable_parts: VariablePartsType):
"""
Yield URL parts. The given parts are usually in reverse order.
"""
curr_parts = variable_parts
var_any = []
while curr_parts:
(curr_parts, (var_type, part)) = curr_parts
if var_type == Routes._VAR_ANY_NODE:
var_any.a... |
def precess_coordinates(ra, dec,
epoch_one, epoch_two,
jd=None,
mu_ra=0.0,
mu_dec=0.0,
outscalar=False):
'''Precesses target coordinates `ra`, `dec` from `epoch_one` to `epoch_two`.
This take... | def function[precess_coordinates, parameter[ra, dec, epoch_one, epoch_two, jd, mu_ra, mu_dec, outscalar]]:
constant[Precesses target coordinates `ra`, `dec` from `epoch_one` to `epoch_two`.
This takes into account the jd of the observations, as well as the proper
motion of the target mu_ra, mu_dec. Ada... | keyword[def] identifier[precess_coordinates] ( identifier[ra] , identifier[dec] ,
identifier[epoch_one] , identifier[epoch_two] ,
identifier[jd] = keyword[None] ,
identifier[mu_ra] = literal[int] ,
identifier[mu_dec] = literal[int] ,
identifier[outscalar] = keyword[False] ):
literal[string]
identifie... | def precess_coordinates(ra, dec, epoch_one, epoch_two, jd=None, mu_ra=0.0, mu_dec=0.0, outscalar=False):
"""Precesses target coordinates `ra`, `dec` from `epoch_one` to `epoch_two`.
This takes into account the jd of the observations, as well as the proper
motion of the target mu_ra, mu_dec. Adapted from J.... |
def make_unpublished(self, request, queryset):
"""
Marks selected news items as unpublished
"""
rows_updated = queryset.update(is_published=False)
self.message_user(request,
ungettext('%(count)d newsitem was unpublished',
... | def function[make_unpublished, parameter[self, request, queryset]]:
constant[
Marks selected news items as unpublished
]
variable[rows_updated] assign[=] call[name[queryset].update, parameter[]]
call[name[self].message_user, parameter[name[request], binary_operation[call[name... | keyword[def] identifier[make_unpublished] ( identifier[self] , identifier[request] , identifier[queryset] ):
literal[string]
identifier[rows_updated] = identifier[queryset] . identifier[update] ( identifier[is_published] = keyword[False] )
identifier[self] . identifier[message_user] ( iden... | def make_unpublished(self, request, queryset):
"""
Marks selected news items as unpublished
"""
rows_updated = queryset.update(is_published=False)
self.message_user(request, ungettext('%(count)d newsitem was unpublished', '%(count)d newsitems were unpublished', rows_updated) % {'count': ... |
def translate(self, desired_locale=None):
"""Translate this message to the desired locale.
:param desired_locale: The desired locale to translate the message to,
if no locale is provided the message will be
translated to the system's default... | def function[translate, parameter[self, desired_locale]]:
constant[Translate this message to the desired locale.
:param desired_locale: The desired locale to translate the message to,
if no locale is provided the message will be
translated t... | keyword[def] identifier[translate] ( identifier[self] , identifier[desired_locale] = keyword[None] ):
literal[string]
identifier[translated_message] = identifier[Message] . identifier[_translate_msgid] ( identifier[self] . identifier[msgid] ,
identifier[self] . identifier[domain] ,
... | def translate(self, desired_locale=None):
"""Translate this message to the desired locale.
:param desired_locale: The desired locale to translate the message to,
if no locale is provided the message will be
translated to the system's default loc... |
def filesFromHere_explore(self, astr_startPath = '/'):
"""
Return a list of path/files from "here" in the stree, using
the child explore access.
:param astr_startPath: path from which to start
:return:
"""
self.l_fwd = []
... | def function[filesFromHere_explore, parameter[self, astr_startPath]]:
constant[
Return a list of path/files from "here" in the stree, using
the child explore access.
:param astr_startPath: path from which to start
:return:
]
name[self].l_fwd a... | keyword[def] identifier[filesFromHere_explore] ( identifier[self] , identifier[astr_startPath] = literal[string] ):
literal[string]
identifier[self] . identifier[l_fwd] =[]
identifier[self] . identifier[treeExplore] ( identifier[startPath] = identifier[astr_startPath] , identif... | def filesFromHere_explore(self, astr_startPath='/'):
"""
Return a list of path/files from "here" in the stree, using
the child explore access.
:param astr_startPath: path from which to start
:return:
"""
self.l_fwd = []
self.treeExplore(startPath=... |
def _parse_value(self): # type: () -> Item
"""
Attempts to parse a value at the current position.
"""
self.mark()
c = self._current
trivia = Trivia()
if c == StringType.SLB.value:
return self._parse_basic_string()
elif c == StringType.SLL.val... | def function[_parse_value, parameter[self]]:
constant[
Attempts to parse a value at the current position.
]
call[name[self].mark, parameter[]]
variable[c] assign[=] name[self]._current
variable[trivia] assign[=] call[name[Trivia], parameter[]]
if compare[name[c] e... | keyword[def] identifier[_parse_value] ( identifier[self] ):
literal[string]
identifier[self] . identifier[mark] ()
identifier[c] = identifier[self] . identifier[_current]
identifier[trivia] = identifier[Trivia] ()
keyword[if] identifier[c] == identifier[StringType] . i... | def _parse_value(self): # type: () -> Item
'\n Attempts to parse a value at the current position.\n '
self.mark()
c = self._current
trivia = Trivia()
if c == StringType.SLB.value:
return self._parse_basic_string() # depends on [control=['if'], data=[]]
elif c == StringTyp... |
def get_vcs_details_output_vcs_details_node_vcs_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vcs_details = ET.Element("get_vcs_details")
config = get_vcs_details
output = ET.SubElement(get_vcs_details, "output")
vcs_details = ... | def function[get_vcs_details_output_vcs_details_node_vcs_type, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_vcs_details] assign[=] call[name[ET].Element, parameter[constant[get_vcs_details]]]
... | keyword[def] identifier[get_vcs_details_output_vcs_details_node_vcs_type] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_vcs_details] = identifier[ET] . identifier[Element] ( literal[... | def get_vcs_details_output_vcs_details_node_vcs_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_vcs_details = ET.Element('get_vcs_details')
config = get_vcs_details
output = ET.SubElement(get_vcs_details, 'output')
vcs_details = ET.SubElement(output, 'v... |
def push_build_set(id, tag_prefix):
"""
Push build set to Brew
"""
req = swagger_client.BuildConfigSetRecordPushRequestRest()
req.tag_prefix = tag_prefix
req.build_config_set_record_id = id
response = utils.checked_api_call(pnc_api.build_push, 'push_record_set', body=req)
if response:
... | def function[push_build_set, parameter[id, tag_prefix]]:
constant[
Push build set to Brew
]
variable[req] assign[=] call[name[swagger_client].BuildConfigSetRecordPushRequestRest, parameter[]]
name[req].tag_prefix assign[=] name[tag_prefix]
name[req].build_config_set_record_id ass... | keyword[def] identifier[push_build_set] ( identifier[id] , identifier[tag_prefix] ):
literal[string]
identifier[req] = identifier[swagger_client] . identifier[BuildConfigSetRecordPushRequestRest] ()
identifier[req] . identifier[tag_prefix] = identifier[tag_prefix]
identifier[req] . identifier[bu... | def push_build_set(id, tag_prefix):
"""
Push build set to Brew
"""
req = swagger_client.BuildConfigSetRecordPushRequestRest()
req.tag_prefix = tag_prefix
req.build_config_set_record_id = id
response = utils.checked_api_call(pnc_api.build_push, 'push_record_set', body=req)
if response:
... |
def check_signature(self, signature, timestamp, nonce):
"""
验证微信消息真实性
:param signature: 微信加密签名
:param timestamp: 时间戳
:param nonce: 随机数
:return: 通过验证返回 True, 未通过验证返回 False
"""
if not signature or not timestamp or not nonce:
return False
... | def function[check_signature, parameter[self, signature, timestamp, nonce]]:
constant[
验证微信消息真实性
:param signature: 微信加密签名
:param timestamp: 时间戳
:param nonce: 随机数
:return: 通过验证返回 True, 未通过验证返回 False
]
if <ast.BoolOp object at 0x7da2054a4ee0> begin[:]
... | keyword[def] identifier[check_signature] ( identifier[self] , identifier[signature] , identifier[timestamp] , identifier[nonce] ):
literal[string]
keyword[if] keyword[not] identifier[signature] keyword[or] keyword[not] identifier[timestamp] keyword[or] keyword[not] identifier[nonce] :
... | def check_signature(self, signature, timestamp, nonce):
"""
验证微信消息真实性
:param signature: 微信加密签名
:param timestamp: 时间戳
:param nonce: 随机数
:return: 通过验证返回 True, 未通过验证返回 False
"""
if not signature or not timestamp or (not nonce):
return False # depends on [con... |
def _process_stream_delta(self, delta_stream):
"""Bookkeeping on internal data structures while iterating a stream."""
for pchange in delta_stream:
if pchange.kind == ChangeType.ADD:
self.policy_files.setdefault(
pchange.file_path, PolicyCollection()).add(... | def function[_process_stream_delta, parameter[self, delta_stream]]:
constant[Bookkeeping on internal data structures while iterating a stream.]
for taget[name[pchange]] in starred[name[delta_stream]] begin[:]
if compare[name[pchange].kind equal[==] name[ChangeType].ADD] begin[:]
... | keyword[def] identifier[_process_stream_delta] ( identifier[self] , identifier[delta_stream] ):
literal[string]
keyword[for] identifier[pchange] keyword[in] identifier[delta_stream] :
keyword[if] identifier[pchange] . identifier[kind] == identifier[ChangeType] . identifier[ADD] :
... | def _process_stream_delta(self, delta_stream):
"""Bookkeeping on internal data structures while iterating a stream."""
for pchange in delta_stream:
if pchange.kind == ChangeType.ADD:
self.policy_files.setdefault(pchange.file_path, PolicyCollection()).add(pchange.policy) # depends on [contro... |
def get_entries(self, criteria, inc_structure=False, optional_data=None):
"""
Get ComputedEntries satisfying a particular criteria.
.. note::
The get_entries_in_system and get_entries methods should be used
with care. In essence, all entries, GGA, GGA+U or otherwise,
... | def function[get_entries, parameter[self, criteria, inc_structure, optional_data]]:
constant[
Get ComputedEntries satisfying a particular criteria.
.. note::
The get_entries_in_system and get_entries methods should be used
with care. In essence, all entries, GGA, GGA+U... | keyword[def] identifier[get_entries] ( identifier[self] , identifier[criteria] , identifier[inc_structure] = keyword[False] , identifier[optional_data] = keyword[None] ):
literal[string]
identifier[all_entries] = identifier[list] ()
identifier[optional_data] =[] keyword[if] keyword[not] ... | def get_entries(self, criteria, inc_structure=False, optional_data=None):
"""
Get ComputedEntries satisfying a particular criteria.
.. note::
The get_entries_in_system and get_entries methods should be used
with care. In essence, all entries, GGA, GGA+U or otherwise,
... |
def _checkDocstringFormat(self, node_type, node, linenoDocstring):
"""
Check opening/closing of docstring.
@param node_type: type of node
@param node: current node of pylint
@param linenoDocstring: linenumber of docstring
"""
# Check the opening/closing of docstr... | def function[_checkDocstringFormat, parameter[self, node_type, node, linenoDocstring]]:
constant[
Check opening/closing of docstring.
@param node_type: type of node
@param node: current node of pylint
@param linenoDocstring: linenumber of docstring
]
variable[doc... | keyword[def] identifier[_checkDocstringFormat] ( identifier[self] , identifier[node_type] , identifier[node] , identifier[linenoDocstring] ):
literal[string]
identifier[docstringStrippedSpaces] = identifier[node] . identifier[doc] . identifier[strip] ( literal[string] )
keyword[if... | def _checkDocstringFormat(self, node_type, node, linenoDocstring):
"""
Check opening/closing of docstring.
@param node_type: type of node
@param node: current node of pylint
@param linenoDocstring: linenumber of docstring
"""
# Check the opening/closing of docstring.
... |
def lock(self):
"""This method locks the database."""
self.password = None
self.keyfile = None
self.groups[:] = []
self.entries[:] = []
self._group_order[:] = []
self._entry_order[:] = []
self.root_group = v1Group()
self._num_groups = 1
... | def function[lock, parameter[self]]:
constant[This method locks the database.]
name[self].password assign[=] constant[None]
name[self].keyfile assign[=] constant[None]
call[name[self].groups][<ast.Slice object at 0x7da1b26c4790>] assign[=] list[[]]
call[name[self].entries][<ast.S... | keyword[def] identifier[lock] ( identifier[self] ):
literal[string]
identifier[self] . identifier[password] = keyword[None]
identifier[self] . identifier[keyfile] = keyword[None]
identifier[self] . identifier[groups] [:]=[]
identifier[self] . identifier[entries] [:]=[]... | def lock(self):
"""This method locks the database."""
self.password = None
self.keyfile = None
self.groups[:] = []
self.entries[:] = []
self._group_order[:] = []
self._entry_order[:] = []
self.root_group = v1Group()
self._num_groups = 1
self._num_entries = 0
return True |
def get_event_question(self, id, question_id, **data):
"""
GET /events/:id/questions/:question_id/
This endpoint will return :format:`question` for a specific question id.
"""
return self.get("/events/{0}/questions/{0}/".format(id,question_id), data=data) | def function[get_event_question, parameter[self, id, question_id]]:
constant[
GET /events/:id/questions/:question_id/
This endpoint will return :format:`question` for a specific question id.
]
return[call[name[self].get, parameter[call[constant[/events/{0}/questions/{0}/].format, par... | keyword[def] identifier[get_event_question] ( identifier[self] , identifier[id] , identifier[question_id] ,** identifier[data] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( literal[string] . identifier[format] ( identifier[id] , identifier[question_id] ), identifier[data... | def get_event_question(self, id, question_id, **data):
"""
GET /events/:id/questions/:question_id/
This endpoint will return :format:`question` for a specific question id.
"""
return self.get('/events/{0}/questions/{0}/'.format(id, question_id), data=data) |
def scheduled(self, offset=0, count=25):
'''Return all the currently-scheduled jobs'''
return self.client('jobs', 'scheduled', self.name, offset, count) | def function[scheduled, parameter[self, offset, count]]:
constant[Return all the currently-scheduled jobs]
return[call[name[self].client, parameter[constant[jobs], constant[scheduled], name[self].name, name[offset], name[count]]]] | keyword[def] identifier[scheduled] ( identifier[self] , identifier[offset] = literal[int] , identifier[count] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[client] ( literal[string] , literal[string] , identifier[self] . identifier[name] , identifier[offset] , ide... | def scheduled(self, offset=0, count=25):
"""Return all the currently-scheduled jobs"""
return self.client('jobs', 'scheduled', self.name, offset, count) |
def _cleanUpdatesList(self, col, cellIdx, seg):
"""
Removes any update that would be for the given col, cellIdx, segIdx.
NOTE: logically, we need to do this when we delete segments, so that if
an update refers to a segment that was just deleted, we also remove
that update from the update list. Howe... | def function[_cleanUpdatesList, parameter[self, col, cellIdx, seg]]:
constant[
Removes any update that would be for the given col, cellIdx, segIdx.
NOTE: logically, we need to do this when we delete segments, so that if
an update refers to a segment that was just deleted, we also remove
that up... | keyword[def] identifier[_cleanUpdatesList] ( identifier[self] , identifier[col] , identifier[cellIdx] , identifier[seg] ):
literal[string]
keyword[for] identifier[key] , identifier[updateList] keyword[in] identifier[self] . identifier[segmentUpdates] . identifier[iteritems] ():
identifi... | def _cleanUpdatesList(self, col, cellIdx, seg):
"""
Removes any update that would be for the given col, cellIdx, segIdx.
NOTE: logically, we need to do this when we delete segments, so that if
an update refers to a segment that was just deleted, we also remove
that update from the update list. Howe... |
def check_sla(self, sla, diff_metric):
"""
Check whether the SLA has passed or failed
"""
try:
if sla.display is '%':
diff_val = float(diff_metric['percent_diff'])
else:
diff_val = float(diff_metric['absolute_diff'])
except ValueError:
return False
if not (sla.c... | def function[check_sla, parameter[self, sla, diff_metric]]:
constant[
Check whether the SLA has passed or failed
]
<ast.Try object at 0x7da1b00b7bb0>
if <ast.UnaryOp object at 0x7da18f00c250> begin[:]
<ast.AugAssign object at 0x7da18f00d600>
call[name[self].sla_failur... | keyword[def] identifier[check_sla] ( identifier[self] , identifier[sla] , identifier[diff_metric] ):
literal[string]
keyword[try] :
keyword[if] identifier[sla] . identifier[display] keyword[is] literal[string] :
identifier[diff_val] = identifier[float] ( identifier[diff_metric] [ literal... | def check_sla(self, sla, diff_metric):
"""
Check whether the SLA has passed or failed
"""
try:
if sla.display is '%':
diff_val = float(diff_metric['percent_diff']) # depends on [control=['if'], data=[]]
else:
diff_val = float(diff_metric['absolute_diff']) # depe... |
def get_x_inds(self, *dynac_type):
"""
Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list.
"""
return [i for i, x in e... | def function[get_x_inds, parameter[self]]:
constant[
Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list.
]
return[<ast.Lis... | keyword[def] identifier[get_x_inds] ( identifier[self] ,* identifier[dynac_type] ):
literal[string]
keyword[return] [ identifier[i] keyword[for] identifier[i] , identifier[x] keyword[in] identifier[enumerate] ( identifier[self] . identifier[lattice] ) keyword[for] identifier[y] keyword[in] i... | def get_x_inds(self, *dynac_type):
"""
Return the indices into the lattice list attribute of elements whose Dynac
type matches the input string. Multiple input strings can be given, either
as a comma-separated list or as a genuine Python list.
"""
return [i for (i, x) in enumera... |
def count(self, strg, case_sensitive=False, *args, **kwargs):
"""Get the count of a word or phrase `s` within this WordList.
:param strg: The string to count.
:param case_sensitive: A boolean, whether or not the search is case-sensitive.
"""
if not case_sensitive:
return [word.lower() for wo... | def function[count, parameter[self, strg, case_sensitive]]:
constant[Get the count of a word or phrase `s` within this WordList.
:param strg: The string to count.
:param case_sensitive: A boolean, whether or not the search is case-sensitive.
]
if <ast.UnaryOp object at 0x7da18f09c4f0> begin[... | keyword[def] identifier[count] ( identifier[self] , identifier[strg] , identifier[case_sensitive] = keyword[False] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[case_sensitive] :
keyword[return] [ identifier[word] . identifier[lower] () keyword... | def count(self, strg, case_sensitive=False, *args, **kwargs):
"""Get the count of a word or phrase `s` within this WordList.
:param strg: The string to count.
:param case_sensitive: A boolean, whether or not the search is case-sensitive.
"""
if not case_sensitive:
return [word.lower() for wo... |
def _compute_childtab(self, lcptab):
"""Computes the child 'up' and 'down' arrays in O(n) based on the LCP table.
Abouelhoda et al. (2004).
"""
last_index = -1
stack = [0]
n = len(lcptab)
childtab_up = np.zeros(n, dtype=np.int) # Zeros / -1 ?
childtab_do... | def function[_compute_childtab, parameter[self, lcptab]]:
constant[Computes the child 'up' and 'down' arrays in O(n) based on the LCP table.
Abouelhoda et al. (2004).
]
variable[last_index] assign[=] <ast.UnaryOp object at 0x7da18dc986d0>
variable[stack] assign[=] list[[<ast.Con... | keyword[def] identifier[_compute_childtab] ( identifier[self] , identifier[lcptab] ):
literal[string]
identifier[last_index] =- literal[int]
identifier[stack] =[ literal[int] ]
identifier[n] = identifier[len] ( identifier[lcptab] )
identifier[childtab_up] = identifier[np... | def _compute_childtab(self, lcptab):
"""Computes the child 'up' and 'down' arrays in O(n) based on the LCP table.
Abouelhoda et al. (2004).
"""
last_index = -1
stack = [0]
n = len(lcptab)
childtab_up = np.zeros(n, dtype=np.int) # Zeros / -1 ?
childtab_down = np.zeros(n, dtype=n... |
def machine_info():
"""Retrieve core and memory information for the current machine.
"""
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
"name":... | def function[machine_info, parameter[]]:
constant[Retrieve core and memory information for the current machine.
]
import module[psutil]
variable[BYTES_IN_GIG] assign[=] constant[1073741824.0]
variable[free_bytes] assign[=] call[name[psutil].virtual_memory, parameter[]].total
return[l... | keyword[def] identifier[machine_info] ():
literal[string]
keyword[import] identifier[psutil]
identifier[BYTES_IN_GIG] = literal[int]
identifier[free_bytes] = identifier[psutil] . identifier[virtual_memory] (). identifier[total]
keyword[return] [{ literal[string] : identifier[float] ( lit... | def machine_info():
"""Retrieve core and memory information for the current machine.
"""
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{'memory': float('%.1f' % (free_bytes / BYTES_IN_GIG)), 'cores': multiprocessing.cpu_count(), 'name': socket.getho... |
def subintf_real_ip_check_gw_port(self, gw_port, ip_addr, netmask):
"""
checks running-cfg derived ip_addr and netmask against neutron-db
gw_port
"""
if gw_port is not None:
found = False
for i in range(len(gw_port['fixed_ips'])):
target_ip... | def function[subintf_real_ip_check_gw_port, parameter[self, gw_port, ip_addr, netmask]]:
constant[
checks running-cfg derived ip_addr and netmask against neutron-db
gw_port
]
if compare[name[gw_port] is_not constant[None]] begin[:]
variable[found] assign[=] consta... | keyword[def] identifier[subintf_real_ip_check_gw_port] ( identifier[self] , identifier[gw_port] , identifier[ip_addr] , identifier[netmask] ):
literal[string]
keyword[if] identifier[gw_port] keyword[is] keyword[not] keyword[None] :
identifier[found] = keyword[False]
k... | def subintf_real_ip_check_gw_port(self, gw_port, ip_addr, netmask):
"""
checks running-cfg derived ip_addr and netmask against neutron-db
gw_port
"""
if gw_port is not None:
found = False
for i in range(len(gw_port['fixed_ips'])):
target_ip = gw_port['fixed_ip... |
def room(request, slug, template="room.html"):
"""
Show a room.
"""
context = {"room": get_object_or_404(ChatRoom, slug=slug)}
return render(request, template, context) | def function[room, parameter[request, slug, template]]:
constant[
Show a room.
]
variable[context] assign[=] dictionary[[<ast.Constant object at 0x7da18fe92f80>], [<ast.Call object at 0x7da18fe92bf0>]]
return[call[name[render], parameter[name[request], name[template], name[context]]]] | keyword[def] identifier[room] ( identifier[request] , identifier[slug] , identifier[template] = literal[string] ):
literal[string]
identifier[context] ={ literal[string] : identifier[get_object_or_404] ( identifier[ChatRoom] , identifier[slug] = identifier[slug] )}
keyword[return] identifier[render] ... | def room(request, slug, template='room.html'):
"""
Show a room.
"""
context = {'room': get_object_or_404(ChatRoom, slug=slug)}
return render(request, template, context) |
def me(self):
"""Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
"""
self_id = self._state.user.id
return self.get_member(self_id) | def function[me, parameter[self]]:
constant[Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
]
variable[self_id] assign[=] name[self]._state.user.id
return[call[name[self].get_member, parameter[name[... | keyword[def] identifier[me] ( identifier[self] ):
literal[string]
identifier[self_id] = identifier[self] . identifier[_state] . identifier[user] . identifier[id]
keyword[return] identifier[self] . identifier[get_member] ( identifier[self_id] ) | def me(self):
"""Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
"""
self_id = self._state.user.id
return self.get_member(self_id) |
def is_list(str):
""" Determines if an item in a paragraph is a list.
If all of the lines in the markup start with a "*" or "1."
this indicates a list as parsed by parse_paragraphs().
It can be drawn with draw_list().
"""
for chunk in str.split("\n"):
chunk = chunk.replace... | def function[is_list, parameter[str]]:
constant[ Determines if an item in a paragraph is a list.
If all of the lines in the markup start with a "*" or "1."
this indicates a list as parsed by parse_paragraphs().
It can be drawn with draw_list().
]
for taget[name[chunk]] in starred[... | keyword[def] identifier[is_list] ( identifier[str] ):
literal[string]
keyword[for] identifier[chunk] keyword[in] identifier[str] . identifier[split] ( literal[string] ):
identifier[chunk] = identifier[chunk] . identifier[replace] ( literal[string] , literal[string] )
keyword[if] key... | def is_list(str):
""" Determines if an item in a paragraph is a list.
If all of the lines in the markup start with a "*" or "1."
this indicates a list as parsed by parse_paragraphs().
It can be drawn with draw_list().
"""
for chunk in str.split('\n'):
chunk = chunk.replace('\t', '... |
def get_py_dtypes(data_frame):
'''
Return a `pandas.DataFrame` containing Python type information for the
columns in `data_frame`.
Args:
data_frame (pandas.DataFrame) : Data frame containing data columns.
Returns:
(pandas.DataFrame) : Data frame indexed by the column names from
... | def function[get_py_dtypes, parameter[data_frame]]:
constant[
Return a `pandas.DataFrame` containing Python type information for the
columns in `data_frame`.
Args:
data_frame (pandas.DataFrame) : Data frame containing data columns.
Returns:
(pandas.DataFrame) : Data frame ind... | keyword[def] identifier[get_py_dtypes] ( identifier[data_frame] ):
literal[string]
identifier[df_py_dtypes] = identifier[data_frame] . identifier[dtypes] . identifier[map] ( identifier[get_py_dtype] ). identifier[to_frame] ( literal[string] ). identifier[copy] ()
identifier[df_py_dtypes] . identifier[... | def get_py_dtypes(data_frame):
"""
Return a `pandas.DataFrame` containing Python type information for the
columns in `data_frame`.
Args:
data_frame (pandas.DataFrame) : Data frame containing data columns.
Returns:
(pandas.DataFrame) : Data frame indexed by the column names from
... |
def _print_general_vs_table(self, idset1, idset2):
"""
:param idset1:
:param idset2:
"""
ref1name = ''
set1_hasref = isinstance(idset1, idset_with_reference)
if set1_hasref:
ref1arr = np.array(idset1.reflst)
ref1name = idset1.refname
... | def function[_print_general_vs_table, parameter[self, idset1, idset2]]:
constant[
:param idset1:
:param idset2:
]
variable[ref1name] assign[=] constant[]
variable[set1_hasref] assign[=] call[name[isinstance], parameter[name[idset1], name[idset_with_reference]]]
if... | keyword[def] identifier[_print_general_vs_table] ( identifier[self] , identifier[idset1] , identifier[idset2] ):
literal[string]
identifier[ref1name] = literal[string]
identifier[set1_hasref] = identifier[isinstance] ( identifier[idset1] , identifier[idset_with_reference] )
keywo... | def _print_general_vs_table(self, idset1, idset2):
"""
:param idset1:
:param idset2:
"""
ref1name = ''
set1_hasref = isinstance(idset1, idset_with_reference)
if set1_hasref:
ref1arr = np.array(idset1.reflst)
ref1name = idset1.refname # depends on [control=['if'],... |
def get_by_type(self, _type):
"""
Return all of the instances of :class:`ComponentType` ``_type``.
"""
r = {}
for k, v in self.items():
if get_component_type(k) is _type:
r[k] = v
return r | def function[get_by_type, parameter[self, _type]]:
constant[
Return all of the instances of :class:`ComponentType` ``_type``.
]
variable[r] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da18dc99cc0>, <ast.Name object at 0x7da18dc9b310>]]] in starred[call[na... | keyword[def] identifier[get_by_type] ( identifier[self] , identifier[_type] ):
literal[string]
identifier[r] ={}
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[self] . identifier[items] ():
keyword[if] identifier[get_component_type] ( identifier[k] ) key... | def get_by_type(self, _type):
"""
Return all of the instances of :class:`ComponentType` ``_type``.
"""
r = {}
for (k, v) in self.items():
if get_component_type(k) is _type:
r[k] = v # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
retur... |
def _eval_summary(self, context: MonitorContext, feed_dict: Optional[Dict]=None) -> None:
"""
Evaluates the summary tensor and writes the result to the event file.
:param context: Monitor context
:param feed_dict: Input values dictionary to be provided to the `session.run`
when e... | def function[_eval_summary, parameter[self, context, feed_dict]]:
constant[
Evaluates the summary tensor and writes the result to the event file.
:param context: Monitor context
:param feed_dict: Input values dictionary to be provided to the `session.run`
when evaluating the summ... | keyword[def] identifier[_eval_summary] ( identifier[self] , identifier[context] : identifier[MonitorContext] , identifier[feed_dict] : identifier[Optional] [ identifier[Dict] ]= keyword[None] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[_summary] keyword[is] key... | def _eval_summary(self, context: MonitorContext, feed_dict: Optional[Dict]=None) -> None:
"""
Evaluates the summary tensor and writes the result to the event file.
:param context: Monitor context
:param feed_dict: Input values dictionary to be provided to the `session.run`
when evalu... |
def trim(hdu, datasec='DATASEC'):
"""TRIM a CFHT MEGAPRIME frame using the DATASEC keyword"""
datasec = re.findall(r'(\d+)',
hdu.header.get(datasec))
l = int(datasec[0]) - 1
r = int(datasec[1])
b = int(datasec[2]) - 1
t = int(datasec[3])
logger.info("Trimming [%d:%d... | def function[trim, parameter[hdu, datasec]]:
constant[TRIM a CFHT MEGAPRIME frame using the DATASEC keyword]
variable[datasec] assign[=] call[name[re].findall, parameter[constant[(\d+)], call[name[hdu].header.get, parameter[name[datasec]]]]]
variable[l] assign[=] binary_operation[call[name[int]... | keyword[def] identifier[trim] ( identifier[hdu] , identifier[datasec] = literal[string] ):
literal[string]
identifier[datasec] = identifier[re] . identifier[findall] ( literal[string] ,
identifier[hdu] . identifier[header] . identifier[get] ( identifier[datasec] ))
identifier[l] = identifier[int]... | def trim(hdu, datasec='DATASEC'):
"""TRIM a CFHT MEGAPRIME frame using the DATASEC keyword"""
datasec = re.findall('(\\d+)', hdu.header.get(datasec))
l = int(datasec[0]) - 1
r = int(datasec[1])
b = int(datasec[2]) - 1
t = int(datasec[3])
logger.info('Trimming [%d:%d,%d:%d]' % (l, r, b, t))
... |
async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() | <ast.AsyncFunctionDef object at 0x7da1b01e57e0> | keyword[async] keyword[def] identifier[set_tz] ( identifier[self] ):
literal[string]
identifier[settings] = keyword[await] identifier[self] . identifier[api] . identifier[account] . identifier[settings] . identifier[get] ()
identifier[tz] = identifier[settings] . identifier[time_zone] .... | async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() |
def get_submodule_list(package_path: str) -> Tuple[ModuleDescription, ...]:
"""Get list of submodules for some package by its path. E.g ``pkg.subpackage``"""
pkg = importlib.import_module(package_path)
subs = (
ModuleDescription(
name=modname,
path="{}.{}".format(package_pat... | def function[get_submodule_list, parameter[package_path]]:
constant[Get list of submodules for some package by its path. E.g ``pkg.subpackage``]
variable[pkg] assign[=] call[name[importlib].import_module, parameter[name[package_path]]]
variable[subs] assign[=] <ast.GeneratorExp object at 0x7da20... | keyword[def] identifier[get_submodule_list] ( identifier[package_path] : identifier[str] )-> identifier[Tuple] [ identifier[ModuleDescription] ,...]:
literal[string]
identifier[pkg] = identifier[importlib] . identifier[import_module] ( identifier[package_path] )
identifier[subs] =(
identifier[Mo... | def get_submodule_list(package_path: str) -> Tuple[ModuleDescription, ...]:
"""Get list of submodules for some package by its path. E.g ``pkg.subpackage``"""
pkg = importlib.import_module(package_path)
subs = (ModuleDescription(name=modname, path='{}.{}'.format(package_path, modname), is_package=ispkg) for ... |
def _handle_function_exists(self, node, scope, ctxt, stream):
"""Handle the function_exists unary operator
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
res = fields.Int()
try:
func = self._handle_node(node.exp... | def function[_handle_function_exists, parameter[self, node, scope, ctxt, stream]]:
constant[Handle the function_exists unary operator
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
]
variable[res] assign[=] call[name[fields].Int, param... | keyword[def] identifier[_handle_function_exists] ( identifier[self] , identifier[node] , identifier[scope] , identifier[ctxt] , identifier[stream] ):
literal[string]
identifier[res] = identifier[fields] . identifier[Int] ()
keyword[try] :
identifier[func] = identifier[self] . ... | def _handle_function_exists(self, node, scope, ctxt, stream):
"""Handle the function_exists unary operator
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
res = fields.Int()
try:
func = self._handle_node(node.expr, scope, ctxt, ... |
def setup(self, bottom, top):
"""
Setup data layer according to parameters:
- voc_dir: path to PASCAL VOC year dir
- split: train / val / test
- mean: tuple of mean values to subtract
- randomize: load in random order (default: True)
- seed: seed for randomizatio... | def function[setup, parameter[self, bottom, top]]:
constant[
Setup data layer according to parameters:
- voc_dir: path to PASCAL VOC year dir
- split: train / val / test
- mean: tuple of mean values to subtract
- randomize: load in random order (default: True)
- ... | keyword[def] identifier[setup] ( identifier[self] , identifier[bottom] , identifier[top] ):
literal[string]
identifier[params] = identifier[eval] ( identifier[self] . identifier[param_str] )
identifier[self] . identifier[voc_dir] = identifier[params] [ literal[string] ]
i... | def setup(self, bottom, top):
"""
Setup data layer according to parameters:
- voc_dir: path to PASCAL VOC year dir
- split: train / val / test
- mean: tuple of mean values to subtract
- randomize: load in random order (default: True)
- seed: seed for randomization (d... |
def export_model(self, export_formats, export_dir=None):
"""Exports model based on export_formats.
Subclasses should override _export_model() to actually
export model to local directory.
Args:
export_formats (list): List of formats that should be exported.
expor... | def function[export_model, parameter[self, export_formats, export_dir]]:
constant[Exports model based on export_formats.
Subclasses should override _export_model() to actually
export model to local directory.
Args:
export_formats (list): List of formats that should be expor... | keyword[def] identifier[export_model] ( identifier[self] , identifier[export_formats] , identifier[export_dir] = keyword[None] ):
literal[string]
identifier[export_dir] = identifier[export_dir] keyword[or] identifier[self] . identifier[logdir]
keyword[return] identifier[self] . identif... | def export_model(self, export_formats, export_dir=None):
"""Exports model based on export_formats.
Subclasses should override _export_model() to actually
export model to local directory.
Args:
export_formats (list): List of formats that should be exported.
export_di... |
def make_idd_index(extract_func, fname, debug):
"""generate the iddindex"""
astr = _readfname(fname)
# fname is exhausted by the above read
# reconstitute fname as a StringIO
fname = StringIO(astr)
# glist = iddgroups.iddtxt2grouplist(astr.decode('ISO-8859-2'))
blocklst, commlst,... | def function[make_idd_index, parameter[extract_func, fname, debug]]:
constant[generate the iddindex]
variable[astr] assign[=] call[name[_readfname], parameter[name[fname]]]
variable[fname] assign[=] call[name[StringIO], parameter[name[astr]]]
<ast.Tuple object at 0x7da20e9b3eb0> assign[=... | keyword[def] identifier[make_idd_index] ( identifier[extract_func] , identifier[fname] , identifier[debug] ):
literal[string]
identifier[astr] = identifier[_readfname] ( identifier[fname] )
identifier[fname] = identifier[StringIO] ( identifier[astr] )
identifier[blocklst] , ide... | def make_idd_index(extract_func, fname, debug):
"""generate the iddindex"""
astr = _readfname(fname)
# fname is exhausted by the above read
# reconstitute fname as a StringIO
fname = StringIO(astr)
# glist = iddgroups.iddtxt2grouplist(astr.decode('ISO-8859-2'))
(blocklst, commlst, commdct) =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.