code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def attributes(self, params=None):
"""
Gets the attributes from a Group/Indicator or Victim
Yields: attribute json
"""
if params is None:
params = {}
if not self.can_update():
self._tcex.handle_error(910, [self.type])
for a in self.tc_re... | def function[attributes, parameter[self, params]]:
constant[
Gets the attributes from a Group/Indicator or Victim
Yields: attribute json
]
if compare[name[params] is constant[None]] begin[:]
variable[params] assign[=] dictionary[[], []]
if <ast.UnaryOp o... | keyword[def] identifier[attributes] ( identifier[self] , identifier[params] = keyword[None] ):
literal[string]
keyword[if] identifier[params] keyword[is] keyword[None] :
identifier[params] ={}
keyword[if] keyword[not] identifier[self] . identifier[can_update] ():
... | def attributes(self, params=None):
"""
Gets the attributes from a Group/Indicator or Victim
Yields: attribute json
"""
if params is None:
params = {} # depends on [control=['if'], data=['params']]
if not self.can_update():
self._tcex.handle_error(910, [self.type]) ... |
def write_fix_accuracy(self, accuracy=None):
"""
Write the GPS fix accuracy header::
writer.write_fix_accuracy()
# -> HFFXA500
writer.write_fix_accuracy(25)
# -> HFFXA025
:param accuracy: the estimated GPS fix accuracy in meters (optional)
... | def function[write_fix_accuracy, parameter[self, accuracy]]:
constant[
Write the GPS fix accuracy header::
writer.write_fix_accuracy()
# -> HFFXA500
writer.write_fix_accuracy(25)
# -> HFFXA025
:param accuracy: the estimated GPS fix accuracy in m... | keyword[def] identifier[write_fix_accuracy] ( identifier[self] , identifier[accuracy] = keyword[None] ):
literal[string]
keyword[if] identifier[accuracy] keyword[is] keyword[None] :
identifier[accuracy] = literal[int]
identifier[accuracy] = identifier[int] ( identifier[a... | def write_fix_accuracy(self, accuracy=None):
"""
Write the GPS fix accuracy header::
writer.write_fix_accuracy()
# -> HFFXA500
writer.write_fix_accuracy(25)
# -> HFFXA025
:param accuracy: the estimated GPS fix accuracy in meters (optional)
"... |
def resolve(self, var, context):
"""Resolves a variable out of context if it's not in quotes"""
if var is None:
return var
if var[0] in ('"', "'") and var[-1] == var[0]:
return var[1:-1]
else:
return template.Variable(var).resolve(context) | def function[resolve, parameter[self, var, context]]:
constant[Resolves a variable out of context if it's not in quotes]
if compare[name[var] is constant[None]] begin[:]
return[name[var]]
if <ast.BoolOp object at 0x7da1b0651390> begin[:]
return[call[name[var]][<ast.Slice object a... | keyword[def] identifier[resolve] ( identifier[self] , identifier[var] , identifier[context] ):
literal[string]
keyword[if] identifier[var] keyword[is] keyword[None] :
keyword[return] identifier[var]
keyword[if] identifier[var] [ literal[int] ] keyword[in] ( literal[strin... | def resolve(self, var, context):
"""Resolves a variable out of context if it's not in quotes"""
if var is None:
return var # depends on [control=['if'], data=['var']]
if var[0] in ('"', "'") and var[-1] == var[0]:
return var[1:-1] # depends on [control=['if'], data=[]]
else:
re... |
def annotate(head, list):
"""Add '/' suffixes to directories."""
for i in range(len(list)):
if os.path.isdir(os.path.join(head, list[i])):
list[i] = list[i] + '/' | def function[annotate, parameter[head, list]]:
constant[Add '/' suffixes to directories.]
for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter[name[list]]]]]] begin[:]
if call[name[os].path.isdir, parameter[call[name[os].path.join, parameter[name[head], cal... | keyword[def] identifier[annotate] ( identifier[head] , identifier[list] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[list] )):
keyword[if] identifier[os] . identifier[path] . identifier[isdir] ( identifier[os] . identifier[path] . i... | def annotate(head, list):
"""Add '/' suffixes to directories."""
for i in range(len(list)):
if os.path.isdir(os.path.join(head, list[i])):
list[i] = list[i] + '/' # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['i']] |
def send_sms(self, text, **kw):
"""
Send an SMS. Since Free only allows us to send SMSes to ourselves you
don't have to provide your phone number.
"""
params = {
'user': self._user,
'pass': self._passwd,
'msg': text
}
kw.setde... | def function[send_sms, parameter[self, text]]:
constant[
Send an SMS. Since Free only allows us to send SMSes to ourselves you
don't have to provide your phone number.
]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da1b1018fa0>, <ast.Constant object at 0x7da1... | keyword[def] identifier[send_sms] ( identifier[self] , identifier[text] ,** identifier[kw] ):
literal[string]
identifier[params] ={
literal[string] : identifier[self] . identifier[_user] ,
literal[string] : identifier[self] . identifier[_passwd] ,
literal[string] : ident... | def send_sms(self, text, **kw):
"""
Send an SMS. Since Free only allows us to send SMSes to ourselves you
don't have to provide your phone number.
"""
params = {'user': self._user, 'pass': self._passwd, 'msg': text}
kw.setdefault('verify', False)
if not kw['verify']:
# re... |
def data_vectors(self):
"""The per-sample data in a vector.
Returns:
dict: A dict where the keys are the fields in the record and the
values are the corresponding arrays.
Examples:
>>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN,
... | def function[data_vectors, parameter[self]]:
constant[The per-sample data in a vector.
Returns:
dict: A dict where the keys are the fields in the record and the
values are the corresponding arrays.
Examples:
>>> sampleset = dimod.SampleSet.from_samples([[-1,... | keyword[def] identifier[data_vectors] ( identifier[self] ):
literal[string]
keyword[return] { identifier[field] : identifier[self] . identifier[record] [ identifier[field] ] keyword[for] identifier[field] keyword[in] identifier[self] . identifier[record] . identifier[dtype] . identifier[names]
... | def data_vectors(self):
"""The per-sample data in a vector.
Returns:
dict: A dict where the keys are the fields in the record and the
values are the corresponding arrays.
Examples:
>>> sampleset = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN,
... |
def build(cli, path, package):
"""Build CLI dynamically based on the package structure.
"""
for _, name, ispkg in iter_modules(path):
module = import_module(f'.{name}', package)
if ispkg:
build(cli.group(name)(module.group),
module.__path__,
mo... | def function[build, parameter[cli, path, package]]:
constant[Build CLI dynamically based on the package structure.
]
for taget[tuple[[<ast.Name object at 0x7da2054a5660>, <ast.Name object at 0x7da2054a6ef0>, <ast.Name object at 0x7da2054a5b40>]]] in starred[call[name[iter_modules], parameter[name[pa... | keyword[def] identifier[build] ( identifier[cli] , identifier[path] , identifier[package] ):
literal[string]
keyword[for] identifier[_] , identifier[name] , identifier[ispkg] keyword[in] identifier[iter_modules] ( identifier[path] ):
identifier[module] = identifier[import_module] ( literal[stri... | def build(cli, path, package):
"""Build CLI dynamically based on the package structure.
"""
for (_, name, ispkg) in iter_modules(path):
module = import_module(f'.{name}', package)
if ispkg:
build(cli.group(name)(module.group), module.__path__, module.__package__) # depends on [c... |
def create_symmetric_key(self, algorithm, length):
"""
Create a symmetric key.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created key will be compliant.
length(int): The length of the key to be created. ... | def function[create_symmetric_key, parameter[self, algorithm, length]]:
constant[
Create a symmetric key.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created key will be compliant.
length(int): The length... | keyword[def] identifier[create_symmetric_key] ( identifier[self] , identifier[algorithm] , identifier[length] ):
literal[string]
keyword[if] identifier[algorithm] keyword[not] keyword[in] identifier[self] . identifier[_symmetric_key_algorithms] . identifier[keys] ():
keyword[raise]... | def create_symmetric_key(self, algorithm, length):
"""
Create a symmetric key.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created key will be compliant.
length(int): The length of the key to be created. This... |
def get_action(self, action_name, action_id):
"""
Get an action.
action_name -- name of the action
action_id -- ID of the action
Returns the requested action if found, else None.
"""
if action_name not in self.actions:
return None
for action... | def function[get_action, parameter[self, action_name, action_id]]:
constant[
Get an action.
action_name -- name of the action
action_id -- ID of the action
Returns the requested action if found, else None.
]
if compare[name[action_name] <ast.NotIn object at 0x7d... | keyword[def] identifier[get_action] ( identifier[self] , identifier[action_name] , identifier[action_id] ):
literal[string]
keyword[if] identifier[action_name] keyword[not] keyword[in] identifier[self] . identifier[actions] :
keyword[return] keyword[None]
keyword[for] ... | def get_action(self, action_name, action_id):
"""
Get an action.
action_name -- name of the action
action_id -- ID of the action
Returns the requested action if found, else None.
"""
if action_name not in self.actions:
return None # depends on [control=['if'], ... |
def mean(self):
"""Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible.
"""
return np.dot(np.array(self.norm_scores), self.weights) | def function[mean, parameter[self]]:
constant[Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible.
]
return[call[name[np].dot, parameter[call[name[np].array... | keyword[def] identifier[mean] ( identifier[self] ):
literal[string]
keyword[return] identifier[np] . identifier[dot] ( identifier[np] . identifier[array] ( identifier[self] . identifier[norm_scores] ), identifier[self] . identifier[weights] ) | def mean(self):
"""Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible.
"""
return np.dot(np.array(self.norm_scores), self.weights) |
def edge_iterator(edges=[], edges_fn=None):
"""Yield documents from edge for loading into ArangoDB"""
for edge in itertools.chain(edges, files.read_edges(edges_fn)):
subj = copy.deepcopy(edge["edge"]["subject"])
subj_id = str(utils._create_hash_from_doc(subj))
subj["_key"] = subj_id
... | def function[edge_iterator, parameter[edges, edges_fn]]:
constant[Yield documents from edge for loading into ArangoDB]
for taget[name[edge]] in starred[call[name[itertools].chain, parameter[name[edges], call[name[files].read_edges, parameter[name[edges_fn]]]]]] begin[:]
variable[subj] as... | keyword[def] identifier[edge_iterator] ( identifier[edges] =[], identifier[edges_fn] = keyword[None] ):
literal[string]
keyword[for] identifier[edge] keyword[in] identifier[itertools] . identifier[chain] ( identifier[edges] , identifier[files] . identifier[read_edges] ( identifier[edges_fn] )):
... | def edge_iterator(edges=[], edges_fn=None):
"""Yield documents from edge for loading into ArangoDB"""
for edge in itertools.chain(edges, files.read_edges(edges_fn)):
subj = copy.deepcopy(edge['edge']['subject'])
subj_id = str(utils._create_hash_from_doc(subj))
subj['_key'] = subj_id
... |
def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry.
"""
return (self in IPv4Network('0.0.0.0/8') or
self in IPv4Network('10.0.0.0/8')... | def function[is_private, parameter[self]]:
constant[Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry.
]
return[<ast.BoolOp object at 0x7da204345de0>] | keyword[def] identifier[is_private] ( identifier[self] ):
literal[string]
keyword[return] ( identifier[self] keyword[in] identifier[IPv4Network] ( literal[string] ) keyword[or]
identifier[self] keyword[in] identifier[IPv4Network] ( literal[string] ) keyword[or]
identifier[se... | def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry.
"""
return self in IPv4Network('0.0.0.0/8') or self in IPv4Network('10.0.0.0/8') or self in IPv4Network('... |
def oil(data_set='three_phase_oil_flow'):
"""The three phase oil data from Bishop and James (1993)."""
if not data_available(data_set):
download_data(data_set)
oil_train_file = os.path.join(data_path, data_set, 'DataTrn.txt')
oil_trainlbls_file = os.path.join(data_path, data_set, 'DataTrnLbls.tx... | def function[oil, parameter[data_set]]:
constant[The three phase oil data from Bishop and James (1993).]
if <ast.UnaryOp object at 0x7da1b1c6bbe0> begin[:]
call[name[download_data], parameter[name[data_set]]]
variable[oil_train_file] assign[=] call[name[os].path.join, parameter[n... | keyword[def] identifier[oil] ( identifier[data_set] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[data_available] ( identifier[data_set] ):
identifier[download_data] ( identifier[data_set] )
identifier[oil_train_file] = identifier[os] . identifier[path] . identifi... | def oil(data_set='three_phase_oil_flow'):
"""The three phase oil data from Bishop and James (1993)."""
if not data_available(data_set):
download_data(data_set) # depends on [control=['if'], data=[]]
oil_train_file = os.path.join(data_path, data_set, 'DataTrn.txt')
oil_trainlbls_file = os.path.j... |
def md2tvd(self, kind='linear'):
"""
Provides an transformation and interpolation function that converts
MD to TVD.
Args:
kind (str): The kind of interpolation to do, e.g. 'linear',
'cubic', 'nearest'.
Returns:
function.
"""
... | def function[md2tvd, parameter[self, kind]]:
constant[
Provides an transformation and interpolation function that converts
MD to TVD.
Args:
kind (str): The kind of interpolation to do, e.g. 'linear',
'cubic', 'nearest'.
Returns:
function.... | keyword[def] identifier[md2tvd] ( identifier[self] , identifier[kind] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[position] keyword[is] keyword[None] :
keyword[return] keyword[lambda] identifier[x] : identifier[x]
keyword[return] ident... | def md2tvd(self, kind='linear'):
"""
Provides an transformation and interpolation function that converts
MD to TVD.
Args:
kind (str): The kind of interpolation to do, e.g. 'linear',
'cubic', 'nearest'.
Returns:
function.
"""
if se... |
def get_user(self, attr_map=None):
"""
Returns a UserObj (or whatever the self.user_class is) by using the
user's access token.
:param attr_map: Dictionary map from Cognito attributes to attribute
names we would like to show to our users
:return:
"""
user ... | def function[get_user, parameter[self, attr_map]]:
constant[
Returns a UserObj (or whatever the self.user_class is) by using the
user's access token.
:param attr_map: Dictionary map from Cognito attributes to attribute
names we would like to show to our users
:return:
... | keyword[def] identifier[get_user] ( identifier[self] , identifier[attr_map] = keyword[None] ):
literal[string]
identifier[user] = identifier[self] . identifier[client] . identifier[get_user] (
identifier[AccessToken] = identifier[self] . identifier[access_token]
)
identi... | def get_user(self, attr_map=None):
"""
Returns a UserObj (or whatever the self.user_class is) by using the
user's access token.
:param attr_map: Dictionary map from Cognito attributes to attribute
names we would like to show to our users
:return:
"""
user = self.c... |
def add_embedding(self, name, W, b, input_dim, output_channels, has_bias,
input_name, output_name):
"""
Add an embedding layer to the model.
Parameters
----------
name: str
The name of this layer
W: numpy.array
Weight matrix ... | def function[add_embedding, parameter[self, name, W, b, input_dim, output_channels, has_bias, input_name, output_name]]:
constant[
Add an embedding layer to the model.
Parameters
----------
name: str
The name of this layer
W: numpy.array
Weight ma... | keyword[def] identifier[add_embedding] ( identifier[self] , identifier[name] , identifier[W] , identifier[b] , identifier[input_dim] , identifier[output_channels] , identifier[has_bias] ,
identifier[input_name] , identifier[output_name] ):
literal[string]
identifier[spec] = identifier[self] . ide... | def add_embedding(self, name, W, b, input_dim, output_channels, has_bias, input_name, output_name):
"""
Add an embedding layer to the model.
Parameters
----------
name: str
The name of this layer
W: numpy.array
Weight matrix of shape (output_channels,... |
def get(version: str) -> 'Protocol':
"""
Return enum instance corresponding to input version value ('1.6' etc.)
"""
return Protocol.V_13 if version == Protocol.V_13.value.name else Protocol.DEFAULT | def function[get, parameter[version]]:
constant[
Return enum instance corresponding to input version value ('1.6' etc.)
]
return[<ast.IfExp object at 0x7da2041d8a30>] | keyword[def] identifier[get] ( identifier[version] : identifier[str] )-> literal[string] :
literal[string]
keyword[return] identifier[Protocol] . identifier[V_13] keyword[if] identifier[version] == identifier[Protocol] . identifier[V_13] . identifier[value] . identifier[name] keyword[else] id... | def get(version: str) -> 'Protocol':
"""
Return enum instance corresponding to input version value ('1.6' etc.)
"""
return Protocol.V_13 if version == Protocol.V_13.value.name else Protocol.DEFAULT |
def write_copy_button(self, text, text_to_copy):
"""Writes a button with 'text' which can be used
to copy 'text_to_copy' to clipboard when it's clicked."""
self.write_copy_script = True
self.write('<button onclick="cp(\'{}\');">{}</button>'
.format(text_to_copy, tex... | def function[write_copy_button, parameter[self, text, text_to_copy]]:
constant[Writes a button with 'text' which can be used
to copy 'text_to_copy' to clipboard when it's clicked.]
name[self].write_copy_script assign[=] constant[True]
call[name[self].write, parameter[call[constant[<bu... | keyword[def] identifier[write_copy_button] ( identifier[self] , identifier[text] , identifier[text_to_copy] ):
literal[string]
identifier[self] . identifier[write_copy_script] = keyword[True]
identifier[self] . identifier[write] ( literal[string]
. identifier[format] ( identifier... | def write_copy_button(self, text, text_to_copy):
"""Writes a button with 'text' which can be used
to copy 'text_to_copy' to clipboard when it's clicked."""
self.write_copy_script = True
self.write('<button onclick="cp(\'{}\');">{}</button>'.format(text_to_copy, text)) |
def _get_cycles(graph_dict, path, visited, result, vertice):
"""recursive function doing the real work for get_cycles"""
if vertice in path:
cycle = [vertice]
for node in path[::-1]:
if node == vertice:
break
cycle.insert(0, node)
# make a canonica... | def function[_get_cycles, parameter[graph_dict, path, visited, result, vertice]]:
constant[recursive function doing the real work for get_cycles]
if compare[name[vertice] in name[path]] begin[:]
variable[cycle] assign[=] list[[<ast.Name object at 0x7da1b059eda0>]]
for tag... | keyword[def] identifier[_get_cycles] ( identifier[graph_dict] , identifier[path] , identifier[visited] , identifier[result] , identifier[vertice] ):
literal[string]
keyword[if] identifier[vertice] keyword[in] identifier[path] :
identifier[cycle] =[ identifier[vertice] ]
keyword[for] i... | def _get_cycles(graph_dict, path, visited, result, vertice):
"""recursive function doing the real work for get_cycles"""
if vertice in path:
cycle = [vertice]
for node in path[::-1]:
if node == vertice:
break # depends on [control=['if'], data=[]]
cycle.i... |
def add_data_file(self, from_fp, timestamp=None, content_type=None):
# type: (IO, Optional[datetime.datetime], Optional[str]) -> Text
"""Copy inputs to data/ folder."""
self.self_check()
tmp_dir, tmp_prefix = os.path.split(self.temp_prefix)
with tempfile.NamedTemporaryFile(
... | def function[add_data_file, parameter[self, from_fp, timestamp, content_type]]:
constant[Copy inputs to data/ folder.]
call[name[self].self_check, parameter[]]
<ast.Tuple object at 0x7da18bc72ad0> assign[=] call[name[os].path.split, parameter[name[self].temp_prefix]]
with call[name[tempf... | keyword[def] identifier[add_data_file] ( identifier[self] , identifier[from_fp] , identifier[timestamp] = keyword[None] , identifier[content_type] = keyword[None] ):
literal[string]
identifier[self] . identifier[self_check] ()
identifier[tmp_dir] , identifier[tmp_prefix] = identifier[os] ... | def add_data_file(self, from_fp, timestamp=None, content_type=None):
# type: (IO, Optional[datetime.datetime], Optional[str]) -> Text
'Copy inputs to data/ folder.'
self.self_check()
(tmp_dir, tmp_prefix) = os.path.split(self.temp_prefix)
with tempfile.NamedTemporaryFile(prefix=tmp_prefix, dir=tmp_d... |
def fetch_gpml_usps_resampled_data(transpose_data=True, data_home=None):
"""
Fetch the USPS handwritten digits dataset from the internet and parse
appropriately into python arrays
>>> usps_resampled = fetch_gpml_usps_resampled_data()
>>> usps_resampled.train.targets.shape
(4649,)
>>> usps... | def function[fetch_gpml_usps_resampled_data, parameter[transpose_data, data_home]]:
constant[
Fetch the USPS handwritten digits dataset from the internet and parse
appropriately into python arrays
>>> usps_resampled = fetch_gpml_usps_resampled_data()
>>> usps_resampled.train.targets.shape
... | keyword[def] identifier[fetch_gpml_usps_resampled_data] ( identifier[transpose_data] = keyword[True] , identifier[data_home] = keyword[None] ):
literal[string]
identifier[data_home] = identifier[get_data_home] ( identifier[data_home] = identifier[data_home] )
identifier[data_filename] = identifier[os]... | def fetch_gpml_usps_resampled_data(transpose_data=True, data_home=None):
"""
Fetch the USPS handwritten digits dataset from the internet and parse
appropriately into python arrays
>>> usps_resampled = fetch_gpml_usps_resampled_data()
>>> usps_resampled.train.targets.shape
(4649,)
>>> usps... |
def schedCoroSafePend(self, coro):
'''
Schedules a coroutine to run as soon as possible on the same event loop that this Base is running on
Note:
This method may *not* be run inside an event loop
'''
if __debug__:
import synapse.lib.threads as s_threads ... | def function[schedCoroSafePend, parameter[self, coro]]:
constant[
Schedules a coroutine to run as soon as possible on the same event loop that this Base is running on
Note:
This method may *not* be run inside an event loop
]
if name[__debug__] begin[:]
import... | keyword[def] identifier[schedCoroSafePend] ( identifier[self] , identifier[coro] ):
literal[string]
keyword[if] identifier[__debug__] :
keyword[import] identifier[synapse] . identifier[lib] . identifier[threads] keyword[as] identifier[s_threads]
keyword[assert] ident... | def schedCoroSafePend(self, coro):
"""
Schedules a coroutine to run as soon as possible on the same event loop that this Base is running on
Note:
This method may *not* be run inside an event loop
"""
if __debug__:
import synapse.lib.threads as s_threads # avoid impo... |
def are_equal(self, mol1, mol2):
"""
Compare the bond table of the two molecules.
Args:
mol1: first molecule. pymatgen Molecule object.
mol2: second moleculs. pymatgen Molecule objec.
"""
b1 = set(self._get_bonds(mol1))
b2 = set(self._get_bonds(mo... | def function[are_equal, parameter[self, mol1, mol2]]:
constant[
Compare the bond table of the two molecules.
Args:
mol1: first molecule. pymatgen Molecule object.
mol2: second moleculs. pymatgen Molecule objec.
]
variable[b1] assign[=] call[name[set], par... | keyword[def] identifier[are_equal] ( identifier[self] , identifier[mol1] , identifier[mol2] ):
literal[string]
identifier[b1] = identifier[set] ( identifier[self] . identifier[_get_bonds] ( identifier[mol1] ))
identifier[b2] = identifier[set] ( identifier[self] . identifier[_get_bonds] ( i... | def are_equal(self, mol1, mol2):
"""
Compare the bond table of the two molecules.
Args:
mol1: first molecule. pymatgen Molecule object.
mol2: second moleculs. pymatgen Molecule objec.
"""
b1 = set(self._get_bonds(mol1))
b2 = set(self._get_bonds(mol2))
ret... |
def upload(self, fd, name=None, folder_key=None, filedrop_key=None,
path=None, action_on_duplicate=None):
"""Upload file, returns UploadResult object
fd -- file-like object to upload from, expects exclusive access
name -- file name
folder_key -- folderkey of the target fo... | def function[upload, parameter[self, fd, name, folder_key, filedrop_key, path, action_on_duplicate]]:
constant[Upload file, returns UploadResult object
fd -- file-like object to upload from, expects exclusive access
name -- file name
folder_key -- folderkey of the target folder
... | keyword[def] identifier[upload] ( identifier[self] , identifier[fd] , identifier[name] = keyword[None] , identifier[folder_key] = keyword[None] , identifier[filedrop_key] = keyword[None] ,
identifier[path] = keyword[None] , identifier[action_on_duplicate] = keyword[None] ):
literal[string]
... | def upload(self, fd, name=None, folder_key=None, filedrop_key=None, path=None, action_on_duplicate=None):
"""Upload file, returns UploadResult object
fd -- file-like object to upload from, expects exclusive access
name -- file name
folder_key -- folderkey of the target folder
path -... |
def weighted_sample(bn, e):
"""Sample an event from bn that's consistent with the evidence e;
return the event and its weight, the likelihood that the event
accords to the evidence."""
w = 1
event = dict(e) # boldface x in Fig. 14.15
for node in bn.nodes:
Xi = node.variable
if Xi... | def function[weighted_sample, parameter[bn, e]]:
constant[Sample an event from bn that's consistent with the evidence e;
return the event and its weight, the likelihood that the event
accords to the evidence.]
variable[w] assign[=] constant[1]
variable[event] assign[=] call[name[dict], p... | keyword[def] identifier[weighted_sample] ( identifier[bn] , identifier[e] ):
literal[string]
identifier[w] = literal[int]
identifier[event] = identifier[dict] ( identifier[e] )
keyword[for] identifier[node] keyword[in] identifier[bn] . identifier[nodes] :
identifier[Xi] = identifier[... | def weighted_sample(bn, e):
"""Sample an event from bn that's consistent with the evidence e;
return the event and its weight, the likelihood that the event
accords to the evidence."""
w = 1
event = dict(e) # boldface x in Fig. 14.15
for node in bn.nodes:
Xi = node.variable
if X... |
def keystone(*arg):
"""
Swift annotation for adding function to process keystone 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_eve... | def function[keystone, parameter[]]:
constant[
Swift annotation for adding function to process keystone 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 notific... | keyword[def] identifier[keystone] (* identifier[arg] ):
literal[string]
identifier[check_event_type] ( identifier[Openstack] . identifier[Keystone] ,* identifier[arg] )
identifier[event_type] = identifier[arg] [ literal[int] ]
keyword[def] identifier[decorator] ( identifier[func] ):
ke... | def keystone(*arg):
"""
Swift annotation for adding function to process keystone 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_eve... |
def patch_namespaced_custom_object_status(self, group, version, namespace, plural, name, body, **kwargs): # noqa: E501
"""patch_namespaced_custom_object_status # noqa: E501
partially update status of the specified namespace scoped custom object # noqa: E501
This method makes a synchronous HT... | def function[patch_namespaced_custom_object_status, parameter[self, group, version, namespace, plural, name, body]]:
constant[patch_namespaced_custom_object_status # noqa: E501
partially update status of the specified namespace scoped custom object # noqa: E501
This method makes a synchronous... | keyword[def] identifier[patch_namespaced_custom_object_status] ( identifier[self] , identifier[group] , identifier[version] , identifier[namespace] , identifier[plural] , identifier[name] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[Tr... | def patch_namespaced_custom_object_status(self, group, version, namespace, plural, name, body, **kwargs): # noqa: E501
"patch_namespaced_custom_object_status # noqa: E501\n\n partially update status of the specified namespace scoped custom object # noqa: E501\n This method makes a synchronous HTTP ... |
def antipode(lon, lat):
"""
Calculates the antipode (opposite point on the globe) of the given point or
points. Input and output is expected to be in radians.
Parameters
----------
lon : number or sequence of numbers
Longitude in radians
lat : number or sequence of numbers
L... | def function[antipode, parameter[lon, lat]]:
constant[
Calculates the antipode (opposite point on the globe) of the given point or
points. Input and output is expected to be in radians.
Parameters
----------
lon : number or sequence of numbers
Longitude in radians
lat : number o... | keyword[def] identifier[antipode] ( identifier[lon] , identifier[lat] ):
literal[string]
identifier[x] , identifier[y] , identifier[z] = identifier[sph2cart] ( identifier[lon] , identifier[lat] )
keyword[return] identifier[cart2sph] (- identifier[x] ,- identifier[y] ,- identifier[z] ) | def antipode(lon, lat):
"""
Calculates the antipode (opposite point on the globe) of the given point or
points. Input and output is expected to be in radians.
Parameters
----------
lon : number or sequence of numbers
Longitude in radians
lat : number or sequence of numbers
L... |
def _parse_meta(self, meta):
"""
Parse the _meta element from a dynamic host inventory output.
"""
for hostname, hostvars in meta.get('hostvars', {}).items():
for var_key, var_val in hostvars.items():
self._get_host(hostname)['hostvars'][var_key] = var_val | def function[_parse_meta, parameter[self, meta]]:
constant[
Parse the _meta element from a dynamic host inventory output.
]
for taget[tuple[[<ast.Name object at 0x7da1b1dfac80>, <ast.Name object at 0x7da1b1dfabf0>]]] in starred[call[call[name[meta].get, parameter[constant[hostvars], dict... | keyword[def] identifier[_parse_meta] ( identifier[self] , identifier[meta] ):
literal[string]
keyword[for] identifier[hostname] , identifier[hostvars] keyword[in] identifier[meta] . identifier[get] ( literal[string] ,{}). identifier[items] ():
keyword[for] identifier[var_key] , ide... | def _parse_meta(self, meta):
"""
Parse the _meta element from a dynamic host inventory output.
"""
for (hostname, hostvars) in meta.get('hostvars', {}).items():
for (var_key, var_val) in hostvars.items():
self._get_host(hostname)['hostvars'][var_key] = var_val # depends on [... |
def create(self, params, args, data):
# type: (str, dict, dict) -> AppModel
"""
POST /resource/model_cls/
data
Create new resource
"""
ctx = self._create_context(params, args, data)
model = self._create_one(ctx)
self._save_one(model, ctx)
... | def function[create, parameter[self, params, args, data]]:
constant[
POST /resource/model_cls/
data
Create new resource
]
variable[ctx] assign[=] call[name[self]._create_context, parameter[name[params], name[args], name[data]]]
variable[model] assign[=] call[name... | keyword[def] identifier[create] ( identifier[self] , identifier[params] , identifier[args] , identifier[data] ):
literal[string]
identifier[ctx] = identifier[self] . identifier[_create_context] ( identifier[params] , identifier[args] , identifier[data] )
identifier[model] = identifier[sel... | def create(self, params, args, data):
# type: (str, dict, dict) -> AppModel
'\n POST /resource/model_cls/\n data\n\n Create new resource\n '
ctx = self._create_context(params, args, data)
model = self._create_one(ctx)
self._save_one(model, ctx)
return self._return_sav... |
def runRemoteCommand(self, cmd, args, abandonOnFailure=True,
evaluateCommand=lambda cmd: cmd.didFail()):
"""generic RemoteCommand boilerplate"""
cmd = remotecommand.RemoteCommand(cmd, args)
if hasattr(self, "rc_log"):
cmd.useLog(self.rc_log, False)
d ... | def function[runRemoteCommand, parameter[self, cmd, args, abandonOnFailure, evaluateCommand]]:
constant[generic RemoteCommand boilerplate]
variable[cmd] assign[=] call[name[remotecommand].RemoteCommand, parameter[name[cmd], name[args]]]
if call[name[hasattr], parameter[name[self], constant[rc_lo... | keyword[def] identifier[runRemoteCommand] ( identifier[self] , identifier[cmd] , identifier[args] , identifier[abandonOnFailure] = keyword[True] ,
identifier[evaluateCommand] = keyword[lambda] identifier[cmd] : identifier[cmd] . identifier[didFail] ()):
literal[string]
identifier[cmd] = identifie... | def runRemoteCommand(self, cmd, args, abandonOnFailure=True, evaluateCommand=lambda cmd: cmd.didFail()):
"""generic RemoteCommand boilerplate"""
cmd = remotecommand.RemoteCommand(cmd, args)
if hasattr(self, 'rc_log'):
cmd.useLog(self.rc_log, False) # depends on [control=['if'], data=[]]
d = sel... |
def parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Diagnose script for checking the current system.')
choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
for choice in choices:
... | def function[parse_args, parameter[]]:
constant[Parse arguments.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
variable[choices] assign[=] list[[<ast.Constant object at 0x7da20e955a50>, <ast.Constant object at 0x7da20e9547c0>, <ast.Constant object at 0x7da20e955540... | keyword[def] identifier[parse_args] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[formatter_class] = identifier[argparse] . identifier[ArgumentDefaultsHelpFormatter] ,
identifier[description] = literal[string] )
identifier[choices] =[... | def parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Diagnose script for checking the current system.')
choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
for choice in choices:
parser.add_ar... |
def toVertical(self,R,phi=None):
"""
NAME:
toVertical
PURPOSE:
convert a 3D potential into a linear (vertical) potential at R
INPUT:
R - Galactocentric radius at which to create the vertical potential (can be Quantity)
phi= (None) Galacto... | def function[toVertical, parameter[self, R, phi]]:
constant[
NAME:
toVertical
PURPOSE:
convert a 3D potential into a linear (vertical) potential at R
INPUT:
R - Galactocentric radius at which to create the vertical potential (can be Quantity)
... | keyword[def] identifier[toVertical] ( identifier[self] , identifier[R] , identifier[phi] = keyword[None] ):
literal[string]
keyword[if] identifier[_APY_LOADED] keyword[and] identifier[isinstance] ( identifier[R] , identifier[units] . identifier[Quantity] ):
identifier[R] = identifie... | def toVertical(self, R, phi=None):
"""
NAME:
toVertical
PURPOSE:
convert a 3D potential into a linear (vertical) potential at R
INPUT:
R - Galactocentric radius at which to create the vertical potential (can be Quantity)
phi= (None) Galactoce... |
def split_results(self):
"""
Convenience method to separate failed and successful results.
.. versionadded:: 2.0.0
This function will split the results of the failed operation
(see :attr:`.all_results`) into "good" and "bad" dictionaries.
The intent is for the applicat... | def function[split_results, parameter[self]]:
constant[
Convenience method to separate failed and successful results.
.. versionadded:: 2.0.0
This function will split the results of the failed operation
(see :attr:`.all_results`) into "good" and "bad" dictionaries.
The... | keyword[def] identifier[split_results] ( identifier[self] ):
literal[string]
identifier[ret_ok] , identifier[ret_fail] ={},{}
identifier[count] = literal[int]
identifier[nokey_prefix] =([ literal[string] ]+ identifier[sorted] ( identifier[filter] ( identifier[bool] , identifier[... | def split_results(self):
"""
Convenience method to separate failed and successful results.
.. versionadded:: 2.0.0
This function will split the results of the failed operation
(see :attr:`.all_results`) into "good" and "bad" dictionaries.
The intent is for the application ... |
def get_crime_category(self, id, date=None):
"""
Get a particular crime category by ID, valid at a particular date. Uses
the crime-categories_ API call.
:rtype: CrimeCategory
:param str id: The ID of the crime category to get.
:param date: The date that the given crime c... | def function[get_crime_category, parameter[self, id, date]]:
constant[
Get a particular crime category by ID, valid at a particular date. Uses
the crime-categories_ API call.
:rtype: CrimeCategory
:param str id: The ID of the crime category to get.
:param date: The date ... | keyword[def] identifier[get_crime_category] ( identifier[self] , identifier[id] , identifier[date] = keyword[None] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[_get_crime_categories] ( identifier[date] = identifier[date] )[ identifier[id] ]
... | def get_crime_category(self, id, date=None):
"""
Get a particular crime category by ID, valid at a particular date. Uses
the crime-categories_ API call.
:rtype: CrimeCategory
:param str id: The ID of the crime category to get.
:param date: The date that the given crime categ... |
def _flatten_action_profile(action_profile, indptr):
"""
Flatten the given action profile.
Parameters
----------
action_profile : array_like(int or array_like(float, ndim=1))
Profile of actions of the N players, where each player i' action
is a pure action (int) or a mixed action (a... | def function[_flatten_action_profile, parameter[action_profile, indptr]]:
constant[
Flatten the given action profile.
Parameters
----------
action_profile : array_like(int or array_like(float, ndim=1))
Profile of actions of the N players, where each player i' action
is a pure ac... | keyword[def] identifier[_flatten_action_profile] ( identifier[action_profile] , identifier[indptr] ):
literal[string]
identifier[N] = identifier[len] ( identifier[indptr] )- literal[int]
identifier[out] = identifier[np] . identifier[empty] ( identifier[indptr] [- literal[int] ])
keyword[for] i... | def _flatten_action_profile(action_profile, indptr):
"""
Flatten the given action profile.
Parameters
----------
action_profile : array_like(int or array_like(float, ndim=1))
Profile of actions of the N players, where each player i' action
is a pure action (int) or a mixed action (a... |
def fingerprint(self):
"""A total graph fingerprint
The result is invariant under permutation of the vertex indexes. The
chance that two different (molecular) graphs yield the same
fingerprint is small but not zero. (See unit tests.)"""
if self.num_vertices == 0:
... | def function[fingerprint, parameter[self]]:
constant[A total graph fingerprint
The result is invariant under permutation of the vertex indexes. The
chance that two different (molecular) graphs yield the same
fingerprint is small but not zero. (See unit tests.)]
if compa... | keyword[def] identifier[fingerprint] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[num_vertices] == literal[int] :
keyword[return] identifier[np] . identifier[zeros] ( literal[int] , identifier[np] . identifier[ubyte] )
keyword[else] :
... | def fingerprint(self):
"""A total graph fingerprint
The result is invariant under permutation of the vertex indexes. The
chance that two different (molecular) graphs yield the same
fingerprint is small but not zero. (See unit tests.)"""
if self.num_vertices == 0:
return... |
def convert2(self, imtls, sids):
"""
Convert a probability map into a composite array of shape (N,)
and dtype `imtls.dt`.
:param imtls:
DictArray instance
:param sids:
the IDs of the sites we are interested in
:returns:
an array of cur... | def function[convert2, parameter[self, imtls, sids]]:
constant[
Convert a probability map into a composite array of shape (N,)
and dtype `imtls.dt`.
:param imtls:
DictArray instance
:param sids:
the IDs of the sites we are interested in
:returns:
... | keyword[def] identifier[convert2] ( identifier[self] , identifier[imtls] , identifier[sids] ):
literal[string]
keyword[assert] identifier[self] . identifier[shape_z] == literal[int] , identifier[self] . identifier[shape_z]
identifier[curves] = identifier[numpy] . identifier[zeros] ( iden... | def convert2(self, imtls, sids):
"""
Convert a probability map into a composite array of shape (N,)
and dtype `imtls.dt`.
:param imtls:
DictArray instance
:param sids:
the IDs of the sites we are interested in
:returns:
an array of curves ... |
def Get_RpRs(d, **kwargs):
'''
Returns the value of the planet radius over the stellar radius
for a given depth :py:obj:`d`, given
the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`.
'''
if ps is None:
raise Exception("Unable to import `pysyzygy`.")
def Depth(RpRs, **kwa... | def function[Get_RpRs, parameter[d]]:
constant[
Returns the value of the planet radius over the stellar radius
for a given depth :py:obj:`d`, given
the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`.
]
if compare[name[ps] is constant[None]] begin[:]
<ast.Raise object at 0... | keyword[def] identifier[Get_RpRs] ( identifier[d] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[ps] keyword[is] keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] )
keyword[def] identifier[Depth] ( identifier[RpRs] ,** identifier[kwargs] ):
... | def Get_RpRs(d, **kwargs):
"""
Returns the value of the planet radius over the stellar radius
for a given depth :py:obj:`d`, given
the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`.
"""
if ps is None:
raise Exception('Unable to import `pysyzygy`.') # depends on [control=['if'],... |
def mount_share(share_path):
"""Mounts a share at /Volumes
Args:
share_path: String URL with all auth info to connect to file share.
Returns:
The mount point or raises an error.
"""
sh_url = CFURLCreateWithString(None, share_path, None)
# Set UI to reduced interaction
open_... | def function[mount_share, parameter[share_path]]:
constant[Mounts a share at /Volumes
Args:
share_path: String URL with all auth info to connect to file share.
Returns:
The mount point or raises an error.
]
variable[sh_url] assign[=] call[name[CFURLCreateWithString], parame... | keyword[def] identifier[mount_share] ( identifier[share_path] ):
literal[string]
identifier[sh_url] = identifier[CFURLCreateWithString] ( keyword[None] , identifier[share_path] , keyword[None] )
identifier[open_options] ={ identifier[NetFS] . identifier[kNAUIOptionKey] : identifier[NetFS] . ident... | def mount_share(share_path):
"""Mounts a share at /Volumes
Args:
share_path: String URL with all auth info to connect to file share.
Returns:
The mount point or raises an error.
"""
sh_url = CFURLCreateWithString(None, share_path, None)
# Set UI to reduced interaction
open_... |
def merge_dicts(src, patch):
"""Merge contents of dict `patch` into `src`."""
for key in patch:
if key in src:
if isinstance(src[key], dict) and isinstance(patch[key], dict):
merge_dicts(src[key], patch[key])
else:
src[key] = merge_values(src[key],... | def function[merge_dicts, parameter[src, patch]]:
constant[Merge contents of dict `patch` into `src`.]
for taget[name[key]] in starred[name[patch]] begin[:]
if compare[name[key] in name[src]] begin[:]
if <ast.BoolOp object at 0x7da1b06c8e50> begin[:]
... | keyword[def] identifier[merge_dicts] ( identifier[src] , identifier[patch] ):
literal[string]
keyword[for] identifier[key] keyword[in] identifier[patch] :
keyword[if] identifier[key] keyword[in] identifier[src] :
keyword[if] identifier[isinstance] ( identifier[src] [ identifier... | def merge_dicts(src, patch):
"""Merge contents of dict `patch` into `src`."""
for key in patch:
if key in src:
if isinstance(src[key], dict) and isinstance(patch[key], dict):
merge_dicts(src[key], patch[key]) # depends on [control=['if'], data=[]]
else:
... |
def _filter_or_exclude(self, negate, *args, **kwargs):
"""
Overrides default behavior to handle linguist fields.
"""
from .models import Translation
new_args = self.get_cleaned_args(args)
new_kwargs = self.get_cleaned_kwargs(kwargs)
translation_args = self.get_t... | def function[_filter_or_exclude, parameter[self, negate]]:
constant[
Overrides default behavior to handle linguist fields.
]
from relative_module[models] import module[Translation]
variable[new_args] assign[=] call[name[self].get_cleaned_args, parameter[name[args]]]
variable[... | keyword[def] identifier[_filter_or_exclude] ( identifier[self] , identifier[negate] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[from] . identifier[models] keyword[import] identifier[Translation]
identifier[new_args] = identifier[self] . identifier[get_cleaned_... | def _filter_or_exclude(self, negate, *args, **kwargs):
"""
Overrides default behavior to handle linguist fields.
"""
from .models import Translation
new_args = self.get_cleaned_args(args)
new_kwargs = self.get_cleaned_kwargs(kwargs)
translation_args = self.get_translation_args(args)
... |
def create_or_replace_primary_key(self,
table: str,
fieldnames: Sequence[str]) -> int:
"""Make a primary key, or replace it if it exists."""
# *** create_or_replace_primary_key: Uses code specific to MySQL
sql = """
... | def function[create_or_replace_primary_key, parameter[self, table, fieldnames]]:
constant[Make a primary key, or replace it if it exists.]
variable[sql] assign[=] call[constant[
SELECT COUNT(*)
FROM information_schema.table_constraints
WHERE table_name=?
A... | keyword[def] identifier[create_or_replace_primary_key] ( identifier[self] ,
identifier[table] : identifier[str] ,
identifier[fieldnames] : identifier[Sequence] [ identifier[str] ])-> identifier[int] :
literal[string]
identifier[sql] = literal[string] . identifier[format] ( identifier[sel... | def create_or_replace_primary_key(self, table: str, fieldnames: Sequence[str]) -> int:
"""Make a primary key, or replace it if it exists."""
# *** create_or_replace_primary_key: Uses code specific to MySQL
sql = "\n SELECT COUNT(*)\n FROM information_schema.table_constraints\n ... |
def send_activation_email(self, user):
"""
Send the activation email. The activation key is the username,
signed using TimestampSigner.
"""
activation_key = self.get_activation_key(user)
context = self.get_email_context(activation_key)
context['user'] = user
... | def function[send_activation_email, parameter[self, user]]:
constant[
Send the activation email. The activation key is the username,
signed using TimestampSigner.
]
variable[activation_key] assign[=] call[name[self].get_activation_key, parameter[name[user]]]
variable[con... | keyword[def] identifier[send_activation_email] ( identifier[self] , identifier[user] ):
literal[string]
identifier[activation_key] = identifier[self] . identifier[get_activation_key] ( identifier[user] )
identifier[context] = identifier[self] . identifier[get_email_context] ( identifier[ac... | def send_activation_email(self, user):
"""
Send the activation email. The activation key is the username,
signed using TimestampSigner.
"""
activation_key = self.get_activation_key(user)
context = self.get_email_context(activation_key)
context['user'] = user
subject = render... |
def extrude_triangulation(vertices,
faces,
height,
**kwargs):
"""
Turn a 2D triangulation into a watertight Trimesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle in... | def function[extrude_triangulation, parameter[vertices, faces, height]]:
constant[
Turn a 2D triangulation into a watertight Trimesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle indexes of vertices
height : float
Distance to ex... | keyword[def] identifier[extrude_triangulation] ( identifier[vertices] ,
identifier[faces] ,
identifier[height] ,
** identifier[kwargs] ):
literal[string]
identifier[vertices] = identifier[np] . identifier[asanyarray] ( identifier[vertices] , identifier[dtype] = identifier[np] . identifier[float64] )
... | def extrude_triangulation(vertices, faces, height, **kwargs):
"""
Turn a 2D triangulation into a watertight Trimesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle indexes of vertices
height : float
Distance to extrude triangulation
... |
def get_permissions_for_role(role, brain_or_object):
"""Return the permissions of the role which are granted on the object
Code extracted from `IRoleManager.permissionsOfRole`
:param role: The role to check the permission
:param brain_or_object: Catalog brain or object
:returns: List of permission... | def function[get_permissions_for_role, parameter[role, brain_or_object]]:
constant[Return the permissions of the role which are granted on the object
Code extracted from `IRoleManager.permissionsOfRole`
:param role: The role to check the permission
:param brain_or_object: Catalog brain or object
... | keyword[def] identifier[get_permissions_for_role] ( identifier[role] , identifier[brain_or_object] ):
literal[string]
identifier[obj] = identifier[api] . identifier[get_object] ( identifier[brain_or_object] )
identifier[valid_roles] = identifier[get_valid_roles_for] ( identifier[obj] )
keyw... | def get_permissions_for_role(role, brain_or_object):
"""Return the permissions of the role which are granted on the object
Code extracted from `IRoleManager.permissionsOfRole`
:param role: The role to check the permission
:param brain_or_object: Catalog brain or object
:returns: List of permission... |
def solveServiceArea(self,facilities,method="POST",
barriers=None,
polylineBarriers=None,
polygonBarriers=None,
travelMode=None,
attributeParameterValues=None,
defaultBre... | def function[solveServiceArea, parameter[self, facilities, method, barriers, polylineBarriers, polygonBarriers, travelMode, attributeParameterValues, defaultBreaks, excludeSourcesFromPolygons, mergeSimilarPolygonRanges, outputLines, outputPolygons, overlapLines, overlapPolygons, splitLinesAtBreaks, splitPolygonsAtBreak... | keyword[def] identifier[solveServiceArea] ( identifier[self] , identifier[facilities] , identifier[method] = literal[string] ,
identifier[barriers] = keyword[None] ,
identifier[polylineBarriers] = keyword[None] ,
identifier[polygonBarriers] = keyword[None] ,
identifier[travelMode] = keyword[None] ,
identifier[at... | def solveServiceArea(self, facilities, method='POST', barriers=None, polylineBarriers=None, polygonBarriers=None, travelMode=None, attributeParameterValues=None, defaultBreaks=None, excludeSourcesFromPolygons=None, mergeSimilarPolygonRanges=None, outputLines=None, outputPolygons=None, overlapLines=None, overlapPolygons... |
def metablockLength(self):
"""Read MNIBBLES and meta block length;
if empty block, skip block and return true.
"""
self.MLEN = self.verboseRead(MetablockLengthAlphabet())
if self.MLEN:
return False
#empty block; skip and return False
self.verboseRead(R... | def function[metablockLength, parameter[self]]:
constant[Read MNIBBLES and meta block length;
if empty block, skip block and return true.
]
name[self].MLEN assign[=] call[name[self].verboseRead, parameter[call[name[MetablockLengthAlphabet], parameter[]]]]
if name[self].MLEN begin... | keyword[def] identifier[metablockLength] ( identifier[self] ):
literal[string]
identifier[self] . identifier[MLEN] = identifier[self] . identifier[verboseRead] ( identifier[MetablockLengthAlphabet] ())
keyword[if] identifier[self] . identifier[MLEN] :
keyword[return] keyword... | def metablockLength(self):
"""Read MNIBBLES and meta block length;
if empty block, skip block and return true.
"""
self.MLEN = self.verboseRead(MetablockLengthAlphabet())
if self.MLEN:
return False # depends on [control=['if'], data=[]]
#empty block; skip and return False
se... |
def SETNAE(cpu, dest):
"""
Sets byte if not above or equal.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0)) | def function[SETNAE, parameter[cpu, dest]]:
constant[
Sets byte if not above or equal.
:param cpu: current CPU.
:param dest: destination operand.
]
call[name[dest].write, parameter[call[name[Operators].ITEBV, parameter[name[dest].size, name[cpu].CF, constant[1], constant... | keyword[def] identifier[SETNAE] ( identifier[cpu] , identifier[dest] ):
literal[string]
identifier[dest] . identifier[write] ( identifier[Operators] . identifier[ITEBV] ( identifier[dest] . identifier[size] , identifier[cpu] . identifier[CF] , literal[int] , literal[int] )) | def SETNAE(cpu, dest):
"""
Sets byte if not above or equal.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0)) |
def _encode_multipart_formdata(fields, files):
"""
Create a multipart encoded form for use in PUTing and POSTing.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, bo... | def function[_encode_multipart_formdata, parameter[fields, files]]:
constant[
Create a multipart encoded form for use in PUTing and POSTing.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as fil... | keyword[def] identifier[_encode_multipart_formdata] ( identifier[fields] , identifier[files] ):
literal[string]
identifier[BOUNDARY] = literal[string]
identifier[CRLF] = literal[string]
identifier[L] =[]
keyword[for] ( identifier[key] , identifier[value] ) keyword[in] identifier[fields] :... | def _encode_multipart_formdata(fields, files):
"""
Create a multipart encoded form for use in PUTing and POSTing.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, bo... |
def main_subtask(module_name, method_prefixs=["task_"], optional_params={}):
"""
http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse
As of 2.7, optparse is deprecated, and will hopefully go away in the future
"""
parser = argparse.ArgumentParser(description="")
parse... | def function[main_subtask, parameter[module_name, method_prefixs, optional_params]]:
constant[
http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse
As of 2.7, optparse is deprecated, and will hopefully go away in the future
]
variable[parser] assign[=] call[name[a... | keyword[def] identifier[main_subtask] ( identifier[module_name] , identifier[method_prefixs] =[ literal[string] ], identifier[optional_params] ={}):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = literal[string] )
identifier[parser] .... | def main_subtask(module_name, method_prefixs=['task_'], optional_params={}):
"""
http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse
As of 2.7, optparse is deprecated, and will hopefully go away in the future
"""
parser = argparse.ArgumentParser(description='')
parse... |
def crop_coords(img, padding):
"""Find coordinates describing extent of non-zero portion of image, padded"""
coords = np.nonzero(img)
empty_axis_exists = np.any([len(arr) == 0 for arr in coords])
if empty_axis_exists:
end_coords = img.shape
beg_coords = np.zeros((1, img.ndim)).astype(in... | def function[crop_coords, parameter[img, padding]]:
constant[Find coordinates describing extent of non-zero portion of image, padded]
variable[coords] assign[=] call[name[np].nonzero, parameter[name[img]]]
variable[empty_axis_exists] assign[=] call[name[np].any, parameter[<ast.ListComp object at... | keyword[def] identifier[crop_coords] ( identifier[img] , identifier[padding] ):
literal[string]
identifier[coords] = identifier[np] . identifier[nonzero] ( identifier[img] )
identifier[empty_axis_exists] = identifier[np] . identifier[any] ([ identifier[len] ( identifier[arr] )== literal[int] keyword... | def crop_coords(img, padding):
"""Find coordinates describing extent of non-zero portion of image, padded"""
coords = np.nonzero(img)
empty_axis_exists = np.any([len(arr) == 0 for arr in coords])
if empty_axis_exists:
end_coords = img.shape
beg_coords = np.zeros((1, img.ndim)).astype(int... |
def select_lamb(self, lamb=None, out=bool):
""" Return a wavelength index array
Return a boolean or integer index array, hereafter called 'ind'
The array refers to the reference time vector self.ddataRef['lamb']
Parameters
----------
lamb : None / float / np.ndarray... | def function[select_lamb, parameter[self, lamb, out]]:
constant[ Return a wavelength index array
Return a boolean or integer index array, hereafter called 'ind'
The array refers to the reference time vector self.ddataRef['lamb']
Parameters
----------
lamb : None / f... | keyword[def] identifier[select_lamb] ( identifier[self] , identifier[lamb] = keyword[None] , identifier[out] = identifier[bool] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_isSpectral] ():
identifier[msg] = literal[string]
keyword[raise] i... | def select_lamb(self, lamb=None, out=bool):
""" Return a wavelength index array
Return a boolean or integer index array, hereafter called 'ind'
The array refers to the reference time vector self.ddataRef['lamb']
Parameters
----------
lamb : None / float / np.ndarray / l... |
def get(key, profile=None):
'''
Get a value from memcached
'''
conn = salt.utils.memcached.get_conn(profile)
return salt.utils.memcached.get(conn, key) | def function[get, parameter[key, profile]]:
constant[
Get a value from memcached
]
variable[conn] assign[=] call[name[salt].utils.memcached.get_conn, parameter[name[profile]]]
return[call[name[salt].utils.memcached.get, parameter[name[conn], name[key]]]] | keyword[def] identifier[get] ( identifier[key] , identifier[profile] = keyword[None] ):
literal[string]
identifier[conn] = identifier[salt] . identifier[utils] . identifier[memcached] . identifier[get_conn] ( identifier[profile] )
keyword[return] identifier[salt] . identifier[utils] . identifier[memc... | def get(key, profile=None):
"""
Get a value from memcached
"""
conn = salt.utils.memcached.get_conn(profile)
return salt.utils.memcached.get(conn, key) |
def get_possible_paths(base_path, path_regex):
"""
Looks for path_regex within base_path. Each match is append
in the returned list.
path_regex may contain subfolder structure.
If any part of the folder structure is a
:param base_path: str
:param path_regex: str
:return list of string... | def function[get_possible_paths, parameter[base_path, path_regex]]:
constant[
Looks for path_regex within base_path. Each match is append
in the returned list.
path_regex may contain subfolder structure.
If any part of the folder structure is a
:param base_path: str
:param path_regex: ... | keyword[def] identifier[get_possible_paths] ( identifier[base_path] , identifier[path_regex] ):
literal[string]
keyword[if] keyword[not] identifier[path_regex] :
keyword[return] []
keyword[if] identifier[len] ( identifier[path_regex] )< literal[int] :
keyword[return] []
key... | def get_possible_paths(base_path, path_regex):
"""
Looks for path_regex within base_path. Each match is append
in the returned list.
path_regex may contain subfolder structure.
If any part of the folder structure is a
:param base_path: str
:param path_regex: str
:return list of string... |
def from_verb(cls, verb):
"""
Constructs a :class:`Spoolverb` instance from the string
representation of the given verb.
Args:
verb (str): representation of the verb e.g.:
``'ASCRIBESPOOL01LOAN12/150526150528'``. Can also be in
binary format (... | def function[from_verb, parameter[cls, verb]]:
constant[
Constructs a :class:`Spoolverb` instance from the string
representation of the given verb.
Args:
verb (str): representation of the verb e.g.:
``'ASCRIBESPOOL01LOAN12/150526150528'``. Can also be in
... | keyword[def] identifier[from_verb] ( identifier[cls] , identifier[verb] ):
literal[string]
identifier[pattern] = literal[string]
keyword[try] :
identifier[verb] = identifier[verb] . identifier[decode] ()
keyword[except] identifier[AttributeError] :
keyw... | def from_verb(cls, verb):
"""
Constructs a :class:`Spoolverb` instance from the string
representation of the given verb.
Args:
verb (str): representation of the verb e.g.:
``'ASCRIBESPOOL01LOAN12/150526150528'``. Can also be in
binary format (:obj... |
def constructTotalCounts(self, logger):
'''
This function constructs the total count for each valid character in the array or loads them if they already exist.
These will always be stored in '<DIR>/totalCounts.p', a pickled file
'''
self.totalSize = self.bwt.shape[0]
... | def function[constructTotalCounts, parameter[self, logger]]:
constant[
This function constructs the total count for each valid character in the array or loads them if they already exist.
These will always be stored in '<DIR>/totalCounts.p', a pickled file
]
name[self].totalSize a... | keyword[def] identifier[constructTotalCounts] ( identifier[self] , identifier[logger] ):
literal[string]
identifier[self] . identifier[totalSize] = identifier[self] . identifier[bwt] . identifier[shape] [ literal[int] ]
identifier[abtFN] = identifier[self] . identifier[dirName] + literal[... | def constructTotalCounts(self, logger):
"""
This function constructs the total count for each valid character in the array or loads them if they already exist.
These will always be stored in '<DIR>/totalCounts.p', a pickled file
"""
self.totalSize = self.bwt.shape[0]
abtFN = self.dir... |
def weld_str_startswith(array, pat):
"""Check which elements start with pattern.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
pat : str
To check for.
Returns
-------
WeldObject
Representation of this computation.
"""
obj_id, wel... | def function[weld_str_startswith, parameter[array, pat]]:
constant[Check which elements start with pattern.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
pat : str
To check for.
Returns
-------
WeldObject
Representation of this comput... | keyword[def] identifier[weld_str_startswith] ( identifier[array] , identifier[pat] ):
literal[string]
identifier[obj_id] , identifier[weld_obj] = identifier[create_weld_object] ( identifier[array] )
identifier[pat_id] = identifier[get_weld_obj_id] ( identifier[weld_obj] , identifier[pat] )
liter... | def weld_str_startswith(array, pat):
"""Check which elements start with pattern.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
pat : str
To check for.
Returns
-------
WeldObject
Representation of this computation.
"""
(obj_id, we... |
def getChecks(self, **parameters):
"""Pulls all checks from pingdom
Optional Parameters:
* limit -- Limits the number of returned probes to the
specified quantity.
Type: Integer (max 25000)
Default: 25000
* offset -- Offs... | def function[getChecks, parameter[self]]:
constant[Pulls all checks from pingdom
Optional Parameters:
* limit -- Limits the number of returned probes to the
specified quantity.
Type: Integer (max 25000)
Default: 25000
* o... | keyword[def] identifier[getChecks] ( identifier[self] ,** identifier[parameters] ):
literal[string]
keyword[for] identifier[key] keyword[in] identifier[parameters] :
keyword[if] identifier[key] keyword[not] keyword[in] [ literal[string] , literal[string] , literal[strin... | def getChecks(self, **parameters):
"""Pulls all checks from pingdom
Optional Parameters:
* limit -- Limits the number of returned probes to the
specified quantity.
Type: Integer (max 25000)
Default: 25000
* offset -- Offset f... |
def _parse_doc(doc):
"""Parse a docstring.
Parse a docstring and extract three components; headline, description,
and map of arguments to help texts.
Args:
doc: docstring.
Returns:
a dictionary.
"""
lines = doc.split("\n")
descriptions = list(itertools.takewhile(_checker(_... | def function[_parse_doc, parameter[doc]]:
constant[Parse a docstring.
Parse a docstring and extract three components; headline, description,
and map of arguments to help texts.
Args:
doc: docstring.
Returns:
a dictionary.
]
variable[lines] assign[=] call[name[doc].spli... | keyword[def] identifier[_parse_doc] ( identifier[doc] ):
literal[string]
identifier[lines] = identifier[doc] . identifier[split] ( literal[string] )
identifier[descriptions] = identifier[list] ( identifier[itertools] . identifier[takewhile] ( identifier[_checker] ( identifier[_KEYWORDS] ), identifier[... | def _parse_doc(doc):
"""Parse a docstring.
Parse a docstring and extract three components; headline, description,
and map of arguments to help texts.
Args:
doc: docstring.
Returns:
a dictionary.
"""
lines = doc.split('\n')
descriptions = list(itertools.takewhile(_checker(_... |
def name_to_object(repo, name, return_ref=False):
"""
:return: object specified by the given name, hexshas ( short and long )
as well as references are supported
:param return_ref: if name specifies a reference, we will return the reference
instead of the object. Otherwise it will raise BadO... | def function[name_to_object, parameter[repo, name, return_ref]]:
constant[
:return: object specified by the given name, hexshas ( short and long )
as well as references are supported
:param return_ref: if name specifies a reference, we will return the reference
instead of the object. Oth... | keyword[def] identifier[name_to_object] ( identifier[repo] , identifier[name] , identifier[return_ref] = keyword[False] ):
literal[string]
identifier[hexsha] = keyword[None]
keyword[if] identifier[repo] . identifier[re_hexsha_shortened] . identifier[match] ( identifier[name] ):
keywor... | def name_to_object(repo, name, return_ref=False):
"""
:return: object specified by the given name, hexshas ( short and long )
as well as references are supported
:param return_ref: if name specifies a reference, we will return the reference
instead of the object. Otherwise it will raise BadO... |
def _unpack_storm_date(date):
'''
given a packed storm date field, unpack and return 'YYYY-MM-DD' string.
'''
year = (date & 0x7f) + 2000 # 7 bits
day = (date >> 7) & 0x01f # 5 bits
month = (date >> 12) & 0x0f # 4 bits
return "%s-%s-%s" % (year, month, day) | def function[_unpack_storm_date, parameter[date]]:
constant[
given a packed storm date field, unpack and return 'YYYY-MM-DD' string.
]
variable[year] assign[=] binary_operation[binary_operation[name[date] <ast.BitAnd object at 0x7da2590d6b60> constant[127]] + constant[2000]]
vari... | keyword[def] identifier[_unpack_storm_date] ( identifier[date] ):
literal[string]
identifier[year] =( identifier[date] & literal[int] )+ literal[int]
identifier[day] =( identifier[date] >> literal[int] )& literal[int]
identifier[month] =( identifier[date] >> literal[int] )& lite... | def _unpack_storm_date(date):
"""
given a packed storm date field, unpack and return 'YYYY-MM-DD' string.
"""
year = (date & 127) + 2000 # 7 bits
day = date >> 7 & 31 # 5 bits
month = date >> 12 & 15 # 4 bits
return '%s-%s-%s' % (year, month, day) |
def xarray_to_ndarray(data, *, var_names=None, combined=True):
"""Take xarray data and unpacks into variables and data into list and numpy array respectively.
Assumes that chain and draw are in coordinates
Parameters
----------
data: xarray.DataSet
Data in an xarray from an InferenceData o... | def function[xarray_to_ndarray, parameter[data]]:
constant[Take xarray data and unpacks into variables and data into list and numpy array respectively.
Assumes that chain and draw are in coordinates
Parameters
----------
data: xarray.DataSet
Data in an xarray from an InferenceData obje... | keyword[def] identifier[xarray_to_ndarray] ( identifier[data] ,*, identifier[var_names] = keyword[None] , identifier[combined] = keyword[True] ):
literal[string]
identifier[unpacked_data] , identifier[unpacked_var_names] ,=[],[]
keyword[for] identifier[var_name] , identifier[selection] , identi... | def xarray_to_ndarray(data, *, var_names=None, combined=True):
"""Take xarray data and unpacks into variables and data into list and numpy array respectively.
Assumes that chain and draw are in coordinates
Parameters
----------
data: xarray.DataSet
Data in an xarray from an InferenceData o... |
def clone(self) -> "Event":
"""
Clone the event
Returns:
:class:`slack.events.Event`
"""
return self.__class__(copy.deepcopy(self.event), copy.deepcopy(self.metadata)) | def function[clone, parameter[self]]:
constant[
Clone the event
Returns:
:class:`slack.events.Event`
]
return[call[name[self].__class__, parameter[call[name[copy].deepcopy, parameter[name[self].event]], call[name[copy].deepcopy, parameter[name[self].metadata]]]]] | keyword[def] identifier[clone] ( identifier[self] )-> literal[string] :
literal[string]
keyword[return] identifier[self] . identifier[__class__] ( identifier[copy] . identifier[deepcopy] ( identifier[self] . identifier[event] ), identifier[copy] . identifier[deepcopy] ( identifier[self] . identifi... | def clone(self) -> 'Event':
"""
Clone the event
Returns:
:class:`slack.events.Event`
"""
return self.__class__(copy.deepcopy(self.event), copy.deepcopy(self.metadata)) |
def response_from_prediction(self, y_pred, single=True):
"""Turns a model's prediction in *y_pred* into a JSON
response.
"""
result = y_pred.tolist()
if single:
result = result[0]
response = {
'metadata': get_metadata(),
'result': resul... | def function[response_from_prediction, parameter[self, y_pred, single]]:
constant[Turns a model's prediction in *y_pred* into a JSON
response.
]
variable[result] assign[=] call[name[y_pred].tolist, parameter[]]
if name[single] begin[:]
variable[result] assign[=] c... | keyword[def] identifier[response_from_prediction] ( identifier[self] , identifier[y_pred] , identifier[single] = keyword[True] ):
literal[string]
identifier[result] = identifier[y_pred] . identifier[tolist] ()
keyword[if] identifier[single] :
identifier[result] = identifier[r... | def response_from_prediction(self, y_pred, single=True):
"""Turns a model's prediction in *y_pred* into a JSON
response.
"""
result = y_pred.tolist()
if single:
result = result[0] # depends on [control=['if'], data=[]]
response = {'metadata': get_metadata(), 'result': result}
... |
def get_default_blocks(self, top=False):
"""
Return a list of column default block tuples (URL, verbose name).
Used for quick add block buttons.
"""
default_blocks = []
for block_model, block_name in self.glitter_page.default_blocks:
block = apps.get_model(b... | def function[get_default_blocks, parameter[self, top]]:
constant[
Return a list of column default block tuples (URL, verbose name).
Used for quick add block buttons.
]
variable[default_blocks] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b1123b50>, <ast.... | keyword[def] identifier[get_default_blocks] ( identifier[self] , identifier[top] = keyword[False] ):
literal[string]
identifier[default_blocks] =[]
keyword[for] identifier[block_model] , identifier[block_name] keyword[in] identifier[self] . identifier[glitter_page] . identifier[default... | def get_default_blocks(self, top=False):
"""
Return a list of column default block tuples (URL, verbose name).
Used for quick add block buttons.
"""
default_blocks = []
for (block_model, block_name) in self.glitter_page.default_blocks:
block = apps.get_model(block_model)
... |
def get_locale_choices(locale_dir):
"""
Get a list of locale file names in the given locale dir.
"""
#/
file_name_s = os.listdir(locale_dir)
#/
choice_s = []
for file_name in file_name_s:
if file_name.endswith(I18n.TT_FILE_EXT... | def function[get_locale_choices, parameter[locale_dir]]:
constant[
Get a list of locale file names in the given locale dir.
]
variable[file_name_s] assign[=] call[name[os].listdir, parameter[name[locale_dir]]]
variable[choice_s] assign[=] list[[]]
for taget[name[file_name... | keyword[def] identifier[get_locale_choices] ( identifier[locale_dir] ):
literal[string]
identifier[file_name_s] = identifier[os] . identifier[listdir] ( identifier[locale_dir] )
identifier[choice_s] =[]
keyword[for] identifier[file_name] keyword[in] identifi... | def get_locale_choices(locale_dir):
"""
Get a list of locale file names in the given locale dir.
"""
#/
file_name_s = os.listdir(locale_dir)
#/
choice_s = []
for file_name in file_name_s:
if file_name.endswith(I18n.TT_FILE_EXT_STXT):
(file_name_noext, _) = os.... |
def obfn_dfd(self):
r"""Compute data fidelity term :math:`(1/2) \sum_k \| W (\sum_m
\mathbf{d}_m * \mathbf{x}_{k,m} - \mathbf{s}_k) \|_2^2`
"""
Ef = self.eval_Rf(self.Xf)
E = sl.irfftn(Ef, self.cri.Nv, self.cri.axisN)
return (np.linalg.norm(self.W * E)**2) / 2.0 | def function[obfn_dfd, parameter[self]]:
constant[Compute data fidelity term :math:`(1/2) \sum_k \| W (\sum_m
\mathbf{d}_m * \mathbf{x}_{k,m} - \mathbf{s}_k) \|_2^2`
]
variable[Ef] assign[=] call[name[self].eval_Rf, parameter[name[self].Xf]]
variable[E] assign[=] call[name[sl].ir... | keyword[def] identifier[obfn_dfd] ( identifier[self] ):
literal[string]
identifier[Ef] = identifier[self] . identifier[eval_Rf] ( identifier[self] . identifier[Xf] )
identifier[E] = identifier[sl] . identifier[irfftn] ( identifier[Ef] , identifier[self] . identifier[cri] . identifier[Nv] ... | def obfn_dfd(self):
"""Compute data fidelity term :math:`(1/2) \\sum_k \\| W (\\sum_m
\\mathbf{d}_m * \\mathbf{x}_{k,m} - \\mathbf{s}_k) \\|_2^2`
"""
Ef = self.eval_Rf(self.Xf)
E = sl.irfftn(Ef, self.cri.Nv, self.cri.axisN)
return np.linalg.norm(self.W * E) ** 2 / 2.0 |
def get_locales(self):
"""Get a list of supported locales.
Computes the list using ``I18N_LANGUAGES`` configuration variable.
"""
if self._locales_cache is None:
langs = [self.babel.default_locale]
for l, dummy_title in current_app.config.get('I18N_LANGUAGES', []... | def function[get_locales, parameter[self]]:
constant[Get a list of supported locales.
Computes the list using ``I18N_LANGUAGES`` configuration variable.
]
if compare[name[self]._locales_cache is constant[None]] begin[:]
variable[langs] assign[=] list[[<ast.Attribute obje... | keyword[def] identifier[get_locales] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_locales_cache] keyword[is] keyword[None] :
identifier[langs] =[ identifier[self] . identifier[babel] . identifier[default_locale] ]
keyword[for] identi... | def get_locales(self):
"""Get a list of supported locales.
Computes the list using ``I18N_LANGUAGES`` configuration variable.
"""
if self._locales_cache is None:
langs = [self.babel.default_locale]
for (l, dummy_title) in current_app.config.get('I18N_LANGUAGES', []):
... |
def _advapi32_create_handles(cipher, key, iv):
"""
Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
HCRYPTPROV must be released by close_context_handle() and the
HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.
:param cipher:
A unicode string o... | def function[_advapi32_create_handles, parameter[cipher, key, iv]]:
constant[
Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
HCRYPTPROV must be released by close_context_handle() and the
HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.
:param cip... | keyword[def] identifier[_advapi32_create_handles] ( identifier[cipher] , identifier[key] , identifier[iv] ):
literal[string]
identifier[context_handle] = keyword[None]
keyword[if] identifier[cipher] == literal[string] :
identifier[algorithm_id] ={
literal[int] : identifier[Advapi... | def _advapi32_create_handles(cipher, key, iv):
"""
Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
HCRYPTPROV must be released by close_context_handle() and the
HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.
:param cipher:
A unicode string o... |
def containsPval(self, paramName, value):
"""Returns true if *value* for parameter type *paramName* is in the
auto parameters
:param paramName: the name of the auto-parameter to match, e.g. 'frequency'
:type paramName: str
:param value: the value of the parameter to search for
... | def function[containsPval, parameter[self, paramName, value]]:
constant[Returns true if *value* for parameter type *paramName* is in the
auto parameters
:param paramName: the name of the auto-parameter to match, e.g. 'frequency'
:type paramName: str
:param value: the value of t... | keyword[def] identifier[containsPval] ( identifier[self] , identifier[paramName] , identifier[value] ):
literal[string]
identifier[params] = identifier[self] . identifier[_autoParams] . identifier[allData] ()
identifier[steps] = identifier[self] . identifier[autoParamRang... | def containsPval(self, paramName, value):
"""Returns true if *value* for parameter type *paramName* is in the
auto parameters
:param paramName: the name of the auto-parameter to match, e.g. 'frequency'
:type paramName: str
:param value: the value of the parameter to search for
... |
def read(self, vals):
"""Read values.
Args:
vals (list): list of strings representing values
"""
i = 0
if len(vals[i]) == 0:
self.city = None
else:
self.city = vals[i]
i += 1
if len(vals[i]) == 0:
self.stat... | def function[read, parameter[self, vals]]:
constant[Read values.
Args:
vals (list): list of strings representing values
]
variable[i] assign[=] constant[0]
if compare[call[name[len], parameter[call[name[vals]][name[i]]]] equal[==] constant[0]] begin[:]
... | keyword[def] identifier[read] ( identifier[self] , identifier[vals] ):
literal[string]
identifier[i] = literal[int]
keyword[if] identifier[len] ( identifier[vals] [ identifier[i] ])== literal[int] :
identifier[self] . identifier[city] = keyword[None]
keyword[else] ... | def read(self, vals):
"""Read values.
Args:
vals (list): list of strings representing values
"""
i = 0
if len(vals[i]) == 0:
self.city = None # depends on [control=['if'], data=[]]
else:
self.city = vals[i]
i += 1
if len(vals[i]) == 0:
self.... |
def get_text(html_content, display_images=False, deduplicate_captions=False, display_links=False):
'''
::param: html_content
::returns:
a text representation of the html content.
'''
html_content = html_content.strip()
if not html_content:
return ""
# strip XML declaration, ... | def function[get_text, parameter[html_content, display_images, deduplicate_captions, display_links]]:
constant[
::param: html_content
::returns:
a text representation of the html content.
]
variable[html_content] assign[=] call[name[html_content].strip, parameter[]]
if <ast.U... | keyword[def] identifier[get_text] ( identifier[html_content] , identifier[display_images] = keyword[False] , identifier[deduplicate_captions] = keyword[False] , identifier[display_links] = keyword[False] ):
literal[string]
identifier[html_content] = identifier[html_content] . identifier[strip] ()
keyw... | def get_text(html_content, display_images=False, deduplicate_captions=False, display_links=False):
"""
::param: html_content
::returns:
a text representation of the html content.
"""
html_content = html_content.strip()
if not html_content:
return '' # depends on [control=['if'],... |
def get_banks_by_assessment_offered(self, assessment_offered_id):
"""Gets the list of ``Banks`` mapped to an ``AssessmentOffered``.
arg: assessment_offered_id (osid.id.Id): ``Id`` of an
``AssessmentOffered``
return: (osid.assessment.BankList) - list of banks
raise: N... | def function[get_banks_by_assessment_offered, parameter[self, assessment_offered_id]]:
constant[Gets the list of ``Banks`` mapped to an ``AssessmentOffered``.
arg: assessment_offered_id (osid.id.Id): ``Id`` of an
``AssessmentOffered``
return: (osid.assessment.BankList) - list... | keyword[def] identifier[get_banks_by_assessment_offered] ( identifier[self] , identifier[assessment_offered_id] ):
literal[string]
identifier[mgr] = identifier[self] . identifier[_get_provider_manager] ( literal[string] , identifier[local] = keyword[True] )
identifier[loo... | def get_banks_by_assessment_offered(self, assessment_offered_id):
"""Gets the list of ``Banks`` mapped to an ``AssessmentOffered``.
arg: assessment_offered_id (osid.id.Id): ``Id`` of an
``AssessmentOffered``
return: (osid.assessment.BankList) - list of banks
raise: NotFo... |
def set_pkg_licenses_concluded(self, doc, licenses):
"""Sets the package's concluded licenses.
licenses - License info.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined.
Raises SPDXValueError if data malformed.
"""
sel... | def function[set_pkg_licenses_concluded, parameter[self, doc, licenses]]:
constant[Sets the package's concluded licenses.
licenses - License info.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined.
Raises SPDXValueError if data malform... | keyword[def] identifier[set_pkg_licenses_concluded] ( identifier[self] , identifier[doc] , identifier[licenses] ):
literal[string]
identifier[self] . identifier[assert_package_exists] ()
keyword[if] keyword[not] identifier[self] . identifier[package_conc_lics_set] :
identifi... | def set_pkg_licenses_concluded(self, doc, licenses):
"""Sets the package's concluded licenses.
licenses - License info.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined.
Raises SPDXValueError if data malformed.
"""
self.assert... |
def add_arguments(cls, parser, sys_arg_list=None):
"""
Arguments for the ICMPecho health monitor plugin.
"""
parser.add_argument('--icmp_check_interval',
dest='icmp_check_interval',
required=False, default=2, type=float,
... | def function[add_arguments, parameter[cls, parser, sys_arg_list]]:
constant[
Arguments for the ICMPecho health monitor plugin.
]
call[name[parser].add_argument, parameter[constant[--icmp_check_interval]]]
return[list[[<ast.Constant object at 0x7da18dc9aa10>]]] | keyword[def] identifier[add_arguments] ( identifier[cls] , identifier[parser] , identifier[sys_arg_list] = keyword[None] ):
literal[string]
identifier[parser] . identifier[add_argument] ( literal[string] ,
identifier[dest] = literal[string] ,
identifier[required] = keyword[False] ... | def add_arguments(cls, parser, sys_arg_list=None):
"""
Arguments for the ICMPecho health monitor plugin.
"""
parser.add_argument('--icmp_check_interval', dest='icmp_check_interval', required=False, default=2, type=float, help="ICMPecho interval in seconds, default 2 (only for 'icmpecho' health ... |
def set_do_not_order_list(self, restricted_list, on_error='fail'):
"""Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : container[Asset], SecurityList
The assets that cannot be ordered.
"""
if isinstance(restricted_list... | def function[set_do_not_order_list, parameter[self, restricted_list, on_error]]:
constant[Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : container[Asset], SecurityList
The assets that cannot be ordered.
]
if call[nam... | keyword[def] identifier[set_do_not_order_list] ( identifier[self] , identifier[restricted_list] , identifier[on_error] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[restricted_list] , identifier[SecurityList] ):
identifier[warnings] . identifier[... | def set_do_not_order_list(self, restricted_list, on_error='fail'):
"""Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : container[Asset], SecurityList
The assets that cannot be ordered.
"""
if isinstance(restricted_list, Securi... |
def add_signature(key, inputs, outputs):
"""Adds a signature to current graph.
Args:
key: Signature key as a string.
inputs: Signature inputs as a map from string to Tensor or SparseTensor.
outputs: Signature outputs as a map from string to Tensor or SparseTensor.
(Recall that a Variable is not a... | def function[add_signature, parameter[key, inputs, outputs]]:
constant[Adds a signature to current graph.
Args:
key: Signature key as a string.
inputs: Signature inputs as a map from string to Tensor or SparseTensor.
outputs: Signature outputs as a map from string to Tensor or SparseTensor.
... | keyword[def] identifier[add_signature] ( identifier[key] , identifier[inputs] , identifier[outputs] ):
literal[string]
identifier[_check_dict_maps_to_tensors_or_sparse_tensors] ( identifier[inputs] )
identifier[_check_dict_maps_to_tensors_or_sparse_tensors] ( identifier[outputs] )
identifier[input_info] ... | def add_signature(key, inputs, outputs):
"""Adds a signature to current graph.
Args:
key: Signature key as a string.
inputs: Signature inputs as a map from string to Tensor or SparseTensor.
outputs: Signature outputs as a map from string to Tensor or SparseTensor.
(Recall that a Variable is not... |
def discard(self, element):
"""Remove an element. Do not raise an exception if absent."""
key = self._transform(element)
if key in self._elements:
del self._elements[key] | def function[discard, parameter[self, element]]:
constant[Remove an element. Do not raise an exception if absent.]
variable[key] assign[=] call[name[self]._transform, parameter[name[element]]]
if compare[name[key] in name[self]._elements] begin[:]
<ast.Delete object at 0x7da204564a90> | keyword[def] identifier[discard] ( identifier[self] , identifier[element] ):
literal[string]
identifier[key] = identifier[self] . identifier[_transform] ( identifier[element] )
keyword[if] identifier[key] keyword[in] identifier[self] . identifier[_elements] :
keyword[del] ... | def discard(self, element):
"""Remove an element. Do not raise an exception if absent."""
key = self._transform(element)
if key in self._elements:
del self._elements[key] # depends on [control=['if'], data=['key']] |
def element_should_contain_text(self, locator, expected, message=''):
"""Verifies element identified by ``locator`` contains text ``expected``.
If you wish to assert an exact (not a substring) match on the text
of the element, use `Element Text Should Be`.
Key attributes for arbi... | def function[element_should_contain_text, parameter[self, locator, expected, message]]:
constant[Verifies element identified by ``locator`` contains text ``expected``.
If you wish to assert an exact (not a substring) match on the text
of the element, use `Element Text Should Be`.
Key a... | keyword[def] identifier[element_should_contain_text] ( identifier[self] , identifier[locator] , identifier[expected] , identifier[message] = literal[string] ):
literal[string]
identifier[self] . identifier[_info] ( literal[string]
%( identifier[locator] , identifier[expected] ))
... | def element_should_contain_text(self, locator, expected, message=''):
"""Verifies element identified by ``locator`` contains text ``expected``.
If you wish to assert an exact (not a substring) match on the text
of the element, use `Element Text Should Be`.
Key attributes for arbitrary elem... |
def check_str_length(str_to_check, limit=MAX_LENGTH):
"""Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns: The string it self... | def function[check_str_length, parameter[str_to_check, limit]]:
constant[Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns... | keyword[def] identifier[check_str_length] ( identifier[str_to_check] , identifier[limit] = identifier[MAX_LENGTH] ):
literal[string]
identifier[str_bytes] = identifier[str_to_check] . identifier[encode] ( identifier[UTF8] )
identifier[str_len] = identifier[len] ( identifier[str_bytes] )
identifie... | def check_str_length(str_to_check, limit=MAX_LENGTH):
"""Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns: The string it self... |
def fuzzer(buffer, fuzz_factor=101):
"""Fuzz given buffer.
Take a buffer of bytes, create a copy, and replace some bytes
with random values. Number of bytes to modify depends on fuzz_factor.
This code is taken from Charlie Miller's fuzzer code.
:param buffer: the data to fuzz.
:type buffer: by... | def function[fuzzer, parameter[buffer, fuzz_factor]]:
constant[Fuzz given buffer.
Take a buffer of bytes, create a copy, and replace some bytes
with random values. Number of bytes to modify depends on fuzz_factor.
This code is taken from Charlie Miller's fuzzer code.
:param buffer: the data to... | keyword[def] identifier[fuzzer] ( identifier[buffer] , identifier[fuzz_factor] = literal[int] ):
literal[string]
identifier[buf] = identifier[deepcopy] ( identifier[buffer] )
identifier[num_writes] = identifier[number_of_bytes_to_modify] ( identifier[len] ( identifier[buf] ), identifier[fuzz_factor] )... | def fuzzer(buffer, fuzz_factor=101):
"""Fuzz given buffer.
Take a buffer of bytes, create a copy, and replace some bytes
with random values. Number of bytes to modify depends on fuzz_factor.
This code is taken from Charlie Miller's fuzzer code.
:param buffer: the data to fuzz.
:type buffer: by... |
def get_direction(self, direction, rev=False):
"""
Translate a direction in compass degrees into 'up' or 'down'.
"""
if (direction < 90.0) or (direction >= 270.0):
if not rev:
return 'up'
else:
return 'down'
elif (90.0 <= di... | def function[get_direction, parameter[self, direction, rev]]:
constant[
Translate a direction in compass degrees into 'up' or 'down'.
]
if <ast.BoolOp object at 0x7da1b0c24d90> begin[:]
if <ast.UnaryOp object at 0x7da1b0c271f0> begin[:]
return[constant[up]] | keyword[def] identifier[get_direction] ( identifier[self] , identifier[direction] , identifier[rev] = keyword[False] ):
literal[string]
keyword[if] ( identifier[direction] < literal[int] ) keyword[or] ( identifier[direction] >= literal[int] ):
keyword[if] keyword[not] identifier[rev]... | def get_direction(self, direction, rev=False):
"""
Translate a direction in compass degrees into 'up' or 'down'.
"""
if direction < 90.0 or direction >= 270.0:
if not rev:
return 'up' # depends on [control=['if'], data=[]]
else:
return 'down' # depends o... |
def alternator(*pipes):
''' a lot like zip, just instead of:
(a,b),(a,b),(a,b)
it works more like:
a,b,a,b,a,b,a
until one of the pipes ends '''
try:
for p in cycle(map(iter, pipes)):
yield next(p)
except StopIteration:
pass | def function[alternator, parameter[]]:
constant[ a lot like zip, just instead of:
(a,b),(a,b),(a,b)
it works more like:
a,b,a,b,a,b,a
until one of the pipes ends ]
<ast.Try object at 0x7da20c7966b0> | keyword[def] identifier[alternator] (* identifier[pipes] ):
literal[string]
keyword[try] :
keyword[for] identifier[p] keyword[in] identifier[cycle] ( identifier[map] ( identifier[iter] , identifier[pipes] )):
keyword[yield] identifier[next] ( identifier[p] )
keyword[except] ... | def alternator(*pipes):
""" a lot like zip, just instead of:
(a,b),(a,b),(a,b)
it works more like:
a,b,a,b,a,b,a
until one of the pipes ends """
try:
for p in cycle(map(iter, pipes)):
yield next(p) # depends on [control=['for'], data=['p']] # depends... |
def omg(args):
"""
%prog omg weightsfile
Run Sankoff's OMG algorithm to get orthologs. Download OMG code at:
<http://137.122.149.195/IsbraSoftware/OMGMec.html>
This script only writes the partitions, but not launch OMGMec. You may need to:
$ parallel "java -cp ~/code/OMGMec TestOMGMec {} 4 > ... | def function[omg, parameter[args]]:
constant[
%prog omg weightsfile
Run Sankoff's OMG algorithm to get orthologs. Download OMG code at:
<http://137.122.149.195/IsbraSoftware/OMGMec.html>
This script only writes the partitions, but not launch OMGMec. You may need to:
$ parallel "java -cp ~... | keyword[def] identifier[omg] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[omg] . identifier[__doc__] )
identifier[opts] , identifier[args] = identifier[p] . identifier[parse_args] ( identifier[args] )
keyword[if] identifier[len] ( identifier[args]... | def omg(args):
"""
%prog omg weightsfile
Run Sankoff's OMG algorithm to get orthologs. Download OMG code at:
<http://137.122.149.195/IsbraSoftware/OMGMec.html>
This script only writes the partitions, but not launch OMGMec. You may need to:
$ parallel "java -cp ~/code/OMGMec TestOMGMec {} 4 > ... |
def popup(self, title, callfn, initialdir=None):
"""Let user select a directory."""
super(DirectorySelection, self).popup(title, callfn, initialdir) | def function[popup, parameter[self, title, callfn, initialdir]]:
constant[Let user select a directory.]
call[call[name[super], parameter[name[DirectorySelection], name[self]]].popup, parameter[name[title], name[callfn], name[initialdir]]] | keyword[def] identifier[popup] ( identifier[self] , identifier[title] , identifier[callfn] , identifier[initialdir] = keyword[None] ):
literal[string]
identifier[super] ( identifier[DirectorySelection] , identifier[self] ). identifier[popup] ( identifier[title] , identifier[callfn] , identifier[ini... | def popup(self, title, callfn, initialdir=None):
"""Let user select a directory."""
super(DirectorySelection, self).popup(title, callfn, initialdir) |
def emit_nicknames(self):
"""
Send the nickname list to the Websocket. Called whenever the
nicknames list changes.
"""
nicknames = [{"nickname": name, "color": color(name)}
for name in sorted(self.nicknames.keys())]
self.namespace.emit("nicknames", ni... | def function[emit_nicknames, parameter[self]]:
constant[
Send the nickname list to the Websocket. Called whenever the
nicknames list changes.
]
variable[nicknames] assign[=] <ast.ListComp object at 0x7da1b0fe4370>
call[name[self].namespace.emit, parameter[constant[nicknam... | keyword[def] identifier[emit_nicknames] ( identifier[self] ):
literal[string]
identifier[nicknames] =[{ literal[string] : identifier[name] , literal[string] : identifier[color] ( identifier[name] )}
keyword[for] identifier[name] keyword[in] identifier[sorted] ( identifier[self] . identi... | def emit_nicknames(self):
"""
Send the nickname list to the Websocket. Called whenever the
nicknames list changes.
"""
nicknames = [{'nickname': name, 'color': color(name)} for name in sorted(self.nicknames.keys())]
self.namespace.emit('nicknames', nicknames) |
def _login(self, username, password, client_id, client_secret):
"""Performs login with the provided credentials"""
url = self.api_url + self.auth_token_url
auth_string = '%s:%s' % (client_id, client_secret)
authorization = base64.b64encode(auth_string.encode()).decode()
headers =... | def function[_login, parameter[self, username, password, client_id, client_secret]]:
constant[Performs login with the provided credentials]
variable[url] assign[=] binary_operation[name[self].api_url + name[self].auth_token_url]
variable[auth_string] assign[=] binary_operation[constant[%s:%s] <a... | keyword[def] identifier[_login] ( identifier[self] , identifier[username] , identifier[password] , identifier[client_id] , identifier[client_secret] ):
literal[string]
identifier[url] = identifier[self] . identifier[api_url] + identifier[self] . identifier[auth_token_url]
identifier[auth_... | def _login(self, username, password, client_id, client_secret):
"""Performs login with the provided credentials"""
url = self.api_url + self.auth_token_url
auth_string = '%s:%s' % (client_id, client_secret)
authorization = base64.b64encode(auth_string.encode()).decode()
headers = {'Authorization': '... |
def _request_sender(self, packet: dict):
"""
Sends a request to a server from a ServiceClient
auto dispatch method called from self.send()
"""
node_id = self._get_node_id_for_packet(packet)
client_protocol = self._client_protocols.get(node_id)
if node_id and clie... | def function[_request_sender, parameter[self, packet]]:
constant[
Sends a request to a server from a ServiceClient
auto dispatch method called from self.send()
]
variable[node_id] assign[=] call[name[self]._get_node_id_for_packet, parameter[name[packet]]]
variable[client_... | keyword[def] identifier[_request_sender] ( identifier[self] , identifier[packet] : identifier[dict] ):
literal[string]
identifier[node_id] = identifier[self] . identifier[_get_node_id_for_packet] ( identifier[packet] )
identifier[client_protocol] = identifier[self] . identifier[_client_pro... | def _request_sender(self, packet: dict):
"""
Sends a request to a server from a ServiceClient
auto dispatch method called from self.send()
"""
node_id = self._get_node_id_for_packet(packet)
client_protocol = self._client_protocols.get(node_id)
if node_id and client_protocol:
... |
def env(ctx, *args, **kwargs):
"""
print debug info about running environment
"""
import sys, platform, os, shutil
from pkg_resources import get_distribution, working_set
print("\n##################\n")
print("Information about the running environment of brother_ql.")
print("(Please prov... | def function[env, parameter[ctx]]:
constant[
print debug info about running environment
]
import module[sys], module[platform], module[os], module[shutil]
from relative_module[pkg_resources] import module[get_distribution], module[working_set]
call[name[print], parameter[constant[
######... | keyword[def] identifier[env] ( identifier[ctx] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[sys] , identifier[platform] , identifier[os] , identifier[shutil]
keyword[from] identifier[pkg_resources] keyword[import] identifier[get_distribution] , identifi... | def env(ctx, *args, **kwargs):
"""
print debug info about running environment
"""
import sys, platform, os, shutil
from pkg_resources import get_distribution, working_set
print('\n##################\n')
print('Information about the running environment of brother_ql.')
print('(Please prov... |
def get_host_binds(container_map, config_name, config, instance, policy, named_volumes):
"""
Generates the list of host volumes and named volumes (where applicable) for the host config ``bind`` argument
during container creation.
:param container_map: Container map.
:type container_map: dockermap.m... | def function[get_host_binds, parameter[container_map, config_name, config, instance, policy, named_volumes]]:
constant[
Generates the list of host volumes and named volumes (where applicable) for the host config ``bind`` argument
during container creation.
:param container_map: Container map.
:... | keyword[def] identifier[get_host_binds] ( identifier[container_map] , identifier[config_name] , identifier[config] , identifier[instance] , identifier[policy] , identifier[named_volumes] ):
literal[string]
keyword[def] identifier[volume_str] ( identifier[paths] , identifier[readonly] ):
keyword[r... | def get_host_binds(container_map, config_name, config, instance, policy, named_volumes):
"""
Generates the list of host volumes and named volumes (where applicable) for the host config ``bind`` argument
during container creation.
:param container_map: Container map.
:type container_map: dockermap.m... |
def assign_parser(self, name):
'''
Restricts parsing
**name** is a name of the parser class
NB: this is the PUBLIC method
@procedure
'''
for n, p in list(self.Parsers.items()):
if n != name:
del self.Parsers[n]
if len(self.Parse... | def function[assign_parser, parameter[self, name]]:
constant[
Restricts parsing
**name** is a name of the parser class
NB: this is the PUBLIC method
@procedure
]
for taget[tuple[[<ast.Name object at 0x7da18f7206a0>, <ast.Name object at 0x7da18f720a60>]]] in starre... | keyword[def] identifier[assign_parser] ( identifier[self] , identifier[name] ):
literal[string]
keyword[for] identifier[n] , identifier[p] keyword[in] identifier[list] ( identifier[self] . identifier[Parsers] . identifier[items] ()):
keyword[if] identifier[n] != identifier[name] :
... | def assign_parser(self, name):
"""
Restricts parsing
**name** is a name of the parser class
NB: this is the PUBLIC method
@procedure
"""
for (n, p) in list(self.Parsers.items()):
if n != name:
del self.Parsers[n] # depends on [control=['if'], data=['n... |
def xpath(self, *args, **kwargs):
""" Perform XPath on the passage XML
:param args: Ordered arguments for etree._Element().xpath()
:param kwargs: Named arguments
:return: Result list
:rtype: list(etree._Element)
"""
if "smart_strings" not in kwargs:
k... | def function[xpath, parameter[self]]:
constant[ Perform XPath on the passage XML
:param args: Ordered arguments for etree._Element().xpath()
:param kwargs: Named arguments
:return: Result list
:rtype: list(etree._Element)
]
if compare[constant[smart_strings] <ast... | keyword[def] identifier[xpath] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] :
identifier[kwargs] [ literal[string] ]= keyword[False]
keyword[return] identifier[sel... | def xpath(self, *args, **kwargs):
""" Perform XPath on the passage XML
:param args: Ordered arguments for etree._Element().xpath()
:param kwargs: Named arguments
:return: Result list
:rtype: list(etree._Element)
"""
if 'smart_strings' not in kwargs:
kwargs['smart... |
def nl_cb_call(cb, type_, msg):
"""Call a callback function.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink-private/netlink.h#L136
Positional arguments:
cb -- nl_cb class instance.
type_ -- callback type integer (e.g. NL_CB_MSG_OUT).
msg -- Netlink message (nl_msg class inst... | def function[nl_cb_call, parameter[cb, type_, msg]]:
constant[Call a callback function.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink-private/netlink.h#L136
Positional arguments:
cb -- nl_cb class instance.
type_ -- callback type integer (e.g. NL_CB_MSG_OUT).
msg -- Net... | keyword[def] identifier[nl_cb_call] ( identifier[cb] , identifier[type_] , identifier[msg] ):
literal[string]
identifier[cb] . identifier[cb_active] = identifier[type_]
identifier[ret] = identifier[cb] . identifier[cb_set] [ identifier[type_] ]( identifier[msg] , identifier[cb] . identifier[cb_args] ... | def nl_cb_call(cb, type_, msg):
"""Call a callback function.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink-private/netlink.h#L136
Positional arguments:
cb -- nl_cb class instance.
type_ -- callback type integer (e.g. NL_CB_MSG_OUT).
msg -- Netlink message (nl_msg class inst... |
def to_export(export):
"""Serializes export to id string
:param export: object to serialize
:return: string id
"""
from sevenbridges.models.storage_export import Export
if not export:
raise SbgError('Export is required!')
elif isinstance(export, Export... | def function[to_export, parameter[export]]:
constant[Serializes export to id string
:param export: object to serialize
:return: string id
]
from relative_module[sevenbridges.models.storage_export] import module[Export]
if <ast.UnaryOp object at 0x7da2041d8400> begin[:]
... | keyword[def] identifier[to_export] ( identifier[export] ):
literal[string]
keyword[from] identifier[sevenbridges] . identifier[models] . identifier[storage_export] keyword[import] identifier[Export]
keyword[if] keyword[not] identifier[export] :
keyword[raise] identifier... | def to_export(export):
"""Serializes export to id string
:param export: object to serialize
:return: string id
"""
from sevenbridges.models.storage_export import Export
if not export:
raise SbgError('Export is required!') # depends on [control=['if'], data=[]]
elif isins... |
def dump_header(iterable, allow_token=True):
"""Dump an HTTP header again. This is the reversal of
:func:`parse_list_header`, :func:`parse_set_header` and
:func:`parse_dict_header`. This also quotes strings that include an
equals sign unless you pass it as dict of key, value pairs.
>>> dump_heade... | def function[dump_header, parameter[iterable, allow_token]]:
constant[Dump an HTTP header again. This is the reversal of
:func:`parse_list_header`, :func:`parse_set_header` and
:func:`parse_dict_header`. This also quotes strings that include an
equals sign unless you pass it as dict of key, value ... | keyword[def] identifier[dump_header] ( identifier[iterable] , identifier[allow_token] = keyword[True] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[iterable] , identifier[dict] ):
identifier[items] =[]
keyword[for] identifier[key] , identifier[value] keyword[in] i... | def dump_header(iterable, allow_token=True):
"""Dump an HTTP header again. This is the reversal of
:func:`parse_list_header`, :func:`parse_set_header` and
:func:`parse_dict_header`. This also quotes strings that include an
equals sign unless you pass it as dict of key, value pairs.
>>> dump_heade... |
def zdivide(a, b, null=0):
'''
zdivide(a, b) returns the quotient a / b as a numpy array object. Unlike numpy's divide function
or a/b syntax, zdivide will thread over the earliest dimension possible; thus if a.shape is
(4,2) and b.shape is 4, zdivide(a,b) is a equivalent to [ai*zinv(bi) for (ai,bi)... | def function[zdivide, parameter[a, b, null]]:
constant[
zdivide(a, b) returns the quotient a / b as a numpy array object. Unlike numpy's divide function
or a/b syntax, zdivide will thread over the earliest dimension possible; thus if a.shape is
(4,2) and b.shape is 4, zdivide(a,b) is a equivalen... | keyword[def] identifier[zdivide] ( identifier[a] , identifier[b] , identifier[null] = literal[int] ):
literal[string]
( identifier[a] , identifier[b] )= identifier[unbroadcast] ( identifier[a] , identifier[b] )
keyword[return] identifier[czdivide] ( identifier[a] , identifier[b] , identifier[null] = i... | def zdivide(a, b, null=0):
"""
zdivide(a, b) returns the quotient a / b as a numpy array object. Unlike numpy's divide function
or a/b syntax, zdivide will thread over the earliest dimension possible; thus if a.shape is
(4,2) and b.shape is 4, zdivide(a,b) is a equivalent to [ai*zinv(bi) for (ai,bi)... |
def move_safe(origin, target):
"""
Move file, skip if exists
"""
if origin == target:
return origin
if file_exists(target):
return target
shutil.move(origin, target)
return target | def function[move_safe, parameter[origin, target]]:
constant[
Move file, skip if exists
]
if compare[name[origin] equal[==] name[target]] begin[:]
return[name[origin]]
if call[name[file_exists], parameter[name[target]]] begin[:]
return[name[target]]
call[name[shut... | keyword[def] identifier[move_safe] ( identifier[origin] , identifier[target] ):
literal[string]
keyword[if] identifier[origin] == identifier[target] :
keyword[return] identifier[origin]
keyword[if] identifier[file_exists] ( identifier[target] ):
keyword[return] identifier[target... | def move_safe(origin, target):
"""
Move file, skip if exists
"""
if origin == target:
return origin # depends on [control=['if'], data=['origin']]
if file_exists(target):
return target # depends on [control=['if'], data=[]]
shutil.move(origin, target)
return target |
async def get_version(self, timeout: int = 15) -> Optional[str]:
"""Execute FFmpeg process and parse the version information.
Return full FFmpeg version string. Such as 3.4.2-tessus
"""
command = ["-version"]
# open input for capture 1 frame
is_open = await self.open(cm... | <ast.AsyncFunctionDef object at 0x7da1b04d5ed0> | keyword[async] keyword[def] identifier[get_version] ( identifier[self] , identifier[timeout] : identifier[int] = literal[int] )-> identifier[Optional] [ identifier[str] ]:
literal[string]
identifier[command] =[ literal[string] ]
identifier[is_open] = keyword[await] identifier[s... | async def get_version(self, timeout: int=15) -> Optional[str]:
"""Execute FFmpeg process and parse the version information.
Return full FFmpeg version string. Such as 3.4.2-tessus
"""
command = ['-version']
# open input for capture 1 frame
is_open = await self.open(cmd=command, input_so... |
def rfc3339(self):
"""Return an RFC 3339-compliant timestamp.
Returns:
(str): Timestamp string according to RFC 3339 spec.
"""
if self._nanosecond == 0:
return to_rfc3339(self)
nanos = str(self._nanosecond).rjust(9, '0').rstrip("0")
return "{}.{}Z... | def function[rfc3339, parameter[self]]:
constant[Return an RFC 3339-compliant timestamp.
Returns:
(str): Timestamp string according to RFC 3339 spec.
]
if compare[name[self]._nanosecond equal[==] constant[0]] begin[:]
return[call[name[to_rfc3339], parameter[name[self... | keyword[def] identifier[rfc3339] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_nanosecond] == literal[int] :
keyword[return] identifier[to_rfc3339] ( identifier[self] )
identifier[nanos] = identifier[str] ( identifier[self] . identifier[_na... | def rfc3339(self):
"""Return an RFC 3339-compliant timestamp.
Returns:
(str): Timestamp string according to RFC 3339 spec.
"""
if self._nanosecond == 0:
return to_rfc3339(self) # depends on [control=['if'], data=[]]
nanos = str(self._nanosecond).rjust(9, '0').rstrip('0'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.