code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def query(options, collection_name, num_to_skip, num_to_return,
query, field_selector, opts, check_keys=False, ctx=None):
"""Get a **query** message."""
if ctx:
return _query_compressed(options, collection_name, num_to_skip,
num_to_return, query, field_selector... | def function[query, parameter[options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, check_keys, ctx]]:
constant[Get a **query** message.]
if name[ctx] begin[:]
return[call[name[_query_compressed], parameter[name[options], name[collection_name], name[num_to_skip], nam... | keyword[def] identifier[query] ( identifier[options] , identifier[collection_name] , identifier[num_to_skip] , identifier[num_to_return] ,
identifier[query] , identifier[field_selector] , identifier[opts] , identifier[check_keys] = keyword[False] , identifier[ctx] = keyword[None] ):
literal[string]
keywor... | def query(options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, check_keys=False, ctx=None):
"""Get a **query** message."""
if ctx:
return _query_compressed(options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, check_keys, ctx) # depends on [con... |
def post(self, *args, **kwargs):
"""Save file and return saved info or report errors."""
if self.upload_allowed():
form = self.get_upload_form()
result = {}
if form.is_valid():
storage = self.get_storage()
result['is_valid'] = True
... | def function[post, parameter[self]]:
constant[Save file and return saved info or report errors.]
if call[name[self].upload_allowed, parameter[]] begin[:]
variable[form] assign[=] call[name[self].get_upload_form, parameter[]]
variable[result] assign[=] dictionary[[], []]
... | keyword[def] identifier[post] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[upload_allowed] ():
identifier[form] = identifier[self] . identifier[get_upload_form] ()
identifier[result] ={}
... | def post(self, *args, **kwargs):
"""Save file and return saved info or report errors."""
if self.upload_allowed():
form = self.get_upload_form()
result = {}
if form.is_valid():
storage = self.get_storage()
result['is_valid'] = True
info = form.stash(st... |
def parse_from_calc(self):
"""
Parses the datafolder, stores results.
This parser for this simple code does simply store in the DB a node
representing the file of forces in real space
"""
from aiida.common.exceptions import InvalidOperation
from aiida.common impor... | def function[parse_from_calc, parameter[self]]:
constant[
Parses the datafolder, stores results.
This parser for this simple code does simply store in the DB a node
representing the file of forces in real space
]
from relative_module[aiida.common.exceptions] import module[Inv... | keyword[def] identifier[parse_from_calc] ( identifier[self] ):
literal[string]
keyword[from] identifier[aiida] . identifier[common] . identifier[exceptions] keyword[import] identifier[InvalidOperation]
keyword[from] identifier[aiida] . identifier[common] keyword[import] identifier[a... | def parse_from_calc(self):
"""
Parses the datafolder, stores results.
This parser for this simple code does simply store in the DB a node
representing the file of forces in real space
"""
from aiida.common.exceptions import InvalidOperation
from aiida.common import aiidalogge... |
def _error(self, x):
"""Error function.
Once self.y_desired has been defined, compute the error
of input x using the forward model.
"""
y_pred = self.fmodel.predict_y(x)
err_v = y_pred - self.goal
error = sum(e*e for e in err_v)
return error | def function[_error, parameter[self, x]]:
constant[Error function.
Once self.y_desired has been defined, compute the error
of input x using the forward model.
]
variable[y_pred] assign[=] call[name[self].fmodel.predict_y, parameter[name[x]]]
variable[err_v] assign[=] bina... | keyword[def] identifier[_error] ( identifier[self] , identifier[x] ):
literal[string]
identifier[y_pred] = identifier[self] . identifier[fmodel] . identifier[predict_y] ( identifier[x] )
identifier[err_v] = identifier[y_pred] - identifier[self] . identifier[goal]
identifier[error... | def _error(self, x):
"""Error function.
Once self.y_desired has been defined, compute the error
of input x using the forward model.
"""
y_pred = self.fmodel.predict_y(x)
err_v = y_pred - self.goal
error = sum((e * e for e in err_v))
return error |
def _batches(iterable, size):
"""
Take an iterator and yield its contents in groups of `size` items.
"""
sourceiter = iter(iterable)
while True:
try:
batchiter = islice(sourceiter, size)
yield chain([next(batchiter)], batchiter)
except StopIteration:
... | def function[_batches, parameter[iterable, size]]:
constant[
Take an iterator and yield its contents in groups of `size` items.
]
variable[sourceiter] assign[=] call[name[iter], parameter[name[iterable]]]
while constant[True] begin[:]
<ast.Try object at 0x7da1b0394730> | keyword[def] identifier[_batches] ( identifier[iterable] , identifier[size] ):
literal[string]
identifier[sourceiter] = identifier[iter] ( identifier[iterable] )
keyword[while] keyword[True] :
keyword[try] :
identifier[batchiter] = identifier[islice] ( identifier[sourceiter] , i... | def _batches(iterable, size):
"""
Take an iterator and yield its contents in groups of `size` items.
"""
sourceiter = iter(iterable)
while True:
try:
batchiter = islice(sourceiter, size)
yield chain([next(batchiter)], batchiter) # depends on [control=['try'], data=[]... |
def ndxlist(self):
"""Return a list of groups in the same format as :func:`gromacs.cbook.get_ndx_groups`.
Format:
[ {'name': group_name, 'natoms': number_atoms, 'nr': # group_number}, ....]
"""
return [{'name': name, 'natoms': len(atomnumbers), 'nr': nr+1} for
... | def function[ndxlist, parameter[self]]:
constant[Return a list of groups in the same format as :func:`gromacs.cbook.get_ndx_groups`.
Format:
[ {'name': group_name, 'natoms': number_atoms, 'nr': # group_number}, ....]
]
return[<ast.ListComp object at 0x7da18bc72a70>] | keyword[def] identifier[ndxlist] ( identifier[self] ):
literal[string]
keyword[return] [{ literal[string] : identifier[name] , literal[string] : identifier[len] ( identifier[atomnumbers] ), literal[string] : identifier[nr] + literal[int] } keyword[for]
identifier[nr] ,( identifier[name] ,... | def ndxlist(self):
"""Return a list of groups in the same format as :func:`gromacs.cbook.get_ndx_groups`.
Format:
[ {'name': group_name, 'natoms': number_atoms, 'nr': # group_number}, ....]
"""
return [{'name': name, 'natoms': len(atomnumbers), 'nr': nr + 1} for (nr, (name, atomnum... |
def _cleanup(self, lr_decay_opt_states_reset: str, process_manager: Optional['DecoderProcessManager'] = None,
keep_training_state = False):
"""
Cleans parameter files, training state directory and waits for remaining decoding processes.
"""
utils.cleanup_params_files(sel... | def function[_cleanup, parameter[self, lr_decay_opt_states_reset, process_manager, keep_training_state]]:
constant[
Cleans parameter files, training state directory and waits for remaining decoding processes.
]
call[name[utils].cleanup_params_files, parameter[name[self].model.output_dir,... | keyword[def] identifier[_cleanup] ( identifier[self] , identifier[lr_decay_opt_states_reset] : identifier[str] , identifier[process_manager] : identifier[Optional] [ literal[string] ]= keyword[None] ,
identifier[keep_training_state] = keyword[False] ):
literal[string]
identifier[utils] . identifie... | def _cleanup(self, lr_decay_opt_states_reset: str, process_manager: Optional['DecoderProcessManager']=None, keep_training_state=False):
"""
Cleans parameter files, training state directory and waits for remaining decoding processes.
"""
utils.cleanup_params_files(self.model.output_dir, self.max_... |
def detection(reference_tempi, reference_weight, estimated_tempi, tol=0.08):
"""Compute the tempo detection accuracy metric.
Parameters
----------
reference_tempi : np.ndarray, shape=(2,)
Two non-negative reference tempi
reference_weight : float > 0
The relative strength of ``refer... | def function[detection, parameter[reference_tempi, reference_weight, estimated_tempi, tol]]:
constant[Compute the tempo detection accuracy metric.
Parameters
----------
reference_tempi : np.ndarray, shape=(2,)
Two non-negative reference tempi
reference_weight : float > 0
The re... | keyword[def] identifier[detection] ( identifier[reference_tempi] , identifier[reference_weight] , identifier[estimated_tempi] , identifier[tol] = literal[int] ):
literal[string]
identifier[validate] ( identifier[reference_tempi] , identifier[reference_weight] , identifier[estimated_tempi] )
keyword[... | def detection(reference_tempi, reference_weight, estimated_tempi, tol=0.08):
"""Compute the tempo detection accuracy metric.
Parameters
----------
reference_tempi : np.ndarray, shape=(2,)
Two non-negative reference tempi
reference_weight : float > 0
The relative strength of ``refer... |
def match_files(files, pattern: Pattern):
"""Yields file name if matches a regular expression pattern."""
for name in files:
if re.match(pattern, name):
yield name | def function[match_files, parameter[files, pattern]]:
constant[Yields file name if matches a regular expression pattern.]
for taget[name[name]] in starred[name[files]] begin[:]
if call[name[re].match, parameter[name[pattern], name[name]]] begin[:]
<ast.Yield objec... | keyword[def] identifier[match_files] ( identifier[files] , identifier[pattern] : identifier[Pattern] ):
literal[string]
keyword[for] identifier[name] keyword[in] identifier[files] :
keyword[if] identifier[re] . identifier[match] ( identifier[pattern] , identifier[name] ):
keyword... | def match_files(files, pattern: Pattern):
"""Yields file name if matches a regular expression pattern."""
for name in files:
if re.match(pattern, name):
yield name # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['name']] |
def isUpdated(self):
"""
Figures out if the file had previously errored and hasn't
been fixed since given a numerical time
"""
modified_time = self.getmtime()
valid = modified_time > self.__stamp
return valid | def function[isUpdated, parameter[self]]:
constant[
Figures out if the file had previously errored and hasn't
been fixed since given a numerical time
]
variable[modified_time] assign[=] call[name[self].getmtime, parameter[]]
variable[valid] assign[=] compare[name[modified... | keyword[def] identifier[isUpdated] ( identifier[self] ):
literal[string]
identifier[modified_time] = identifier[self] . identifier[getmtime] ()
identifier[valid] = identifier[modified_time] > identifier[self] . identifier[__stamp]
keyword[return] identifier[valid] | def isUpdated(self):
"""
Figures out if the file had previously errored and hasn't
been fixed since given a numerical time
"""
modified_time = self.getmtime()
valid = modified_time > self.__stamp
return valid |
def numbafy(fn, args, compiler="jit", **nbkws):
"""
Compile a string, sympy expression or symengine expression using numba.
Not all functions are supported by Python's numerical package (numpy). For
difficult cases, valid Python code (as string) may be more suitable than
symbolic expressions coming... | def function[numbafy, parameter[fn, args, compiler]]:
constant[
Compile a string, sympy expression or symengine expression using numba.
Not all functions are supported by Python's numerical package (numpy). For
difficult cases, valid Python code (as string) may be more suitable than
symbolic ex... | keyword[def] identifier[numbafy] ( identifier[fn] , identifier[args] , identifier[compiler] = literal[string] ,** identifier[nbkws] ):
literal[string]
identifier[kwargs] ={}
keyword[if] keyword[not] identifier[isinstance] ( identifier[args] ,( identifier[tuple] , identifier[list] )):
identi... | def numbafy(fn, args, compiler='jit', **nbkws):
"""
Compile a string, sympy expression or symengine expression using numba.
Not all functions are supported by Python's numerical package (numpy). For
difficult cases, valid Python code (as string) may be more suitable than
symbolic expressions coming... |
def model_metrics(self, timeoutSecs=60, **kwargs):
'''
ModelMetrics list.
'''
result = self.do_json_request('/3/ModelMetrics.json', cmd='get', timeout=timeoutSecs)
h2o_sandbox.check_sandbox_for_errors()
return result | def function[model_metrics, parameter[self, timeoutSecs]]:
constant[
ModelMetrics list.
]
variable[result] assign[=] call[name[self].do_json_request, parameter[constant[/3/ModelMetrics.json]]]
call[name[h2o_sandbox].check_sandbox_for_errors, parameter[]]
return[name[result]] | keyword[def] identifier[model_metrics] ( identifier[self] , identifier[timeoutSecs] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[result] = identifier[self] . identifier[do_json_request] ( literal[string] , identifier[cmd] = literal[string] , identifier[timeout] = identifier[timeoutSe... | def model_metrics(self, timeoutSecs=60, **kwargs):
"""
ModelMetrics list.
"""
result = self.do_json_request('/3/ModelMetrics.json', cmd='get', timeout=timeoutSecs)
h2o_sandbox.check_sandbox_for_errors()
return result |
def demean_forward_returns(factor_data, grouper=None):
"""
Convert forward returns to returns relative to mean
period wise all-universe or group returns.
group-wise normalization incorporates the assumption of a
group neutral portfolio constraint and thus allows allows the
factor to be evaluated... | def function[demean_forward_returns, parameter[factor_data, grouper]]:
constant[
Convert forward returns to returns relative to mean
period wise all-universe or group returns.
group-wise normalization incorporates the assumption of a
group neutral portfolio constraint and thus allows allows the
... | keyword[def] identifier[demean_forward_returns] ( identifier[factor_data] , identifier[grouper] = keyword[None] ):
literal[string]
identifier[factor_data] = identifier[factor_data] . identifier[copy] ()
keyword[if] keyword[not] identifier[grouper] :
identifier[grouper] = identifier[factor... | def demean_forward_returns(factor_data, grouper=None):
"""
Convert forward returns to returns relative to mean
period wise all-universe or group returns.
group-wise normalization incorporates the assumption of a
group neutral portfolio constraint and thus allows allows the
factor to be evaluated... |
def parse_uci(self, uci: str) -> Move:
"""
Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
... | def function[parse_uci, parameter[self, uci]]:
constant[
Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in ... | keyword[def] identifier[parse_uci] ( identifier[self] , identifier[uci] : identifier[str] )-> identifier[Move] :
literal[string]
identifier[move] = identifier[Move] . identifier[from_uci] ( identifier[uci] )
keyword[if] keyword[not] identifier[move] :
keyword[return] ident... | def parse_uci(self, uci: str) -> Move:
"""
Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
cu... |
def signUserCsr(self, xcsr, signas, outp=None):
'''
Signs a user CSR with a CA keypair.
Args:
cert (OpenSSL.crypto.X509Req): The certificate signing request.
signas (str): The CA keypair name to sign the CSR with.
outp (synapse.lib.output.Output): The output ... | def function[signUserCsr, parameter[self, xcsr, signas, outp]]:
constant[
Signs a user CSR with a CA keypair.
Args:
cert (OpenSSL.crypto.X509Req): The certificate signing request.
signas (str): The CA keypair name to sign the CSR with.
outp (synapse.lib.outpu... | keyword[def] identifier[signUserCsr] ( identifier[self] , identifier[xcsr] , identifier[signas] , identifier[outp] = keyword[None] ):
literal[string]
identifier[pkey] = identifier[xcsr] . identifier[get_pubkey] ()
identifier[name] = identifier[xcsr] . identifier[get_subject] (). identifier... | def signUserCsr(self, xcsr, signas, outp=None):
"""
Signs a user CSR with a CA keypair.
Args:
cert (OpenSSL.crypto.X509Req): The certificate signing request.
signas (str): The CA keypair name to sign the CSR with.
outp (synapse.lib.output.Output): The output buff... |
def get_assessment_part_form_for_create_for_assessment_part(self, assessment_part_id, assessment_part_record_types):
"""Gets the assessment part form for creating new assessment parts under another assessment part.
A new form should be requested for each create transaction.
arg: assessment_... | def function[get_assessment_part_form_for_create_for_assessment_part, parameter[self, assessment_part_id, assessment_part_record_types]]:
constant[Gets the assessment part form for creating new assessment parts under another assessment part.
A new form should be requested for each create transaction.
... | keyword[def] identifier[get_assessment_part_form_for_create_for_assessment_part] ( identifier[self] , identifier[assessment_part_id] , identifier[assessment_part_record_types] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[assessment_part_id] , identifier[ABCId] )... | def get_assessment_part_form_for_create_for_assessment_part(self, assessment_part_id, assessment_part_record_types):
"""Gets the assessment part form for creating new assessment parts under another assessment part.
A new form should be requested for each create transaction.
arg: assessment_part... |
def example_lab_to_rgb():
"""
Conversions to RGB are a little more complex mathematically. There are also
several kinds of RGB color spaces. When converting from a device-independent
color space to RGB, sRGB is assumed unless otherwise specified with the
target_rgb keyword arg.
"""
print("=... | def function[example_lab_to_rgb, parameter[]]:
constant[
Conversions to RGB are a little more complex mathematically. There are also
several kinds of RGB color spaces. When converting from a device-independent
color space to RGB, sRGB is assumed unless otherwise specified with the
target_rgb key... | keyword[def] identifier[example_lab_to_rgb] ():
literal[string]
identifier[print] ( literal[string] )
identifier[lab] = identifier[LabColor] ( literal[int] , literal[int] ,- literal[int] )
identifier[print] ( identifier[lab] )
identifier[rgb] = identifier[convert_color] ( ide... | def example_lab_to_rgb():
"""
Conversions to RGB are a little more complex mathematically. There are also
several kinds of RGB color spaces. When converting from a device-independent
color space to RGB, sRGB is assumed unless otherwise specified with the
target_rgb keyword arg.
"""
print('==... |
def packed_workflow(self, packed): # type: (Text) -> None
"""Pack CWL description to generate re-runnable CWL object in RO."""
self.self_check()
rel_path = posixpath.join(_posix_path(WORKFLOW), "packed.cwl")
# Write as binary
with self.write_bag_file(rel_path, encoding=None) as ... | def function[packed_workflow, parameter[self, packed]]:
constant[Pack CWL description to generate re-runnable CWL object in RO.]
call[name[self].self_check, parameter[]]
variable[rel_path] assign[=] call[name[posixpath].join, parameter[call[name[_posix_path], parameter[name[WORKFLOW]]], constant... | keyword[def] identifier[packed_workflow] ( identifier[self] , identifier[packed] ):
literal[string]
identifier[self] . identifier[self_check] ()
identifier[rel_path] = identifier[posixpath] . identifier[join] ( identifier[_posix_path] ( identifier[WORKFLOW] ), literal[string] )
... | def packed_workflow(self, packed): # type: (Text) -> None
'Pack CWL description to generate re-runnable CWL object in RO.'
self.self_check()
rel_path = posixpath.join(_posix_path(WORKFLOW), 'packed.cwl')
# Write as binary
with self.write_bag_file(rel_path, encoding=None) as write_pack:
# YA... |
def hash_algo(self):
"""
:return:
A unicode string of "md2", "md5", "sha1", "sha224", "sha256",
"sha384", "sha512", "sha512_224", "sha512_256"
"""
algorithm = self['algorithm'].native
algo_map = {
'md2_rsa': 'md2',
'md5_rsa': 'md5... | def function[hash_algo, parameter[self]]:
constant[
:return:
A unicode string of "md2", "md5", "sha1", "sha224", "sha256",
"sha384", "sha512", "sha512_224", "sha512_256"
]
variable[algorithm] assign[=] call[name[self]][constant[algorithm]].native
variable[... | keyword[def] identifier[hash_algo] ( identifier[self] ):
literal[string]
identifier[algorithm] = identifier[self] [ literal[string] ]. identifier[native]
identifier[algo_map] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[st... | def hash_algo(self):
"""
:return:
A unicode string of "md2", "md5", "sha1", "sha224", "sha256",
"sha384", "sha512", "sha512_224", "sha512_256"
"""
algorithm = self['algorithm'].native
algo_map = {'md2_rsa': 'md2', 'md5_rsa': 'md5', 'sha1_rsa': 'sha1', 'sha224_rsa': 's... |
def compute_exports(exports):
"""Compute a dictionary of exports given one of the parameters
to the Export() function or the exports argument to SConscript()."""
loc, glob = get_calling_namespaces()
retval = {}
try:
for export in exports:
if SCons.Util.is_Dict(export):
... | def function[compute_exports, parameter[exports]]:
constant[Compute a dictionary of exports given one of the parameters
to the Export() function or the exports argument to SConscript().]
<ast.Tuple object at 0x7da20c76eb30> assign[=] call[name[get_calling_namespaces], parameter[]]
variable[r... | keyword[def] identifier[compute_exports] ( identifier[exports] ):
literal[string]
identifier[loc] , identifier[glob] = identifier[get_calling_namespaces] ()
identifier[retval] ={}
keyword[try] :
keyword[for] identifier[export] keyword[in] identifier[exports] :
keyword[i... | def compute_exports(exports):
"""Compute a dictionary of exports given one of the parameters
to the Export() function or the exports argument to SConscript()."""
(loc, glob) = get_calling_namespaces()
retval = {}
try:
for export in exports:
if SCons.Util.is_Dict(export):
... |
def safe(self,x):
"""removes nans and infs from outputs."""
x[np.isinf(x)] = 1
x[np.isnan(x)] = 1
return x | def function[safe, parameter[self, x]]:
constant[removes nans and infs from outputs.]
call[name[x]][call[name[np].isinf, parameter[name[x]]]] assign[=] constant[1]
call[name[x]][call[name[np].isnan, parameter[name[x]]]] assign[=] constant[1]
return[name[x]] | keyword[def] identifier[safe] ( identifier[self] , identifier[x] ):
literal[string]
identifier[x] [ identifier[np] . identifier[isinf] ( identifier[x] )]= literal[int]
identifier[x] [ identifier[np] . identifier[isnan] ( identifier[x] )]= literal[int]
keyword[return] identifier... | def safe(self, x):
"""removes nans and infs from outputs."""
x[np.isinf(x)] = 1
x[np.isnan(x)] = 1
return x |
def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n... | def function[image_predict_proba, parameter[self, X]]:
constant[
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples]... | keyword[def] identifier[image_predict_proba] ( identifier[self] , identifier[X] ):
literal[string]
identifier[self] . identifier[_check_image] ( identifier[X] )
identifier[new_shape] =( identifier[X] . identifier[shape] [ literal[int] ]* identifier[X] . identifier[shape] [ literal[int... | def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n_pixels_x, n_p... |
def fetch_object(self, doc_id):
"""Fetch the document by its PK."""
try:
return self.object_class.objects.get(pk=doc_id)
except self.object_class.DoesNotExist:
raise ReferenceNotFoundError | def function[fetch_object, parameter[self, doc_id]]:
constant[Fetch the document by its PK.]
<ast.Try object at 0x7da1b0ca78e0> | keyword[def] identifier[fetch_object] ( identifier[self] , identifier[doc_id] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[object_class] . identifier[objects] . identifier[get] ( identifier[pk] = identifier[doc_id] )
keyword[except] identif... | def fetch_object(self, doc_id):
"""Fetch the document by its PK."""
try:
return self.object_class.objects.get(pk=doc_id) # depends on [control=['try'], data=[]]
except self.object_class.DoesNotExist:
raise ReferenceNotFoundError # depends on [control=['except'], data=[]] |
def reset(self, iface=None, client_mac=None, xid=None, scriptfile=None):
"""Reset object attributes when state is INIT."""
logger.debug('Reseting attributes.')
if iface is None:
iface = conf.iface
if client_mac is None:
# scapy for python 3 returns byte, not tuple... | def function[reset, parameter[self, iface, client_mac, xid, scriptfile]]:
constant[Reset object attributes when state is INIT.]
call[name[logger].debug, parameter[constant[Reseting attributes.]]]
if compare[name[iface] is constant[None]] begin[:]
variable[iface] assign[=] name[co... | keyword[def] identifier[reset] ( identifier[self] , identifier[iface] = keyword[None] , identifier[client_mac] = keyword[None] , identifier[xid] = keyword[None] , identifier[scriptfile] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
keyword[if... | def reset(self, iface=None, client_mac=None, xid=None, scriptfile=None):
"""Reset object attributes when state is INIT."""
logger.debug('Reseting attributes.')
if iface is None:
iface = conf.iface # depends on [control=['if'], data=['iface']]
if client_mac is None:
# scapy for python 3 ... |
def create_app():
""" Flask application factory """
# Setup Flask app and app.config
app = Flask(__name__)
app.config.from_object(__name__+'.ConfigClass')
# Initialize Flask extensions
db = SQLAlchemy(app) # Initialize Flask-SQLAlchemy
# Define the User data... | def function[create_app, parameter[]]:
constant[ Flask application factory ]
variable[app] assign[=] call[name[Flask], parameter[name[__name__]]]
call[name[app].config.from_object, parameter[binary_operation[name[__name__] + constant[.ConfigClass]]]]
variable[db] assign[=] call[name[SQLA... | keyword[def] identifier[create_app] ():
literal[string]
identifier[app] = identifier[Flask] ( identifier[__name__] )
identifier[app] . identifier[config] . identifier[from_object] ( identifier[__name__] + literal[string] )
identifier[db] = identifier[SQLAlchemy] ( identifier[app] )
... | def create_app():
""" Flask application factory """
# Setup Flask app and app.config
app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass')
# Initialize Flask extensions
db = SQLAlchemy(app) # Initialize Flask-SQLAlchemy
# Define the User data-model. Make sure to add flask_... |
def _sync_folder_to_container(self, folder_path, container, prefix, delete,
include_hidden, ignore, ignore_timestamps, object_prefix, verbose):
"""
This is the internal method that is called recursively to handle
nested folder structures.
"""
fnames = os.listdir(folde... | def function[_sync_folder_to_container, parameter[self, folder_path, container, prefix, delete, include_hidden, ignore, ignore_timestamps, object_prefix, verbose]]:
constant[
This is the internal method that is called recursively to handle
nested folder structures.
]
variable[fna... | keyword[def] identifier[_sync_folder_to_container] ( identifier[self] , identifier[folder_path] , identifier[container] , identifier[prefix] , identifier[delete] ,
identifier[include_hidden] , identifier[ignore] , identifier[ignore_timestamps] , identifier[object_prefix] , identifier[verbose] ):
literal[str... | def _sync_folder_to_container(self, folder_path, container, prefix, delete, include_hidden, ignore, ignore_timestamps, object_prefix, verbose):
"""
This is the internal method that is called recursively to handle
nested folder structures.
"""
fnames = os.listdir(folder_path)
ignore =... |
def all_table_names_in_database(self, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments."""
if not self.allow_multi_schema_metadata_fetch:
return []
return self.db_engine_spec.fetch_result_sets(self... | def function[all_table_names_in_database, parameter[self, cache, cache_timeout, force]]:
constant[Parameters need to be passed as keyword arguments.]
if <ast.UnaryOp object at 0x7da1b2030b20> begin[:]
return[list[[]]]
return[call[name[self].db_engine_spec.fetch_result_sets, parameter[name[se... | keyword[def] identifier[all_table_names_in_database] ( identifier[self] , identifier[cache] = keyword[False] ,
identifier[cache_timeout] = keyword[None] , identifier[force] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[allow_multi_schema_metadata_fetc... | def all_table_names_in_database(self, cache=False, cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments."""
if not self.allow_multi_schema_metadata_fetch:
return [] # depends on [control=['if'], data=[]]
return self.db_engine_spec.fetch_result_sets(self, 'table') |
def main_executable_region_limbos_contain(self, addr):
"""
Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes
after the beginning of the section. We take care of that here.
:param int addr: The address to check.
:return:... | def function[main_executable_region_limbos_contain, parameter[self, addr]]:
constant[
Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes
after the beginning of the section. We take care of that here.
:param int addr: The address... | keyword[def] identifier[main_executable_region_limbos_contain] ( identifier[self] , identifier[addr] ):
literal[string]
identifier[TOLERANCE] = literal[int]
identifier[closest_region] = keyword[None]
identifier[least_limbo] = keyword[None]
keyword[for] identifier[s... | def main_executable_region_limbos_contain(self, addr):
"""
Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes
after the beginning of the section. We take care of that here.
:param int addr: The address to check.
:return: A 2... |
def cli(ctx, data, verbose, color, format, editor):
"""Query a meetup database.
"""
ctx.obj['verbose'] = verbose
if verbose:
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
ctx.obj['datadir'] = os.path.abspath(data)
if 'db' no... | def function[cli, parameter[ctx, data, verbose, color, format, editor]]:
constant[Query a meetup database.
]
call[name[ctx].obj][constant[verbose]] assign[=] name[verbose]
if name[verbose] begin[:]
call[name[logging].basicConfig, parameter[]]
call[call[name[lo... | keyword[def] identifier[cli] ( identifier[ctx] , identifier[data] , identifier[verbose] , identifier[color] , identifier[format] , identifier[editor] ):
literal[string]
identifier[ctx] . identifier[obj] [ literal[string] ]= identifier[verbose]
keyword[if] identifier[verbose] :
identifier[lo... | def cli(ctx, data, verbose, color, format, editor):
"""Query a meetup database.
"""
ctx.obj['verbose'] = verbose
if verbose:
logging.basicConfig(level=logging.INFO)
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) # depends on [control=['if'], data=[]]
ctx.obj['datadir'... |
def run(self):
'''Reads from the channel (pipe) that is the output pipe for a
called Popen. As we are reading from the pipe, the output is added
to a deque. After the size of the deque exceeds the sizelimit
earlier (older) entries are removed.
This means the returned output is c... | def function[run, parameter[self]]:
constant[Reads from the channel (pipe) that is the output pipe for a
called Popen. As we are reading from the pipe, the output is added
to a deque. After the size of the deque exceeds the sizelimit
earlier (older) entries are removed.
This mea... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[while] keyword[True] :
identifier[line] = identifier[self] . identifier[chan] . identifier[read] ( identifier[self] . identifier[chunksize] )
keyword[if] keywor... | def run(self):
"""Reads from the channel (pipe) that is the output pipe for a
called Popen. As we are reading from the pipe, the output is added
to a deque. After the size of the deque exceeds the sizelimit
earlier (older) entries are removed.
This means the returned output is chunk... |
def set_zero_config(self):
"""Set config such that radiative forcing and temperature output will be zero
This method is intended as a convenience only, it does not handle everything in
an obvious way. Adjusting the parameter settings still requires great care and
may behave unepexctedly... | def function[set_zero_config, parameter[self]]:
constant[Set config such that radiative forcing and temperature output will be zero
This method is intended as a convenience only, it does not handle everything in
an obvious way. Adjusting the parameter settings still requires great care and
... | keyword[def] identifier[set_zero_config] ( identifier[self] ):
literal[string]
identifier[zero_emissions] . identifier[write] ( identifier[join] ( identifier[self] . identifier[run_dir] , identifier[self] . identifier[_scen_file_name] ), identifier[self] . identifier[version] )
i... | def set_zero_config(self):
"""Set config such that radiative forcing and temperature output will be zero
This method is intended as a convenience only, it does not handle everything in
an obvious way. Adjusting the parameter settings still requires great care and
may behave unepexctedly.
... |
def onCall(self, n): #pylint: disable=invalid-name
"""
Adds a condition for when the stub is called. When the condition is met, a special
return value can be returned. Adds the specified call number into the condition
list.
For example, when the stub function is called the secon... | def function[onCall, parameter[self, n]]:
constant[
Adds a condition for when the stub is called. When the condition is met, a special
return value can be returned. Adds the specified call number into the condition
list.
For example, when the stub function is called the second t... | keyword[def] identifier[onCall] ( identifier[self] , identifier[n] ):
literal[string]
identifier[cond_oncall] = identifier[n] + literal[int]
keyword[return] identifier[_SinonStubCondition] ( identifier[copy] = identifier[self] . identifier[_copy] , identifier[oncall] = identifier[cond_on... | def onCall(self, n): #pylint: disable=invalid-name
'\n Adds a condition for when the stub is called. When the condition is met, a special\n return value can be returned. Adds the specified call number into the condition\n list.\n\n For example, when the stub function is called the secon... |
def public_dsn(dsn):
'''Transform a standard Sentry DSN into a public one'''
m = RE_DSN.match(dsn)
if not m:
log.error('Unable to parse Sentry DSN')
public = '{scheme}://{client_id}@{domain}/{site_id}'.format(
**m.groupdict())
return public | def function[public_dsn, parameter[dsn]]:
constant[Transform a standard Sentry DSN into a public one]
variable[m] assign[=] call[name[RE_DSN].match, parameter[name[dsn]]]
if <ast.UnaryOp object at 0x7da18f09d7e0> begin[:]
call[name[log].error, parameter[constant[Unable to parse S... | keyword[def] identifier[public_dsn] ( identifier[dsn] ):
literal[string]
identifier[m] = identifier[RE_DSN] . identifier[match] ( identifier[dsn] )
keyword[if] keyword[not] identifier[m] :
identifier[log] . identifier[error] ( literal[string] )
identifier[public] = literal[string] . id... | def public_dsn(dsn):
"""Transform a standard Sentry DSN into a public one"""
m = RE_DSN.match(dsn)
if not m:
log.error('Unable to parse Sentry DSN') # depends on [control=['if'], data=[]]
public = '{scheme}://{client_id}@{domain}/{site_id}'.format(**m.groupdict())
return public |
def download(self, field):
"""Download a file.
:param field: file field to download
:type field: string
:rtype: a file handle
"""
if not field.startswith('output'):
raise ValueError("Only processor results (output.* fields) can be downloaded")
if fi... | def function[download, parameter[self, field]]:
constant[Download a file.
:param field: file field to download
:type field: string
:rtype: a file handle
]
if <ast.UnaryOp object at 0x7da1b26ac550> begin[:]
<ast.Raise object at 0x7da1b26ad0c0>
if compare[... | keyword[def] identifier[download] ( identifier[self] , identifier[field] ):
literal[string]
keyword[if] keyword[not] identifier[field] . identifier[startswith] ( literal[string] ):
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] identifier[field] ke... | def download(self, field):
"""Download a file.
:param field: file field to download
:type field: string
:rtype: a file handle
"""
if not field.startswith('output'):
raise ValueError('Only processor results (output.* fields) can be downloaded') # depends on [control=['i... |
def _refresh_controller_id(self):
"""Determine the Kafka cluster controller."""
version = self._matching_api_version(MetadataRequest)
if 1 <= version <= 6:
request = MetadataRequest[version]()
response = self._send_request_to_node(self._client.least_loaded_node(), request... | def function[_refresh_controller_id, parameter[self]]:
constant[Determine the Kafka cluster controller.]
variable[version] assign[=] call[name[self]._matching_api_version, parameter[name[MetadataRequest]]]
if compare[constant[1] less_or_equal[<=] name[version]] begin[:]
variable[... | keyword[def] identifier[_refresh_controller_id] ( identifier[self] ):
literal[string]
identifier[version] = identifier[self] . identifier[_matching_api_version] ( identifier[MetadataRequest] )
keyword[if] literal[int] <= identifier[version] <= literal[int] :
identifier[reques... | def _refresh_controller_id(self):
"""Determine the Kafka cluster controller."""
version = self._matching_api_version(MetadataRequest)
if 1 <= version <= 6:
request = MetadataRequest[version]()
response = self._send_request_to_node(self._client.least_loaded_node(), request)
controller... |
def auth_finish(self, _unused):
"""Handle success of the legacy authentication."""
self.lock.acquire()
try:
self.__logger.debug("Authenticated")
self.authenticated=True
self.state_change("authorized",self.my_jid)
self._post_auth()
finally:
... | def function[auth_finish, parameter[self, _unused]]:
constant[Handle success of the legacy authentication.]
call[name[self].lock.acquire, parameter[]]
<ast.Try object at 0x7da2046226e0> | keyword[def] identifier[auth_finish] ( identifier[self] , identifier[_unused] ):
literal[string]
identifier[self] . identifier[lock] . identifier[acquire] ()
keyword[try] :
identifier[self] . identifier[__logger] . identifier[debug] ( literal[string] )
identifier[... | def auth_finish(self, _unused):
"""Handle success of the legacy authentication."""
self.lock.acquire()
try:
self.__logger.debug('Authenticated')
self.authenticated = True
self.state_change('authorized', self.my_jid)
self._post_auth() # depends on [control=['try'], data=[]]
... |
def validate_client_id(self, client_id, request, *args, **kwargs):
"""Ensure client_id belong to a valid and active client."""
log.debug('Validate client %r', client_id)
client = request.client or self._clientgetter(client_id)
if client:
# attach client to request object
... | def function[validate_client_id, parameter[self, client_id, request]]:
constant[Ensure client_id belong to a valid and active client.]
call[name[log].debug, parameter[constant[Validate client %r], name[client_id]]]
variable[client] assign[=] <ast.BoolOp object at 0x7da1b020dc30>
if name[... | keyword[def] identifier[validate_client_id] ( identifier[self] , identifier[client_id] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] , identifier[client_id] )
identifier[client] = identifier[request... | def validate_client_id(self, client_id, request, *args, **kwargs):
"""Ensure client_id belong to a valid and active client."""
log.debug('Validate client %r', client_id)
client = request.client or self._clientgetter(client_id)
if client:
# attach client to request object
request.client =... |
def _queue_response_channel(self, obj):
"""Generate the feedback channel name from the object's id.
:param obj: The Channels message object.
"""
return '{}.{}'.format(state.MANAGER_EXECUTOR_CHANNELS.queue_response, obj[ExecutorProtocol.DATA_ID]) | def function[_queue_response_channel, parameter[self, obj]]:
constant[Generate the feedback channel name from the object's id.
:param obj: The Channels message object.
]
return[call[constant[{}.{}].format, parameter[name[state].MANAGER_EXECUTOR_CHANNELS.queue_response, call[name[obj]][name[... | keyword[def] identifier[_queue_response_channel] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[return] literal[string] . identifier[format] ( identifier[state] . identifier[MANAGER_EXECUTOR_CHANNELS] . identifier[queue_response] , identifier[obj] [ identifier[ExecutorProtocol] . ... | def _queue_response_channel(self, obj):
"""Generate the feedback channel name from the object's id.
:param obj: The Channels message object.
"""
return '{}.{}'.format(state.MANAGER_EXECUTOR_CHANNELS.queue_response, obj[ExecutorProtocol.DATA_ID]) |
def qualified_name(self):
"""Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
"""
parent = self.full_parent_name
if parent:
... | def function[qualified_name, parameter[self]]:
constant[Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
]
variable[parent] assign[=] ... | keyword[def] identifier[qualified_name] ( identifier[self] ):
literal[string]
identifier[parent] = identifier[self] . identifier[full_parent_name]
keyword[if] identifier[parent] :
keyword[return] identifier[parent] + literal[string] + identifier[self] . identifier[name]
... | def qualified_name(self):
"""Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``?one two three`` the qualified name would be
``one two three``.
"""
parent = self.full_parent_name
if parent:
return... |
def rmse(self, relative_to='AME2003'):
"""Calculate root mean squared error
Parameters
----------
relative_to : string,
a valid mass table name.
Example:
----------
>>> template = '{0:10}|{1:^6.2f}|{2:^6.2f}|{3:^6.2f}'
>>> print 'Model '... | def function[rmse, parameter[self, relative_to]]:
constant[Calculate root mean squared error
Parameters
----------
relative_to : string,
a valid mass table name.
Example:
----------
>>> template = '{0:10}|{1:^6.2f}|{2:^6.2f}|{3:^6.2f}'
>>> pr... | keyword[def] identifier[rmse] ( identifier[self] , identifier[relative_to] = literal[string] ):
literal[string]
identifier[error] = identifier[self] . identifier[error] ( identifier[relative_to] = identifier[relative_to] )
keyword[return] identifier[math] . identifier[sqrt] (( identifier... | def rmse(self, relative_to='AME2003'):
"""Calculate root mean squared error
Parameters
----------
relative_to : string,
a valid mass table name.
Example:
----------
>>> template = '{0:10}|{1:^6.2f}|{2:^6.2f}|{3:^6.2f}'
>>> print 'Model ', 'A... |
def match(self, s=''):
"""return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options.
"""
match = s.lower()
res = {}
for k in sorted(self)... | def function[match, parameter[self, s]]:
constant[return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options.
]
variable[match] assign[=] call[name[s].low... | keyword[def] identifier[match] ( identifier[self] , identifier[s] = literal[string] ):
literal[string]
identifier[match] = identifier[s] . identifier[lower] ()
identifier[res] ={}
keyword[for] identifier[k] keyword[in] identifier[sorted] ( identifier[self] ):
ident... | def match(self, s=''):
"""return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options.
"""
match = s.lower()
res = {}
for k in sorted(self):
s = st... |
def log_entries(self, time_zone='UTC', is_overview=False,
include=None, fetch_all=True):
"""Query for log entries on an incident instance."""
endpoint = '/'.join((self.endpoint, self.id, 'log_entries'))
query_params = {
'time_zone': time_zone,
'is_ove... | def function[log_entries, parameter[self, time_zone, is_overview, include, fetch_all]]:
constant[Query for log entries on an incident instance.]
variable[endpoint] assign[=] call[constant[/].join, parameter[tuple[[<ast.Attribute object at 0x7da1b06fefe0>, <ast.Attribute object at 0x7da1b06ffa00>, <ast.C... | keyword[def] identifier[log_entries] ( identifier[self] , identifier[time_zone] = literal[string] , identifier[is_overview] = keyword[False] ,
identifier[include] = keyword[None] , identifier[fetch_all] = keyword[True] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[join] ((... | def log_entries(self, time_zone='UTC', is_overview=False, include=None, fetch_all=True):
"""Query for log entries on an incident instance."""
endpoint = '/'.join((self.endpoint, self.id, 'log_entries'))
query_params = {'time_zone': time_zone, 'is_overview': json.dumps(is_overview)}
if include:
q... |
def on_batch_begin(self, train, **kwargs:Any)->None:
"Record learning rate and momentum at beginning of batch."
if train:
self.lrs.append(self.opt.lr)
self.moms.append(self.opt.mom) | def function[on_batch_begin, parameter[self, train]]:
constant[Record learning rate and momentum at beginning of batch.]
if name[train] begin[:]
call[name[self].lrs.append, parameter[name[self].opt.lr]]
call[name[self].moms.append, parameter[name[self].opt.mom]] | keyword[def] identifier[on_batch_begin] ( identifier[self] , identifier[train] ,** identifier[kwargs] : identifier[Any] )-> keyword[None] :
literal[string]
keyword[if] identifier[train] :
identifier[self] . identifier[lrs] . identifier[append] ( identifier[self] . identifier[opt] . id... | def on_batch_begin(self, train, **kwargs: Any) -> None:
"""Record learning rate and momentum at beginning of batch."""
if train:
self.lrs.append(self.opt.lr)
self.moms.append(self.opt.mom) # depends on [control=['if'], data=[]] |
def remove_class(self, ioclass):
"""Remove VNXIOClass instance from policy."""
current_ioclasses = self.ioclasses
new_ioclasses = filter(lambda x: x.name != ioclass.name,
current_ioclasses)
self.modify(new_ioclasses=new_ioclasses) | def function[remove_class, parameter[self, ioclass]]:
constant[Remove VNXIOClass instance from policy.]
variable[current_ioclasses] assign[=] name[self].ioclasses
variable[new_ioclasses] assign[=] call[name[filter], parameter[<ast.Lambda object at 0x7da1b1150400>, name[current_ioclasses]]]
... | keyword[def] identifier[remove_class] ( identifier[self] , identifier[ioclass] ):
literal[string]
identifier[current_ioclasses] = identifier[self] . identifier[ioclasses]
identifier[new_ioclasses] = identifier[filter] ( keyword[lambda] identifier[x] : identifier[x] . identifier[name] != ... | def remove_class(self, ioclass):
"""Remove VNXIOClass instance from policy."""
current_ioclasses = self.ioclasses
new_ioclasses = filter(lambda x: x.name != ioclass.name, current_ioclasses)
self.modify(new_ioclasses=new_ioclasses) |
def _controller(self):
"""Return the server controller."""
def server_controller(cmd_id, cmd_body, _):
"""Server controler."""
if not self.init_logginig:
# the reason put the codes here is because we cannot get
# kvstore.rank earlier
... | def function[_controller, parameter[self]]:
constant[Return the server controller.]
def function[server_controller, parameter[cmd_id, cmd_body, _]]:
constant[Server controler.]
if <ast.UnaryOp object at 0x7da2049603d0> begin[:]
variable[head] assig... | keyword[def] identifier[_controller] ( identifier[self] ):
literal[string]
keyword[def] identifier[server_controller] ( identifier[cmd_id] , identifier[cmd_body] , identifier[_] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[init_logginig] :
... | def _controller(self):
"""Return the server controller."""
def server_controller(cmd_id, cmd_body, _):
"""Server controler."""
if not self.init_logginig:
# the reason put the codes here is because we cannot get
# kvstore.rank earlier
head = '%(asctime)-15s Se... |
def last_name(anon, obj, field, val):
"""
Returns a random second name
"""
return anon.faker.last_name(field=field) | def function[last_name, parameter[anon, obj, field, val]]:
constant[
Returns a random second name
]
return[call[name[anon].faker.last_name, parameter[]]] | keyword[def] identifier[last_name] ( identifier[anon] , identifier[obj] , identifier[field] , identifier[val] ):
literal[string]
keyword[return] identifier[anon] . identifier[faker] . identifier[last_name] ( identifier[field] = identifier[field] ) | def last_name(anon, obj, field, val):
"""
Returns a random second name
"""
return anon.faker.last_name(field=field) |
def boxed_text_to_image_block(tag):
"covert boxed-text to an image block containing an inline-graphic"
tag_block = OrderedDict()
image_content = body_block_image_content(first(raw_parser.inline_graphic(tag)))
tag_block["type"] = "image"
set_if_value(tag_block, "doi", doi_uri_to_doi(object_id_doi(tag... | def function[boxed_text_to_image_block, parameter[tag]]:
constant[covert boxed-text to an image block containing an inline-graphic]
variable[tag_block] assign[=] call[name[OrderedDict], parameter[]]
variable[image_content] assign[=] call[name[body_block_image_content], parameter[call[name[first]... | keyword[def] identifier[boxed_text_to_image_block] ( identifier[tag] ):
literal[string]
identifier[tag_block] = identifier[OrderedDict] ()
identifier[image_content] = identifier[body_block_image_content] ( identifier[first] ( identifier[raw_parser] . identifier[inline_graphic] ( identifier[tag] )))
... | def boxed_text_to_image_block(tag):
"""covert boxed-text to an image block containing an inline-graphic"""
tag_block = OrderedDict()
image_content = body_block_image_content(first(raw_parser.inline_graphic(tag)))
tag_block['type'] = 'image'
set_if_value(tag_block, 'doi', doi_uri_to_doi(object_id_doi... |
def blur(self, image, geometry, options):
"""
Wrapper for ``_blur``
"""
if options.get('blur'):
return self._blur(image, int(options.get('blur')))
return image | def function[blur, parameter[self, image, geometry, options]]:
constant[
Wrapper for ``_blur``
]
if call[name[options].get, parameter[constant[blur]]] begin[:]
return[call[name[self]._blur, parameter[name[image], call[name[int], parameter[call[name[options].get, parameter[constan... | keyword[def] identifier[blur] ( identifier[self] , identifier[image] , identifier[geometry] , identifier[options] ):
literal[string]
keyword[if] identifier[options] . identifier[get] ( literal[string] ):
keyword[return] identifier[self] . identifier[_blur] ( identifier[image] , ident... | def blur(self, image, geometry, options):
"""
Wrapper for ``_blur``
"""
if options.get('blur'):
return self._blur(image, int(options.get('blur'))) # depends on [control=['if'], data=[]]
return image |
def _forward_kernel(self, F, inputs, states, **kwargs):
""" forward using CUDNN or CPU kenrel"""
if self._layout == 'NTC':
inputs = F.swapaxes(inputs, dim1=0, dim2=1)
if self._projection_size is None:
params = (kwargs['{}{}_{}_{}'.format(d, l, g, t)].reshape(-1)
... | def function[_forward_kernel, parameter[self, F, inputs, states]]:
constant[ forward using CUDNN or CPU kenrel]
if compare[name[self]._layout equal[==] constant[NTC]] begin[:]
variable[inputs] assign[=] call[name[F].swapaxes, parameter[name[inputs]]]
if compare[name[self]._projec... | keyword[def] identifier[_forward_kernel] ( identifier[self] , identifier[F] , identifier[inputs] , identifier[states] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[_layout] == literal[string] :
identifier[inputs] = identifier[F] . identifier[swapa... | def _forward_kernel(self, F, inputs, states, **kwargs):
""" forward using CUDNN or CPU kenrel"""
if self._layout == 'NTC':
inputs = F.swapaxes(inputs, dim1=0, dim2=1) # depends on [control=['if'], data=[]]
if self._projection_size is None:
params = (kwargs['{}{}_{}_{}'.format(d, l, g, t)].r... |
def vcsmode_vcs_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcsmode = ET.SubElement(config, "vcsmode", xmlns="urn:brocade.com:mgmt:brocade-vcs")
vcs_mode = ET.SubElement(vcsmode, "vcs-mode")
vcs_mode.text = kwargs.pop('vcs_mode')
... | def function[vcsmode_vcs_mode, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[vcsmode] assign[=] call[name[ET].SubElement, parameter[name[config], constant[vcsmode]]]
variable[vcs_mode] assi... | keyword[def] identifier[vcsmode_vcs_mode] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[vcsmode] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , identi... | def vcsmode_vcs_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
vcsmode = ET.SubElement(config, 'vcsmode', xmlns='urn:brocade.com:mgmt:brocade-vcs')
vcs_mode = ET.SubElement(vcsmode, 'vcs-mode')
vcs_mode.text = kwargs.pop('vcs_mode')
callback = kwargs.pop('... |
def extend_selection():
"""Checks is the selection is to be extended
The selection is to be extended, if a special modifier key (typically <Ctrl>) is being pressed.
:return: If to extend the selection
:rtype: True
"""
from rafcon.gui.singleton import main_window_controller
currently_presse... | def function[extend_selection, parameter[]]:
constant[Checks is the selection is to be extended
The selection is to be extended, if a special modifier key (typically <Ctrl>) is being pressed.
:return: If to extend the selection
:rtype: True
]
from relative_module[rafcon.gui.singleton] impo... | keyword[def] identifier[extend_selection] ():
literal[string]
keyword[from] identifier[rafcon] . identifier[gui] . identifier[singleton] keyword[import] identifier[main_window_controller]
identifier[currently_pressed_keys] = identifier[main_window_controller] . identifier[currently_pressed_keys] ... | def extend_selection():
"""Checks is the selection is to be extended
The selection is to be extended, if a special modifier key (typically <Ctrl>) is being pressed.
:return: If to extend the selection
:rtype: True
"""
from rafcon.gui.singleton import main_window_controller
currently_presse... |
def change_color(self, selections, value):
'''Change the color of each atom by a certain value. *value*
should be a tuple.
'''
if 'atoms' in selections:
atms = selections['atoms'].mask
if value is None:
#self.radii_state.array[atms] = [vdw_radii.g... | def function[change_color, parameter[self, selections, value]]:
constant[Change the color of each atom by a certain value. *value*
should be a tuple.
]
if compare[constant[atoms] in name[selections]] begin[:]
variable[atms] assign[=] call[name[selections]][constant[atoms... | keyword[def] identifier[change_color] ( identifier[self] , identifier[selections] , identifier[value] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[selections] :
identifier[atms] = identifier[selections] [ literal[string] ]. identifier[mask]
key... | def change_color(self, selections, value):
"""Change the color of each atom by a certain value. *value*
should be a tuple.
"""
if 'atoms' in selections:
atms = selections['atoms'].mask
if value is None:
#self.radii_state.array[atms] = [vdw_radii.get(t) * 0.3 for t i... |
def insert_knot(obj, param, num, **kwargs):
""" Inserts knots n-times to a spline geometry.
The following code snippet illustrates the usage of this function:
.. code-block:: python
# Insert knot u=0.5 to a curve 2 times
operations.insert_knot(curve, [0.5], [2])
# Insert knot v=0... | def function[insert_knot, parameter[obj, param, num]]:
constant[ Inserts knots n-times to a spline geometry.
The following code snippet illustrates the usage of this function:
.. code-block:: python
# Insert knot u=0.5 to a curve 2 times
operations.insert_knot(curve, [0.5], [2])
... | keyword[def] identifier[insert_knot] ( identifier[obj] , identifier[param] , identifier[num] ,** identifier[kwargs] ):
literal[string]
identifier[check_num] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[True] )
keyword[if] identifier[check_num] :
keyword[if] ... | def insert_knot(obj, param, num, **kwargs):
""" Inserts knots n-times to a spline geometry.
The following code snippet illustrates the usage of this function:
.. code-block:: python
# Insert knot u=0.5 to a curve 2 times
operations.insert_knot(curve, [0.5], [2])
# Insert knot v=0... |
def _parse_host(host):
"""
The purpose of this function is to be robust to improper connections
settings provided by users, specifically in the host field.
For example -- when users supply ``https://xx.cloud.databricks.com`` as the
host, we must strip out the protocol to get the... | def function[_parse_host, parameter[host]]:
constant[
The purpose of this function is to be robust to improper connections
settings provided by users, specifically in the host field.
For example -- when users supply ``https://xx.cloud.databricks.com`` as the
host, we must strip ... | keyword[def] identifier[_parse_host] ( identifier[host] ):
literal[string]
identifier[urlparse_host] = identifier[urlparse] . identifier[urlparse] ( identifier[host] ). identifier[hostname]
keyword[if] identifier[urlparse_host] :
keyword[return] identifier[urlparse... | def _parse_host(host):
"""
The purpose of this function is to be robust to improper connections
settings provided by users, specifically in the host field.
For example -- when users supply ``https://xx.cloud.databricks.com`` as the
host, we must strip out the protocol to get the hos... |
def get_account_details(self, account):
""" Get the account details. """
result = {}
try:
luser = self._get_account(account.username)
luser = preload(luser, database=self._database)
except ObjectDoesNotExist:
return result
for i, j in luser.it... | def function[get_account_details, parameter[self, account]]:
constant[ Get the account details. ]
variable[result] assign[=] dictionary[[], []]
<ast.Try object at 0x7da1b0337190>
for taget[tuple[[<ast.Name object at 0x7da18bc70e20>, <ast.Name object at 0x7da18bc72d10>]]] in starred[call[name... | keyword[def] identifier[get_account_details] ( identifier[self] , identifier[account] ):
literal[string]
identifier[result] ={}
keyword[try] :
identifier[luser] = identifier[self] . identifier[_get_account] ( identifier[account] . identifier[username] )
identifier... | def get_account_details(self, account):
""" Get the account details. """
result = {}
try:
luser = self._get_account(account.username)
luser = preload(luser, database=self._database) # depends on [control=['try'], data=[]]
except ObjectDoesNotExist:
return result # depends on [c... |
def get_scoped_config(self, graph):
"""
Compute a configuration using the current scope.
"""
def loader(metadata):
if not self.current_scope:
target = graph.config
else:
target = graph.config.get(self.current_scope, {})
... | def function[get_scoped_config, parameter[self, graph]]:
constant[
Compute a configuration using the current scope.
]
def function[loader, parameter[metadata]]:
if <ast.UnaryOp object at 0x7da1b0e158d0> begin[:]
variable[target] assign[=] name[gra... | keyword[def] identifier[get_scoped_config] ( identifier[self] , identifier[graph] ):
literal[string]
keyword[def] identifier[loader] ( identifier[metadata] ):
keyword[if] keyword[not] identifier[self] . identifier[current_scope] :
identifier[target] = identifier[gra... | def get_scoped_config(self, graph):
"""
Compute a configuration using the current scope.
"""
def loader(metadata):
if not self.current_scope:
target = graph.config # depends on [control=['if'], data=[]]
else:
target = graph.config.get(self.current_scope... |
def _resume(self):
# type: (Descriptor) -> int
"""Resume a download, if possible
:param Descriptor self: this
:rtype: int or None
:return: verified download offset
"""
if self._resume_mgr is None or self._offset > 0 or self._finalized:
return None
... | def function[_resume, parameter[self]]:
constant[Resume a download, if possible
:param Descriptor self: this
:rtype: int or None
:return: verified download offset
]
if <ast.BoolOp object at 0x7da20e956500> begin[:]
return[constant[None]]
variable[rr] assig... | keyword[def] identifier[_resume] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_resume_mgr] keyword[is] keyword[None] keyword[or] identifier[self] . identifier[_offset] > literal[int] keyword[or] identifier[self] . identifier[_finalized] :
keyw... | def _resume(self):
# type: (Descriptor) -> int
'Resume a download, if possible\n :param Descriptor self: this\n :rtype: int or None\n :return: verified download offset\n '
if self._resume_mgr is None or self._offset > 0 or self._finalized:
return None # depends on [contr... |
def _get_key_redis_key(bank, key):
'''
Return the Redis key given the bank name and the key name.
'''
opts = _get_redis_keys_opts()
return '{prefix}{separator}{bank}/{key}'.format(
prefix=opts['key_prefix'],
separator=opts['separator'],
bank=bank,
key=key
) | def function[_get_key_redis_key, parameter[bank, key]]:
constant[
Return the Redis key given the bank name and the key name.
]
variable[opts] assign[=] call[name[_get_redis_keys_opts], parameter[]]
return[call[constant[{prefix}{separator}{bank}/{key}].format, parameter[]]] | keyword[def] identifier[_get_key_redis_key] ( identifier[bank] , identifier[key] ):
literal[string]
identifier[opts] = identifier[_get_redis_keys_opts] ()
keyword[return] literal[string] . identifier[format] (
identifier[prefix] = identifier[opts] [ literal[string] ],
identifier[separator] ... | def _get_key_redis_key(bank, key):
"""
Return the Redis key given the bank name and the key name.
"""
opts = _get_redis_keys_opts()
return '{prefix}{separator}{bank}/{key}'.format(prefix=opts['key_prefix'], separator=opts['separator'], bank=bank, key=key) |
def load_config(self):
"""Load the config from the config file or template."""
config = Config()
self.config_obj = config.load('awsshellrc')
self.config_section = self.config_obj['aws-shell']
self.model_completer.match_fuzzy = self.config_section.as_bool(
'match_fuzzy... | def function[load_config, parameter[self]]:
constant[Load the config from the config file or template.]
variable[config] assign[=] call[name[Config], parameter[]]
name[self].config_obj assign[=] call[name[config].load, parameter[constant[awsshellrc]]]
name[self].config_section assign[=] ... | keyword[def] identifier[load_config] ( identifier[self] ):
literal[string]
identifier[config] = identifier[Config] ()
identifier[self] . identifier[config_obj] = identifier[config] . identifier[load] ( literal[string] )
identifier[self] . identifier[config_section] = identifier[se... | def load_config(self):
"""Load the config from the config file or template."""
config = Config()
self.config_obj = config.load('awsshellrc')
self.config_section = self.config_obj['aws-shell']
self.model_completer.match_fuzzy = self.config_section.as_bool('match_fuzzy')
self.enable_vi_bindings = ... |
def get(self, *args, **kwargs):
"""
Get from the interface collection. It is more accurate to use
kwargs to specify an attribute of the sub interface to retrieve
rather than using an index value. If retrieving using an index,
the collection will first check vlan interfaces and st... | def function[get, parameter[self]]:
constant[
Get from the interface collection. It is more accurate to use
kwargs to specify an attribute of the sub interface to retrieve
rather than using an index value. If retrieving using an index,
the collection will first check vlan interfa... | keyword[def] identifier[get] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[collection] keyword[in] identifier[self] . identifier[items] :
keyword[if] identifier[args] :
identifier[index] = identifier[args] ... | def get(self, *args, **kwargs):
"""
Get from the interface collection. It is more accurate to use
kwargs to specify an attribute of the sub interface to retrieve
rather than using an index value. If retrieving using an index,
the collection will first check vlan interfaces and standa... |
def lm_ffinal(freqs, damping_times, modes):
"""Return the maximum f_final of the modes given, with f_final the frequency
at which the amplitude falls to 1/1000 of the peak amplitude
"""
f_max = {}
for lmn in modes:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
for n in range(... | def function[lm_ffinal, parameter[freqs, damping_times, modes]]:
constant[Return the maximum f_final of the modes given, with f_final the frequency
at which the amplitude falls to 1/1000 of the peak amplitude
]
variable[f_max] assign[=] dictionary[[], []]
for taget[name[lmn]] in starred[... | keyword[def] identifier[lm_ffinal] ( identifier[freqs] , identifier[damping_times] , identifier[modes] ):
literal[string]
identifier[f_max] ={}
keyword[for] identifier[lmn] keyword[in] identifier[modes] :
identifier[l] , identifier[m] , identifier[nmodes] = identifier[int] ( identifier[lm... | def lm_ffinal(freqs, damping_times, modes):
"""Return the maximum f_final of the modes given, with f_final the frequency
at which the amplitude falls to 1/1000 of the peak amplitude
"""
f_max = {}
for lmn in modes:
(l, m, nmodes) = (int(lmn[0]), int(lmn[1]), int(lmn[2]))
for n in ran... |
def api_version(created_ver, last_changed_ver, return_value_ver):
"""Version check decorator. Currently only checks Bigger Than."""
def api_min_version_decorator(function):
def wrapper(function, self, *args, **kwargs):
if not self.version_check_mode == "none":
if self.v... | def function[api_version, parameter[created_ver, last_changed_ver, return_value_ver]]:
constant[Version check decorator. Currently only checks Bigger Than.]
def function[api_min_version_decorator, parameter[function]]:
def function[wrapper, parameter[function, self]]:
... | keyword[def] identifier[api_version] ( identifier[created_ver] , identifier[last_changed_ver] , identifier[return_value_ver] ):
literal[string]
keyword[def] identifier[api_min_version_decorator] ( identifier[function] ):
keyword[def] identifier[wrapper] ( identifier[function] , identifier[self] ... | def api_version(created_ver, last_changed_ver, return_value_ver):
"""Version check decorator. Currently only checks Bigger Than."""
def api_min_version_decorator(function):
def wrapper(function, self, *args, **kwargs):
if not self.version_check_mode == 'none':
if self.versi... |
def ARPLimitExceeded_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ARPLimitExceeded = ET.SubElement(config, "ARPLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
originator_switch_info =... | def function[ARPLimitExceeded_originator_switch_info_switchIpV4Address, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[ARPLimitExceeded] assign[=] call[name[ET].SubElement, parameter[name[config], c... | keyword[def] identifier[ARPLimitExceeded_originator_switch_info_switchIpV4Address] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[ARPLimitExceeded] = identifier[ET] . identifier[SubElemen... | def ARPLimitExceeded_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
ARPLimitExceeded = ET.SubElement(config, 'ARPLimitExceeded', xmlns='http://brocade.com/ns/brocade-notification-stream')
originator_switch_info = ET.SubElement(A... |
def signature(self):
''' Return the function signature
Returns:
(str, list(str)): name, list parameters type
'''
return self.name, [str(x.type) for x in self.elems] | def function[signature, parameter[self]]:
constant[ Return the function signature
Returns:
(str, list(str)): name, list parameters type
]
return[tuple[[<ast.Attribute object at 0x7da18c4cd510>, <ast.ListComp object at 0x7da18c4ccbe0>]]] | keyword[def] identifier[signature] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[name] ,[ identifier[str] ( identifier[x] . identifier[type] ) keyword[for] identifier[x] keyword[in] identifier[self] . identifier[elems] ] | def signature(self):
""" Return the function signature
Returns:
(str, list(str)): name, list parameters type
"""
return (self.name, [str(x.type) for x in self.elems]) |
def add_config(self, config, config_filename):
"""
Updates the content types database with the given configuration.
:param config:
The configuration dictionary.
:param config_filename:
The path of the configuration file.
"""
content_types = config... | def function[add_config, parameter[self, config, config_filename]]:
constant[
Updates the content types database with the given configuration.
:param config:
The configuration dictionary.
:param config_filename:
The path of the configuration file.
]
... | keyword[def] identifier[add_config] ( identifier[self] , identifier[config] , identifier[config_filename] ):
literal[string]
identifier[content_types] = identifier[config] [ literal[string] ]
identifier[comment_groups] = identifier[config] [ literal[string] ]
identifier[self] . i... | def add_config(self, config, config_filename):
"""
Updates the content types database with the given configuration.
:param config:
The configuration dictionary.
:param config_filename:
The path of the configuration file.
"""
content_types = config['conten... |
def plot_eigs(self, colorbar=True, cb_orientation='vertical',
tick_interval=[60, 60], minor_tick_interval=[20, 20],
xlabel='Longitude', ylabel='Latitude',
axes_labelsize=9, tick_labelsize=8, show=True, fname=None,
**kwargs):
"""
Plot the three eigenval... | def function[plot_eigs, parameter[self, colorbar, cb_orientation, tick_interval, minor_tick_interval, xlabel, ylabel, axes_labelsize, tick_labelsize, show, fname]]:
constant[
Plot the three eigenvalues of the tensor.
Usage
-----
x.plot_eigs([tick_interval, minor_tick_interval, x... | keyword[def] identifier[plot_eigs] ( identifier[self] , identifier[colorbar] = keyword[True] , identifier[cb_orientation] = literal[string] ,
identifier[tick_interval] =[ literal[int] , literal[int] ], identifier[minor_tick_interval] =[ literal[int] , literal[int] ],
identifier[xlabel] = literal[string] , identifie... | def plot_eigs(self, colorbar=True, cb_orientation='vertical', tick_interval=[60, 60], minor_tick_interval=[20, 20], xlabel='Longitude', ylabel='Latitude', axes_labelsize=9, tick_labelsize=8, show=True, fname=None, **kwargs):
"""
Plot the three eigenvalues of the tensor.
Usage
-----
... |
def xcorr_plot(template, image, shift=None, cc=None, cc_vec=None, **kwargs):
"""
Plot a template overlying an image aligned by correlation.
:type template: numpy.ndarray
:param template: Short template image
:type image: numpy.ndarray
:param image: Long master image
:type shift: int
:pa... | def function[xcorr_plot, parameter[template, image, shift, cc, cc_vec]]:
constant[
Plot a template overlying an image aligned by correlation.
:type template: numpy.ndarray
:param template: Short template image
:type image: numpy.ndarray
:param image: Long master image
:type shift: int
... | keyword[def] identifier[xcorr_plot] ( identifier[template] , identifier[image] , identifier[shift] = keyword[None] , identifier[cc] = keyword[None] , identifier[cc_vec] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[matplotlib] . identifier[pyplot] keyword[as] ident... | def xcorr_plot(template, image, shift=None, cc=None, cc_vec=None, **kwargs):
"""
Plot a template overlying an image aligned by correlation.
:type template: numpy.ndarray
:param template: Short template image
:type image: numpy.ndarray
:param image: Long master image
:type shift: int
:pa... |
def select(self, selections):
'''Make a selection in this
representation. BallAndStickRenderer support selections of
atoms and bonds.
To select the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selec... | def function[select, parameter[self, selections]]:
constant[Make a selection in this
representation. BallAndStickRenderer support selections of
atoms and bonds.
To select the first atom and the first bond you can use the
following code::
from chemlab... | keyword[def] identifier[select] ( identifier[self] , identifier[selections] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[selections] :
identifier[self] . identifier[selection_state] [ literal[string] ]= identifier[selections] [ literal[string] ]
... | def select(self, selections):
"""Make a selection in this
representation. BallAndStickRenderer support selections of
atoms and bonds.
To select the first atom and the first bond you can use the
following code::
from chemlab.mviewer.state import Selection... |
def safe_load(string):
"""
Parse the provided string returns a dict.
:param string: A string to be parsed.
:return: dict
"""
try:
return yaml.safe_load(string) or {}
except yaml.scanner.ScannerError as e:
sysexit_with_message(str(e)) | def function[safe_load, parameter[string]]:
constant[
Parse the provided string returns a dict.
:param string: A string to be parsed.
:return: dict
]
<ast.Try object at 0x7da20cabcd00> | keyword[def] identifier[safe_load] ( identifier[string] ):
literal[string]
keyword[try] :
keyword[return] identifier[yaml] . identifier[safe_load] ( identifier[string] ) keyword[or] {}
keyword[except] identifier[yaml] . identifier[scanner] . identifier[ScannerError] keyword[as] identifier... | def safe_load(string):
"""
Parse the provided string returns a dict.
:param string: A string to be parsed.
:return: dict
"""
try:
return yaml.safe_load(string) or {} # depends on [control=['try'], data=[]]
except yaml.scanner.ScannerError as e:
sysexit_with_message(str(e)) ... |
def add_field_to_work_item_type(self, field, process_id, wit_ref_name):
"""AddFieldToWorkItemType.
[Preview API] Adds a field to a work item type.
:param :class:`<AddProcessWorkItemTypeFieldRequest> <azure.devops.v5_0.work_item_tracking_process.models.AddProcessWorkItemTypeFieldRequest>` field:
... | def function[add_field_to_work_item_type, parameter[self, field, process_id, wit_ref_name]]:
constant[AddFieldToWorkItemType.
[Preview API] Adds a field to a work item type.
:param :class:`<AddProcessWorkItemTypeFieldRequest> <azure.devops.v5_0.work_item_tracking_process.models.AddProcessWorkIte... | keyword[def] identifier[add_field_to_work_item_type] ( identifier[self] , identifier[field] , identifier[process_id] , identifier[wit_ref_name] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[process_id] keyword[is] keyword[not] keyword[None] :
ident... | def add_field_to_work_item_type(self, field, process_id, wit_ref_name):
"""AddFieldToWorkItemType.
[Preview API] Adds a field to a work item type.
:param :class:`<AddProcessWorkItemTypeFieldRequest> <azure.devops.v5_0.work_item_tracking_process.models.AddProcessWorkItemTypeFieldRequest>` field:
... |
def get_actions(self, request):
"""
Define actions by user's permissions.
"""
actions = super(EntryAdmin, self).get_actions(request)
if not actions:
return actions
if (not request.user.has_perm('zinnia.can_change_author') or
not request.user.ha... | def function[get_actions, parameter[self, request]]:
constant[
Define actions by user's permissions.
]
variable[actions] assign[=] call[call[name[super], parameter[name[EntryAdmin], name[self]]].get_actions, parameter[name[request]]]
if <ast.UnaryOp object at 0x7da1b1ddd330> begi... | keyword[def] identifier[get_actions] ( identifier[self] , identifier[request] ):
literal[string]
identifier[actions] = identifier[super] ( identifier[EntryAdmin] , identifier[self] ). identifier[get_actions] ( identifier[request] )
keyword[if] keyword[not] identifier[actions] :
... | def get_actions(self, request):
"""
Define actions by user's permissions.
"""
actions = super(EntryAdmin, self).get_actions(request)
if not actions:
return actions # depends on [control=['if'], data=[]]
if not request.user.has_perm('zinnia.can_change_author') or not request.user... |
def split_at(it, split_value):
"""Splits an iterator C{it} at values of C{split_value}.
Each instance of C{split_value} is swallowed. The iterator produces
subiterators which need to be consumed fully before the next subiterator
can be used.
"""
def _chunk_iterator(first):
v = first
... | def function[split_at, parameter[it, split_value]]:
constant[Splits an iterator C{it} at values of C{split_value}.
Each instance of C{split_value} is swallowed. The iterator produces
subiterators which need to be consumed fully before the next subiterator
can be used.
]
def function[_c... | keyword[def] identifier[split_at] ( identifier[it] , identifier[split_value] ):
literal[string]
keyword[def] identifier[_chunk_iterator] ( identifier[first] ):
identifier[v] = identifier[first]
keyword[while] identifier[v] != identifier[split_value] :
keyword[yield] ident... | def split_at(it, split_value):
"""Splits an iterator C{it} at values of C{split_value}.
Each instance of C{split_value} is swallowed. The iterator produces
subiterators which need to be consumed fully before the next subiterator
can be used.
"""
def _chunk_iterator(first):
v = first
... |
async def respond(self, *args, **kwargs):
"""
Responds to the message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with ``entity`` already set.
"""
return await self._client.send_message(
await self.get_input_chat(), *... | <ast.AsyncFunctionDef object at 0x7da1b26acf70> | keyword[async] keyword[def] identifier[respond] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] keyword[await] identifier[self] . identifier[_client] . identifier[send_message] (
keyword[await] identifier[self] . identifier[get_input_cha... | async def respond(self, *args, **kwargs):
"""
Responds to the message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with ``entity`` already set.
"""
return await self._client.send_message(await self.get_input_chat(), *args, **kwargs) |
def docgraph2freqt(docgraph, root=None, include_pos=False,
escape_func=FREQT_ESCAPE_FUNC):
"""convert a docgraph into a FREQT string."""
if root is None:
return u"\n".join(
sentence2freqt(docgraph, sentence, include_pos=include_pos,
escape_func=e... | def function[docgraph2freqt, parameter[docgraph, root, include_pos, escape_func]]:
constant[convert a docgraph into a FREQT string.]
if compare[name[root] is constant[None]] begin[:]
return[call[constant[
].join, parameter[<ast.GeneratorExp object at 0x7da1b26ad1e0>]]] | keyword[def] identifier[docgraph2freqt] ( identifier[docgraph] , identifier[root] = keyword[None] , identifier[include_pos] = keyword[False] ,
identifier[escape_func] = identifier[FREQT_ESCAPE_FUNC] ):
literal[string]
keyword[if] identifier[root] keyword[is] keyword[None] :
keyword[return] li... | def docgraph2freqt(docgraph, root=None, include_pos=False, escape_func=FREQT_ESCAPE_FUNC):
"""convert a docgraph into a FREQT string."""
if root is None:
return u'\n'.join((sentence2freqt(docgraph, sentence, include_pos=include_pos, escape_func=escape_func) for sentence in docgraph.sentences)) # depend... |
def generate_cylindrical_points(start, end, start_radius, end_radius,
linspace_count=_LINSPACE_COUNT):
'''Generate a 3d mesh of a cylinder with start and end points, and varying radius
Based on: http://stackoverflow.com/a/32383775
'''
v = end - start
length = norm(v)... | def function[generate_cylindrical_points, parameter[start, end, start_radius, end_radius, linspace_count]]:
constant[Generate a 3d mesh of a cylinder with start and end points, and varying radius
Based on: http://stackoverflow.com/a/32383775
]
variable[v] assign[=] binary_operation[name[end] - ... | keyword[def] identifier[generate_cylindrical_points] ( identifier[start] , identifier[end] , identifier[start_radius] , identifier[end_radius] ,
identifier[linspace_count] = identifier[_LINSPACE_COUNT] ):
literal[string]
identifier[v] = identifier[end] - identifier[start]
identifier[length] = identi... | def generate_cylindrical_points(start, end, start_radius, end_radius, linspace_count=_LINSPACE_COUNT):
"""Generate a 3d mesh of a cylinder with start and end points, and varying radius
Based on: http://stackoverflow.com/a/32383775
"""
v = end - start
length = norm(v)
v = v / length
(n1, n2)... |
def check_not(state, *tests, msg):
"""Run multiple subtests that should fail. If all subtests fail, returns original state (for chaining)
- This function is currently only tested in working with ``has_code()`` in the subtests.
- This function can be thought as a ``NOT(x OR y OR ...)`` statement, since all ... | def function[check_not, parameter[state]]:
constant[Run multiple subtests that should fail. If all subtests fail, returns original state (for chaining)
- This function is currently only tested in working with ``has_code()`` in the subtests.
- This function can be thought as a ``NOT(x OR y OR ...)`` sta... | keyword[def] identifier[check_not] ( identifier[state] ,* identifier[tests] , identifier[msg] ):
literal[string]
keyword[for] identifier[test] keyword[in] identifier[iter_tests] ( identifier[tests] ):
keyword[try] :
identifier[test] ( identifier[state] )
keyword[except] i... | def check_not(state, *tests, msg):
"""Run multiple subtests that should fail. If all subtests fail, returns original state (for chaining)
- This function is currently only tested in working with ``has_code()`` in the subtests.
- This function can be thought as a ``NOT(x OR y OR ...)`` statement, since all ... |
def p_propertyDeclaration_4(p):
"""propertyDeclaration_4 : dataType propertyName array defaultValue ';'"""
p[0] = CIMProperty(p[2], p[4], type=p[1], is_array=True,
array_size=p[3]) | def function[p_propertyDeclaration_4, parameter[p]]:
constant[propertyDeclaration_4 : dataType propertyName array defaultValue ';']
call[name[p]][constant[0]] assign[=] call[name[CIMProperty], parameter[call[name[p]][constant[2]], call[name[p]][constant[4]]]] | keyword[def] identifier[p_propertyDeclaration_4] ( identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[CIMProperty] ( identifier[p] [ literal[int] ], identifier[p] [ literal[int] ], identifier[type] = identifier[p] [ literal[int] ], identifier[is_array] = keyword[True] ,
identi... | def p_propertyDeclaration_4(p):
"""propertyDeclaration_4 : dataType propertyName array defaultValue ';'"""
p[0] = CIMProperty(p[2], p[4], type=p[1], is_array=True, array_size=p[3]) |
def describe_batch_predictions(FilterVariable=None, EQ=None, GT=None, LT=None, GE=None, LE=None, NE=None, Prefix=None, SortOrder=None, NextToken=None, Limit=None):
"""
Returns a list of BatchPrediction operations that match the search criteria in the request.
See also: AWS API Documentation
:e... | def function[describe_batch_predictions, parameter[FilterVariable, EQ, GT, LT, GE, LE, NE, Prefix, SortOrder, NextToken, Limit]]:
constant[
Returns a list of BatchPrediction operations that match the search criteria in the request.
See also: AWS API Documentation
:example: response = clien... | keyword[def] identifier[describe_batch_predictions] ( identifier[FilterVariable] = keyword[None] , identifier[EQ] = keyword[None] , identifier[GT] = keyword[None] , identifier[LT] = keyword[None] , identifier[GE] = keyword[None] , identifier[LE] = keyword[None] , identifier[NE] = keyword[None] , identifier[Prefix] = ... | def describe_batch_predictions(FilterVariable=None, EQ=None, GT=None, LT=None, GE=None, LE=None, NE=None, Prefix=None, SortOrder=None, NextToken=None, Limit=None):
"""
Returns a list of BatchPrediction operations that match the search criteria in the request.
See also: AWS API Documentation
:e... |
def enable(iface):
'''
Enable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.enable 'Local Area Connection #2'
'''
if is_enabled(iface):
return True
cmd = ['netsh', 'interface', 'set', 'interface',
'name={0}'.format(iface),
... | def function[enable, parameter[iface]]:
constant[
Enable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.enable 'Local Area Connection #2'
]
if call[name[is_enabled], parameter[name[iface]]] begin[:]
return[constant[True]]
variable... | keyword[def] identifier[enable] ( identifier[iface] ):
literal[string]
keyword[if] identifier[is_enabled] ( identifier[iface] ):
keyword[return] keyword[True]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] . identifier[format... | def enable(iface):
"""
Enable an interface
CLI Example:
.. code-block:: bash
salt -G 'os_family:Windows' ip.enable 'Local Area Connection #2'
"""
if is_enabled(iface):
return True # depends on [control=['if'], data=[]]
cmd = ['netsh', 'interface', 'set', 'interface', 'nam... |
def delete_port_postcommit(self, context):
"""Delete the port from CVX"""
port = context.current
log_context("delete_port_postcommit: port", port)
self._delete_port_resources(port, context.host)
self._try_to_release_dynamic_segment(context) | def function[delete_port_postcommit, parameter[self, context]]:
constant[Delete the port from CVX]
variable[port] assign[=] name[context].current
call[name[log_context], parameter[constant[delete_port_postcommit: port], name[port]]]
call[name[self]._delete_port_resources, parameter[name[... | keyword[def] identifier[delete_port_postcommit] ( identifier[self] , identifier[context] ):
literal[string]
identifier[port] = identifier[context] . identifier[current]
identifier[log_context] ( literal[string] , identifier[port] )
identifier[self] . identifier[_delete_port_res... | def delete_port_postcommit(self, context):
"""Delete the port from CVX"""
port = context.current
log_context('delete_port_postcommit: port', port)
self._delete_port_resources(port, context.host)
self._try_to_release_dynamic_segment(context) |
def peer_bfd_timers(self, **kwargs):
"""Configure BFD for BGP globally.
Args:
rbridge_id (str): Rbridge to configure. (1, 225, etc)
peer_ip (str): Peer IPv4 address for BFD setting.
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str)... | def function[peer_bfd_timers, parameter[self]]:
constant[Configure BFD for BGP globally.
Args:
rbridge_id (str): Rbridge to configure. (1, 225, etc)
peer_ip (str): Peer IPv4 address for BFD setting.
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
... | keyword[def] identifier[peer_bfd_timers] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[kwargs] . identifier[pop] ( literal[string] )
identifier[kwargs] [ literal[string] ]= identifier[kwargs] . identifier[pop] ( literal[stri... | def peer_bfd_timers(self, **kwargs):
"""Configure BFD for BGP globally.
Args:
rbridge_id (str): Rbridge to configure. (1, 225, etc)
peer_ip (str): Peer IPv4 address for BFD setting.
tx (str): BFD transmit interval in milliseconds (300, 500, etc)
rx (str): BF... |
def _check_valid_data(self, data):
"""Checks that the given data is a float array with four channels.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is invalid.
"""
... | def function[_check_valid_data, parameter[self, data]]:
constant[Checks that the given data is a float array with four channels.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is ... | keyword[def] identifier[_check_valid_data] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] identifier[data] . identifier[dtype] . identifier[type] keyword[is] keyword[not] identifier[np] . identifier[float32] keyword[and] identifier[data] . identifier[dtype] . identifier[... | def _check_valid_data(self, data):
"""Checks that the given data is a float array with four channels.
Parameters
----------
data : :obj:`numpy.ndarray`
The data to check.
Raises
------
ValueError
If the data is invalid.
"""
if dat... |
def check_ip(original_ip):
'''
Checks the format of an IP address and returns it if it is correct. Otherwise it returns None.
'''
ip = original_ip.strip()
parts = ip.split('.')
if len(parts) != 4:
return None
for p in parts:
try:
p = int(p)
if (p < 0)... | def function[check_ip, parameter[original_ip]]:
constant[
Checks the format of an IP address and returns it if it is correct. Otherwise it returns None.
]
variable[ip] assign[=] call[name[original_ip].strip, parameter[]]
variable[parts] assign[=] call[name[ip].split, parameter[constant[.... | keyword[def] identifier[check_ip] ( identifier[original_ip] ):
literal[string]
identifier[ip] = identifier[original_ip] . identifier[strip] ()
identifier[parts] = identifier[ip] . identifier[split] ( literal[string] )
keyword[if] identifier[len] ( identifier[parts] )!= literal[int] :
ke... | def check_ip(original_ip):
"""
Checks the format of an IP address and returns it if it is correct. Otherwise it returns None.
"""
ip = original_ip.strip()
parts = ip.split('.')
if len(parts) != 4:
return None # depends on [control=['if'], data=[]]
for p in parts:
try:
... |
def identify_groups(ref_labels, pred_labels, return_overlaps=False):
"""Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_... | def function[identify_groups, parameter[ref_labels, pred_labels, return_overlaps]]:
constant[Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this wi... | keyword[def] identifier[identify_groups] ( identifier[ref_labels] , identifier[pred_labels] , identifier[return_overlaps] = keyword[False] ):
literal[string]
identifier[ref_unique] , identifier[ref_counts] = identifier[np] . identifier[unique] ( identifier[ref_labels] , identifier[return_counts] = keyword[... | def identify_groups(ref_labels, pred_labels, return_overlaps=False):
"""Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_... |
def _AddEventData(self, event_data):
"""Adds event data.
Args:
event_data (EventData): event data.
"""
identifier = event_data.GetIdentifier()
lookup_key = identifier.CopyToString()
self._storage_writer.AddEventData(event_data)
identifier = event_data.GetIdentifier()
self._event... | def function[_AddEventData, parameter[self, event_data]]:
constant[Adds event data.
Args:
event_data (EventData): event data.
]
variable[identifier] assign[=] call[name[event_data].GetIdentifier, parameter[]]
variable[lookup_key] assign[=] call[name[identifier].CopyToString, param... | keyword[def] identifier[_AddEventData] ( identifier[self] , identifier[event_data] ):
literal[string]
identifier[identifier] = identifier[event_data] . identifier[GetIdentifier] ()
identifier[lookup_key] = identifier[identifier] . identifier[CopyToString] ()
identifier[self] . identifier[_storag... | def _AddEventData(self, event_data):
"""Adds event data.
Args:
event_data (EventData): event data.
"""
identifier = event_data.GetIdentifier()
lookup_key = identifier.CopyToString()
self._storage_writer.AddEventData(event_data)
identifier = event_data.GetIdentifier()
self._event_d... |
def add(self, artifact_type: ArtifactType, src_path: str,
dst_path: str=None):
"""Add an artifact of type `artifact_type` at `src_path`.
`src_path` should be the path of the file relative to project root.
`dst_path`, if given, is the desired path of the artifact in dependent
... | def function[add, parameter[self, artifact_type, src_path, dst_path]]:
constant[Add an artifact of type `artifact_type` at `src_path`.
`src_path` should be the path of the file relative to project root.
`dst_path`, if given, is the desired path of the artifact in dependent
targets, rela... | keyword[def] identifier[add] ( identifier[self] , identifier[artifact_type] : identifier[ArtifactType] , identifier[src_path] : identifier[str] ,
identifier[dst_path] : identifier[str] = keyword[None] ):
literal[string]
keyword[if] identifier[dst_path] keyword[is] keyword[None] :
i... | def add(self, artifact_type: ArtifactType, src_path: str, dst_path: str=None):
"""Add an artifact of type `artifact_type` at `src_path`.
`src_path` should be the path of the file relative to project root.
`dst_path`, if given, is the desired path of the artifact in dependent
targets, relati... |
def get(cls): # type: () -> Shell
"""
Retrieve the current shell.
"""
if cls._shell is not None:
return cls._shell
try:
name, path = detect_shell(os.getpid())
except (RuntimeError, ShellDetectionFailure):
raise RuntimeError("Unable to... | def function[get, parameter[cls]]:
constant[
Retrieve the current shell.
]
if compare[name[cls]._shell is_not constant[None]] begin[:]
return[name[cls]._shell]
<ast.Try object at 0x7da18f7207f0>
name[cls]._shell assign[=] call[name[cls], parameter[name[name], name[pat... | keyword[def] identifier[get] ( identifier[cls] ):
literal[string]
keyword[if] identifier[cls] . identifier[_shell] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[cls] . identifier[_shell]
keyword[try] :
identifier[name] , identifier[pat... | def get(cls): # type: () -> Shell
'\n Retrieve the current shell.\n '
if cls._shell is not None:
return cls._shell # depends on [control=['if'], data=[]]
try:
(name, path) = detect_shell(os.getpid()) # depends on [control=['try'], data=[]]
except (RuntimeError, ShellDete... |
def get_visible_child(self, parent, locator, params=None, timeout=None):
"""
Get child-element both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
... | def function[get_visible_child, parameter[self, parent, locator, params, timeout]]:
constant[
Get child-element both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the elemen... | keyword[def] identifier[get_visible_child] ( identifier[self] , identifier[parent] , identifier[locator] , identifier[params] = keyword[None] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[get_present_child] ( identifier[parent] , identifier[... | def get_visible_child(self, parent, locator, params=None, timeout=None):
"""
Get child-element both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
... |
def toggle_white_spaces(self):
"""
Toggles document white spaces display.
:return: Method success.
:rtype: bool
"""
text_option = self.get_default_text_option()
if text_option.flags().__int__():
text_option = QTextOption()
text_option.set... | def function[toggle_white_spaces, parameter[self]]:
constant[
Toggles document white spaces display.
:return: Method success.
:rtype: bool
]
variable[text_option] assign[=] call[name[self].get_default_text_option, parameter[]]
if call[call[name[text_option].flags... | keyword[def] identifier[toggle_white_spaces] ( identifier[self] ):
literal[string]
identifier[text_option] = identifier[self] . identifier[get_default_text_option] ()
keyword[if] identifier[text_option] . identifier[flags] (). identifier[__int__] ():
identifier[text_option] ... | def toggle_white_spaces(self):
"""
Toggles document white spaces display.
:return: Method success.
:rtype: bool
"""
text_option = self.get_default_text_option()
if text_option.flags().__int__():
text_option = QTextOption()
text_option.setTabStop(self.tabStopW... |
def precompute(self, distance_modulus_array=None):
"""
DEPRECATED: ADW 20170627
Precompute color probabilities for background ('u_background')
and signal ('u_color') for each star in catalog. Precompute
observable fraction in each ROI pixel. # Precompute still
operates... | def function[precompute, parameter[self, distance_modulus_array]]:
constant[
DEPRECATED: ADW 20170627
Precompute color probabilities for background ('u_background')
and signal ('u_color') for each star in catalog. Precompute
observable fraction in each ROI pixel. # Precompute ... | keyword[def] identifier[precompute] ( identifier[self] , identifier[distance_modulus_array] = keyword[None] ):
literal[string]
identifier[msg] = literal[string] % identifier[self] . identifier[__class__] . identifier[__name__]
identifier[DeprecationWarning] ( identifier[msg] )
k... | def precompute(self, distance_modulus_array=None):
"""
DEPRECATED: ADW 20170627
Precompute color probabilities for background ('u_background')
and signal ('u_color') for each star in catalog. Precompute
observable fraction in each ROI pixel. # Precompute still
operates ove... |
def get_variables(self, include_nontrainable=False):
"""
Returns the TensorFlow variables used by the baseline.
Returns:
List of variables
"""
if include_nontrainable:
return [self.all_variables[key] for key in sorted(self.all_variables)]
else:
... | def function[get_variables, parameter[self, include_nontrainable]]:
constant[
Returns the TensorFlow variables used by the baseline.
Returns:
List of variables
]
if name[include_nontrainable] begin[:]
return[<ast.ListComp object at 0x7da18f812620>] | keyword[def] identifier[get_variables] ( identifier[self] , identifier[include_nontrainable] = keyword[False] ):
literal[string]
keyword[if] identifier[include_nontrainable] :
keyword[return] [ identifier[self] . identifier[all_variables] [ identifier[key] ] keyword[for] identifier[k... | def get_variables(self, include_nontrainable=False):
"""
Returns the TensorFlow variables used by the baseline.
Returns:
List of variables
"""
if include_nontrainable:
return [self.all_variables[key] for key in sorted(self.all_variables)] # depends on [control=['if'... |
def cinder(*arg):
"""
Cinder annotation for adding function to process cinder notification.
if event_type include wildcard, will put {pattern: function} into process_wildcard dict
else will put {event_type: function} into process dict
:param arg: event_type of notification
"""
check_event_... | def function[cinder, parameter[]]:
constant[
Cinder annotation for adding function to process cinder notification.
if event_type include wildcard, will put {pattern: function} into process_wildcard dict
else will put {event_type: function} into process dict
:param arg: event_type of notificati... | keyword[def] identifier[cinder] (* identifier[arg] ):
literal[string]
identifier[check_event_type] ( identifier[Openstack] . identifier[Cinder] ,* identifier[arg] )
identifier[event_type] = identifier[arg] [ literal[int] ]
keyword[def] identifier[decorator] ( identifier[func] ):
keywor... | def cinder(*arg):
"""
Cinder annotation for adding function to process cinder notification.
if event_type include wildcard, will put {pattern: function} into process_wildcard dict
else will put {event_type: function} into process dict
:param arg: event_type of notification
"""
check_event_... |
def on_save_interpretation_button(self, event):
"""
on the save button the interpretation is saved to pmag_results_table
data in all coordinate systems
"""
if self.current_fit:
self.current_fit.saved = True
calculation_type = self.current_fit.get(self.COO... | def function[on_save_interpretation_button, parameter[self, event]]:
constant[
on the save button the interpretation is saved to pmag_results_table
data in all coordinate systems
]
if name[self].current_fit begin[:]
name[self].current_fit.saved assign[=] constant[... | keyword[def] identifier[on_save_interpretation_button] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[self] . identifier[current_fit] :
identifier[self] . identifier[current_fit] . identifier[saved] = keyword[True]
identifier[calculatio... | def on_save_interpretation_button(self, event):
"""
on the save button the interpretation is saved to pmag_results_table
data in all coordinate systems
"""
if self.current_fit:
self.current_fit.saved = True
calculation_type = self.current_fit.get(self.COORDINATE_SYSTEM)['... |
def list(self):
"""
List all available data logging sessions
"""
# We have to open this queue before we make the request, to ensure we don't miss the response.
queue = self._pebble.get_endpoint_queue(DataLogging)
self._pebble.send_packet(DataLogging(data=DataLoggingRepo... | def function[list, parameter[self]]:
constant[
List all available data logging sessions
]
variable[queue] assign[=] call[name[self]._pebble.get_endpoint_queue, parameter[name[DataLogging]]]
call[name[self]._pebble.send_packet, parameter[call[name[DataLogging], parameter[]]]]
... | keyword[def] identifier[list] ( identifier[self] ):
literal[string]
identifier[queue] = identifier[self] . identifier[_pebble] . identifier[get_endpoint_queue] ( identifier[DataLogging] )
identifier[self] . identifier[_pebble] . identifier[send_packet] ( identifier[DataLogging] ... | def list(self):
"""
List all available data logging sessions
"""
# We have to open this queue before we make the request, to ensure we don't miss the response.
queue = self._pebble.get_endpoint_queue(DataLogging)
self._pebble.send_packet(DataLogging(data=DataLoggingReportOpenSessions(ses... |
def print_ldamodel_topic_words(topic_word_distrib, vocab, n_top=10, row_labels=DEFAULT_TOPIC_NAME_FMT):
"""Print `n_top` values from a LDA model's topic-word distributions."""
print_ldamodel_distribution(topic_word_distrib, row_labels=row_labels, val_labels=vocab,
top_n=n_top) | def function[print_ldamodel_topic_words, parameter[topic_word_distrib, vocab, n_top, row_labels]]:
constant[Print `n_top` values from a LDA model's topic-word distributions.]
call[name[print_ldamodel_distribution], parameter[name[topic_word_distrib]]] | keyword[def] identifier[print_ldamodel_topic_words] ( identifier[topic_word_distrib] , identifier[vocab] , identifier[n_top] = literal[int] , identifier[row_labels] = identifier[DEFAULT_TOPIC_NAME_FMT] ):
literal[string]
identifier[print_ldamodel_distribution] ( identifier[topic_word_distrib] , identifier[... | def print_ldamodel_topic_words(topic_word_distrib, vocab, n_top=10, row_labels=DEFAULT_TOPIC_NAME_FMT):
"""Print `n_top` values from a LDA model's topic-word distributions."""
print_ldamodel_distribution(topic_word_distrib, row_labels=row_labels, val_labels=vocab, top_n=n_top) |
def sec(x, context=None):
"""
Return the secant of ``x``.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sec,
(BigFloat._implicit_convert(x),),
context,
) | def function[sec, parameter[x, context]]:
constant[
Return the secant of ``x``.
]
return[call[name[_apply_function_in_current_context], parameter[name[BigFloat], name[mpfr].mpfr_sec, tuple[[<ast.Call object at 0x7da18ede7760>]], name[context]]]] | keyword[def] identifier[sec] ( identifier[x] , identifier[context] = keyword[None] ):
literal[string]
keyword[return] identifier[_apply_function_in_current_context] (
identifier[BigFloat] ,
identifier[mpfr] . identifier[mpfr_sec] ,
( identifier[BigFloat] . identifier[_implicit_convert] ( ide... | def sec(x, context=None):
"""
Return the secant of ``x``.
"""
return _apply_function_in_current_context(BigFloat, mpfr.mpfr_sec, (BigFloat._implicit_convert(x),), context) |
def sample(self, n):
""" Samples data into a Pandas DataFrame.
Args:
n: number of sampled counts.
Returns:
A dataframe containing sampled data.
Raises:
Exception if n is larger than number of rows.
"""
row_total_count = 0
row_counts = []
for file in self.files:
w... | def function[sample, parameter[self, n]]:
constant[ Samples data into a Pandas DataFrame.
Args:
n: number of sampled counts.
Returns:
A dataframe containing sampled data.
Raises:
Exception if n is larger than number of rows.
]
variable[row_total_count] assign[=] constan... | keyword[def] identifier[sample] ( identifier[self] , identifier[n] ):
literal[string]
identifier[row_total_count] = literal[int]
identifier[row_counts] =[]
keyword[for] identifier[file] keyword[in] identifier[self] . identifier[files] :
keyword[with] identifier[_util] . identifier[op... | def sample(self, n):
""" Samples data into a Pandas DataFrame.
Args:
n: number of sampled counts.
Returns:
A dataframe containing sampled data.
Raises:
Exception if n is larger than number of rows.
"""
row_total_count = 0
row_counts = []
for file in self.files:
... |
def fixed_terms(self):
'''Return dict of all and only fixed effects in model.'''
return {k: v for (k, v) in self.terms.items() if not v.random} | def function[fixed_terms, parameter[self]]:
constant[Return dict of all and only fixed effects in model.]
return[<ast.DictComp object at 0x7da1b1660c10>] | keyword[def] identifier[fixed_terms] ( identifier[self] ):
literal[string]
keyword[return] { identifier[k] : identifier[v] keyword[for] ( identifier[k] , identifier[v] ) keyword[in] identifier[self] . identifier[terms] . identifier[items] () keyword[if] keyword[not] identifier[v] . identifier[r... | def fixed_terms(self):
"""Return dict of all and only fixed effects in model."""
return {k: v for (k, v) in self.terms.items() if not v.random} |
def pop(self, i):
"""
Pop a column from the H2OFrame at index i.
:param i: The index (int) or name (str) of the column to pop.
:returns: an H2OFrame containing the column dropped from the current frame; the current frame is modified
in-place and loses the column.
"""... | def function[pop, parameter[self, i]]:
constant[
Pop a column from the H2OFrame at index i.
:param i: The index (int) or name (str) of the column to pop.
:returns: an H2OFrame containing the column dropped from the current frame; the current frame is modified
in-place and lo... | keyword[def] identifier[pop] ( identifier[self] , identifier[i] ):
literal[string]
keyword[if] identifier[is_type] ( identifier[i] , identifier[str] ): identifier[i] = identifier[self] . identifier[names] . identifier[index] ( identifier[i] )
identifier[col] = identifier[H2OFrame] . ident... | def pop(self, i):
"""
Pop a column from the H2OFrame at index i.
:param i: The index (int) or name (str) of the column to pop.
:returns: an H2OFrame containing the column dropped from the current frame; the current frame is modified
in-place and loses the column.
"""
... |
def gffselect(args):
"""
%prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag
Try to match up the expected location and gmap locations for particular
genes. translated.ids was generated by fasta.translate --ids. tag must be
one of "complete|pseudogene|partial".
"""
from ... | def function[gffselect, parameter[args]]:
constant[
%prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag
Try to match up the expected location and gmap locations for particular
genes. translated.ids was generated by fasta.translate --ids. tag must be
one of "complete|pseudog... | keyword[def] identifier[gffselect] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[bed] keyword[import] identifier[intersectBed_wao]
identifier[p] = identifier[OptionParser] ( identifier[gffselect] . identifier[__doc__] )
identifier[opt... | def gffselect(args):
"""
%prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag
Try to match up the expected location and gmap locations for particular
genes. translated.ids was generated by fasta.translate --ids. tag must be
one of "complete|pseudogene|partial".
"""
from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.