code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _is_and_or_ternary(node):
"""
Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return (
isinstance(node, astroid.BoolOp)
and node.op ==... | def function[_is_and_or_ternary, parameter[node]]:
constant[
Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
]
return[<ast.BoolOp object at 0x7da1b020df60>] | keyword[def] identifier[_is_and_or_ternary] ( identifier[node] ):
literal[string]
keyword[return] (
identifier[isinstance] ( identifier[node] , identifier[astroid] . identifier[BoolOp] )
keyword[and] identifier[node] . identifier[op] == literal[string]
keyword[and] ide... | def _is_and_or_ternary(node):
"""
Returns true if node is 'condition and true_value or false_value' form.
All of: condition, true_value and false_value should not be a complex boolean expression
"""
return isinstance(node, astroid.BoolOp) and node.op == 'or' and (len(node.values) == 2) ... |
def row(self, idx):
"""
Returns DataFrameRow of the DataFrame given its index.
:param idx: the index of the row in the DataFrame.
:return: returns a DataFrameRow
"""
return DataFrameRow(idx, [x[idx] for x in self], self.colnames) | def function[row, parameter[self, idx]]:
constant[
Returns DataFrameRow of the DataFrame given its index.
:param idx: the index of the row in the DataFrame.
:return: returns a DataFrameRow
]
return[call[name[DataFrameRow], parameter[name[idx], <ast.ListComp object at 0x7da1a... | keyword[def] identifier[row] ( identifier[self] , identifier[idx] ):
literal[string]
keyword[return] identifier[DataFrameRow] ( identifier[idx] ,[ identifier[x] [ identifier[idx] ] keyword[for] identifier[x] keyword[in] identifier[self] ], identifier[self] . identifier[colnames] ) | def row(self, idx):
"""
Returns DataFrameRow of the DataFrame given its index.
:param idx: the index of the row in the DataFrame.
:return: returns a DataFrameRow
"""
return DataFrameRow(idx, [x[idx] for x in self], self.colnames) |
def _value_formatter(self, float_format=None, threshold=None):
"""Returns a function to be applied on each value to format it
"""
# the float_format parameter supersedes self.float_format
if float_format is None:
float_format = self.float_format
# we are going to co... | def function[_value_formatter, parameter[self, float_format, threshold]]:
constant[Returns a function to be applied on each value to format it
]
if compare[name[float_format] is constant[None]] begin[:]
variable[float_format] assign[=] name[self].float_format
if name[floa... | keyword[def] identifier[_value_formatter] ( identifier[self] , identifier[float_format] = keyword[None] , identifier[threshold] = keyword[None] ):
literal[string]
keyword[if] identifier[float_format] keyword[is] keyword[None] :
identifier[float_format] = identifier[self] .... | def _value_formatter(self, float_format=None, threshold=None):
"""Returns a function to be applied on each value to format it
"""
# the float_format parameter supersedes self.float_format
if float_format is None:
float_format = self.float_format # depends on [control=['if'], data=['float_fo... |
def seq_seguid(seq, normalize=True):
"""returns seguid for sequence `seq`
This seguid is compatible with BioPython's seguid.
>>> seq_seguid('')
'2jmj7l5rSw0yVb/vlWAYkK/YBwk'
>>> seq_seguid('ACGT')
'IQiZThf2zKn/I1KtqStlEdsHYDQ'
>>> seq_seguid('acgt')
'IQiZThf2zKn/I1KtqStlEdsHYDQ'
... | def function[seq_seguid, parameter[seq, normalize]]:
constant[returns seguid for sequence `seq`
This seguid is compatible with BioPython's seguid.
>>> seq_seguid('')
'2jmj7l5rSw0yVb/vlWAYkK/YBwk'
>>> seq_seguid('ACGT')
'IQiZThf2zKn/I1KtqStlEdsHYDQ'
>>> seq_seguid('acgt')
'IQiZThf... | keyword[def] identifier[seq_seguid] ( identifier[seq] , identifier[normalize] = keyword[True] ):
literal[string]
identifier[seq] = identifier[normalize_sequence] ( identifier[seq] ) keyword[if] identifier[normalize] keyword[else] identifier[seq]
identifier[bseq] = identifier[seq] . identifier[enco... | def seq_seguid(seq, normalize=True):
"""returns seguid for sequence `seq`
This seguid is compatible with BioPython's seguid.
>>> seq_seguid('')
'2jmj7l5rSw0yVb/vlWAYkK/YBwk'
>>> seq_seguid('ACGT')
'IQiZThf2zKn/I1KtqStlEdsHYDQ'
>>> seq_seguid('acgt')
'IQiZThf2zKn/I1KtqStlEdsHYDQ'
... |
def reset_parcov(self,arg=None):
"""reset the parcov attribute to None
Parameters
----------
arg : str or pyemu.Matrix
the value to assign to the parcov attribute. If None,
the private __parcov attribute is cleared but not reset
"""
self.logger.s... | def function[reset_parcov, parameter[self, arg]]:
constant[reset the parcov attribute to None
Parameters
----------
arg : str or pyemu.Matrix
the value to assign to the parcov attribute. If None,
the private __parcov attribute is cleared but not reset
]
... | keyword[def] identifier[reset_parcov] ( identifier[self] , identifier[arg] = keyword[None] ):
literal[string]
identifier[self] . identifier[logger] . identifier[statement] ( literal[string] )
identifier[self] . identifier[__parcov] = keyword[None]
keyword[if] identifier[arg] ke... | def reset_parcov(self, arg=None):
"""reset the parcov attribute to None
Parameters
----------
arg : str or pyemu.Matrix
the value to assign to the parcov attribute. If None,
the private __parcov attribute is cleared but not reset
"""
self.logger.statemen... |
def _read_xlsx_table(path):
"""Lee la hoja activa de un archivo XLSX a una lista de diccionarios."""
workbook = pyxl.load_workbook(path)
worksheet = workbook.active
table = helpers.sheet_to_table(worksheet)
return table | def function[_read_xlsx_table, parameter[path]]:
constant[Lee la hoja activa de un archivo XLSX a una lista de diccionarios.]
variable[workbook] assign[=] call[name[pyxl].load_workbook, parameter[name[path]]]
variable[worksheet] assign[=] name[workbook].active
variable[table] assign[=] c... | keyword[def] identifier[_read_xlsx_table] ( identifier[path] ):
literal[string]
identifier[workbook] = identifier[pyxl] . identifier[load_workbook] ( identifier[path] )
identifier[worksheet] = identifier[workbook] . identifier[active]
identifier[table] = identifier[helpers] . identifier[sheet_to... | def _read_xlsx_table(path):
"""Lee la hoja activa de un archivo XLSX a una lista de diccionarios."""
workbook = pyxl.load_workbook(path)
worksheet = workbook.active
table = helpers.sheet_to_table(worksheet)
return table |
def siamese_cosine_loss(left, right, y, scope="cosine_loss"):
r"""Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2
Args:
left (tf.Tensor): left ... | def function[siamese_cosine_loss, parameter[left, right, y, scope]]:
constant[Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2
Args:
left (t... | keyword[def] identifier[siamese_cosine_loss] ( identifier[left] , identifier[right] , identifier[y] , identifier[scope] = literal[string] ):
literal[string]
keyword[def] identifier[l2_norm] ( identifier[t] , identifier[eps] = literal[int] ):
literal[string]
keyword[with] identifier[tf... | def siamese_cosine_loss(left, right, y, scope='cosine_loss'):
"""Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\\frac{l \\cdot r}{\\lVert l\\rVert \\lVert r\\rVert} - (2y-1)]^2
Args:
left (tf.Tensor): ... |
def export(self, name, columns, points):
"""Write the points to the Prometheus exporter using Gauge."""
logger.debug("Export {} stats to Prometheus exporter".format(name))
# Remove non number stats and convert all to float (for Boolean)
data = {k: float(v) for (k, v) in iteritems(dict(z... | def function[export, parameter[self, name, columns, points]]:
constant[Write the points to the Prometheus exporter using Gauge.]
call[name[logger].debug, parameter[call[constant[Export {} stats to Prometheus exporter].format, parameter[name[name]]]]]
variable[data] assign[=] <ast.DictComp object... | keyword[def] identifier[export] ( identifier[self] , identifier[name] , identifier[columns] , identifier[points] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[name] ))
identifier[data] ={ identifier[k] : identifier[f... | def export(self, name, columns, points):
"""Write the points to the Prometheus exporter using Gauge."""
logger.debug('Export {} stats to Prometheus exporter'.format(name))
# Remove non number stats and convert all to float (for Boolean)
data = {k: float(v) for (k, v) in iteritems(dict(zip(columns, point... |
def calc_columns_rows(n):
"""
Calculate the number of columns and rows required to divide an image
into ``n`` parts.
Return a tuple of integers in the format (num_columns, num_rows)
"""
num_columns = int(ceil(sqrt(n)))
num_rows = int(ceil(n / float(num_columns)))
return (num_columns, nu... | def function[calc_columns_rows, parameter[n]]:
constant[
Calculate the number of columns and rows required to divide an image
into ``n`` parts.
Return a tuple of integers in the format (num_columns, num_rows)
]
variable[num_columns] assign[=] call[name[int], parameter[call[name[ceil], p... | keyword[def] identifier[calc_columns_rows] ( identifier[n] ):
literal[string]
identifier[num_columns] = identifier[int] ( identifier[ceil] ( identifier[sqrt] ( identifier[n] )))
identifier[num_rows] = identifier[int] ( identifier[ceil] ( identifier[n] / identifier[float] ( identifier[num_columns] )))
... | def calc_columns_rows(n):
"""
Calculate the number of columns and rows required to divide an image
into ``n`` parts.
Return a tuple of integers in the format (num_columns, num_rows)
"""
num_columns = int(ceil(sqrt(n)))
num_rows = int(ceil(n / float(num_columns)))
return (num_columns, nu... |
def whoami(self):
"""
Get information about the access token.
Official docs:
https://monzo.com/docs/#authenticating-requests
:returns: access token details
:rtype: dict
"""
endpoint = '/ping/whoami'
response = self._get_response(
... | def function[whoami, parameter[self]]:
constant[
Get information about the access token.
Official docs:
https://monzo.com/docs/#authenticating-requests
:returns: access token details
:rtype: dict
]
variable[endpoint] assign[=] constant[/ping/whoami]
... | keyword[def] identifier[whoami] ( identifier[self] ):
literal[string]
identifier[endpoint] = literal[string]
identifier[response] = identifier[self] . identifier[_get_response] (
identifier[method] = literal[string] , identifier[endpoint] = identifier[endpoint] ,
)
... | def whoami(self):
"""
Get information about the access token.
Official docs:
https://monzo.com/docs/#authenticating-requests
:returns: access token details
:rtype: dict
"""
endpoint = '/ping/whoami'
response = self._get_response(method='get', endpoint=en... |
def set_one(chainmap, thing_name, callobject):
""" Add a mapping with key thing_name for callobject in chainmap with
namespace handling.
"""
namespaces = reversed(thing_name.split("."))
lstname = []
for name in namespaces:
lstname.insert(0, name)
strname = '.'.join(lstname)
... | def function[set_one, parameter[chainmap, thing_name, callobject]]:
constant[ Add a mapping with key thing_name for callobject in chainmap with
namespace handling.
]
variable[namespaces] assign[=] call[name[reversed], parameter[call[name[thing_name].split, parameter[constant[.]]]]]
v... | keyword[def] identifier[set_one] ( identifier[chainmap] , identifier[thing_name] , identifier[callobject] ):
literal[string]
identifier[namespaces] = identifier[reversed] ( identifier[thing_name] . identifier[split] ( literal[string] ))
identifier[lstname] =[]
keyword[for] identifier[name] keyw... | def set_one(chainmap, thing_name, callobject):
""" Add a mapping with key thing_name for callobject in chainmap with
namespace handling.
"""
namespaces = reversed(thing_name.split('.'))
lstname = []
for name in namespaces:
lstname.insert(0, name)
strname = '.'.join(lstname)
... |
def _execute_pillar(pillar_name, run_type):
'''
Run one or more nagios plugins from pillar data and get the result of run_type
The pillar have to be in this format:
------
webserver:
Ping_google:
- check_icmp: 8.8.8.8
- check_icmp: google.com
Load:
... | def function[_execute_pillar, parameter[pillar_name, run_type]]:
constant[
Run one or more nagios plugins from pillar data and get the result of run_type
The pillar have to be in this format:
------
webserver:
Ping_google:
- check_icmp: 8.8.8.8
- check_icmp: googl... | keyword[def] identifier[_execute_pillar] ( identifier[pillar_name] , identifier[run_type] ):
literal[string]
identifier[groups] = identifier[__salt__] [ literal[string] ]( identifier[pillar_name] )
identifier[data] ={}
keyword[for] identifier[group] keyword[in] identifier[groups] :
i... | def _execute_pillar(pillar_name, run_type):
"""
Run one or more nagios plugins from pillar data and get the result of run_type
The pillar have to be in this format:
------
webserver:
Ping_google:
- check_icmp: 8.8.8.8
- check_icmp: google.com
Load:
... |
def system_call(command):
"""Run a command and return stdout.
Would be better to use subprocess.check_output, but this works on 2.6,
which is still the system Python on CentOS 7."""
p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
return p.stdout.read() | def function[system_call, parameter[command]]:
constant[Run a command and return stdout.
Would be better to use subprocess.check_output, but this works on 2.6,
which is still the system Python on CentOS 7.]
variable[p] assign[=] call[name[subprocess].Popen, parameter[list[[<ast.Name object at 0x7da... | keyword[def] identifier[system_call] ( identifier[command] ):
literal[string]
identifier[p] = identifier[subprocess] . identifier[Popen] ([ identifier[command] ], identifier[stdout] = identifier[subprocess] . identifier[PIPE] , identifier[shell] = keyword[True] )
keyword[return] identifier[p] . identifier[... | def system_call(command):
"""Run a command and return stdout.
Would be better to use subprocess.check_output, but this works on 2.6,
which is still the system Python on CentOS 7."""
p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
return p.stdout.read() |
def query(self, method_verb, endpoint, authenticate=False,
*args, **kwargs):
"""
Queries exchange using given data. Defaults to unauthenticated query.
:param method_verb: valid request type (PUT, GET, POST etc)
:param endpoint: endpoint path for the resource to query, sans ... | def function[query, parameter[self, method_verb, endpoint, authenticate]]:
constant[
Queries exchange using given data. Defaults to unauthenticated query.
:param method_verb: valid request type (PUT, GET, POST etc)
:param endpoint: endpoint path for the resource to query, sans the url &
... | keyword[def] identifier[query] ( identifier[self] , identifier[method_verb] , identifier[endpoint] , identifier[authenticate] = keyword[False] ,
* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[version] :
identifier[endpoint_path] ... | def query(self, method_verb, endpoint, authenticate=False, *args, **kwargs):
"""
Queries exchange using given data. Defaults to unauthenticated query.
:param method_verb: valid request type (PUT, GET, POST etc)
:param endpoint: endpoint path for the resource to query, sans the url &
... |
def insert(self, cache_key, paths, overwrite=False):
"""Cache the output of a build.
By default, checks cache.has(key) first, only proceeding to create and insert an artifact
if it is not already in the cache (though `overwrite` can be used to skip the check and
unconditionally insert).
:param Cac... | def function[insert, parameter[self, cache_key, paths, overwrite]]:
constant[Cache the output of a build.
By default, checks cache.has(key) first, only proceeding to create and insert an artifact
if it is not already in the cache (though `overwrite` can be used to skip the check and
unconditionally... | keyword[def] identifier[insert] ( identifier[self] , identifier[cache_key] , identifier[paths] , identifier[overwrite] = keyword[False] ):
literal[string]
identifier[missing_files] =[ identifier[f] keyword[for] identifier[f] keyword[in] identifier[paths] keyword[if] keyword[not] identifier[os] . ide... | def insert(self, cache_key, paths, overwrite=False):
"""Cache the output of a build.
By default, checks cache.has(key) first, only proceeding to create and insert an artifact
if it is not already in the cache (though `overwrite` can be used to skip the check and
unconditionally insert).
:param Cac... |
def predict(self, X, y=None, output="margin", tree_limit=None):
""" A consistent interface to make predictions from this model.
Parameters
----------
tree_limit : None (default) or int
Limit the number of trees used by the model. By default None means no use the limit of th... | def function[predict, parameter[self, X, y, output, tree_limit]]:
constant[ A consistent interface to make predictions from this model.
Parameters
----------
tree_limit : None (default) or int
Limit the number of trees used by the model. By default None means no use the lim... | keyword[def] identifier[predict] ( identifier[self] , identifier[X] , identifier[y] = keyword[None] , identifier[output] = literal[string] , identifier[tree_limit] = keyword[None] ):
literal[string]
keyword[if] identifier[tree_limit] keyword[is] keyword[None] :
identifier[... | def predict(self, X, y=None, output='margin', tree_limit=None):
""" A consistent interface to make predictions from this model.
Parameters
----------
tree_limit : None (default) or int
Limit the number of trees used by the model. By default None means no use the limit of the
... |
def _populate_spelling_error(word,
suggestions,
contents,
line_offset,
column_offset,
message_start):
"""Create a LinterFailure for word.
This function takes suggesti... | def function[_populate_spelling_error, parameter[word, suggestions, contents, line_offset, column_offset, message_start]]:
constant[Create a LinterFailure for word.
This function takes suggestions from :suggestions: and uses it to
populate the message and candidate replacement. The replacement will
... | keyword[def] identifier[_populate_spelling_error] ( identifier[word] ,
identifier[suggestions] ,
identifier[contents] ,
identifier[line_offset] ,
identifier[column_offset] ,
identifier[message_start] ):
literal[string]
identifier[error_line] = identifier[contents] [ identifier[line_offset] ]
keyw... | def _populate_spelling_error(word, suggestions, contents, line_offset, column_offset, message_start):
"""Create a LinterFailure for word.
This function takes suggestions from :suggestions: and uses it to
populate the message and candidate replacement. The replacement will
be a line in :contents:, as de... |
def terminal(self, text):
"""terminal = '"' . (printable - '"') + . '"'
| "'" . (printable - "'") + . "'" ;
"""
self._attempting(text)
return alternation([
concatenation([
'"',
one_or_more(
exclusion(self.printable, '"')
),
'"'
], ign... | def function[terminal, parameter[self, text]]:
constant[terminal = '"' . (printable - '"') + . '"'
| "'" . (printable - "'") + . "'" ;
]
call[name[self]._attempting, parameter[name[text]]]
return[call[call[call[name[alternation], parameter[list[[<ast.Call object at 0x7da1b01abdc0... | keyword[def] identifier[terminal] ( identifier[self] , identifier[text] ):
literal[string]
identifier[self] . identifier[_attempting] ( identifier[text] )
keyword[return] identifier[alternation] ([
identifier[concatenation] ([
literal[string] ,
identifier[one_or_more] (
identifier... | def terminal(self, text):
"""terminal = '"' . (printable - '"') + . '"'
| "'" . (printable - "'") + . "'" ;
"""
self._attempting(text)
return alternation([concatenation(['"', one_or_more(exclusion(self.printable, '"')), '"'], ignore_whitespace=False), concatenation(["'", one_or_more(excl... |
def subs(self, path):
"""
Search the strings in a config file for a substitutable value, e.g.
"morphologies_dir": "$COMPONENT_DIR/morphologies",
"""
#print_v('Checking for: \n %s, \n %s \n in %s'%(self.substitutes,self.init_substitutes,path))
if type(path) == ... | def function[subs, parameter[self, path]]:
constant[
Search the strings in a config file for a substitutable value, e.g.
"morphologies_dir": "$COMPONENT_DIR/morphologies",
]
if <ast.BoolOp object at 0x7da1b19cbc70> begin[:]
return[name[path]]
for taget[na... | keyword[def] identifier[subs] ( identifier[self] , identifier[path] ):
literal[string]
keyword[if] identifier[type] ( identifier[path] )== identifier[int] keyword[or] identifier[type] ( identifier[path] )== identifier[float] :
keyword[return] identifier[path]
key... | def subs(self, path):
"""
Search the strings in a config file for a substitutable value, e.g.
"morphologies_dir": "$COMPONENT_DIR/morphologies",
"""
#print_v('Checking for: \n %s, \n %s \n in %s'%(self.substitutes,self.init_substitutes,path))
if type(path) == int or type(... |
def _bq_cast(string_field, bq_type):
"""
Helper method that casts a BigQuery row to the appropriate data types.
This is useful because BigQuery returns all fields as strings.
"""
if string_field is None:
return None
elif bq_type == 'INTEGER':
return int(string_field)
elif bq_... | def function[_bq_cast, parameter[string_field, bq_type]]:
constant[
Helper method that casts a BigQuery row to the appropriate data types.
This is useful because BigQuery returns all fields as strings.
]
if compare[name[string_field] is constant[None]] begin[:]
return[constant[None]] | keyword[def] identifier[_bq_cast] ( identifier[string_field] , identifier[bq_type] ):
literal[string]
keyword[if] identifier[string_field] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[elif] identifier[bq_type] == literal[string] :
keyword[return] identifie... | def _bq_cast(string_field, bq_type):
"""
Helper method that casts a BigQuery row to the appropriate data types.
This is useful because BigQuery returns all fields as strings.
"""
if string_field is None:
return None # depends on [control=['if'], data=[]]
elif bq_type == 'INTEGER':
... |
async def house_status_monitor_enable(pyvlx):
"""Enable house status monitor."""
status_monitor_enable = HouseStatusMonitorEnable(pyvlx=pyvlx)
await status_monitor_enable.do_api_call()
if not status_monitor_enable.success:
raise PyVLXException("Unable enable house status monitor.") | <ast.AsyncFunctionDef object at 0x7da2044c2e90> | keyword[async] keyword[def] identifier[house_status_monitor_enable] ( identifier[pyvlx] ):
literal[string]
identifier[status_monitor_enable] = identifier[HouseStatusMonitorEnable] ( identifier[pyvlx] = identifier[pyvlx] )
keyword[await] identifier[status_monitor_enable] . identifier[do_api_call] ()
... | async def house_status_monitor_enable(pyvlx):
"""Enable house status monitor."""
status_monitor_enable = HouseStatusMonitorEnable(pyvlx=pyvlx)
await status_monitor_enable.do_api_call()
if not status_monitor_enable.success:
raise PyVLXException('Unable enable house status monitor.') # depends on... |
def build_def_use(graph, lparams):
"""
Builds the Def-Use and Use-Def (DU/UD) chains of the variables of the
method.
"""
analysis = reach_def_analysis(graph, lparams)
UD = defaultdict(list)
for node in graph.rpo:
for i, ins in node.get_loc_with_ins():
for var in ins.get_... | def function[build_def_use, parameter[graph, lparams]]:
constant[
Builds the Def-Use and Use-Def (DU/UD) chains of the variables of the
method.
]
variable[analysis] assign[=] call[name[reach_def_analysis], parameter[name[graph], name[lparams]]]
variable[UD] assign[=] call[name[defaul... | keyword[def] identifier[build_def_use] ( identifier[graph] , identifier[lparams] ):
literal[string]
identifier[analysis] = identifier[reach_def_analysis] ( identifier[graph] , identifier[lparams] )
identifier[UD] = identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[node] keyw... | def build_def_use(graph, lparams):
"""
Builds the Def-Use and Use-Def (DU/UD) chains of the variables of the
method.
"""
analysis = reach_def_analysis(graph, lparams)
UD = defaultdict(list)
for node in graph.rpo:
for (i, ins) in node.get_loc_with_ins():
for var in ins.get... |
def _handle_inotify_event(self, wd):
"""Handle a series of events coming-in from inotify."""
b = os.read(wd, 1024)
if not b:
return
self.__buffer += b
while 1:
length = len(self.__buffer)
if length < _STRUCT_HEADER_LENGTH:
_... | def function[_handle_inotify_event, parameter[self, wd]]:
constant[Handle a series of events coming-in from inotify.]
variable[b] assign[=] call[name[os].read, parameter[name[wd], constant[1024]]]
if <ast.UnaryOp object at 0x7da1b0980490> begin[:]
return[None]
<ast.AugAssign object a... | keyword[def] identifier[_handle_inotify_event] ( identifier[self] , identifier[wd] ):
literal[string]
identifier[b] = identifier[os] . identifier[read] ( identifier[wd] , literal[int] )
keyword[if] keyword[not] identifier[b] :
keyword[return]
identifier[self] . i... | def _handle_inotify_event(self, wd):
"""Handle a series of events coming-in from inotify."""
b = os.read(wd, 1024)
if not b:
return # depends on [control=['if'], data=[]]
self.__buffer += b
while 1:
length = len(self.__buffer)
if length < _STRUCT_HEADER_LENGTH:
_... |
def combine_mv_and_lv(mv, lv):
"""Combine MV and LV grid topology in PyPSA format
"""
combined = {
c: pd.concat([mv[c], lv[c]], axis=0) for c in list(lv.keys())
}
combined['Transformer'] = mv['Transformer']
return combined | def function[combine_mv_and_lv, parameter[mv, lv]]:
constant[Combine MV and LV grid topology in PyPSA format
]
variable[combined] assign[=] <ast.DictComp object at 0x7da1b0369090>
call[name[combined]][constant[Transformer]] assign[=] call[name[mv]][constant[Transformer]]
return[name[comb... | keyword[def] identifier[combine_mv_and_lv] ( identifier[mv] , identifier[lv] ):
literal[string]
identifier[combined] ={
identifier[c] : identifier[pd] . identifier[concat] ([ identifier[mv] [ identifier[c] ], identifier[lv] [ identifier[c] ]], identifier[axis] = literal[int] ) keyword[for] identifie... | def combine_mv_and_lv(mv, lv):
"""Combine MV and LV grid topology in PyPSA format
"""
combined = {c: pd.concat([mv[c], lv[c]], axis=0) for c in list(lv.keys())}
combined['Transformer'] = mv['Transformer']
return combined |
def time_emd(emd_type, data):
"""Time an EMD command with the given data as arguments"""
emd = {
'cause': _CAUSE_EMD,
'effect': pyphi.subsystem.effect_emd,
'hamming': pyphi.utils.hamming_emd
}[emd_type]
def statement():
for (d1, d2) in data:
emd(d1, d2)
... | def function[time_emd, parameter[emd_type, data]]:
constant[Time an EMD command with the given data as arguments]
variable[emd] assign[=] call[dictionary[[<ast.Constant object at 0x7da18dc073d0>, <ast.Constant object at 0x7da18dc058a0>, <ast.Constant object at 0x7da18dc05120>], [<ast.Name object at 0x7d... | keyword[def] identifier[time_emd] ( identifier[emd_type] , identifier[data] ):
literal[string]
identifier[emd] ={
literal[string] : identifier[_CAUSE_EMD] ,
literal[string] : identifier[pyphi] . identifier[subsystem] . identifier[effect_emd] ,
literal[string] : identifier[pyphi] . identifie... | def time_emd(emd_type, data):
"""Time an EMD command with the given data as arguments"""
emd = {'cause': _CAUSE_EMD, 'effect': pyphi.subsystem.effect_emd, 'hamming': pyphi.utils.hamming_emd}[emd_type]
def statement():
for (d1, d2) in data:
emd(d1, d2) # depends on [control=['for'], dat... |
def exit(self):
"""
Cleanup pid file at exit.
"""
self.logger.warning("Stopping daemon.")
os.remove(self.pid)
sys.exit(0) | def function[exit, parameter[self]]:
constant[
Cleanup pid file at exit.
]
call[name[self].logger.warning, parameter[constant[Stopping daemon.]]]
call[name[os].remove, parameter[name[self].pid]]
call[name[sys].exit, parameter[constant[0]]] | keyword[def] identifier[exit] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logger] . identifier[warning] ( literal[string] )
identifier[os] . identifier[remove] ( identifier[self] . identifier[pid] )
identifier[sys] . identifier[exit] ( literal[int] ) | def exit(self):
"""
Cleanup pid file at exit.
"""
self.logger.warning('Stopping daemon.')
os.remove(self.pid)
sys.exit(0) |
def setup_formats(self):
"""
Inspects its methods to see what it can convert from and to
"""
methods = self.get_methods()
for m in methods:
#Methods named "from_X" will be assumed to convert from format X to the common format
if m.startswith("from_"):
... | def function[setup_formats, parameter[self]]:
constant[
Inspects its methods to see what it can convert from and to
]
variable[methods] assign[=] call[name[self].get_methods, parameter[]]
for taget[name[m]] in starred[name[methods]] begin[:]
if call[name[m].starts... | keyword[def] identifier[setup_formats] ( identifier[self] ):
literal[string]
identifier[methods] = identifier[self] . identifier[get_methods] ()
keyword[for] identifier[m] keyword[in] identifier[methods] :
keyword[if] identifier[m] . identifier[startswith] ( liter... | def setup_formats(self):
"""
Inspects its methods to see what it can convert from and to
"""
methods = self.get_methods()
for m in methods:
#Methods named "from_X" will be assumed to convert from format X to the common format
if m.startswith('from_'):
self.input_f... |
def search_users(self, user_name):
"""Searches for users via provisioning API.
If you get back an error 999, then the provisioning API is not enabled.
:param user_name: name of user to be searched for
:returns: list of usernames that contain user_name as substring
:raises: HTTP... | def function[search_users, parameter[self, user_name]]:
constant[Searches for users via provisioning API.
If you get back an error 999, then the provisioning API is not enabled.
:param user_name: name of user to be searched for
:returns: list of usernames that contain user_name as subs... | keyword[def] identifier[search_users] ( identifier[self] , identifier[user_name] ):
literal[string]
identifier[action_path] = literal[string]
keyword[if] identifier[user_name] :
identifier[action_path] += literal[string] . identifier[format] ( identifier[user_name] )
... | def search_users(self, user_name):
"""Searches for users via provisioning API.
If you get back an error 999, then the provisioning API is not enabled.
:param user_name: name of user to be searched for
:returns: list of usernames that contain user_name as substring
:raises: HTTPResp... |
def on_event(self, evt, is_final):
""" this is invoked from in response to COM PumpWaitingMessages - different thread """
for msg in XmlHelper.message_iter(evt):
# Single security element in historical request
node = msg.GetElement('securityData')
if node.HasElement('... | def function[on_event, parameter[self, evt, is_final]]:
constant[ this is invoked from in response to COM PumpWaitingMessages - different thread ]
for taget[name[msg]] in starred[call[name[XmlHelper].message_iter, parameter[name[evt]]]] begin[:]
variable[node] assign[=] call[name[msg].Ge... | keyword[def] identifier[on_event] ( identifier[self] , identifier[evt] , identifier[is_final] ):
literal[string]
keyword[for] identifier[msg] keyword[in] identifier[XmlHelper] . identifier[message_iter] ( identifier[evt] ):
identifier[node] = identifier[msg] . identifier[Ge... | def on_event(self, evt, is_final):
""" this is invoked from in response to COM PumpWaitingMessages - different thread """
for msg in XmlHelper.message_iter(evt):
# Single security element in historical request
node = msg.GetElement('securityData')
if node.HasElement('securityError'):
... |
def sample(self, sample_indices=None, num_samples=1):
""" returns samples according to the KDE
Parameters
----------
sample_inices: list of ints
Indices into the training data used as centers for the samples
num_samples: int
if samples_indices is None, this specifies how many samples
... | def function[sample, parameter[self, sample_indices, num_samples]]:
constant[ returns samples according to the KDE
Parameters
----------
sample_inices: list of ints
Indices into the training data used as centers for the samples
num_samples: int
if samples_indices is None, this sp... | keyword[def] identifier[sample] ( identifier[self] , identifier[sample_indices] = keyword[None] , identifier[num_samples] = literal[int] ):
literal[string]
keyword[if] identifier[sample_indices] keyword[is] keyword[None] :
identifier[sample_indices] = identifier[np] . identifier[random] . identifier[cho... | def sample(self, sample_indices=None, num_samples=1):
""" returns samples according to the KDE
Parameters
----------
sample_inices: list of ints
Indices into the training data used as centers for the samples
num_samples: int
if samples_indices is None, this specifies how many samples... |
def shutdown(self):
""" Shuts down the daemon process.
"""
if not self._exited:
self._exited = True
# signal task runner to terminate via SIGTERM
if self._task_runner.is_alive():
self._task_runner.terminate()
# if command... | def function[shutdown, parameter[self]]:
constant[ Shuts down the daemon process.
]
if <ast.UnaryOp object at 0x7da18bc73eb0> begin[:]
name[self]._exited assign[=] constant[True]
if call[name[self]._task_runner.is_alive, parameter[]] begin[:]
... | keyword[def] identifier[shutdown] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_exited] :
identifier[self] . identifier[_exited] = keyword[True]
keyword[if] identifier[self] . identifier[_task_runner] . ide... | def shutdown(self):
""" Shuts down the daemon process.
"""
if not self._exited:
self._exited = True
# signal task runner to terminate via SIGTERM
if self._task_runner.is_alive():
self._task_runner.terminate()
# if command server is running, then block ... |
def capitalize_unicode_name(s):
"""
Turns a string such as 'capital delta' into the shortened,
capitalized version, in this case simply 'Delta'. Used as a
transform in sanitize_identifier.
"""
index = s.find('capital')
if index == -1: return s
tail = s[index:].replace('capital', '').stri... | def function[capitalize_unicode_name, parameter[s]]:
constant[
Turns a string such as 'capital delta' into the shortened,
capitalized version, in this case simply 'Delta'. Used as a
transform in sanitize_identifier.
]
variable[index] assign[=] call[name[s].find, parameter[constant[capita... | keyword[def] identifier[capitalize_unicode_name] ( identifier[s] ):
literal[string]
identifier[index] = identifier[s] . identifier[find] ( literal[string] )
keyword[if] identifier[index] ==- literal[int] : keyword[return] identifier[s]
identifier[tail] = identifier[s] [ identifier[index] :]. i... | def capitalize_unicode_name(s):
"""
Turns a string such as 'capital delta' into the shortened,
capitalized version, in this case simply 'Delta'. Used as a
transform in sanitize_identifier.
"""
index = s.find('capital')
if index == -1:
return s # depends on [control=['if'], data=[]]
... |
def _scrub_participant_table(path_to_data):
"""Scrub PII from the given participant table."""
path = os.path.join(path_to_data, "participant.csv")
with open_for_csv(path, "r") as input, open("{}.0".format(path), "w") as output:
reader = csv.reader(input)
writer = csv.writer(output)
h... | def function[_scrub_participant_table, parameter[path_to_data]]:
constant[Scrub PII from the given participant table.]
variable[path] assign[=] call[name[os].path.join, parameter[name[path_to_data], constant[participant.csv]]]
with call[name[open_for_csv], parameter[name[path], constant[r]]] beg... | keyword[def] identifier[_scrub_participant_table] ( identifier[path_to_data] ):
literal[string]
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( identifier[path_to_data] , literal[string] )
keyword[with] identifier[open_for_csv] ( identifier[path] , literal[string] ) keyword[... | def _scrub_participant_table(path_to_data):
"""Scrub PII from the given participant table."""
path = os.path.join(path_to_data, 'participant.csv')
with open_for_csv(path, 'r') as input, open('{}.0'.format(path), 'w') as output:
reader = csv.reader(input)
writer = csv.writer(output)
h... |
def _change_height(self, ax, new_value):
"""Make bars in horizontal bar chart thinner"""
for patch in ax.patches:
current_height = patch.get_height()
diff = current_height - new_value
# we change the bar height
patch.set_height(new_value)
# w... | def function[_change_height, parameter[self, ax, new_value]]:
constant[Make bars in horizontal bar chart thinner]
for taget[name[patch]] in starred[name[ax].patches] begin[:]
variable[current_height] assign[=] call[name[patch].get_height, parameter[]]
variable[diff] assig... | keyword[def] identifier[_change_height] ( identifier[self] , identifier[ax] , identifier[new_value] ):
literal[string]
keyword[for] identifier[patch] keyword[in] identifier[ax] . identifier[patches] :
identifier[current_height] = identifier[patch] . identifier[get_height] ()
... | def _change_height(self, ax, new_value):
"""Make bars in horizontal bar chart thinner"""
for patch in ax.patches:
current_height = patch.get_height()
diff = current_height - new_value
# we change the bar height
patch.set_height(new_value)
# we recenter the bar
pat... |
def log_accept(self, block_id, vtxindex, opcode, op_data):
"""
Log an accepted operation
"""
log.debug("ACCEPT op {} at ({}, {}) ({})".format(opcode, block_id, vtxindex, json.dumps(op_data, sort_keys=True))) | def function[log_accept, parameter[self, block_id, vtxindex, opcode, op_data]]:
constant[
Log an accepted operation
]
call[name[log].debug, parameter[call[constant[ACCEPT op {} at ({}, {}) ({})].format, parameter[name[opcode], name[block_id], name[vtxindex], call[name[json].dumps, parame... | keyword[def] identifier[log_accept] ( identifier[self] , identifier[block_id] , identifier[vtxindex] , identifier[opcode] , identifier[op_data] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] . identifier[format] ( identifier[opcode] , identifier[block_id] , identifier[vtxi... | def log_accept(self, block_id, vtxindex, opcode, op_data):
"""
Log an accepted operation
"""
log.debug('ACCEPT op {} at ({}, {}) ({})'.format(opcode, block_id, vtxindex, json.dumps(op_data, sort_keys=True))) |
def sparsify_rows(x, quantile=0.01):
'''
Return a row-sparse matrix approximating the input `x`.
Parameters
----------
x : np.ndarray [ndim <= 2]
The input matrix to sparsify.
quantile : float in [0, 1.0)
Percentage of magnitude to discard in each row of `x`
Returns
--... | def function[sparsify_rows, parameter[x, quantile]]:
constant[
Return a row-sparse matrix approximating the input `x`.
Parameters
----------
x : np.ndarray [ndim <= 2]
The input matrix to sparsify.
quantile : float in [0, 1.0)
Percentage of magnitude to discard in each row ... | keyword[def] identifier[sparsify_rows] ( identifier[x] , identifier[quantile] = literal[int] ):
literal[string]
keyword[if] identifier[x] . identifier[ndim] == literal[int] :
identifier[x] = identifier[x] . identifier[reshape] (( literal[int] ,- literal[int] ))
keyword[elif] identifier[x]... | def sparsify_rows(x, quantile=0.01):
"""
Return a row-sparse matrix approximating the input `x`.
Parameters
----------
x : np.ndarray [ndim <= 2]
The input matrix to sparsify.
quantile : float in [0, 1.0)
Percentage of magnitude to discard in each row of `x`
Returns
--... |
def _local_update(self, rdict):
"""Call this with a response dictionary to update instance attrs.
If the response has only valid keys, stash meta_data, replace __dict__,
and reassign meta_data.
:param rdict: response attributes derived from server JSON
"""
sanitized = s... | def function[_local_update, parameter[self, rdict]]:
constant[Call this with a response dictionary to update instance attrs.
If the response has only valid keys, stash meta_data, replace __dict__,
and reassign meta_data.
:param rdict: response attributes derived from server JSON
... | keyword[def] identifier[_local_update] ( identifier[self] , identifier[rdict] ):
literal[string]
identifier[sanitized] = identifier[self] . identifier[_check_keys] ( identifier[rdict] )
identifier[temp_meta] = identifier[self] . identifier[_meta_data]
identifier[self] . identifie... | def _local_update(self, rdict):
"""Call this with a response dictionary to update instance attrs.
If the response has only valid keys, stash meta_data, replace __dict__,
and reassign meta_data.
:param rdict: response attributes derived from server JSON
"""
sanitized = self._che... |
def edit(self,
billing_email=None,
company=None,
email=None,
location=None,
name=None):
"""Edit this organization.
:param str billing_email: (optional) Billing email address (private)
:param str company: (optional)
:param ... | def function[edit, parameter[self, billing_email, company, email, location, name]]:
constant[Edit this organization.
:param str billing_email: (optional) Billing email address (private)
:param str company: (optional)
:param str email: (optional) Public email address
:param str l... | keyword[def] identifier[edit] ( identifier[self] ,
identifier[billing_email] = keyword[None] ,
identifier[company] = keyword[None] ,
identifier[email] = keyword[None] ,
identifier[location] = keyword[None] ,
identifier[name] = keyword[None] ):
literal[string]
identifier[json] = keyword[None]
... | def edit(self, billing_email=None, company=None, email=None, location=None, name=None):
"""Edit this organization.
:param str billing_email: (optional) Billing email address (private)
:param str company: (optional)
:param str email: (optional) Public email address
:param str locatio... |
def _skip_children(self, check_name, results):
"""
Recursively skip the children of check_name (presumably because check_name
did not pass).
"""
for name, description in self.child_map[check_name]:
if results[name] is None:
results[name] = CheckResult(... | def function[_skip_children, parameter[self, check_name, results]]:
constant[
Recursively skip the children of check_name (presumably because check_name
did not pass).
]
for taget[tuple[[<ast.Name object at 0x7da1b16b0790>, <ast.Name object at 0x7da1b16b1d50>]]] in starred[call[n... | keyword[def] identifier[_skip_children] ( identifier[self] , identifier[check_name] , identifier[results] ):
literal[string]
keyword[for] identifier[name] , identifier[description] keyword[in] identifier[self] . identifier[child_map] [ identifier[check_name] ]:
keyword[if] identifi... | def _skip_children(self, check_name, results):
"""
Recursively skip the children of check_name (presumably because check_name
did not pass).
"""
for (name, description) in self.child_map[check_name]:
if results[name] is None:
results[name] = CheckResult(name=name, des... |
def play(state):
""" Play sound for a given state.
:param state: a State value.
"""
filename = None
if state == SoundService.State.welcome:
filename = "pad_glow_welcome1.wav"
elif state == SoundService.State.goodbye:
filename = "pad_glow_power_off... | def function[play, parameter[state]]:
constant[ Play sound for a given state.
:param state: a State value.
]
variable[filename] assign[=] constant[None]
if compare[name[state] equal[==] name[SoundService].State.welcome] begin[:]
variable[filename] assign[=] const... | keyword[def] identifier[play] ( identifier[state] ):
literal[string]
identifier[filename] = keyword[None]
keyword[if] identifier[state] == identifier[SoundService] . identifier[State] . identifier[welcome] :
identifier[filename] = literal[string]
keyword[elif] ide... | def play(state):
""" Play sound for a given state.
:param state: a State value.
"""
filename = None
if state == SoundService.State.welcome:
filename = 'pad_glow_welcome1.wav' # depends on [control=['if'], data=[]]
elif state == SoundService.State.goodbye:
filename = 'pa... |
def send(self, data):
"""Send data to socket."""
# send message
_LOGGER.debug("send: " + data)
self.socket.send(data.encode('ascii'))
# sleep needed to prevent flooding the GC100 with sends
sleep(.01) | def function[send, parameter[self, data]]:
constant[Send data to socket.]
call[name[_LOGGER].debug, parameter[binary_operation[constant[send: ] + name[data]]]]
call[name[self].socket.send, parameter[call[name[data].encode, parameter[constant[ascii]]]]]
call[name[sleep], parameter[constan... | keyword[def] identifier[send] ( identifier[self] , identifier[data] ):
literal[string]
identifier[_LOGGER] . identifier[debug] ( literal[string] + identifier[data] )
identifier[self] . identifier[socket] . identifier[send] ( identifier[data] . identifier[encode] ( literal[stri... | def send(self, data):
"""Send data to socket.""" # send message
_LOGGER.debug('send: ' + data)
self.socket.send(data.encode('ascii')) # sleep needed to prevent flooding the GC100 with sends
sleep(0.01) |
def _write(self, session, openFile, replaceParamFile):
"""
Replace Param File Write to File Method
"""
# Retrieve TargetParameter objects
targets = self.targetParameters
# Write lines
openFile.write('%s\n' % self.numParameters)
for target in targets:
... | def function[_write, parameter[self, session, openFile, replaceParamFile]]:
constant[
Replace Param File Write to File Method
]
variable[targets] assign[=] name[self].targetParameters
call[name[openFile].write, parameter[binary_operation[constant[%s
] <ast.Mod object at 0x7da2590... | keyword[def] identifier[_write] ( identifier[self] , identifier[session] , identifier[openFile] , identifier[replaceParamFile] ):
literal[string]
identifier[targets] = identifier[self] . identifier[targetParameters]
identifier[openFile] . identifier[write] ( literal[str... | def _write(self, session, openFile, replaceParamFile):
"""
Replace Param File Write to File Method
"""
# Retrieve TargetParameter objects
targets = self.targetParameters
# Write lines
openFile.write('%s\n' % self.numParameters)
for target in targets:
openFile.write('%s %s... |
def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ
"""
Parameters
----------
states : list
the stack outputs from RNN, which consists of output from each time step (TNC).
Returns
--------
loss : NDArray
loss tensor wi... | def function[hybrid_forward, parameter[self, F]]:
constant[
Parameters
----------
states : list
the stack outputs from RNN, which consists of output from each time step (TNC).
Returns
--------
loss : NDArray
loss tensor with shape (batch_s... | keyword[def] identifier[hybrid_forward] ( identifier[self] , identifier[F] ,* identifier[states] ):
literal[string]
keyword[if] identifier[self] . identifier[_beta] != literal[int] :
keyword[if] identifier[states] :
identifier[means] =[ identifier[self] . id... | def hybrid_forward(self, F, *states): # pylint: disable=arguments-differ
'\n Parameters\n ----------\n states : list\n the stack outputs from RNN, which consists of output from each time step (TNC).\n\n Returns\n --------\n loss : NDArray\n loss tenso... |
def start_file_logger(filename, rank, name='parsl', level=logging.DEBUG, format_string=None):
"""Add a stream log handler.
Args:
- filename (string): Name of the file to write logs to
- name (string): Logger name
- level (logging.LEVEL): Set the logging level.
- format_string (s... | def function[start_file_logger, parameter[filename, rank, name, level, format_string]]:
constant[Add a stream log handler.
Args:
- filename (string): Name of the file to write logs to
- name (string): Logger name
- level (logging.LEVEL): Set the logging level.
- format_strin... | keyword[def] identifier[start_file_logger] ( identifier[filename] , identifier[rank] , identifier[name] = literal[string] , identifier[level] = identifier[logging] . identifier[DEBUG] , identifier[format_string] = keyword[None] ):
literal[string]
keyword[try] :
identifier[os] . identifier[makedir... | def start_file_logger(filename, rank, name='parsl', level=logging.DEBUG, format_string=None):
"""Add a stream log handler.
Args:
- filename (string): Name of the file to write logs to
- name (string): Logger name
- level (logging.LEVEL): Set the logging level.
- format_string (s... |
def mtotdev(data, rate=1.0, data_type="phase", taus=None):
""" PRELIMINARY - REQUIRES FURTHER TESTING.
Modified Total deviation.
Better confidence at long averages for modified Allan
FIXME: bias-correction http://www.wriley.com/CI2.pdf page 6
The variance is scaled up (divided by t... | def function[mtotdev, parameter[data, rate, data_type, taus]]:
constant[ PRELIMINARY - REQUIRES FURTHER TESTING.
Modified Total deviation.
Better confidence at long averages for modified Allan
FIXME: bias-correction http://www.wriley.com/CI2.pdf page 6
The variance is scaled up... | keyword[def] identifier[mtotdev] ( identifier[data] , identifier[rate] = literal[int] , identifier[data_type] = literal[string] , identifier[taus] = keyword[None] ):
literal[string]
identifier[phase] = identifier[input_to_phase] ( identifier[data] , identifier[rate] , identifier[data_type] )
( identifi... | def mtotdev(data, rate=1.0, data_type='phase', taus=None):
""" PRELIMINARY - REQUIRES FURTHER TESTING.
Modified Total deviation.
Better confidence at long averages for modified Allan
FIXME: bias-correction http://www.wriley.com/CI2.pdf page 6
The variance is scaled up (divided by t... |
def clean_translated_locales(configuration, langs=None):
"""
Strips out the warning from all translated po files
about being an English source file.
"""
if not langs:
langs = configuration.translated_locales
for locale in langs:
clean_locale(configuration, locale) | def function[clean_translated_locales, parameter[configuration, langs]]:
constant[
Strips out the warning from all translated po files
about being an English source file.
]
if <ast.UnaryOp object at 0x7da20e9b2b60> begin[:]
variable[langs] assign[=] name[configuration].transl... | keyword[def] identifier[clean_translated_locales] ( identifier[configuration] , identifier[langs] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[langs] :
identifier[langs] = identifier[configuration] . identifier[translated_locales]
keyword[for] identifier[locale] ... | def clean_translated_locales(configuration, langs=None):
"""
Strips out the warning from all translated po files
about being an English source file.
"""
if not langs:
langs = configuration.translated_locales # depends on [control=['if'], data=[]]
for locale in langs:
clean_local... |
def get_cli(cls) -> click.Group:
"""Add a :mod:`click` main function to use as a command line interface."""
main = super().get_cli()
cls._cli_add_flask(main)
return main | def function[get_cli, parameter[cls]]:
constant[Add a :mod:`click` main function to use as a command line interface.]
variable[main] assign[=] call[call[name[super], parameter[]].get_cli, parameter[]]
call[name[cls]._cli_add_flask, parameter[name[main]]]
return[name[main]] | keyword[def] identifier[get_cli] ( identifier[cls] )-> identifier[click] . identifier[Group] :
literal[string]
identifier[main] = identifier[super] (). identifier[get_cli] ()
identifier[cls] . identifier[_cli_add_flask] ( identifier[main] )
keyword[return] identifier[main] | def get_cli(cls) -> click.Group:
"""Add a :mod:`click` main function to use as a command line interface."""
main = super().get_cli()
cls._cli_add_flask(main)
return main |
def filter_slow_requests(slowness):
"""Filter :class:`.Line` objects by their response time.
:param slowness: minimum time, in milliseconds, a server needs to answer
a request. If the server takes more time than that the log line is
accepted.
:type slowness: string
:returns: a function that... | def function[filter_slow_requests, parameter[slowness]]:
constant[Filter :class:`.Line` objects by their response time.
:param slowness: minimum time, in milliseconds, a server needs to answer
a request. If the server takes more time than that the log line is
accepted.
:type slowness: strin... | keyword[def] identifier[filter_slow_requests] ( identifier[slowness] ):
literal[string]
keyword[def] identifier[filter_func] ( identifier[log_line] ):
identifier[slowness_int] = identifier[int] ( identifier[slowness] )
keyword[return] identifier[slowness_int] <= identifier[log_line] . i... | def filter_slow_requests(slowness):
"""Filter :class:`.Line` objects by their response time.
:param slowness: minimum time, in milliseconds, a server needs to answer
a request. If the server takes more time than that the log line is
accepted.
:type slowness: string
:returns: a function that... |
def output_to_bar(self, message, comma=True):
"""
Outputs data to stdout, without buffering.
message: A string containing the data to be output.
comma: Whether or not a comma should be placed at the end of the output.
"""
if comma:
message += ','
sys.... | def function[output_to_bar, parameter[self, message, comma]]:
constant[
Outputs data to stdout, without buffering.
message: A string containing the data to be output.
comma: Whether or not a comma should be placed at the end of the output.
]
if name[comma] begin[:]
... | keyword[def] identifier[output_to_bar] ( identifier[self] , identifier[message] , identifier[comma] = keyword[True] ):
literal[string]
keyword[if] identifier[comma] :
identifier[message] += literal[string]
identifier[sys] . identifier[stdout] . identifier[write] ( identifier... | def output_to_bar(self, message, comma=True):
"""
Outputs data to stdout, without buffering.
message: A string containing the data to be output.
comma: Whether or not a comma should be placed at the end of the output.
"""
if comma:
message += ',' # depends on [control=[... |
def _VarintEncoder():
"""Return an encoder for a basic varint value (does not include tag)."""
def EncodeVarint(write, value):
bits = value & 0x7f
value >>= 7
while value:
write(six.int2byte(0x80|bits))
bits = value & 0x7f
value >>= 7
return write(six.int2byte(bits))
return Enc... | def function[_VarintEncoder, parameter[]]:
constant[Return an encoder for a basic varint value (does not include tag).]
def function[EncodeVarint, parameter[write, value]]:
variable[bits] assign[=] binary_operation[name[value] <ast.BitAnd object at 0x7da2590d6b60> constant[127]]
... | keyword[def] identifier[_VarintEncoder] ():
literal[string]
keyword[def] identifier[EncodeVarint] ( identifier[write] , identifier[value] ):
identifier[bits] = identifier[value] & literal[int]
identifier[value] >>= literal[int]
keyword[while] identifier[value] :
identifier[write] ( i... | def _VarintEncoder():
"""Return an encoder for a basic varint value (does not include tag)."""
def EncodeVarint(write, value):
bits = value & 127
value >>= 7
while value:
write(six.int2byte(128 | bits))
bits = value & 127
value >>= 7 # depends on [co... |
def write_cyc(fn, this, conv=1.0):
""" Write the lattice information to a cyc.dat file (i.e., tblmd input file)
"""
lattice = this.get_cell()
f = paropen(fn, "w")
f.write("<------- Simulation box definition\n")
f.write("<------- Barostat (on = 1, off = 0)\n")
f.write(" 0\n")
f.write("... | def function[write_cyc, parameter[fn, this, conv]]:
constant[ Write the lattice information to a cyc.dat file (i.e., tblmd input file)
]
variable[lattice] assign[=] call[name[this].get_cell, parameter[]]
variable[f] assign[=] call[name[paropen], parameter[name[fn], constant[w]]]
call... | keyword[def] identifier[write_cyc] ( identifier[fn] , identifier[this] , identifier[conv] = literal[int] ):
literal[string]
identifier[lattice] = identifier[this] . identifier[get_cell] ()
identifier[f] = identifier[paropen] ( identifier[fn] , literal[string] )
identifier[f] . identifier[write]... | def write_cyc(fn, this, conv=1.0):
""" Write the lattice information to a cyc.dat file (i.e., tblmd input file)
"""
lattice = this.get_cell()
f = paropen(fn, 'w')
f.write('<------- Simulation box definition\n')
f.write('<------- Barostat (on = 1, off = 0)\n')
f.write(' 0\n')
f.write('<-... |
def install(name=None, refresh=False, fromrepo=None,
pkgs=None, sources=None, **kwargs):
'''
Install the passed package
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo
Specify a pa... | def function[install, parameter[name, refresh, fromrepo, pkgs, sources]]:
constant[
Install the passed package
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo
Specify a package repository ... | keyword[def] identifier[install] ( identifier[name] = keyword[None] , identifier[refresh] = keyword[False] , identifier[fromrepo] = keyword[None] ,
identifier[pkgs] = keyword[None] , identifier[sources] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[pkg... | def install(name=None, refresh=False, fromrepo=None, pkgs=None, sources=None, **kwargs):
"""
Install the passed package
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo
Specify a package reposi... |
def mset(self, mapping):
"""
Sets each key in the ``mapping`` dict to its corresponding value
"""
servers = {}
for key, value in mapping.items():
server_name = self.get_server_name(key)
servers.setdefault(server_name, [])
servers[server_name].a... | def function[mset, parameter[self, mapping]]:
constant[
Sets each key in the ``mapping`` dict to its corresponding value
]
variable[servers] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da18f09f820>, <ast.Name object at 0x7da18f09e7a0>]]] in starred[call[n... | keyword[def] identifier[mset] ( identifier[self] , identifier[mapping] ):
literal[string]
identifier[servers] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[mapping] . identifier[items] ():
identifier[server_name] = identifier[self] . identifier... | def mset(self, mapping):
"""
Sets each key in the ``mapping`` dict to its corresponding value
"""
servers = {}
for (key, value) in mapping.items():
server_name = self.get_server_name(key)
servers.setdefault(server_name, [])
servers[server_name].append((key, value)) #... |
def _validate_data(data):
"""Validates the given data and raises an error if any non-allowed keys are
provided or any required keys are missing.
:param data: Data to send to API
:type data: dict
"""
data_keys = set(data.keys())
extra_keys = data_keys - set(ALLOWED_KEYS)
missing_keys = s... | def function[_validate_data, parameter[data]]:
constant[Validates the given data and raises an error if any non-allowed keys are
provided or any required keys are missing.
:param data: Data to send to API
:type data: dict
]
variable[data_keys] assign[=] call[name[set], parameter[call[na... | keyword[def] identifier[_validate_data] ( identifier[data] ):
literal[string]
identifier[data_keys] = identifier[set] ( identifier[data] . identifier[keys] ())
identifier[extra_keys] = identifier[data_keys] - identifier[set] ( identifier[ALLOWED_KEYS] )
identifier[missing_keys] = identifier[set] ... | def _validate_data(data):
"""Validates the given data and raises an error if any non-allowed keys are
provided or any required keys are missing.
:param data: Data to send to API
:type data: dict
"""
data_keys = set(data.keys())
extra_keys = data_keys - set(ALLOWED_KEYS)
missing_keys = s... |
def disable_all_breakpoints(cls):
""" Disable all breakpoints and udate `active_breakpoint_flag`.
"""
for bp in cls.breakpoints_by_number:
if bp: # breakpoint #0 exists and is always None
bp.enabled = False
cls.update_active_breakpoint_flag()
return | def function[disable_all_breakpoints, parameter[cls]]:
constant[ Disable all breakpoints and udate `active_breakpoint_flag`.
]
for taget[name[bp]] in starred[name[cls].breakpoints_by_number] begin[:]
if name[bp] begin[:]
name[bp].enabled assign[=] constant... | keyword[def] identifier[disable_all_breakpoints] ( identifier[cls] ):
literal[string]
keyword[for] identifier[bp] keyword[in] identifier[cls] . identifier[breakpoints_by_number] :
keyword[if] identifier[bp] :
identifier[bp] . identifier[enabled] = keyword[False]
... | def disable_all_breakpoints(cls):
""" Disable all breakpoints and udate `active_breakpoint_flag`.
"""
for bp in cls.breakpoints_by_number:
if bp: # breakpoint #0 exists and is always None
bp.enabled = False # depends on [control=['if'], data=[]] # depends on [control=['for'], data... |
def _do_validate_sources_present(self, target):
"""Checks whether sources is empty, and either raises a TaskError or just returns False.
The specifics of this behavior are defined by whether the user sets --allow-empty to True/False:
--allow-empty=False will result in a TaskError being raised in the event ... | def function[_do_validate_sources_present, parameter[self, target]]:
constant[Checks whether sources is empty, and either raises a TaskError or just returns False.
The specifics of this behavior are defined by whether the user sets --allow-empty to True/False:
--allow-empty=False will result in a TaskE... | keyword[def] identifier[_do_validate_sources_present] ( identifier[self] , identifier[target] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[validate_sources_present] :
keyword[return] keyword[True]
identifier[sources] = identifier[target] . identifier[sources_rel... | def _do_validate_sources_present(self, target):
"""Checks whether sources is empty, and either raises a TaskError or just returns False.
The specifics of this behavior are defined by whether the user sets --allow-empty to True/False:
--allow-empty=False will result in a TaskError being raised in the event ... |
def get_rate_limits(response):
"""Returns a list of rate limit information from a given response's headers."""
periods = response.headers['X-RateLimit-Period']
if not periods:
return []
rate_limits = []
periods = periods.split(',')
limits = response.headers['X-RateLimit-Limit'].split('... | def function[get_rate_limits, parameter[response]]:
constant[Returns a list of rate limit information from a given response's headers.]
variable[periods] assign[=] call[name[response].headers][constant[X-RateLimit-Period]]
if <ast.UnaryOp object at 0x7da204623820> begin[:]
return[list[[]... | keyword[def] identifier[get_rate_limits] ( identifier[response] ):
literal[string]
identifier[periods] = identifier[response] . identifier[headers] [ literal[string] ]
keyword[if] keyword[not] identifier[periods] :
keyword[return] []
identifier[rate_limits] =[]
identifier[period... | def get_rate_limits(response):
"""Returns a list of rate limit information from a given response's headers."""
periods = response.headers['X-RateLimit-Period']
if not periods:
return [] # depends on [control=['if'], data=[]]
rate_limits = []
periods = periods.split(',')
limits = respons... |
def await_flush_completion(self, timeout=None):
"""
Mark all partitions as ready to send and block until the send is complete
"""
try:
for batch in self._incomplete.all():
log.debug('Waiting on produce to %s',
batch.produce_future.top... | def function[await_flush_completion, parameter[self, timeout]]:
constant[
Mark all partitions as ready to send and block until the send is complete
]
<ast.Try object at 0x7da1b1c29de0> | keyword[def] identifier[await_flush_completion] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[try] :
keyword[for] identifier[batch] keyword[in] identifier[self] . identifier[_incomplete] . identifier[all] ():
identifier[log] . i... | def await_flush_completion(self, timeout=None):
"""
Mark all partitions as ready to send and block until the send is complete
"""
try:
for batch in self._incomplete.all():
log.debug('Waiting on produce to %s', batch.produce_future.topic_partition)
if not batch.pro... |
def prompt_and_select_link(self):
"""
Prompt the user to select a link from a list to open.
Return the link that was selected, or ``None`` if no link was selected.
"""
data = self.get_selected_item()
url_full = data.get('url_full')
permalink = data.get('permalink... | def function[prompt_and_select_link, parameter[self]]:
constant[
Prompt the user to select a link from a list to open.
Return the link that was selected, or ``None`` if no link was selected.
]
variable[data] assign[=] call[name[self].get_selected_item, parameter[]]
varia... | keyword[def] identifier[prompt_and_select_link] ( identifier[self] ):
literal[string]
identifier[data] = identifier[self] . identifier[get_selected_item] ()
identifier[url_full] = identifier[data] . identifier[get] ( literal[string] )
identifier[permalink] = identifier[data] . ide... | def prompt_and_select_link(self):
"""
Prompt the user to select a link from a list to open.
Return the link that was selected, or ``None`` if no link was selected.
"""
data = self.get_selected_item()
url_full = data.get('url_full')
permalink = data.get('permalink')
if url_fu... |
def convert_dt_time(duration, return_iter=False):
"""
Summary:
convert timedelta objects to human readable output
Args:
:duration (datetime.timedelta): time duration to convert
:return_iter (tuple): tuple containing time sequence
Returns:
days, hours, minutes, seconds | ... | def function[convert_dt_time, parameter[duration, return_iter]]:
constant[
Summary:
convert timedelta objects to human readable output
Args:
:duration (datetime.timedelta): time duration to convert
:return_iter (tuple): tuple containing time sequence
Returns:
days, h... | keyword[def] identifier[convert_dt_time] ( identifier[duration] , identifier[return_iter] = keyword[False] ):
literal[string]
keyword[try] :
identifier[days] , identifier[hours] , identifier[minutes] , identifier[seconds] = identifier[convert_timedelta] ( identifier[duration] )
keyword[if... | def convert_dt_time(duration, return_iter=False):
"""
Summary:
convert timedelta objects to human readable output
Args:
:duration (datetime.timedelta): time duration to convert
:return_iter (tuple): tuple containing time sequence
Returns:
days, hours, minutes, seconds | ... |
def kill(self, signal=None):
"""
Kill or send a signal to the container.
Args:
signal (str or int): The signal to send. Defaults to ``SIGKILL``
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return... | def function[kill, parameter[self, signal]]:
constant[
Kill or send a signal to the container.
Args:
signal (str or int): The signal to send. Defaults to ``SIGKILL``
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
... | keyword[def] identifier[kill] ( identifier[self] , identifier[signal] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[client] . identifier[api] . identifier[kill] ( identifier[self] . identifier[id] , identifier[signal] = identifier[signal] ) | def kill(self, signal=None):
"""
Kill or send a signal to the container.
Args:
signal (str or int): The signal to send. Defaults to ``SIGKILL``
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self.cli... |
def interpolate_to_netcdf(self, in_lon, in_lat, out_path, date_unit="seconds since 1970-01-01T00:00",
interp_type="spline"):
"""
Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create
separate directories for each variab... | def function[interpolate_to_netcdf, parameter[self, in_lon, in_lat, out_path, date_unit, interp_type]]:
constant[
Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create
separate directories for each variable if they are not already available.
... | keyword[def] identifier[interpolate_to_netcdf] ( identifier[self] , identifier[in_lon] , identifier[in_lat] , identifier[out_path] , identifier[date_unit] = literal[string] ,
identifier[interp_type] = literal[string] ):
literal[string]
keyword[if] identifier[interp_type] == literal[string] :
... | def interpolate_to_netcdf(self, in_lon, in_lat, out_path, date_unit='seconds since 1970-01-01T00:00', interp_type='spline'):
"""
Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create
separate directories for each variable if they are not already availab... |
def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize):
"""Read MetaMorph STK UIC2Tag from file and return as dict."""
assert dtype == '2I' and byteorder == '<'
values = fh.read_array('<u4', 6*planecount).reshape(planecount, 6)
return {
'ZDistance': values[:, 0] / values[:, 1],
'... | def function[read_uic2tag, parameter[fh, byteorder, dtype, planecount, offsetsize]]:
constant[Read MetaMorph STK UIC2Tag from file and return as dict.]
assert[<ast.BoolOp object at 0x7da1b19a3670>]
variable[values] assign[=] call[call[name[fh].read_array, parameter[constant[<u4], binary_operation[co... | keyword[def] identifier[read_uic2tag] ( identifier[fh] , identifier[byteorder] , identifier[dtype] , identifier[planecount] , identifier[offsetsize] ):
literal[string]
keyword[assert] identifier[dtype] == literal[string] keyword[and] identifier[byteorder] == literal[string]
identifier[values] = id... | def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize):
"""Read MetaMorph STK UIC2Tag from file and return as dict."""
assert dtype == '2I' and byteorder == '<'
values = fh.read_array('<u4', 6 * planecount).reshape(planecount, 6) # julian days
# milliseconds
# julian days
return {'ZDist... |
def _calculate(self, startingPercentage, endPercentage, startDate, endDate):
"""This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. Th... | def function[_calculate, parameter[self, startingPercentage, endPercentage, startDate, endDate]]:
constant[This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines th... | keyword[def] identifier[_calculate] ( identifier[self] , identifier[startingPercentage] , identifier[endPercentage] , identifier[startDate] , identifier[endDate] ):
literal[string]
identifier[errorValues] = identifier[self] . identifier[_get_error_values] ( identifier[startingPercentage] ,... | def _calculate(self, startingPercentage, endPercentage, startDate, endDate):
"""This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`.
Both parameters will be correct at this time.
:param float startingPercentage: Defines the start of the interval. This h... |
def which(self, path, mode="r"):
# type: (Text, Text) -> Tuple[Optional[Text], Optional[FS]]
"""Get a tuple of (name, fs) that the given path would map to.
Arguments:
path (str): A path on the filesystem.
mode (str): An `io.open` mode.
"""
if check_writa... | def function[which, parameter[self, path, mode]]:
constant[Get a tuple of (name, fs) that the given path would map to.
Arguments:
path (str): A path on the filesystem.
mode (str): An `io.open` mode.
]
if call[name[check_writable], parameter[name[mode]]] begin[:]... | keyword[def] identifier[which] ( identifier[self] , identifier[path] , identifier[mode] = literal[string] ):
literal[string]
keyword[if] identifier[check_writable] ( identifier[mode] ):
keyword[return] identifier[self] . identifier[_write_fs_name] , identifier[self] . identifier[wri... | def which(self, path, mode='r'):
# type: (Text, Text) -> Tuple[Optional[Text], Optional[FS]]
'Get a tuple of (name, fs) that the given path would map to.\n\n Arguments:\n path (str): A path on the filesystem.\n mode (str): An `io.open` mode.\n\n '
if check_writable(mode):... |
def score(self):
"""
Calculate and return a heuristic score for this Parser against the provided
script source and path. This is used to order the ArgumentParsers as "most likely to work"
against a given script/source file.
Each parser has a calculate_score() function that retur... | def function[score, parameter[self]]:
constant[
Calculate and return a heuristic score for this Parser against the provided
script source and path. This is used to order the ArgumentParsers as "most likely to work"
against a given script/source file.
Each parser has a calculate_... | keyword[def] identifier[score] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_heuristic_score] keyword[is] keyword[None] :
identifier[matches] = identifier[self] . identifier[heuristic] ()
identifier[self] . identifier[_heuristic_score]... | def score(self):
"""
Calculate and return a heuristic score for this Parser against the provided
script source and path. This is used to order the ArgumentParsers as "most likely to work"
against a given script/source file.
Each parser has a calculate_score() function that returns a... |
def raise_args_err(message='bad arguments', error_class=TypeError):
"""Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1, 2, ... | def function[raise_args_err, parameter[message, error_class]]:
constant[Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1... | keyword[def] identifier[raise_args_err] ( identifier[message] = literal[string] , identifier[error_class] = identifier[TypeError] ):
literal[string]
identifier[frame] = identifier[inspect] . identifier[currentframe] (). identifier[f_back]
keyword[raise] identifier[error_class] ( identifier[message] ... | def raise_args_err(message='bad arguments', error_class=TypeError):
"""Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1, 2, ... |
def image_url(self, width=None, height=None):
"""
Returns URL to placeholder image
Example: http://placehold.it/640x480
"""
width_ = width or self.random_int(max=1024)
height_ = height or self.random_int(max=1024)
placeholder_url = self.random_element(self.image_p... | def function[image_url, parameter[self, width, height]]:
constant[
Returns URL to placeholder image
Example: http://placehold.it/640x480
]
variable[width_] assign[=] <ast.BoolOp object at 0x7da18dc9b8b0>
variable[height_] assign[=] <ast.BoolOp object at 0x7da18dc9a9b0>
... | keyword[def] identifier[image_url] ( identifier[self] , identifier[width] = keyword[None] , identifier[height] = keyword[None] ):
literal[string]
identifier[width_] = identifier[width] keyword[or] identifier[self] . identifier[random_int] ( identifier[max] = literal[int] )
identifier[hei... | def image_url(self, width=None, height=None):
"""
Returns URL to placeholder image
Example: http://placehold.it/640x480
"""
width_ = width or self.random_int(max=1024)
height_ = height or self.random_int(max=1024)
placeholder_url = self.random_element(self.image_placeholder_servi... |
def slope_percentile(self, date, mag):
"""
Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Return... | def function[slope_percentile, parameter[self, date, mag]]:
constant[
Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sort... | keyword[def] identifier[slope_percentile] ( identifier[self] , identifier[date] , identifier[mag] ):
literal[string]
identifier[date_diff] = identifier[date] [ literal[int] :]- identifier[date] [: identifier[len] ( identifier[date] )- literal[int] ]
identifier[mag_diff] = identifier[mag] ... | def slope_percentile(self, date, mag):
"""
Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Returns
... |
def addFASTAEditingCommandLineOptions(parser):
"""
Add standard FASTA editing command-line options to an argparse parser.
These are options that can be used to alter FASTA records, NOT options
that simply select or reject those things (for those see
addFASTAFilteringCommandLineOptions).
@param... | def function[addFASTAEditingCommandLineOptions, parameter[parser]]:
constant[
Add standard FASTA editing command-line options to an argparse parser.
These are options that can be used to alter FASTA records, NOT options
that simply select or reject those things (for those see
addFASTAFilteringC... | keyword[def] identifier[addFASTAEditingCommandLineOptions] ( identifier[parser] ):
literal[string]
identifier[group] = identifier[parser] . identifier[add_mutually_exclusive_group] ()
identifier[group] . identifier[add_argument] (
literal[string] , literal[string] ,
iden... | def addFASTAEditingCommandLineOptions(parser):
"""
Add standard FASTA editing command-line options to an argparse parser.
These are options that can be used to alter FASTA records, NOT options
that simply select or reject those things (for those see
addFASTAFilteringCommandLineOptions).
@param... |
def acquire_subsamples_gp1(input_data, file_name=None):
"""
Function invoked for plotting a grid-plot with 3x2 format, showing the differences in ECG
signals accordingly to the chosen sampling frequency.
Applied in the cell with tag "subsampling_grid_plot_1".
----------
Parameters
--------... | def function[acquire_subsamples_gp1, parameter[input_data, file_name]]:
constant[
Function invoked for plotting a grid-plot with 3x2 format, showing the differences in ECG
signals accordingly to the chosen sampling frequency.
Applied in the cell with tag "subsampling_grid_plot_1".
----------
... | keyword[def] identifier[acquire_subsamples_gp1] ( identifier[input_data] , identifier[file_name] = keyword[None] ):
literal[string]
identifier[fs_orig] = literal[int]
identifier[nbr_samples_orig] = identifier[len] ( identifier[input_data] )
identifier[data_interp] ={ literal[str... | def acquire_subsamples_gp1(input_data, file_name=None):
"""
Function invoked for plotting a grid-plot with 3x2 format, showing the differences in ECG
signals accordingly to the chosen sampling frequency.
Applied in the cell with tag "subsampling_grid_plot_1".
----------
Parameters
--------... |
def process_binding_statements(self):
"""Looks for Binding events in the graph and extracts them into INDRA
statements.
In particular, looks for a Binding event node with outgoing edges
with relations Theme and Theme2 - the entities these edges point to
are the two constituents ... | def function[process_binding_statements, parameter[self]]:
constant[Looks for Binding events in the graph and extracts them into INDRA
statements.
In particular, looks for a Binding event node with outgoing edges
with relations Theme and Theme2 - the entities these edges point to
... | keyword[def] identifier[process_binding_statements] ( identifier[self] ):
literal[string]
identifier[G] = identifier[self] . identifier[G]
identifier[statements] =[]
identifier[binding_nodes] = identifier[self] . identifier[find_event_with_outgoing_edges] ( literal[string] ,
... | def process_binding_statements(self):
"""Looks for Binding events in the graph and extracts them into INDRA
statements.
In particular, looks for a Binding event node with outgoing edges
with relations Theme and Theme2 - the entities these edges point to
are the two constituents of t... |
def run_setup_error_group():
"""Run the phase group example where an error occurs in a setup phase.
The terminal setup phase shortcuts the test. The main phases are
skipped. The PhaseGroup is not entered, so the teardown phases are also
skipped.
"""
test = htf.Test(htf.PhaseGroup(
setup=[error_setu... | def function[run_setup_error_group, parameter[]]:
constant[Run the phase group example where an error occurs in a setup phase.
The terminal setup phase shortcuts the test. The main phases are
skipped. The PhaseGroup is not entered, so the teardown phases are also
skipped.
]
variable[test] ass... | keyword[def] identifier[run_setup_error_group] ():
literal[string]
identifier[test] = identifier[htf] . identifier[Test] ( identifier[htf] . identifier[PhaseGroup] (
identifier[setup] =[ identifier[error_setup_phase] ],
identifier[main] =[ identifier[main_phase] ],
identifier[teardown] =[ identifier[t... | def run_setup_error_group():
"""Run the phase group example where an error occurs in a setup phase.
The terminal setup phase shortcuts the test. The main phases are
skipped. The PhaseGroup is not entered, so the teardown phases are also
skipped.
"""
test = htf.Test(htf.PhaseGroup(setup=[error_setup_p... |
def reconstitute_path(drive, folders):
"""Reverts a tuple from `get_path_components` into a path.
:param drive: A drive (eg 'c:'). Only applicable for NT systems
:param folders: A list of folder names
:return: A path comprising the drive and list of folder names. The path terminate
with a ... | def function[reconstitute_path, parameter[drive, folders]]:
constant[Reverts a tuple from `get_path_components` into a path.
:param drive: A drive (eg 'c:'). Only applicable for NT systems
:param folders: A list of folder names
:return: A path comprising the drive and list of folder names. The path... | keyword[def] identifier[reconstitute_path] ( identifier[drive] , identifier[folders] ):
literal[string]
identifier[reconstituted] = identifier[os] . identifier[path] . identifier[join] ( identifier[drive] , identifier[os] . identifier[path] . identifier[sep] ,* identifier[folders] )
keyword[return] i... | def reconstitute_path(drive, folders):
"""Reverts a tuple from `get_path_components` into a path.
:param drive: A drive (eg 'c:'). Only applicable for NT systems
:param folders: A list of folder names
:return: A path comprising the drive and list of folder names. The path terminate
with a ... |
def store_transition(self, frame, action, reward, done, extra_info=None):
""" Store given transition in the backend """
self.current_idx = (self.current_idx + 1) % self.buffer_capacity
if self.frame_stack_compensation:
# Compensate for frame stack built into the environment
... | def function[store_transition, parameter[self, frame, action, reward, done, extra_info]]:
constant[ Store given transition in the backend ]
name[self].current_idx assign[=] binary_operation[binary_operation[name[self].current_idx + constant[1]] <ast.Mod object at 0x7da2590d6920> name[self].buffer_capaci... | keyword[def] identifier[store_transition] ( identifier[self] , identifier[frame] , identifier[action] , identifier[reward] , identifier[done] , identifier[extra_info] = keyword[None] ):
literal[string]
identifier[self] . identifier[current_idx] =( identifier[self] . identifier[current_idx] + litera... | def store_transition(self, frame, action, reward, done, extra_info=None):
""" Store given transition in the backend """
self.current_idx = (self.current_idx + 1) % self.buffer_capacity
if self.frame_stack_compensation:
# Compensate for frame stack built into the environment
idx_range = np.ar... |
def fix_timestamps(self, time_ref):
"""
manipulates internal time stamps such that the last run ends at time 0
"""
for k,v in self.data.items():
for kk, vv in v.time_stamps.items():
for kkk,vvv in vv.items():
self.data[k].time_stamps[kk][kkk] += time_ref | def function[fix_timestamps, parameter[self, time_ref]]:
constant[
manipulates internal time stamps such that the last run ends at time 0
]
for taget[tuple[[<ast.Name object at 0x7da1b1714f40>, <ast.Name object at 0x7da1b1715d80>]]] in starred[call[name[self].data.items, parameter[]]] begin[:]
... | keyword[def] identifier[fix_timestamps] ( identifier[self] , identifier[time_ref] ):
literal[string]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[self] . identifier[data] . identifier[items] ():
keyword[for] identifier[kk] , identifier[vv] keyword[in] identifier[v] . identifier[... | def fix_timestamps(self, time_ref):
"""
manipulates internal time stamps such that the last run ends at time 0
"""
for (k, v) in self.data.items():
for (kk, vv) in v.time_stamps.items():
for (kkk, vvv) in vv.items():
self.data[k].time_stamps[kk][kkk] += time_ref # depen... |
def runSavedQuery(self, saved_query_obj, returned_properties=None):
"""Query workitems using the :class:`rtcclient.models.SavedQuery`
object
:param saved_query_obj: the :class:`rtcclient.models.SavedQuery`
object
:param returned_properties: the returned properties that you w... | def function[runSavedQuery, parameter[self, saved_query_obj, returned_properties]]:
constant[Query workitems using the :class:`rtcclient.models.SavedQuery`
object
:param saved_query_obj: the :class:`rtcclient.models.SavedQuery`
object
:param returned_properties: the returned... | keyword[def] identifier[runSavedQuery] ( identifier[self] , identifier[saved_query_obj] , identifier[returned_properties] = keyword[None] ):
literal[string]
keyword[try] :
identifier[saved_query_id] = identifier[saved_query_obj] . identifier[results] . identifier[split] ( literal[stri... | def runSavedQuery(self, saved_query_obj, returned_properties=None):
"""Query workitems using the :class:`rtcclient.models.SavedQuery`
object
:param saved_query_obj: the :class:`rtcclient.models.SavedQuery`
object
:param returned_properties: the returned properties that you want.... |
def builtin_list():
"""Show a listing of all our builtin templates"""
for template in resource_listdir(__name__, "templates"):
builtin, ext = os.path.splitext(os.path.basename(abspath(template)))
if ext == '.yml':
continue
help_obj = load_template_help(builtin)
if 'n... | def function[builtin_list, parameter[]]:
constant[Show a listing of all our builtin templates]
for taget[name[template]] in starred[call[name[resource_listdir], parameter[name[__name__], constant[templates]]]] begin[:]
<ast.Tuple object at 0x7da1b26ac820> assign[=] call[name[os].path.spl... | keyword[def] identifier[builtin_list] ():
literal[string]
keyword[for] identifier[template] keyword[in] identifier[resource_listdir] ( identifier[__name__] , literal[string] ):
identifier[builtin] , identifier[ext] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[os] . id... | def builtin_list():
"""Show a listing of all our builtin templates"""
for template in resource_listdir(__name__, 'templates'):
(builtin, ext) = os.path.splitext(os.path.basename(abspath(template)))
if ext == '.yml':
continue # depends on [control=['if'], data=[]]
help_obj = ... |
def _execute(self, sender, event_args):
'''
Event handler for timer that processes all queued messages.
'''
with self._lock:
while not self._messages.empty():
msg, args, kwargs = self._messages.get(False)
for subscriber in self._subscribers[msg... | def function[_execute, parameter[self, sender, event_args]]:
constant[
Event handler for timer that processes all queued messages.
]
with name[self]._lock begin[:]
while <ast.UnaryOp object at 0x7da18bccae90> begin[:]
<ast.Tuple object at 0x7da2043... | keyword[def] identifier[_execute] ( identifier[self] , identifier[sender] , identifier[event_args] ):
literal[string]
keyword[with] identifier[self] . identifier[_lock] :
keyword[while] keyword[not] identifier[self] . identifier[_messages] . identifier[empty] ():
id... | def _execute(self, sender, event_args):
"""
Event handler for timer that processes all queued messages.
"""
with self._lock:
while not self._messages.empty():
(msg, args, kwargs) = self._messages.get(False)
for subscriber in self._subscribers[msg]:
... |
def get_colour(self, val, colformat='hex'):
""" Given a value, return a colour within the colour scale """
try:
# Sanity checks
val = re.sub("[^0-9\.]", "", str(val))
if val == '':
val = self.minval
val = float(val)
val = max(val, self.minval)
val = min(val, self.maxval)
domain_nums = list... | def function[get_colour, parameter[self, val, colformat]]:
constant[ Given a value, return a colour within the colour scale ]
<ast.Try object at 0x7da18eb57e80> | keyword[def] identifier[get_colour] ( identifier[self] , identifier[val] , identifier[colformat] = literal[string] ):
literal[string]
keyword[try] :
identifier[val] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[str] ( identifier[val] ))
keyword[if] identifier[v... | def get_colour(self, val, colformat='hex'):
""" Given a value, return a colour within the colour scale """
try: # Sanity checks
val = re.sub('[^0-9\\.]', '', str(val))
if val == '':
val = self.minval # depends on [control=['if'], data=['val']]
val = float(val)
val =... |
def do_clearaccess(self, line):
"""clearaccess Remove all subjects from access policy Only the submitter will
have access to the object."""
self._split_args(line, 0, 0)
self._command_processor.get_session().get_access_control().clear()
self._print_info_if_verbose("Removed all sub... | def function[do_clearaccess, parameter[self, line]]:
constant[clearaccess Remove all subjects from access policy Only the submitter will
have access to the object.]
call[name[self]._split_args, parameter[name[line], constant[0], constant[0]]]
call[call[call[name[self]._command_processor.... | keyword[def] identifier[do_clearaccess] ( identifier[self] , identifier[line] ):
literal[string]
identifier[self] . identifier[_split_args] ( identifier[line] , literal[int] , literal[int] )
identifier[self] . identifier[_command_processor] . identifier[get_session] (). identifier[get_acce... | def do_clearaccess(self, line):
"""clearaccess Remove all subjects from access policy Only the submitter will
have access to the object."""
self._split_args(line, 0, 0)
self._command_processor.get_session().get_access_control().clear()
self._print_info_if_verbose('Removed all subjects from acces... |
def write_sample_sheet(output_file, accessions, names, celfile_urls, sel=None):
"""Generate a sample sheet in tab-separated text format.
The columns contain the following sample attributes:
1) accession
2) name
3) CEL file name
4) CEL file URL
Parameters
----------
output_file: str... | def function[write_sample_sheet, parameter[output_file, accessions, names, celfile_urls, sel]]:
constant[Generate a sample sheet in tab-separated text format.
The columns contain the following sample attributes:
1) accession
2) name
3) CEL file name
4) CEL file URL
Parameters
-----... | keyword[def] identifier[write_sample_sheet] ( identifier[output_file] , identifier[accessions] , identifier[names] , identifier[celfile_urls] , identifier[sel] = keyword[None] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[output_file] , identifier[str] )
keyword[assert] iden... | def write_sample_sheet(output_file, accessions, names, celfile_urls, sel=None):
"""Generate a sample sheet in tab-separated text format.
The columns contain the following sample attributes:
1) accession
2) name
3) CEL file name
4) CEL file URL
Parameters
----------
output_file: str... |
def covar(self, x, y, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None):
"""Calculate the covariance cov[x,y] between and x and y, possibly on a grid defined by binby.
Example:
>>> df.covar("x**2+y**2+z**2", "-log(-E+1)")
array(52.69461456005138)
... | def function[covar, parameter[self, x, y, binby, limits, shape, selection, delay, progress]]:
constant[Calculate the covariance cov[x,y] between and x and y, possibly on a grid defined by binby.
Example:
>>> df.covar("x**2+y**2+z**2", "-log(-E+1)")
array(52.69461456005138)
>>> ... | keyword[def] identifier[covar] ( identifier[self] , identifier[x] , identifier[y] , identifier[binby] =[], identifier[limits] = keyword[None] , identifier[shape] = identifier[default_shape] , identifier[selection] = keyword[False] , identifier[delay] = keyword[False] , identifier[progress] = keyword[None] ):
... | def covar(self, x, y, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None):
"""Calculate the covariance cov[x,y] between and x and y, possibly on a grid defined by binby.
Example:
>>> df.covar("x**2+y**2+z**2", "-log(-E+1)")
array(52.69461456005138)
... |
def experiments_predictions_image_set_create(self, experiment_id, run_id, filename):
"""Create a prediction image set from a given tar archive that was
produced as the result of a successful model run.
Returns None if the specified model run does not exist or did not
finish successfully... | def function[experiments_predictions_image_set_create, parameter[self, experiment_id, run_id, filename]]:
constant[Create a prediction image set from a given tar archive that was
produced as the result of a successful model run.
Returns None if the specified model run does not exist or did not
... | keyword[def] identifier[experiments_predictions_image_set_create] ( identifier[self] , identifier[experiment_id] , identifier[run_id] , identifier[filename] ):
literal[string]
identifier[model_run] = identifier[self] . identifier[experiments_predictions_get] ( identifier[experiment_id] , i... | def experiments_predictions_image_set_create(self, experiment_id, run_id, filename):
"""Create a prediction image set from a given tar archive that was
produced as the result of a successful model run.
Returns None if the specified model run does not exist or did not
finish successfully. Ra... |
def summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
"""
if tag is None:
tag = "tensors/"
for t_name in list(tensor_dict):
t = tensor_dict[t_name]
tf.summary.histogram(tag... | def function[summarize_tensors, parameter[tensor_dict, tag]]:
constant[Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
]
if compare[name[tag] is constant[None]] begin[:]
variable[tag] assign[=] constant... | keyword[def] identifier[summarize_tensors] ( identifier[tensor_dict] , identifier[tag] = keyword[None] ):
literal[string]
keyword[if] identifier[tag] keyword[is] keyword[None] :
identifier[tag] = literal[string]
keyword[for] identifier[t_name] keyword[in] identifier[list] ( identifier[tensor_di... | def summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
"""
if tag is None:
tag = 'tensors/' # depends on [control=['if'], data=['tag']]
for t_name in list(tensor_dict):
... |
def default_start_index(self, value):
"""Validate and set the default start index."""
if not isinstance(value, int):
raise TypeError('default_start_index attribute must be of int '
'type.')
self._default_start_index = value | def function[default_start_index, parameter[self, value]]:
constant[Validate and set the default start index.]
if <ast.UnaryOp object at 0x7da1b0359270> begin[:]
<ast.Raise object at 0x7da1b0359e10>
name[self]._default_start_index assign[=] name[value] | keyword[def] identifier[default_start_index] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[int] ):
keyword[raise] identifier[TypeError] ( literal[string]
literal[string] )
... | def default_start_index(self, value):
"""Validate and set the default start index."""
if not isinstance(value, int):
raise TypeError('default_start_index attribute must be of int type.') # depends on [control=['if'], data=[]]
self._default_start_index = value |
def build(self, jokers=False, num_jokers=0):
"""
Builds a standard 52 card French deck of Card instances.
:arg bool jokers:
Whether or not to include jokers in the deck.
:arg int num_jokers:
The number of jokers to include.
"""
jokers = jokers or... | def function[build, parameter[self, jokers, num_jokers]]:
constant[
Builds a standard 52 card French deck of Card instances.
:arg bool jokers:
Whether or not to include jokers in the deck.
:arg int num_jokers:
The number of jokers to include.
]
v... | keyword[def] identifier[build] ( identifier[self] , identifier[jokers] = keyword[False] , identifier[num_jokers] = literal[int] ):
literal[string]
identifier[jokers] = identifier[jokers] keyword[or] identifier[self] . identifier[jokers]
identifier[num_jokers] = identifier[num_jokers] k... | def build(self, jokers=False, num_jokers=0):
"""
Builds a standard 52 card French deck of Card instances.
:arg bool jokers:
Whether or not to include jokers in the deck.
:arg int num_jokers:
The number of jokers to include.
"""
jokers = jokers or self.jo... |
def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | def function[set, parameter[self, id, translation, domain]]:
constant[
Sets a message translation.
]
assert[call[name[isinstance], parameter[name[id], tuple[[<ast.Name object at 0x7da1b20d5a50>, <ast.Name object at 0x7da1b20d4970>]]]]]
assert[call[name[isinstance], parameter[name[transla... | keyword[def] identifier[set] ( identifier[self] , identifier[id] , identifier[translation] , identifier[domain] = literal[string] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[id] ,( identifier[str] , identifier[unicode] ))
keyword[assert] identifier[isinstance] ... | def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) |
def median_filter(tr, multiplier=10, windowlength=0.5,
interp_len=0.05, debug=0):
"""
Filter out spikes in data above a multiple of MAD of the data.
Currently only has the ability to replaces spikes with linear
interpolation. In the future we would aim to fill the gap with something
... | def function[median_filter, parameter[tr, multiplier, windowlength, interp_len, debug]]:
constant[
Filter out spikes in data above a multiple of MAD of the data.
Currently only has the ability to replaces spikes with linear
interpolation. In the future we would aim to fill the gap with something
... | keyword[def] identifier[median_filter] ( identifier[tr] , identifier[multiplier] = literal[int] , identifier[windowlength] = literal[int] ,
identifier[interp_len] = literal[int] , identifier[debug] = literal[int] ):
literal[string]
identifier[num_cores] = identifier[cpu_count] ()
keyword[if] identif... | def median_filter(tr, multiplier=10, windowlength=0.5, interp_len=0.05, debug=0):
"""
Filter out spikes in data above a multiple of MAD of the data.
Currently only has the ability to replaces spikes with linear
interpolation. In the future we would aim to fill the gap with something
more appropria... |
def _sb_short_word(self, term, r1_prefixes=None):
"""Return True iff term is a short word.
(...according to the Porter2 specification.)
Parameters
----------
term : str
The term to examine
r1_prefixes : set
Prefixes to consider
Returns
... | def function[_sb_short_word, parameter[self, term, r1_prefixes]]:
constant[Return True iff term is a short word.
(...according to the Porter2 specification.)
Parameters
----------
term : str
The term to examine
r1_prefixes : set
Prefixes to consi... | keyword[def] identifier[_sb_short_word] ( identifier[self] , identifier[term] , identifier[r1_prefixes] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_sb_r1] ( identifier[term] , identifier[r1_prefixes] )== identifier[len] (
identifier[term]
) keywo... | def _sb_short_word(self, term, r1_prefixes=None):
"""Return True iff term is a short word.
(...according to the Porter2 specification.)
Parameters
----------
term : str
The term to examine
r1_prefixes : set
Prefixes to consider
Returns
... |
def check_input_layer(layer, purpose):
"""Function to check if the layer is valid.
The function will also set the monkey patching if needed.
:param layer: The layer to test.
:type layer: QgsMapLayer
:param purpose: The expected purpose of the layer.
:type purpose: basestring
:return: A t... | def function[check_input_layer, parameter[layer, purpose]]:
constant[Function to check if the layer is valid.
The function will also set the monkey patching if needed.
:param layer: The layer to test.
:type layer: QgsMapLayer
:param purpose: The expected purpose of the layer.
:type purpos... | keyword[def] identifier[check_input_layer] ( identifier[layer] , identifier[purpose] ):
literal[string]
keyword[if] keyword[not] identifier[layer] . identifier[isValid] ():
identifier[title] = identifier[tr] (
literal[string] ). identifier[format] ( identifier[purpose] = identifier[purp... | def check_input_layer(layer, purpose):
"""Function to check if the layer is valid.
The function will also set the monkey patching if needed.
:param layer: The layer to test.
:type layer: QgsMapLayer
:param purpose: The expected purpose of the layer.
:type purpose: basestring
:return: A t... |
def _retrieve_users(self):
"""
Retrieve user objects of the entire administration.
:return: list of dictionary with users information
:rtype: list(dict)
-------
"""
users_url = self._build_url('users')
response = self._request('GET', users_url)
u... | def function[_retrieve_users, parameter[self]]:
constant[
Retrieve user objects of the entire administration.
:return: list of dictionary with users information
:rtype: list(dict)
-------
]
variable[users_url] assign[=] call[name[self]._build_url, parameter[cons... | keyword[def] identifier[_retrieve_users] ( identifier[self] ):
literal[string]
identifier[users_url] = identifier[self] . identifier[_build_url] ( literal[string] )
identifier[response] = identifier[self] . identifier[_request] ( literal[string] , identifier[users_url] )
identifie... | def _retrieve_users(self):
"""
Retrieve user objects of the entire administration.
:return: list of dictionary with users information
:rtype: list(dict)
-------
"""
users_url = self._build_url('users')
response = self._request('GET', users_url)
users = response.... |
def getApplicationPropertyBool(self, pchAppKey, eProperty):
"""Returns a bool value for an application property. Returns false in all error cases."""
fn = self.function_table.getApplicationPropertyBool
peError = EVRApplicationError()
result = fn(pchAppKey, eProperty, byref(peError))
... | def function[getApplicationPropertyBool, parameter[self, pchAppKey, eProperty]]:
constant[Returns a bool value for an application property. Returns false in all error cases.]
variable[fn] assign[=] name[self].function_table.getApplicationPropertyBool
variable[peError] assign[=] call[name[EVRAppl... | keyword[def] identifier[getApplicationPropertyBool] ( identifier[self] , identifier[pchAppKey] , identifier[eProperty] ):
literal[string]
identifier[fn] = identifier[self] . identifier[function_table] . identifier[getApplicationPropertyBool]
identifier[peError] = identifier[EVRApplicatio... | def getApplicationPropertyBool(self, pchAppKey, eProperty):
"""Returns a bool value for an application property. Returns false in all error cases."""
fn = self.function_table.getApplicationPropertyBool
peError = EVRApplicationError()
result = fn(pchAppKey, eProperty, byref(peError))
return (result, ... |
def _parse_comment(self):
"""Parse an HTML comment at the head of the wikicode string."""
self._head += 4
reset = self._head - 1
self._push()
while True:
this = self._read()
if this == self.END:
self._pop()
self._head = rese... | def function[_parse_comment, parameter[self]]:
constant[Parse an HTML comment at the head of the wikicode string.]
<ast.AugAssign object at 0x7da2044c3370>
variable[reset] assign[=] binary_operation[name[self]._head - constant[1]]
call[name[self]._push, parameter[]]
while constant[Tr... | keyword[def] identifier[_parse_comment] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_head] += literal[int]
identifier[reset] = identifier[self] . identifier[_head] - literal[int]
identifier[self] . identifier[_push] ()
keyword[while] keyword[Tru... | def _parse_comment(self):
"""Parse an HTML comment at the head of the wikicode string."""
self._head += 4
reset = self._head - 1
self._push()
while True:
this = self._read()
if this == self.END:
self._pop()
self._head = reset
self._emit_text('<!--'... |
def run(self):
"""overridden from install_lib class"""
install_lib.install_lib.run(self)
# manually install included directories if any
if include_dirs:
for directory in include_dirs:
dest = join(self.install_dir, directory)
if sys.version_info... | def function[run, parameter[self]]:
constant[overridden from install_lib class]
call[name[install_lib].install_lib.run, parameter[name[self]]]
if name[include_dirs] begin[:]
for taget[name[directory]] in starred[name[include_dirs]] begin[:]
variable[dest] ... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[install_lib] . identifier[install_lib] . identifier[run] ( identifier[self] )
keyword[if] identifier[include_dirs] :
keyword[for] identifier[directory] keyword[in] identifier[include_dir... | def run(self):
"""overridden from install_lib class"""
install_lib.install_lib.run(self)
# manually install included directories if any
if include_dirs:
for directory in include_dirs:
dest = join(self.install_dir, directory)
if sys.version_info >= (3, 0):
... |
def remove(self, data):
"""
Removes a data node from the list. If the list contains more than one
node having the same data that shall be removed, then the node having
the first occurrency of the data is removed.
:param data: the data to be removed in the new list node
:... | def function[remove, parameter[self, data]]:
constant[
Removes a data node from the list. If the list contains more than one
node having the same data that shall be removed, then the node having
the first occurrency of the data is removed.
:param data: the data to be removed in ... | keyword[def] identifier[remove] ( identifier[self] , identifier[data] ):
literal[string]
identifier[current_node] = identifier[self] . identifier[_first_node]
identifier[deleted] = keyword[False]
keyword[if] identifier[self] . identifier[_size] == literal[int] :
k... | def remove(self, data):
"""
Removes a data node from the list. If the list contains more than one
node having the same data that shall be removed, then the node having
the first occurrency of the data is removed.
:param data: the data to be removed in the new list node
:type... |
def HStruct_selectFields(structT, fieldsToUse):
"""
Select fields from structure (rest will become spacing)
:param structT: HStruct type instance
:param fieldsToUse: dict {name:{...}} or set of names to select,
dictionary is used to select nested fields
in HStruct or HUnion fields
... | def function[HStruct_selectFields, parameter[structT, fieldsToUse]]:
constant[
Select fields from structure (rest will become spacing)
:param structT: HStruct type instance
:param fieldsToUse: dict {name:{...}} or set of names to select,
dictionary is used to select nested fields
in... | keyword[def] identifier[HStruct_selectFields] ( identifier[structT] , identifier[fieldsToUse] ):
literal[string]
identifier[template] =[]
identifier[fieldsToUse] = identifier[fieldsToUse]
identifier[foundNames] = identifier[set] ()
keyword[for] identifier[f] keyword[in] identifier[stru... | def HStruct_selectFields(structT, fieldsToUse):
"""
Select fields from structure (rest will become spacing)
:param structT: HStruct type instance
:param fieldsToUse: dict {name:{...}} or set of names to select,
dictionary is used to select nested fields
in HStruct or HUnion fields
... |
def pause_resume(self):
"""Toggle between pausing or resuming downloading."""
if self.is_paused():
urlopen(self.url + "&mode=resume")
else:
urlopen(self.url + "&mode=pause") | def function[pause_resume, parameter[self]]:
constant[Toggle between pausing or resuming downloading.]
if call[name[self].is_paused, parameter[]] begin[:]
call[name[urlopen], parameter[binary_operation[name[self].url + constant[&mode=resume]]]] | keyword[def] identifier[pause_resume] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_paused] ():
identifier[urlopen] ( identifier[self] . identifier[url] + literal[string] )
keyword[else] :
identifier[urlopen] ( identifier[self... | def pause_resume(self):
"""Toggle between pausing or resuming downloading."""
if self.is_paused():
urlopen(self.url + '&mode=resume') # depends on [control=['if'], data=[]]
else:
urlopen(self.url + '&mode=pause') |
async def receive_message_batch_async(self, max_batch_size=None, on_message_received=None, timeout=0):
"""Receive a batch of messages asynchronously. This method will return as soon as some
messages are available rather than waiting to achieve a specific batch size, and
therefore the number of m... | <ast.AsyncFunctionDef object at 0x7da20e962dd0> | keyword[async] keyword[def] identifier[receive_message_batch_async] ( identifier[self] , identifier[max_batch_size] = keyword[None] , identifier[on_message_received] = keyword[None] , identifier[timeout] = literal[int] ):
literal[string]
identifier[self] . identifier[_message_received_callback] = ... | async def receive_message_batch_async(self, max_batch_size=None, on_message_received=None, timeout=0):
"""Receive a batch of messages asynchronously. This method will return as soon as some
messages are available rather than waiting to achieve a specific batch size, and
therefore the number of messa... |
def validate_group(images):
"""Validates that the combination of folder and name for all images in
a group is unique. Raises a ValueError exception if uniqueness
constraint is violated.
Parameters
----------
images : List(GroupImage)
List of images in group
... | def function[validate_group, parameter[images]]:
constant[Validates that the combination of folder and name for all images in
a group is unique. Raises a ValueError exception if uniqueness
constraint is violated.
Parameters
----------
images : List(GroupImage)
... | keyword[def] identifier[validate_group] ( identifier[images] ):
literal[string]
identifier[image_ids] = identifier[set] ()
keyword[for] identifier[image] keyword[in] identifier[images] :
identifier[key] = identifier[image] . identifier[folder] + identifier[image] . identifi... | def validate_group(images):
"""Validates that the combination of folder and name for all images in
a group is unique. Raises a ValueError exception if uniqueness
constraint is violated.
Parameters
----------
images : List(GroupImage)
List of images in group
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.