code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def set_baseline(self, version):
"""Set the baseline into the creation information table
version: str
The version of the current database to set in the information
table. The baseline must be in the format x.x.x where x are numbers.
"""
pattern = re.compile(r"^\d... | def function[set_baseline, parameter[self, version]]:
constant[Set the baseline into the creation information table
version: str
The version of the current database to set in the information
table. The baseline must be in the format x.x.x where x are numbers.
]
v... | keyword[def] identifier[set_baseline] ( identifier[self] , identifier[version] ):
literal[string]
identifier[pattern] = identifier[re] . identifier[compile] ( literal[string] )
keyword[if] keyword[not] identifier[re] . identifier[match] ( identifier[pattern] , identifier[version] ):
... | def set_baseline(self, version):
"""Set the baseline into the creation information table
version: str
The version of the current database to set in the information
table. The baseline must be in the format x.x.x where x are numbers.
"""
pattern = re.compile('^\\d+\\.\\d+... |
def _get_join_indexers(self):
""" return the join indexers """
return _get_join_indexers(self.left_join_keys,
self.right_join_keys,
sort=self.sort,
how=self.how) | def function[_get_join_indexers, parameter[self]]:
constant[ return the join indexers ]
return[call[name[_get_join_indexers], parameter[name[self].left_join_keys, name[self].right_join_keys]]] | keyword[def] identifier[_get_join_indexers] ( identifier[self] ):
literal[string]
keyword[return] identifier[_get_join_indexers] ( identifier[self] . identifier[left_join_keys] ,
identifier[self] . identifier[right_join_keys] ,
identifier[sort] = identifier[self] . identifier[sor... | def _get_join_indexers(self):
""" return the join indexers """
return _get_join_indexers(self.left_join_keys, self.right_join_keys, sort=self.sort, how=self.how) |
def load_pa11y_ignore_rules(file=None, url=None): # pylint: disable=redefined-builtin
"""
Load the pa11y ignore rules from the given file or URL.
"""
if not file and not url:
return None
if file:
file = Path(file)
if not file.isfile():
msg = (
u"... | def function[load_pa11y_ignore_rules, parameter[file, url]]:
constant[
Load the pa11y ignore rules from the given file or URL.
]
if <ast.BoolOp object at 0x7da20c6aa5c0> begin[:]
return[constant[None]]
if name[file] begin[:]
variable[file] assign[=] call[name[Path... | keyword[def] identifier[load_pa11y_ignore_rules] ( identifier[file] = keyword[None] , identifier[url] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[file] keyword[and] keyword[not] identifier[url] :
keyword[return] keyword[None]
keyword[if] identifier[file] :
... | def load_pa11y_ignore_rules(file=None, url=None): # pylint: disable=redefined-builtin
'\n Load the pa11y ignore rules from the given file or URL.\n '
if not file and (not url):
return None # depends on [control=['if'], data=[]]
if file:
file = Path(file)
if not file.isfile():... |
def transformer_tpu_range(rhp):
"""Small range of hyperparameters."""
# After starting from base, set intervals for some parameters.
rhp.set_float("learning_rate", 0.3, 3.0, scale=rhp.LOG_SCALE)
rhp.set_discrete("learning_rate_warmup_steps",
[1000, 2000, 4000, 8000, 16000])
rhp.set_float("i... | def function[transformer_tpu_range, parameter[rhp]]:
constant[Small range of hyperparameters.]
call[name[rhp].set_float, parameter[constant[learning_rate], constant[0.3], constant[3.0]]]
call[name[rhp].set_discrete, parameter[constant[learning_rate_warmup_steps], list[[<ast.Constant object at 0x... | keyword[def] identifier[transformer_tpu_range] ( identifier[rhp] ):
literal[string]
identifier[rhp] . identifier[set_float] ( literal[string] , literal[int] , literal[int] , identifier[scale] = identifier[rhp] . identifier[LOG_SCALE] )
identifier[rhp] . identifier[set_discrete] ( literal[string] ,
[ li... | def transformer_tpu_range(rhp):
"""Small range of hyperparameters."""
# After starting from base, set intervals for some parameters.
rhp.set_float('learning_rate', 0.3, 3.0, scale=rhp.LOG_SCALE)
rhp.set_discrete('learning_rate_warmup_steps', [1000, 2000, 4000, 8000, 16000])
rhp.set_float('initialize... |
def execute_edit(args, root_dir=None):
"""Edit a existing queue command in the daemon.
Args:
args['key'] int: The key of the queue entry to be edited
root_dir (string): The path to the root directory the daemon is running in.
"""
# Get editor
EDITOR = os.environ.get('EDITOR', 'vim')... | def function[execute_edit, parameter[args, root_dir]]:
constant[Edit a existing queue command in the daemon.
Args:
args['key'] int: The key of the queue entry to be edited
root_dir (string): The path to the root directory the daemon is running in.
]
variable[EDITOR] assign[=] ca... | keyword[def] identifier[execute_edit] ( identifier[args] , identifier[root_dir] = keyword[None] ):
literal[string]
identifier[EDITOR] = identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] )
identifier[key] = identifier[args] [ literal[string] ]
ide... | def execute_edit(args, root_dir=None):
"""Edit a existing queue command in the daemon.
Args:
args['key'] int: The key of the queue entry to be edited
root_dir (string): The path to the root directory the daemon is running in.
"""
# Get editor
EDITOR = os.environ.get('EDITOR', 'vim')... |
def get_string(ea):
"""Read the string at the given ea.
This function uses IDA's string APIs and does not implement any special logic.
"""
# We get the item-head because the `GetStringType` function only works on the head of an item.
string_type = idc.GetStringType(idaapi.get_item_head(ea))
if... | def function[get_string, parameter[ea]]:
constant[Read the string at the given ea.
This function uses IDA's string APIs and does not implement any special logic.
]
variable[string_type] assign[=] call[name[idc].GetStringType, parameter[call[name[idaapi].get_item_head, parameter[name[ea]]]]]
... | keyword[def] identifier[get_string] ( identifier[ea] ):
literal[string]
identifier[string_type] = identifier[idc] . identifier[GetStringType] ( identifier[idaapi] . identifier[get_item_head] ( identifier[ea] ))
keyword[if] identifier[string_type] keyword[is] keyword[None] :
keyword[r... | def get_string(ea):
"""Read the string at the given ea.
This function uses IDA's string APIs and does not implement any special logic.
"""
# We get the item-head because the `GetStringType` function only works on the head of an item.
string_type = idc.GetStringType(idaapi.get_item_head(ea))
if ... |
def register_exception(self, task, raised_exception, exception_details, event_details=None):
""" :meth:`.WSimpleTrackerStorage.register_exception` method implementation
"""
if self.record_exception() is True:
record = WSimpleTrackerStorage.ExceptionRecord(
task, raised_exception, exception_details, event_d... | def function[register_exception, parameter[self, task, raised_exception, exception_details, event_details]]:
constant[ :meth:`.WSimpleTrackerStorage.register_exception` method implementation
]
if compare[call[name[self].record_exception, parameter[]] is constant[True]] begin[:]
variabl... | keyword[def] identifier[register_exception] ( identifier[self] , identifier[task] , identifier[raised_exception] , identifier[exception_details] , identifier[event_details] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[record_exception] () keyword[is] keyword[True] :
identi... | def register_exception(self, task, raised_exception, exception_details, event_details=None):
""" :meth:`.WSimpleTrackerStorage.register_exception` method implementation
"""
if self.record_exception() is True:
record = WSimpleTrackerStorage.ExceptionRecord(task, raised_exception, exception_details, eve... |
def draw_sample(num_samples, num_classes, logits, num_trials, dtype, seed):
"""Sample a multinomial.
The batch shape is given by broadcasting num_trials with
remove_last_dimension(logits).
Args:
num_samples: Python int or singleton integer Tensor: number of multinomial
samples to draw.
num_class... | def function[draw_sample, parameter[num_samples, num_classes, logits, num_trials, dtype, seed]]:
constant[Sample a multinomial.
The batch shape is given by broadcasting num_trials with
remove_last_dimension(logits).
Args:
num_samples: Python int or singleton integer Tensor: number of multinomial
... | keyword[def] identifier[draw_sample] ( identifier[num_samples] , identifier[num_classes] , identifier[logits] , identifier[num_trials] , identifier[dtype] , identifier[seed] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
identifier[num_trials] = identifie... | def draw_sample(num_samples, num_classes, logits, num_trials, dtype, seed):
"""Sample a multinomial.
The batch shape is given by broadcasting num_trials with
remove_last_dimension(logits).
Args:
num_samples: Python int or singleton integer Tensor: number of multinomial
samples to draw.
num_cla... |
def get_data(self, cache=True, as_text=False, parse_form_data=False):
"""This reads the buffered incoming data from the client into one
bytestring. By default this is cached but that behavior can be
changed by setting `cache` to `False`.
Usually it's a bad idea to call this method with... | def function[get_data, parameter[self, cache, as_text, parse_form_data]]:
constant[This reads the buffered incoming data from the client into one
bytestring. By default this is cached but that behavior can be
changed by setting `cache` to `False`.
Usually it's a bad idea to call this m... | keyword[def] identifier[get_data] ( identifier[self] , identifier[cache] = keyword[True] , identifier[as_text] = keyword[False] , identifier[parse_form_data] = keyword[False] ):
literal[string]
identifier[rv] = identifier[getattr] ( identifier[self] , literal[string] , keyword[None] )
keyw... | def get_data(self, cache=True, as_text=False, parse_form_data=False):
"""This reads the buffered incoming data from the client into one
bytestring. By default this is cached but that behavior can be
changed by setting `cache` to `False`.
Usually it's a bad idea to call this method without ... |
def extract_angular(fileobj, keywords, comment_tags, options):
"""Extract messages from angular template (HTML) files that use the
angular-gettext translate directive as per
https://angular-gettext.rocketeer.be/ .
:param fileobj: the file-like object the messages should be extracted
... | def function[extract_angular, parameter[fileobj, keywords, comment_tags, options]]:
constant[Extract messages from angular template (HTML) files that use the
angular-gettext translate directive as per
https://angular-gettext.rocketeer.be/ .
:param fileobj: the file-like object the messages should b... | keyword[def] identifier[extract_angular] ( identifier[fileobj] , identifier[keywords] , identifier[comment_tags] , identifier[options] ):
literal[string]
keyword[if] identifier[keywords] :
identifier[logging] . identifier[debug] ( literal[string] )
keyword[if] identifier[comment_tags] :
... | def extract_angular(fileobj, keywords, comment_tags, options):
"""Extract messages from angular template (HTML) files that use the
angular-gettext translate directive as per
https://angular-gettext.rocketeer.be/ .
:param fileobj: the file-like object the messages should be extracted
... |
def apps(self):
"""
Dictionary with loaded applications.
"""
logger.debug("initialize applications ...")
enabled = None
apps = self.args.apps or self._config_apps.keys()
unknown = set(apps) - set(self._config_apps.keys())
if unknown:
raise LogR... | def function[apps, parameter[self]]:
constant[
Dictionary with loaded applications.
]
call[name[logger].debug, parameter[constant[initialize applications ...]]]
variable[enabled] assign[=] constant[None]
variable[apps] assign[=] <ast.BoolOp object at 0x7da20c6a9ba0>
... | keyword[def] identifier[apps] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[enabled] = keyword[None]
identifier[apps] = identifier[self] . identifier[args] . identifier[apps] keyword[or] identifier[self] . identifier... | def apps(self):
"""
Dictionary with loaded applications.
"""
logger.debug('initialize applications ...')
enabled = None
apps = self.args.apps or self._config_apps.keys()
unknown = set(apps) - set(self._config_apps.keys())
if unknown:
raise LogRaptorArgumentError('--apps',... |
def cmd_fw_manifest_purge(self):
'''remove all downloaded manifests'''
for filepath in self.find_manifests():
os.unlink(filepath)
self.manifests_parse() | def function[cmd_fw_manifest_purge, parameter[self]]:
constant[remove all downloaded manifests]
for taget[name[filepath]] in starred[call[name[self].find_manifests, parameter[]]] begin[:]
call[name[os].unlink, parameter[name[filepath]]]
call[name[self].manifests_parse, parameter[... | keyword[def] identifier[cmd_fw_manifest_purge] ( identifier[self] ):
literal[string]
keyword[for] identifier[filepath] keyword[in] identifier[self] . identifier[find_manifests] ():
identifier[os] . identifier[unlink] ( identifier[filepath] )
identifier[self] . identifier[ma... | def cmd_fw_manifest_purge(self):
"""remove all downloaded manifests"""
for filepath in self.find_manifests():
os.unlink(filepath) # depends on [control=['for'], data=['filepath']]
self.manifests_parse() |
def bdd_common_after_scenario(context_or_world, scenario, status):
"""Clean method that will be executed after each scenario in behave or lettuce
:param context_or_world: behave context or lettuce world
:param scenario: running scenario
:param status: scenario status (passed, failed or skipped)
"""... | def function[bdd_common_after_scenario, parameter[context_or_world, scenario, status]]:
constant[Clean method that will be executed after each scenario in behave or lettuce
:param context_or_world: behave context or lettuce world
:param scenario: running scenario
:param status: scenario status (pas... | keyword[def] identifier[bdd_common_after_scenario] ( identifier[context_or_world] , identifier[scenario] , identifier[status] ):
literal[string]
keyword[if] identifier[status] == literal[string] :
keyword[return]
keyword[elif] identifier[status] == literal[string] :
identifier[tes... | def bdd_common_after_scenario(context_or_world, scenario, status):
"""Clean method that will be executed after each scenario in behave or lettuce
:param context_or_world: behave context or lettuce world
:param scenario: running scenario
:param status: scenario status (passed, failed or skipped)
"""... |
def _stroke_simplification(self, pointlist):
"""The Douglas-Peucker line simplification takes a list of points as an
argument. It tries to simplifiy this list by removing as many points
as possible while still maintaining the overall shape of the stroke.
It does so by taking the... | def function[_stroke_simplification, parameter[self, pointlist]]:
constant[The Douglas-Peucker line simplification takes a list of points as an
argument. It tries to simplifiy this list by removing as many points
as possible while still maintaining the overall shape of the stroke.
... | keyword[def] identifier[_stroke_simplification] ( identifier[self] , identifier[pointlist] ):
literal[string]
identifier[dmax] = literal[int]
identifier[index] = literal[int]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] (... | def _stroke_simplification(self, pointlist):
"""The Douglas-Peucker line simplification takes a list of points as an
argument. It tries to simplifiy this list by removing as many points
as possible while still maintaining the overall shape of the stroke.
It does so by taking the fir... |
def setSectionCount(self, count):
"""
Sets the number of editors that the serial widget should have.
:param count | <int>
"""
# cap the sections at 10
count = max(1, min(count, 10))
# create additional editors
while self.la... | def function[setSectionCount, parameter[self, count]]:
constant[
Sets the number of editors that the serial widget should have.
:param count | <int>
]
variable[count] assign[=] call[name[max], parameter[constant[1], call[name[min], parameter[name[count], constant[10... | keyword[def] identifier[setSectionCount] ( identifier[self] , identifier[count] ):
literal[string]
identifier[count] = identifier[max] ( literal[int] , identifier[min] ( identifier[count] , literal[int] ))
keyword[while] identifier[self] . identifier[layout] (). i... | def setSectionCount(self, count):
"""
Sets the number of editors that the serial widget should have.
:param count | <int>
""" # cap the sections at 10
count = max(1, min(count, 10)) # create additional editors
while self.layout().count() < count:
editor = XLin... |
def makedir(dir_name):
"""
"Strong" directory maker.
"Strong" version of `os.mkdir`. If `dir_name` already exists, this deletes
it first.
**Parameters**
**dir_name** : string
Path to a file directory that may or may not already exist.
**See Also:**
:func:`ta... | def function[makedir, parameter[dir_name]]:
constant[
"Strong" directory maker.
"Strong" version of `os.mkdir`. If `dir_name` already exists, this deletes
it first.
**Parameters**
**dir_name** : string
Path to a file directory that may or may not already exist.
*... | keyword[def] identifier[makedir] ( identifier[dir_name] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[dir_name] ):
identifier[delete] ( identifier[dir_name] )
identifier[os] . identifier[mkdir] ( identifier[dir_name] ) | def makedir(dir_name):
"""
"Strong" directory maker.
"Strong" version of `os.mkdir`. If `dir_name` already exists, this deletes
it first.
**Parameters**
**dir_name** : string
Path to a file directory that may or may not already exist.
**See Also:**
:func:`ta... |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
AlarmModify.get_arguments(self)
self._alarm_id = self.args.alarm_id if self.args.alarm_id is not None else None
self.get_api_parameters() | def function[get_arguments, parameter[self]]:
constant[
Extracts the specific arguments of this CLI
]
call[name[AlarmModify].get_arguments, parameter[name[self]]]
name[self]._alarm_id assign[=] <ast.IfExp object at 0x7da1b0146470>
call[name[self].get_api_parameters, param... | keyword[def] identifier[get_arguments] ( identifier[self] ):
literal[string]
identifier[AlarmModify] . identifier[get_arguments] ( identifier[self] )
identifier[self] . identifier[_alarm_id] = identifier[self] . identifier[args] . identifier[alarm_id] keyword[if] identifier[self] . iden... | def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
AlarmModify.get_arguments(self)
self._alarm_id = self.args.alarm_id if self.args.alarm_id is not None else None
self.get_api_parameters() |
def _dict_to_obj(self, d):
"""Converts a dictionary of json object to a Python object."""
if JsonEncoder.TYPE_ID not in d:
return d
type_name = d.pop(JsonEncoder.TYPE_ID)
if type_name in _TYPE_NAME_TO_DECODER:
decoder = _TYPE_NAME_TO_DECODER[type_name]
return decoder(d)
else:
... | def function[_dict_to_obj, parameter[self, d]]:
constant[Converts a dictionary of json object to a Python object.]
if compare[name[JsonEncoder].TYPE_ID <ast.NotIn object at 0x7da2590d7190> name[d]] begin[:]
return[name[d]]
variable[type_name] assign[=] call[name[d].pop, parameter[name[Js... | keyword[def] identifier[_dict_to_obj] ( identifier[self] , identifier[d] ):
literal[string]
keyword[if] identifier[JsonEncoder] . identifier[TYPE_ID] keyword[not] keyword[in] identifier[d] :
keyword[return] identifier[d]
identifier[type_name] = identifier[d] . identifier[pop] ( identifie... | def _dict_to_obj(self, d):
"""Converts a dictionary of json object to a Python object."""
if JsonEncoder.TYPE_ID not in d:
return d # depends on [control=['if'], data=['d']]
type_name = d.pop(JsonEncoder.TYPE_ID)
if type_name in _TYPE_NAME_TO_DECODER:
decoder = _TYPE_NAME_TO_DECODER[typ... |
def getHighOrderSequenceChunk(it, switchover=1000, w=40, n=2048):
"""
Given an iteration index, returns a list of vectors to be appended to the
input stream, as well as a string label identifying the sequence. This
version generates a bunch of high order sequences. The first element always
provides sufficient... | def function[getHighOrderSequenceChunk, parameter[it, switchover, w, n]]:
constant[
Given an iteration index, returns a list of vectors to be appended to the
input stream, as well as a string label identifying the sequence. This
version generates a bunch of high order sequences. The first element always
... | keyword[def] identifier[getHighOrderSequenceChunk] ( identifier[it] , identifier[switchover] = literal[int] , identifier[w] = literal[int] , identifier[n] = literal[int] ):
literal[string]
keyword[if] identifier[it] % literal[int] == literal[int] :
identifier[s] = identifier[numpy] . identifier[random] .... | def getHighOrderSequenceChunk(it, switchover=1000, w=40, n=2048):
"""
Given an iteration index, returns a list of vectors to be appended to the
input stream, as well as a string label identifying the sequence. This
version generates a bunch of high order sequences. The first element always
provides sufficie... |
def generate_py_abilities(data):
"""Generate the list of functions in actions.py."""
def print_action(func_id, name, func, ab_id, general_id):
args = [func_id, '"%s"' % name, func, ab_id]
if general_id:
args.append(general_id)
print(" Function.ability(%s)," % ", ".join(str(v) for v in args))
... | def function[generate_py_abilities, parameter[data]]:
constant[Generate the list of functions in actions.py.]
def function[print_action, parameter[func_id, name, func, ab_id, general_id]]:
variable[args] assign[=] list[[<ast.Name object at 0x7da2041d8f10>, <ast.BinOp object at 0x7da2041d... | keyword[def] identifier[generate_py_abilities] ( identifier[data] ):
literal[string]
keyword[def] identifier[print_action] ( identifier[func_id] , identifier[name] , identifier[func] , identifier[ab_id] , identifier[general_id] ):
identifier[args] =[ identifier[func_id] , literal[string] % identifier[nam... | def generate_py_abilities(data):
"""Generate the list of functions in actions.py."""
def print_action(func_id, name, func, ab_id, general_id):
args = [func_id, '"%s"' % name, func, ab_id]
if general_id:
args.append(general_id) # depends on [control=['if'], data=[]]
print(' ... |
def _build_google_client(service, api_version, http_auth):
"""
Google build client helper.
:param service: service to build client for
:type service: ``str``
:param api_version: API version to use.
:type api_version: ``str``
:param http_auth: Initialized HTTP client to use.
:type http... | def function[_build_google_client, parameter[service, api_version, http_auth]]:
constant[
Google build client helper.
:param service: service to build client for
:type service: ``str``
:param api_version: API version to use.
:type api_version: ``str``
:param http_auth: Initialized HTT... | keyword[def] identifier[_build_google_client] ( identifier[service] , identifier[api_version] , identifier[http_auth] ):
literal[string]
identifier[client] = identifier[build] ( identifier[service] , identifier[api_version] , identifier[http] = identifier[http_auth] )
keyword[return] identifier[clien... | def _build_google_client(service, api_version, http_auth):
"""
Google build client helper.
:param service: service to build client for
:type service: ``str``
:param api_version: API version to use.
:type api_version: ``str``
:param http_auth: Initialized HTTP client to use.
:type http... |
def sum(a, axis=-1):
"""Sum TT-vector over specified axes"""
d = a.d
crs = _vector.vector.to_list(a.tt if isinstance(a, _matrix.matrix) else a)
if axis < 0:
axis = range(a.d)
elif isinstance(axis, int):
axis = [axis]
axis = list(axis)[::-1]
for ax in axis:
crs[ax] = _... | def function[sum, parameter[a, axis]]:
constant[Sum TT-vector over specified axes]
variable[d] assign[=] name[a].d
variable[crs] assign[=] call[name[_vector].vector.to_list, parameter[<ast.IfExp object at 0x7da20c6c6b60>]]
if compare[name[axis] less[<] constant[0]] begin[:]
... | keyword[def] identifier[sum] ( identifier[a] , identifier[axis] =- literal[int] ):
literal[string]
identifier[d] = identifier[a] . identifier[d]
identifier[crs] = identifier[_vector] . identifier[vector] . identifier[to_list] ( identifier[a] . identifier[tt] keyword[if] identifier[isinstance] ( ide... | def sum(a, axis=-1):
"""Sum TT-vector over specified axes"""
d = a.d
crs = _vector.vector.to_list(a.tt if isinstance(a, _matrix.matrix) else a)
if axis < 0:
axis = range(a.d) # depends on [control=['if'], data=['axis']]
elif isinstance(axis, int):
axis = [axis] # depends on [contro... |
def load_feedback():
""" Open existing feedback file """
result = {}
if os.path.exists(_feedback_file):
f = open(_feedback_file, 'r')
cont = f.read()
f.close()
else:
cont = '{}'
try:
result = json.loads(cont) if cont else {}
except ValueError as e:
... | def function[load_feedback, parameter[]]:
constant[ Open existing feedback file ]
variable[result] assign[=] dictionary[[], []]
if call[name[os].path.exists, parameter[name[_feedback_file]]] begin[:]
variable[f] assign[=] call[name[open], parameter[name[_feedback_file], constant[... | keyword[def] identifier[load_feedback] ():
literal[string]
identifier[result] ={}
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[_feedback_file] ):
identifier[f] = identifier[open] ( identifier[_feedback_file] , literal[string] )
identifier[cont] = i... | def load_feedback():
""" Open existing feedback file """
result = {}
if os.path.exists(_feedback_file):
f = open(_feedback_file, 'r')
cont = f.read()
f.close() # depends on [control=['if'], data=[]]
else:
cont = '{}'
try:
result = json.loads(cont) if cont els... |
def parse(cls, resource, direction="children", **additional_parameters) -> "DtsCollection":
""" Given a dict representation of a json object, generate a DTS Collection
:param resource:
:type resource: dict
:param direction: Direction of the hydra:members value
:return: DTSCollec... | def function[parse, parameter[cls, resource, direction]]:
constant[ Given a dict representation of a json object, generate a DTS Collection
:param resource:
:type resource: dict
:param direction: Direction of the hydra:members value
:return: DTSCollection parsed
:rtype: ... | keyword[def] identifier[parse] ( identifier[cls] , identifier[resource] , identifier[direction] = literal[string] ,** identifier[additional_parameters] )-> literal[string] :
literal[string]
identifier[data] = identifier[jsonld] . identifier[expand] ( identifier[resource] )
keyword[if] id... | def parse(cls, resource, direction='children', **additional_parameters) -> 'DtsCollection':
""" Given a dict representation of a json object, generate a DTS Collection
:param resource:
:type resource: dict
:param direction: Direction of the hydra:members value
:return: DTSCollection... |
def login(self, user, password, token=None, callback=None):
"""Login with a username and password
Arguments:
user - username or email address
password - the password for the account
Keyword Arguments:
token - meteor resume token
callback - callback function cont... | def function[login, parameter[self, user, password, token, callback]]:
constant[Login with a username and password
Arguments:
user - username or email address
password - the password for the account
Keyword Arguments:
token - meteor resume token
callback - callb... | keyword[def] identifier[login] ( identifier[self] , identifier[user] , identifier[password] , identifier[token] = keyword[None] , identifier[callback] = keyword[None] ):
literal[string]
identifier[hashed] = identifier[hashlib] . identifier[sha256] ( identifier[password] ... | def login(self, user, password, token=None, callback=None):
"""Login with a username and password
Arguments:
user - username or email address
password - the password for the account
Keyword Arguments:
token - meteor resume token
callback - callback function containi... |
def DbDeleteDevice(self, argin):
""" Delete a devcie from database
:param argin: device name
:type: tango.DevString
:return:
:rtype: tango.DevVoid """
self._log.debug("In DbDeleteDevice()")
ret, dev_name, dfm = check_device_name(argin)
if not ret:
... | def function[DbDeleteDevice, parameter[self, argin]]:
constant[ Delete a devcie from database
:param argin: device name
:type: tango.DevString
:return:
:rtype: tango.DevVoid ]
call[name[self]._log.debug, parameter[constant[In DbDeleteDevice()]]]
<ast.Tuple object... | keyword[def] identifier[DbDeleteDevice] ( identifier[self] , identifier[argin] ):
literal[string]
identifier[self] . identifier[_log] . identifier[debug] ( literal[string] )
identifier[ret] , identifier[dev_name] , identifier[dfm] = identifier[check_device_name] ( identifier[argin] )
... | def DbDeleteDevice(self, argin):
""" Delete a devcie from database
:param argin: device name
:type: tango.DevString
:return:
:rtype: tango.DevVoid """
self._log.debug('In DbDeleteDevice()')
(ret, dev_name, dfm) = check_device_name(argin)
if not ret:
self.warn_str... |
def get_requests(self):
"""
Creates product structure and returns list of files for download
:return: list of download requests
:rtype: list(download.DownloadRequest)
"""
safe = self.get_safe_struct()
self.download_list = []
self.structure_recursion(safe... | def function[get_requests, parameter[self]]:
constant[
Creates product structure and returns list of files for download
:return: list of download requests
:rtype: list(download.DownloadRequest)
]
variable[safe] assign[=] call[name[self].get_safe_struct, parameter[]]
... | keyword[def] identifier[get_requests] ( identifier[self] ):
literal[string]
identifier[safe] = identifier[self] . identifier[get_safe_struct] ()
identifier[self] . identifier[download_list] =[]
identifier[self] . identifier[structure_recursion] ( identifier[safe] , identifier[sel... | def get_requests(self):
"""
Creates product structure and returns list of files for download
:return: list of download requests
:rtype: list(download.DownloadRequest)
"""
safe = self.get_safe_struct()
self.download_list = []
self.structure_recursion(safe, self.parent_fol... |
def saveWeights(sim):
''' Save the weights for each plastic synapse '''
with open(sim.weightsfilename,'w') as fid:
for weightdata in sim.allWeights:
fid.write('%0.0f' % weightdata[0]) # Time
for i in range(1,len(weightdata)): fid.write('\t%0.8f' % weightdata[i])
fid.w... | def function[saveWeights, parameter[sim]]:
constant[ Save the weights for each plastic synapse ]
with call[name[open], parameter[name[sim].weightsfilename, constant[w]]] begin[:]
for taget[name[weightdata]] in starred[name[sim].allWeights] begin[:]
call[name[fid].... | keyword[def] identifier[saveWeights] ( identifier[sim] ):
literal[string]
keyword[with] identifier[open] ( identifier[sim] . identifier[weightsfilename] , literal[string] ) keyword[as] identifier[fid] :
keyword[for] identifier[weightdata] keyword[in] identifier[sim] . identifier[allWeights] :... | def saveWeights(sim):
""" Save the weights for each plastic synapse """
with open(sim.weightsfilename, 'w') as fid:
for weightdata in sim.allWeights:
fid.write('%0.0f' % weightdata[0]) # Time
for i in range(1, len(weightdata)):
fid.write('\t%0.8f' % weightdata[i]... |
def suspend_all(self):
"""
Suspend all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.suspend)
yield from pool.join() | def function[suspend_all, parameter[self]]:
constant[
Suspend all nodes
]
variable[pool] assign[=] call[name[Pool], parameter[]]
for taget[name[node]] in starred[call[name[self].nodes.values, parameter[]]] begin[:]
call[name[pool].append, parameter[name[node].susp... | keyword[def] identifier[suspend_all] ( identifier[self] ):
literal[string]
identifier[pool] = identifier[Pool] ( identifier[concurrency] = literal[int] )
keyword[for] identifier[node] keyword[in] identifier[self] . identifier[nodes] . identifier[values] ():
identifier[pool]... | def suspend_all(self):
"""
Suspend all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.suspend) # depends on [control=['for'], data=['node']]
yield from pool.join() |
def execute_cmdLine_instructions(instructions, m, l):
""" Applies the instructions given via
<instructions> on the manager <m> """
opt_lut = dict()
inst_lut = dict()
for k, v in six.iteritems(instructions):
bits = k.split('-', 1)
if len(bits) == 1:
if v not in m.modul... | def function[execute_cmdLine_instructions, parameter[instructions, m, l]]:
constant[ Applies the instructions given via
<instructions> on the manager <m> ]
variable[opt_lut] assign[=] call[name[dict], parameter[]]
variable[inst_lut] assign[=] call[name[dict], parameter[]]
for tag... | keyword[def] identifier[execute_cmdLine_instructions] ( identifier[instructions] , identifier[m] , identifier[l] ):
literal[string]
identifier[opt_lut] = identifier[dict] ()
identifier[inst_lut] = identifier[dict] ()
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[six] . iden... | def execute_cmdLine_instructions(instructions, m, l):
""" Applies the instructions given via
<instructions> on the manager <m> """
opt_lut = dict()
inst_lut = dict()
for (k, v) in six.iteritems(instructions):
bits = k.split('-', 1)
if len(bits) == 1:
if v not in m.mod... |
def currency(money):
"""
Фильтр валюты. Форматирует цену в соответствии с установленным количеством знаков после запятой,
а также добавлеят символ валюты.
:param money:
:return:
"""
decimals = getattr(settings, 'MIDNIGHT_CATALOG_DECIMALS', 2)
money = round(float(money), decimals)
sym... | def function[currency, parameter[money]]:
constant[
Фильтр валюты. Форматирует цену в соответствии с установленным количеством знаков после запятой,
а также добавлеят символ валюты.
:param money:
:return:
]
variable[decimals] assign[=] call[name[getattr], parameter[name[settings], co... | keyword[def] identifier[currency] ( identifier[money] ):
literal[string]
identifier[decimals] = identifier[getattr] ( identifier[settings] , literal[string] , literal[int] )
identifier[money] = identifier[round] ( identifier[float] ( identifier[money] ), identifier[decimals] )
identifier[symbol] ... | def currency(money):
"""
Фильтр валюты. Форматирует цену в соответствии с установленным количеством знаков после запятой,
а также добавлеят символ валюты.
:param money:
:return:
"""
decimals = getattr(settings, 'MIDNIGHT_CATALOG_DECIMALS', 2)
money = round(float(money), decimals)
sym... |
def write(self, filename=None):
"""Write the PE file.
This function will process all headers and components
of the PE file and include all changes made (by just
assigning to attributes in the PE objects) and write
the changes back to a file whose name is provided as
... | def function[write, parameter[self, filename]]:
constant[Write the PE file.
This function will process all headers and components
of the PE file and include all changes made (by just
assigning to attributes in the PE objects) and write
the changes back to a file whose na... | keyword[def] identifier[write] ( identifier[self] , identifier[filename] = keyword[None] ):
literal[string]
identifier[file_data] = identifier[list] ( identifier[self] . identifier[__data__] )
keyword[for] identifier[structure] keyword[in] identifier[self] . identifier[__structures__] ... | def write(self, filename=None):
"""Write the PE file.
This function will process all headers and components
of the PE file and include all changes made (by just
assigning to attributes in the PE objects) and write
the changes back to a file whose name is provided as
... |
def fan_speed(self, speed: int = None) -> bool:
"""Adjust Fan Speed by Specifying 1,2,3 as argument or cycle
through speeds increasing by one"""
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
head = helpers.req_headers(self.manager)
if ... | def function[fan_speed, parameter[self, speed]]:
constant[Adjust Fan Speed by Specifying 1,2,3 as argument or cycle
through speeds increasing by one]
variable[body] assign[=] call[name[helpers].req_body, parameter[name[self].manager, constant[devicestatus]]]
call[name[body]][constant... | keyword[def] identifier[fan_speed] ( identifier[self] , identifier[speed] : identifier[int] = keyword[None] )-> identifier[bool] :
literal[string]
identifier[body] = identifier[helpers] . identifier[req_body] ( identifier[self] . identifier[manager] , literal[string] )
identifier[body] [ l... | def fan_speed(self, speed: int=None) -> bool:
"""Adjust Fan Speed by Specifying 1,2,3 as argument or cycle
through speeds increasing by one"""
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
head = helpers.req_headers(self.manager)
if self.details.get('mode... |
def ColumnTypeParser(description):
"""Parses a single column description. Internal helper method.
Args:
description: a column description in the possible formats:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'}... | def function[ColumnTypeParser, parameter[description]]:
constant[Parses a single column description. Internal helper method.
Args:
description: a column description in the possible formats:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', ... | keyword[def] identifier[ColumnTypeParser] ( identifier[description] ):
literal[string]
keyword[if] keyword[not] identifier[description] :
keyword[raise] identifier[DataTableException] ( literal[string] )
keyword[if] keyword[not] identifier[isinstance] ( identifier[description] ,( identifi... | def ColumnTypeParser(description):
"""Parses a single column description. Internal helper method.
Args:
description: a column description in the possible formats:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'}... |
def ignore_file_extension(self, extension):
"""
Configure a file extension to be ignored.
:param extension: file extension to be ignored
(ex. .less, .scss, etc)
"""
logger.info('Ignoring file extension: {}'.format(extension))
self.watcher.ignore... | def function[ignore_file_extension, parameter[self, extension]]:
constant[
Configure a file extension to be ignored.
:param extension: file extension to be ignored
(ex. .less, .scss, etc)
]
call[name[logger].info, parameter[call[constant[Ignoring file e... | keyword[def] identifier[ignore_file_extension] ( identifier[self] , identifier[extension] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[extension] ))
identifier[self] . identifier[watcher] . identifier[ignore_file_extension] ( ... | def ignore_file_extension(self, extension):
"""
Configure a file extension to be ignored.
:param extension: file extension to be ignored
(ex. .less, .scss, etc)
"""
logger.info('Ignoring file extension: {}'.format(extension))
self.watcher.ignore_file_extens... |
def boolean_sparse(a, b, operation=np.logical_and):
"""
Find common rows between two arrays very quickly
using 3D boolean sparse matrices.
Parameters
-----------
a: (n, d) int, coordinates in space
b: (m, d) int, coordinates in space
operation: numpy operation function, ie:
... | def function[boolean_sparse, parameter[a, b, operation]]:
constant[
Find common rows between two arrays very quickly
using 3D boolean sparse matrices.
Parameters
-----------
a: (n, d) int, coordinates in space
b: (m, d) int, coordinates in space
operation: numpy operation function... | keyword[def] identifier[boolean_sparse] ( identifier[a] , identifier[b] , identifier[operation] = identifier[np] . identifier[logical_and] ):
literal[string]
keyword[import] identifier[sparse]
identifier[extrema] = identifier[np] . identifier[array] ([ identifier[a] . identifier[min]... | def boolean_sparse(a, b, operation=np.logical_and):
"""
Find common rows between two arrays very quickly
using 3D boolean sparse matrices.
Parameters
-----------
a: (n, d) int, coordinates in space
b: (m, d) int, coordinates in space
operation: numpy operation function, ie:
... |
def symmetric_strength_of_connection(A, theta=0):
"""Symmetric Strength Measure.
Compute strength of connection matrix using the standard symmetric measure
An off-diagonal connection A[i,j] is strong iff::
abs(A[i,j]) >= theta * sqrt( abs(A[i,i]) * abs(A[j,j]) )
Parameters
----------
... | def function[symmetric_strength_of_connection, parameter[A, theta]]:
constant[Symmetric Strength Measure.
Compute strength of connection matrix using the standard symmetric measure
An off-diagonal connection A[i,j] is strong iff::
abs(A[i,j]) >= theta * sqrt( abs(A[i,i]) * abs(A[j,j]) )
... | keyword[def] identifier[symmetric_strength_of_connection] ( identifier[A] , identifier[theta] = literal[int] ):
literal[string]
keyword[if] identifier[theta] < literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] identifier[sparse] . identifier[isspmatrix_c... | def symmetric_strength_of_connection(A, theta=0):
"""Symmetric Strength Measure.
Compute strength of connection matrix using the standard symmetric measure
An off-diagonal connection A[i,j] is strong iff::
abs(A[i,j]) >= theta * sqrt( abs(A[i,i]) * abs(A[j,j]) )
Parameters
----------
... |
def StartFlowAndWait(client_id,
token=None,
timeout=DEFAULT_TIMEOUT,
**flow_args):
"""Runs a flow and waits for it to finish.
Args:
client_id: The client id of the client to run on.
token: The datastore access token.
timeout: How long to wa... | def function[StartFlowAndWait, parameter[client_id, token, timeout]]:
constant[Runs a flow and waits for it to finish.
Args:
client_id: The client id of the client to run on.
token: The datastore access token.
timeout: How long to wait for a flow to complete, maximum.
**flow_args: Pass throug... | keyword[def] identifier[StartFlowAndWait] ( identifier[client_id] ,
identifier[token] = keyword[None] ,
identifier[timeout] = identifier[DEFAULT_TIMEOUT] ,
** identifier[flow_args] ):
literal[string]
identifier[flow_urn] = identifier[flow] . identifier[StartAFF4Flow] (
identifier[client_id] = identifier[c... | def StartFlowAndWait(client_id, token=None, timeout=DEFAULT_TIMEOUT, **flow_args):
"""Runs a flow and waits for it to finish.
Args:
client_id: The client id of the client to run on.
token: The datastore access token.
timeout: How long to wait for a flow to complete, maximum.
**flow_args: Pass thr... |
def tokenize_asdl(buf):
"""Tokenize the given buffer. Yield Token objects."""
for lineno, line in enumerate(buf.splitlines(), 1):
for m in re.finditer(r'\s*(\w+|--.*|.)', line.strip()):
c = m.group(1)
if c[0].isalpha():
# Some kind of identifier
if... | def function[tokenize_asdl, parameter[buf]]:
constant[Tokenize the given buffer. Yield Token objects.]
for taget[tuple[[<ast.Name object at 0x7da2043460b0>, <ast.Name object at 0x7da204346dd0>]]] in starred[call[name[enumerate], parameter[call[name[buf].splitlines, parameter[]], constant[1]]]] begin[:]
... | keyword[def] identifier[tokenize_asdl] ( identifier[buf] ):
literal[string]
keyword[for] identifier[lineno] , identifier[line] keyword[in] identifier[enumerate] ( identifier[buf] . identifier[splitlines] (), literal[int] ):
keyword[for] identifier[m] keyword[in] identifier[re] . identifier[f... | def tokenize_asdl(buf):
"""Tokenize the given buffer. Yield Token objects."""
for (lineno, line) in enumerate(buf.splitlines(), 1):
for m in re.finditer('\\s*(\\w+|--.*|.)', line.strip()):
c = m.group(1)
if c[0].isalpha():
# Some kind of identifier
... |
def as_single_element(self):
"""
Processes the response as a single-element response,
like config_get or system_counters_get.
If there is more then one element in the response or no
elements this raises a ResponseError
"""
if self.as_return_etree is None:
... | def function[as_single_element, parameter[self]]:
constant[
Processes the response as a single-element response,
like config_get or system_counters_get.
If there is more then one element in the response or no
elements this raises a ResponseError
]
if compare[name[... | keyword[def] identifier[as_single_element] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[as_return_etree] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[if] identifier[len] ( identifier[self] . identifier[as_return_etr... | def as_single_element(self):
"""
Processes the response as a single-element response,
like config_get or system_counters_get.
If there is more then one element in the response or no
elements this raises a ResponseError
"""
if self.as_return_etree is None:
return N... |
def word_ngrams(s, n=3, token_fn=tokens.on_whitespace):
"""
Word-level n-grams in a string
By default, whitespace is assumed to be a word boundary.
>>> ng.word_ngrams('This is not a test!')
[('This', 'is', 'not'), ('is', 'not', 'a'), ('not', 'a', 'test!')]
If the sequence'... | def function[word_ngrams, parameter[s, n, token_fn]]:
constant[
Word-level n-grams in a string
By default, whitespace is assumed to be a word boundary.
>>> ng.word_ngrams('This is not a test!')
[('This', 'is', 'not'), ('is', 'not', 'a'), ('not', 'a', 'test!')]
If the s... | keyword[def] identifier[word_ngrams] ( identifier[s] , identifier[n] = literal[int] , identifier[token_fn] = identifier[tokens] . identifier[on_whitespace] ):
literal[string]
identifier[tokens] = identifier[token_fn] ( identifier[s] )
keyword[return] identifier[__ngrams] ( identifier[tokens] , identi... | def word_ngrams(s, n=3, token_fn=tokens.on_whitespace):
"""
Word-level n-grams in a string
By default, whitespace is assumed to be a word boundary.
>>> ng.word_ngrams('This is not a test!')
[('This', 'is', 'not'), ('is', 'not', 'a'), ('not', 'a', 'test!')]
If the sequence'... |
def parse_lit(self, lines):
'''
Parse a string line-by-line delineating comments and code
:returns: An tuple of boolean/list-of-string pairs. True designates a
comment; False designates code.
'''
comment_char = '#' # TODO: move this into a directive option
co... | def function[parse_lit, parameter[self, lines]]:
constant[
Parse a string line-by-line delineating comments and code
:returns: An tuple of boolean/list-of-string pairs. True designates a
comment; False designates code.
]
variable[comment_char] assign[=] constant[#]
... | keyword[def] identifier[parse_lit] ( identifier[self] , identifier[lines] ):
literal[string]
identifier[comment_char] = literal[string]
identifier[comment] = identifier[re] . identifier[compile] ( literal[string] . identifier[format] ( identifier[comment_char] ))
identifier[secti... | def parse_lit(self, lines):
"""
Parse a string line-by-line delineating comments and code
:returns: An tuple of boolean/list-of-string pairs. True designates a
comment; False designates code.
"""
comment_char = '#' # TODO: move this into a directive option
comment = re.... |
def extract_script(embedded_hex):
"""
Given a hex file containing the MicroPython runtime and an embedded Python
script, will extract the original Python script.
Returns a string containing the original embedded script.
"""
hex_lines = embedded_hex.split('\n')
script_addr_high = hex((_SCRIP... | def function[extract_script, parameter[embedded_hex]]:
constant[
Given a hex file containing the MicroPython runtime and an embedded Python
script, will extract the original Python script.
Returns a string containing the original embedded script.
]
variable[hex_lines] assign[=] call[nam... | keyword[def] identifier[extract_script] ( identifier[embedded_hex] ):
literal[string]
identifier[hex_lines] = identifier[embedded_hex] . identifier[split] ( literal[string] )
identifier[script_addr_high] = identifier[hex] (( identifier[_SCRIPT_ADDR] >> literal[int] )& literal[int] )[ literal[int] :]. ... | def extract_script(embedded_hex):
"""
Given a hex file containing the MicroPython runtime and an embedded Python
script, will extract the original Python script.
Returns a string containing the original embedded script.
"""
hex_lines = embedded_hex.split('\n')
script_addr_high = hex(_SCRIPT... |
def add_membership(self, member, role=github.GithubObject.NotSet):
"""
:calls: `PUT /teams/:id/memberships/:user <http://developer.github.com/v3/orgs/teams>`_
:param member: :class:`github.Nameduser.NamedUser`
:param role: string
:rtype: None
"""
assert isinstance... | def function[add_membership, parameter[self, member, role]]:
constant[
:calls: `PUT /teams/:id/memberships/:user <http://developer.github.com/v3/orgs/teams>`_
:param member: :class:`github.Nameduser.NamedUser`
:param role: string
:rtype: None
]
assert[call[name[isinst... | keyword[def] identifier[add_membership] ( identifier[self] , identifier[member] , identifier[role] = identifier[github] . identifier[GithubObject] . identifier[NotSet] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[member] , identifier[github] . identifier[NamedUser] . iden... | def add_membership(self, member, role=github.GithubObject.NotSet):
"""
:calls: `PUT /teams/:id/memberships/:user <http://developer.github.com/v3/orgs/teams>`_
:param member: :class:`github.Nameduser.NamedUser`
:param role: string
:rtype: None
"""
assert isinstance(member,... |
def put_job_into(self, tube_name, data, pri=65536, delay=0, ttr=120):
"""Insert a new job into a specific queue. Wrapper around :func:`put_job`.
:param tube_name: Tube name
:type tube_name: str
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or... | def function[put_job_into, parameter[self, tube_name, data, pri, delay, ttr]]:
constant[Insert a new job into a specific queue. Wrapper around :func:`put_job`.
:param tube_name: Tube name
:type tube_name: str
:param data: Job body
:type data: Text (either str which will be encod... | keyword[def] identifier[put_job_into] ( identifier[self] , identifier[tube_name] , identifier[data] , identifier[pri] = literal[int] , identifier[delay] = literal[int] , identifier[ttr] = literal[int] ):
literal[string]
keyword[with] identifier[self] . identifier[using] ( identifier[tube_name] ) k... | def put_job_into(self, tube_name, data, pri=65536, delay=0, ttr=120):
"""Insert a new job into a specific queue. Wrapper around :func:`put_job`.
:param tube_name: Tube name
:type tube_name: str
:param data: Job body
:type data: Text (either str which will be encoded as utf-8, or byt... |
def session_rollback(self, session):
"""Send session_rollback signal in sqlalchemy ``after_rollback``.
This marks the failure of session so the session may enter commit
phase.
"""
# this may happen when there's nothing to rollback
if not hasattr(session, 'meepo_unique_id... | def function[session_rollback, parameter[self, session]]:
constant[Send session_rollback signal in sqlalchemy ``after_rollback``.
This marks the failure of session so the session may enter commit
phase.
]
if <ast.UnaryOp object at 0x7da20cabc2e0> begin[:]
call[na... | keyword[def] identifier[session_rollback] ( identifier[self] , identifier[session] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[session] , literal[string] ):
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
... | def session_rollback(self, session):
"""Send session_rollback signal in sqlalchemy ``after_rollback``.
This marks the failure of session so the session may enter commit
phase.
"""
# this may happen when there's nothing to rollback
if not hasattr(session, 'meepo_unique_id'):
... |
def insert(self, index, *grids):
"""Return a copy with ``grids`` inserted before ``index``.
The given grids are inserted (as a block) into ``self``, yielding
a new grid whose number of dimensions is the sum of the numbers of
dimensions of all involved grids.
Note that no changes... | def function[insert, parameter[self, index]]:
constant[Return a copy with ``grids`` inserted before ``index``.
The given grids are inserted (as a block) into ``self``, yielding
a new grid whose number of dimensions is the sum of the numbers of
dimensions of all involved grids.
N... | keyword[def] identifier[insert] ( identifier[self] , identifier[index] ,* identifier[grids] ):
literal[string]
identifier[index] , identifier[index_in] = identifier[safe_int_conv] ( identifier[index] ), identifier[index]
keyword[if] keyword[not] - identifier[self] . identifier[ndim] <= i... | def insert(self, index, *grids):
"""Return a copy with ``grids`` inserted before ``index``.
The given grids are inserted (as a block) into ``self``, yielding
a new grid whose number of dimensions is the sum of the numbers of
dimensions of all involved grids.
Note that no changes are... |
def mfpt_sensitivity(T, target, i):
r"""Sensitivity matrix of the mean first-passage time from specified state.
Parameters
----------
T : (M, M) ndarray
Transition matrix
target : int or list
Target state or set for mfpt computation
i : int
Compute the sensitivity for st... | def function[mfpt_sensitivity, parameter[T, target, i]]:
constant[Sensitivity matrix of the mean first-passage time from specified state.
Parameters
----------
T : (M, M) ndarray
Transition matrix
target : int or list
Target state or set for mfpt computation
i : int
... | keyword[def] identifier[mfpt_sensitivity] ( identifier[T] , identifier[target] , identifier[i] ):
literal[string]
identifier[T] = identifier[_types] . identifier[ensure_ndarray_or_sparse] ( identifier[T] , identifier[ndim] = literal[int] , identifier[uniform] = keyword[True] , identifier[kind] = liter... | def mfpt_sensitivity(T, target, i):
"""Sensitivity matrix of the mean first-passage time from specified state.
Parameters
----------
T : (M, M) ndarray
Transition matrix
target : int or list
Target state or set for mfpt computation
i : int
Compute the sensitivity for sta... |
def _add_event_in_element(self, element, event):
"""
Add a type of event in element.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param event: The type of event.
:type event: str
"""
if not self.main_scrip... | def function[_add_event_in_element, parameter[self, element, event]]:
constant[
Add a type of event in element.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param event: The type of event.
:type event: str
]
... | keyword[def] identifier[_add_event_in_element] ( identifier[self] , identifier[element] , identifier[event] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[main_script_added] :
identifier[self] . identifier[_generate_main_scripts] ()
keyword[if] ... | def _add_event_in_element(self, element, event):
"""
Add a type of event in element.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param event: The type of event.
:type event: str
"""
if not self.main_script_added:
... |
def enable_server(name, backend, socket=DEFAULT_SOCKET_URL):
'''
Enable Server in haproxy
name
Server to enable
backend
haproxy backend, or all backends if "*" is supplied
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block::... | def function[enable_server, parameter[name, backend, socket]]:
constant[
Enable Server in haproxy
name
Server to enable
backend
haproxy backend, or all backends if "*" is supplied
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. ... | keyword[def] identifier[enable_server] ( identifier[name] , identifier[backend] , identifier[socket] = identifier[DEFAULT_SOCKET_URL] ):
literal[string]
keyword[if] identifier[backend] == literal[string] :
identifier[backends] = identifier[show_backends] ( identifier[socket] = identifier[socket]... | def enable_server(name, backend, socket=DEFAULT_SOCKET_URL):
"""
Enable Server in haproxy
name
Server to enable
backend
haproxy backend, or all backends if "*" is supplied
socket
haproxy stats socket, default ``/var/run/haproxy.sock``
CLI Example:
.. code-block::... |
def multibox(centers, pitch, colors=None):
"""
Return a Trimesh object with a box at every center.
Doesn't do anything nice or fancy.
Parameters
-----------
centers: (n,3) float, center of boxes that are occupied
pitch: float, the edge length of a voxel
colors: (3,) or (4,) or (n,3) ... | def function[multibox, parameter[centers, pitch, colors]]:
constant[
Return a Trimesh object with a box at every center.
Doesn't do anything nice or fancy.
Parameters
-----------
centers: (n,3) float, center of boxes that are occupied
pitch: float, the edge length of a voxel
colo... | keyword[def] identifier[multibox] ( identifier[centers] , identifier[pitch] , identifier[colors] = keyword[None] ):
literal[string]
keyword[from] . keyword[import] identifier[primitives]
keyword[from] . identifier[base] keyword[import] identifier[Trimesh]
identifier[b] = identifier[primitiv... | def multibox(centers, pitch, colors=None):
"""
Return a Trimesh object with a box at every center.
Doesn't do anything nice or fancy.
Parameters
-----------
centers: (n,3) float, center of boxes that are occupied
pitch: float, the edge length of a voxel
colors: (3,) or (4,) or (n,3) ... |
def p_single_statement_delays(self, p):
'single_statement : DELAY expression SEMICOLON'
p[0] = SingleStatement(DelayStatement(
p[2], lineno=p.lineno(1)), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | def function[p_single_statement_delays, parameter[self, p]]:
constant[single_statement : DELAY expression SEMICOLON]
call[name[p]][constant[0]] assign[=] call[name[SingleStatement], parameter[call[name[DelayStatement], parameter[call[name[p]][constant[2]]]]]]
call[name[p].set_lineno, parameter[c... | keyword[def] identifier[p_single_statement_delays] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[SingleStatement] ( identifier[DelayStatement] (
identifier[p] [ literal[int] ], identifier[lineno] = identifier[p] . identifier[lineno] ( lite... | def p_single_statement_delays(self, p):
"""single_statement : DELAY expression SEMICOLON"""
p[0] = SingleStatement(DelayStatement(p[2], lineno=p.lineno(1)), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
async def _send_scan_event(self, device):
"""Send a scan event from a device."""
conn_string = str(device.iotile_id)
info = {
'connection_string': conn_string,
'uuid': device.iotile_id,
'signal_strength': 100,
'validity_period': self.ExpirationTim... | <ast.AsyncFunctionDef object at 0x7da18f723730> | keyword[async] keyword[def] identifier[_send_scan_event] ( identifier[self] , identifier[device] ):
literal[string]
identifier[conn_string] = identifier[str] ( identifier[device] . identifier[iotile_id] )
identifier[info] ={
literal[string] : identifier[conn_string] ,
l... | async def _send_scan_event(self, device):
"""Send a scan event from a device."""
conn_string = str(device.iotile_id)
info = {'connection_string': conn_string, 'uuid': device.iotile_id, 'signal_strength': 100, 'validity_period': self.ExpirationTime}
await self.notify_event(conn_string, 'device_seen', inf... |
def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
"""
column = col[self.col_name].replace({np.nan: np.inf})
frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict... | def function[_fit, parameter[self, col]]:
constant[Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
]
variable[column] assign[=] call[call[name[col]][name[self].col_name].replace, parameter[dictionary[[<ast.Attribut... | keyword[def] identifier[_fit] ( identifier[self] , identifier[col] ):
literal[string]
identifier[column] = identifier[col] [ identifier[self] . identifier[col_name] ]. identifier[replace] ({ identifier[np] . identifier[nan] : identifier[np] . identifier[inf] })
identifier[frequencies] = i... | def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
"""
column = col[self.col_name].replace({np.nan: np.inf})
frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict()
# next... |
def _filter_deprecation_warnings():
"""Apply filters to deprecation warnings.
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
... | def function[_filter_deprecation_warnings, parameter[]]:
constant[Apply filters to deprecation warnings.
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users. Additionally, silence the `Ch... | keyword[def] identifier[_filter_deprecation_warnings] ():
literal[string]
identifier[deprecation_filter] =( literal[string] , keyword[None] , identifier[DeprecationWarning] ,
identifier[re] . identifier[compile] ( literal[string] , identifier[re] . identifier[UNICODE] ), literal[int] )
... | def _filter_deprecation_warnings():
"""Apply filters to deprecation warnings.
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
... |
def reference_id(self, reference_id):
"""
Sets the reference_id of this Order.
A client specified identifier to associate an entity in another system with this order.
:param reference_id: The reference_id of this Order.
:type: str
"""
if reference_id is None:
... | def function[reference_id, parameter[self, reference_id]]:
constant[
Sets the reference_id of this Order.
A client specified identifier to associate an entity in another system with this order.
:param reference_id: The reference_id of this Order.
:type: str
]
if ... | keyword[def] identifier[reference_id] ( identifier[self] , identifier[reference_id] ):
literal[string]
keyword[if] identifier[reference_id] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] identifier[len] ( identifier[refe... | def reference_id(self, reference_id):
"""
Sets the reference_id of this Order.
A client specified identifier to associate an entity in another system with this order.
:param reference_id: The reference_id of this Order.
:type: str
"""
if reference_id is None:
rai... |
def fetch_pkg_list(self):
"""Fetch and cache master list of package names from PYPI"""
self.logger.debug("DEBUG: Fetching package name list from PyPI")
package_list = self.list_packages()
cPickle.dump(package_list, open(self.pkg_cache_file, "w"))
self.pkg_list = package_list | def function[fetch_pkg_list, parameter[self]]:
constant[Fetch and cache master list of package names from PYPI]
call[name[self].logger.debug, parameter[constant[DEBUG: Fetching package name list from PyPI]]]
variable[package_list] assign[=] call[name[self].list_packages, parameter[]]
cal... | keyword[def] identifier[fetch_pkg_list] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
identifier[package_list] = identifier[self] . identifier[list_packages] ()
identifier[cPickle] . identifier[dump] ( identifie... | def fetch_pkg_list(self):
"""Fetch and cache master list of package names from PYPI"""
self.logger.debug('DEBUG: Fetching package name list from PyPI')
package_list = self.list_packages()
cPickle.dump(package_list, open(self.pkg_cache_file, 'w'))
self.pkg_list = package_list |
def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1):
"""Sync most recent file by date, time attribues"""
files = command.list_files(*filters, remote_dir=remote_dir)
most_recent = sorted(files, key=lambda f: f.datetime)
to_sync = most_recent[-count:]
_notify_sync(Directi... | def function[down_by_time, parameter[]]:
constant[Sync most recent file by date, time attribues]
variable[files] assign[=] call[name[command].list_files, parameter[<ast.Starred object at 0x7da18f721300>]]
variable[most_recent] assign[=] call[name[sorted], parameter[name[files]]]
variable... | keyword[def] identifier[down_by_time] (* identifier[filters] , identifier[remote_dir] = identifier[DEFAULT_REMOTE_DIR] , identifier[local_dir] = literal[string] , identifier[count] = literal[int] ):
literal[string]
identifier[files] = identifier[command] . identifier[list_files] (* identifier[filters] , id... | def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir='.', count=1):
"""Sync most recent file by date, time attribues"""
files = command.list_files(*filters, remote_dir=remote_dir)
most_recent = sorted(files, key=lambda f: f.datetime)
to_sync = most_recent[-count:]
_notify_sync(Directi... |
def update_bucket(self, bucket_name, access_control='private', version_control=False, log_destination=None, lifecycle_rules=None, tag_list=None, notification_settings=None, region_replication=None, access_policy=None):
'''
a method for updating the properties of a bucket in S3
:param bucke... | def function[update_bucket, parameter[self, bucket_name, access_control, version_control, log_destination, lifecycle_rules, tag_list, notification_settings, region_replication, access_policy]]:
constant[
a method for updating the properties of a bucket in S3
:param bucket_name: string with ... | keyword[def] identifier[update_bucket] ( identifier[self] , identifier[bucket_name] , identifier[access_control] = literal[string] , identifier[version_control] = keyword[False] , identifier[log_destination] = keyword[None] , identifier[lifecycle_rules] = keyword[None] , identifier[tag_list] = keyword[None] , identif... | def update_bucket(self, bucket_name, access_control='private', version_control=False, log_destination=None, lifecycle_rules=None, tag_list=None, notification_settings=None, region_replication=None, access_policy=None):
"""
a method for updating the properties of a bucket in S3
:param bucket_nam... |
def generate_reset_password_token(self, user):
"""
Generates a unique reset password token for the specified user.
:param user: The user to work with
"""
password_hash = self.hash_data(user.password) if user.password else None
data = [str(user.id), password_hash]
... | def function[generate_reset_password_token, parameter[self, user]]:
constant[
Generates a unique reset password token for the specified user.
:param user: The user to work with
]
variable[password_hash] assign[=] <ast.IfExp object at 0x7da20c6c7c10>
variable[data] assign... | keyword[def] identifier[generate_reset_password_token] ( identifier[self] , identifier[user] ):
literal[string]
identifier[password_hash] = identifier[self] . identifier[hash_data] ( identifier[user] . identifier[password] ) keyword[if] identifier[user] . identifier[password] keyword[else] keywo... | def generate_reset_password_token(self, user):
"""
Generates a unique reset password token for the specified user.
:param user: The user to work with
"""
password_hash = self.hash_data(user.password) if user.password else None
data = [str(user.id), password_hash]
return self.sec... |
def __we_c(cls, calib, tc, temp, we_v):
"""
Compute weC from sensor temperature compensation of weV, aeV
"""
we_t = we_v - (calib.we_elc_mv / 1000.0) # remove electronic we zero
we_c = tc.correct(calib, temp, we_t)
# print("D4Datum__we_c: we_t:%f we_c:%s" % (we_t... | def function[__we_c, parameter[cls, calib, tc, temp, we_v]]:
constant[
Compute weC from sensor temperature compensation of weV, aeV
]
variable[we_t] assign[=] binary_operation[name[we_v] - binary_operation[name[calib].we_elc_mv / constant[1000.0]]]
variable[we_c] assign[=] call[n... | keyword[def] identifier[__we_c] ( identifier[cls] , identifier[calib] , identifier[tc] , identifier[temp] , identifier[we_v] ):
literal[string]
identifier[we_t] = identifier[we_v] -( identifier[calib] . identifier[we_elc_mv] / literal[int] )
identifier[we_c] = identifier[tc] . identifier[... | def __we_c(cls, calib, tc, temp, we_v):
"""
Compute weC from sensor temperature compensation of weV, aeV
"""
we_t = we_v - calib.we_elc_mv / 1000.0 # remove electronic we zero
we_c = tc.correct(calib, temp, we_t)
# print("D4Datum__we_c: we_t:%f we_c:%s" % (we_t, we_c), file=sys.stderr)
... |
def precision_recall_by_user(observed_user_items,
recommendations,
cutoffs=[10]):
"""
Compute precision and recall at a given cutoff for each user. In information
retrieval terms, precision represents the ratio of relevant, retrieved items
to the... | def function[precision_recall_by_user, parameter[observed_user_items, recommendations, cutoffs]]:
constant[
Compute precision and recall at a given cutoff for each user. In information
retrieval terms, precision represents the ratio of relevant, retrieved items
to the number of relevant items. Recal... | keyword[def] identifier[precision_recall_by_user] ( identifier[observed_user_items] ,
identifier[recommendations] ,
identifier[cutoffs] =[ literal[int] ]):
literal[string]
keyword[assert] identifier[type] ( identifier[observed_user_items] )== identifier[_SFrame]
keyword[assert] identifier[type] ... | def precision_recall_by_user(observed_user_items, recommendations, cutoffs=[10]):
"""
Compute precision and recall at a given cutoff for each user. In information
retrieval terms, precision represents the ratio of relevant, retrieved items
to the number of relevant items. Recall represents the ratio of ... |
def construct_streamreader_callback(process, handler):
""" here we're constructing a closure for our streamreader callback. this
is used in the case that we pass a callback into _out or _err, meaning we
want to our callback to handle each bit of output
we construct the closure based on how many argume... | def function[construct_streamreader_callback, parameter[process, handler]]:
constant[ here we're constructing a closure for our streamreader callback. this
is used in the case that we pass a callback into _out or _err, meaning we
want to our callback to handle each bit of output
we construct the c... | keyword[def] identifier[construct_streamreader_callback] ( identifier[process] , identifier[handler] ):
literal[string]
identifier[implied_arg] = literal[int]
identifier[partial_args] = literal[int]
identifier[handler_to_inspect] = identifier[handler]
keyword[if] ident... | def construct_streamreader_callback(process, handler):
""" here we're constructing a closure for our streamreader callback. this
is used in the case that we pass a callback into _out or _err, meaning we
want to our callback to handle each bit of output
we construct the closure based on how many argume... |
def search(self, term, type='place', page=False, retry=3, **options):
"""
Search for an item in the Graph API.
:param term: A string describing the search term.
:param type: A string describing the type of items to search for.
:param page: A boolean describing whether to return ... | def function[search, parameter[self, term, type, page, retry]]:
constant[
Search for an item in the Graph API.
:param term: A string describing the search term.
:param type: A string describing the type of items to search for.
:param page: A boolean describing whether to return ... | keyword[def] identifier[search] ( identifier[self] , identifier[term] , identifier[type] = literal[string] , identifier[page] = keyword[False] , identifier[retry] = literal[int] ,** identifier[options] ):
literal[string]
keyword[if] identifier[type] != literal[string] :
keyword[raise... | def search(self, term, type='place', page=False, retry=3, **options):
"""
Search for an item in the Graph API.
:param term: A string describing the search term.
:param type: A string describing the type of items to search for.
:param page: A boolean describing whether to return a ge... |
def slot_remove_nio_binding(self, slot_number, port_number):
"""
Removes a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:returns: removed NIO instance
"""
try:
adapter = self._slots[slot_number]
except In... | def function[slot_remove_nio_binding, parameter[self, slot_number, port_number]]:
constant[
Removes a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:returns: removed NIO instance
]
<ast.Try object at 0x7da20e74be20>
if com... | keyword[def] identifier[slot_remove_nio_binding] ( identifier[self] , identifier[slot_number] , identifier[port_number] ):
literal[string]
keyword[try] :
identifier[adapter] = identifier[self] . identifier[_slots] [ identifier[slot_number] ]
keyword[except] identifier[IndexE... | def slot_remove_nio_binding(self, slot_number, port_number):
"""
Removes a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:returns: removed NIO instance
"""
try:
adapter = self._slots[slot_number] # depends on [control=['try']... |
def write(self, page, data):
"""Send a WRITE command to store data on the tag.
The *page* argument specifies the offset in multiples of 4
bytes. The *data* argument must be a string or bytearray of
length 4.
Command execution errors raise :exc:`Type2TagCommandError`.
"... | def function[write, parameter[self, page, data]]:
constant[Send a WRITE command to store data on the tag.
The *page* argument specifies the offset in multiples of 4
bytes. The *data* argument must be a string or bytearray of
length 4.
Command execution errors raise :exc:`Type2T... | keyword[def] identifier[write] ( identifier[self] , identifier[page] , identifier[data] ):
literal[string]
keyword[if] identifier[len] ( identifier[data] )!= literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[log] . identifier[debug] ( liter... | def write(self, page, data):
"""Send a WRITE command to store data on the tag.
The *page* argument specifies the offset in multiples of 4
bytes. The *data* argument must be a string or bytearray of
length 4.
Command execution errors raise :exc:`Type2TagCommandError`.
"""
... |
def _file_op(source, destination, func, adapter, fatal, logger, must_exist=True, ignore=None):
"""Call func(source, destination)
Args:
source (str | None): Source file or folder
destination (str | None): Destination file or folder
func (callable): Implementation function
adapter... | def function[_file_op, parameter[source, destination, func, adapter, fatal, logger, must_exist, ignore]]:
constant[Call func(source, destination)
Args:
source (str | None): Source file or folder
destination (str | None): Destination file or folder
func (callable): Implementation fun... | keyword[def] identifier[_file_op] ( identifier[source] , identifier[destination] , identifier[func] , identifier[adapter] , identifier[fatal] , identifier[logger] , identifier[must_exist] = keyword[True] , identifier[ignore] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[source] ... | def _file_op(source, destination, func, adapter, fatal, logger, must_exist=True, ignore=None):
"""Call func(source, destination)
Args:
source (str | None): Source file or folder
destination (str | None): Destination file or folder
func (callable): Implementation function
adapter... |
def coordinates(value):
"""
Convert a non-empty string into a list of lon-lat coordinates.
>>> coordinates('')
Traceback (most recent call last):
...
ValueError: Empty list of coordinates: ''
>>> coordinates('1.1 1.2')
[(1.1, 1.2, 0.0)]
>>> coordinates('1.1 1.2, 2.2 2.3')
[(1.1,... | def function[coordinates, parameter[value]]:
constant[
Convert a non-empty string into a list of lon-lat coordinates.
>>> coordinates('')
Traceback (most recent call last):
...
ValueError: Empty list of coordinates: ''
>>> coordinates('1.1 1.2')
[(1.1, 1.2, 0.0)]
>>> coordinates... | keyword[def] identifier[coordinates] ( identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[value] . identifier[strip] ():
keyword[raise] identifier[ValueError] ( literal[string] % identifier[value] )
identifier[points] =[]
identifier[pointset] = identifier[set] ()... | def coordinates(value):
"""
Convert a non-empty string into a list of lon-lat coordinates.
>>> coordinates('')
Traceback (most recent call last):
...
ValueError: Empty list of coordinates: ''
>>> coordinates('1.1 1.2')
[(1.1, 1.2, 0.0)]
>>> coordinates('1.1 1.2, 2.2 2.3')
[(1.1,... |
def find_root_path(absolute_path, relative_path):
"""
Return the root path of a path relative to an absolute path.
Example:
@param absolute_path: an absolute path that is ended by the specified
relative path.
@param relative_path: a relative path that ends the specified absolute
p... | def function[find_root_path, parameter[absolute_path, relative_path]]:
constant[
Return the root path of a path relative to an absolute path.
Example:
@param absolute_path: an absolute path that is ended by the specified
relative path.
@param relative_path: a relative path that ends t... | keyword[def] identifier[find_root_path] ( identifier[absolute_path] , identifier[relative_path] ):
literal[string]
identifier[_absolute_path] = identifier[os] . identifier[path] . identifier[normpath] ( identifier[absolute_path] )
identifier[_relative_path] = identifier[os] . identifier[path] . identi... | def find_root_path(absolute_path, relative_path):
"""
Return the root path of a path relative to an absolute path.
Example:
@param absolute_path: an absolute path that is ended by the specified
relative path.
@param relative_path: a relative path that ends the specified absolute
p... |
def set_wts_get_npred_wt(gta, maskname):
"""Set a weights file and get the weighted npred for all the sources
Parameters
----------
gta : `fermipy.GTAnalysis`
The analysis object
maskname : str
The path to the file with the mask
Returns
-------
odict : dict
... | def function[set_wts_get_npred_wt, parameter[gta, maskname]]:
constant[Set a weights file and get the weighted npred for all the sources
Parameters
----------
gta : `fermipy.GTAnalysis`
The analysis object
maskname : str
The path to the file with the mask
Returns
---... | keyword[def] identifier[set_wts_get_npred_wt] ( identifier[gta] , identifier[maskname] ):
literal[string]
keyword[if] identifier[is_null] ( identifier[maskname] ):
identifier[maskname] = keyword[None]
identifier[gta] . identifier[set_weights_map] ( identifier[maskname] )
keyword[for] ... | def set_wts_get_npred_wt(gta, maskname):
"""Set a weights file and get the weighted npred for all the sources
Parameters
----------
gta : `fermipy.GTAnalysis`
The analysis object
maskname : str
The path to the file with the mask
Returns
-------
odict : dict
... |
def rmsd(df1, df2, heavy_only=True):
"""Compute the Root Mean Square Deviation between molecules
Parameters
----------
df1 : pandas.DataFrame
DataFrame with HETATM, ATOM, and/or ANISOU entries
df2 : pandas.DataFrame
Second DataFrame for RMSD computation a... | def function[rmsd, parameter[df1, df2, heavy_only]]:
constant[Compute the Root Mean Square Deviation between molecules
Parameters
----------
df1 : pandas.DataFrame
DataFrame with HETATM, ATOM, and/or ANISOU entries
df2 : pandas.DataFrame
Second DataFrame ... | keyword[def] identifier[rmsd] ( identifier[df1] , identifier[df2] , identifier[heavy_only] = keyword[True] ):
literal[string]
keyword[if] identifier[df1] . identifier[shape] [ literal[int] ]!= identifier[df2] . identifier[shape] [ literal[int] ]:
keyword[raise] identifier[AttributeEr... | def rmsd(df1, df2, heavy_only=True):
"""Compute the Root Mean Square Deviation between molecules
Parameters
----------
df1 : pandas.DataFrame
DataFrame with HETATM, ATOM, and/or ANISOU entries
df2 : pandas.DataFrame
Second DataFrame for RMSD computation again... |
def is_submodule(self, name):
"""
Returns `True` if and only if `name` starts with the full
import path of `self` and has length at least one greater than
`len(self.name)`.
"""
return self.name != name and name.startswith(self.name) | def function[is_submodule, parameter[self, name]]:
constant[
Returns `True` if and only if `name` starts with the full
import path of `self` and has length at least one greater than
`len(self.name)`.
]
return[<ast.BoolOp object at 0x7da2054a4ac0>] | keyword[def] identifier[is_submodule] ( identifier[self] , identifier[name] ):
literal[string]
keyword[return] identifier[self] . identifier[name] != identifier[name] keyword[and] identifier[name] . identifier[startswith] ( identifier[self] . identifier[name] ) | def is_submodule(self, name):
"""
Returns `True` if and only if `name` starts with the full
import path of `self` and has length at least one greater than
`len(self.name)`.
"""
return self.name != name and name.startswith(self.name) |
def get_fastq_files_props(self,barcode=None):
"""
Returns the DNAnexus file properties for all FASTQ files in the project that match the
specified barcode, or all FASTQ files if not barcode is specified.
Args:
barcode: `str`. If set, then only FASTQ file properties for FA... | def function[get_fastq_files_props, parameter[self, barcode]]:
constant[
Returns the DNAnexus file properties for all FASTQ files in the project that match the
specified barcode, or all FASTQ files if not barcode is specified.
Args:
barcode: `str`. If set, then only FASTQ... | keyword[def] identifier[get_fastq_files_props] ( identifier[self] , identifier[barcode] = keyword[None] ):
literal[string]
identifier[fastqs] = identifier[self] . identifier[get_fastq_dxfile_objects] ( identifier[barcode] = identifier[barcode] )
identifier[dico] ={}
keyword[for] ... | def get_fastq_files_props(self, barcode=None):
"""
Returns the DNAnexus file properties for all FASTQ files in the project that match the
specified barcode, or all FASTQ files if not barcode is specified.
Args:
barcode: `str`. If set, then only FASTQ file properties for FASTQ... |
def processTPED(uniqueSNPs, mapF, fileName, tfam, prefix):
"""Process the TPED file.
:param uniqueSNPs: the unique markers.
:param mapF: a representation of the ``map`` file.
:param fileName: the name of the ``tped`` file.
:param tfam: the name of the ``tfam`` file.
:param prefix: the prefix of... | def function[processTPED, parameter[uniqueSNPs, mapF, fileName, tfam, prefix]]:
constant[Process the TPED file.
:param uniqueSNPs: the unique markers.
:param mapF: a representation of the ``map`` file.
:param fileName: the name of the ``tped`` file.
:param tfam: the name of the ``tfam`` file.
... | keyword[def] identifier[processTPED] ( identifier[uniqueSNPs] , identifier[mapF] , identifier[fileName] , identifier[tfam] , identifier[prefix] ):
literal[string]
keyword[try] :
identifier[shutil] . identifier[copy] ( identifier[tfam] , identifier[prefix] + literal[string] )
keyword[exce... | def processTPED(uniqueSNPs, mapF, fileName, tfam, prefix):
"""Process the TPED file.
:param uniqueSNPs: the unique markers.
:param mapF: a representation of the ``map`` file.
:param fileName: the name of the ``tped`` file.
:param tfam: the name of the ``tfam`` file.
:param prefix: the prefix of... |
def strftime(date_time=None, time_format=None):
"""
将 datetime 对象转换为 str
:param:
* date_time: (obj) datetime 对象
* time_format: (sting) 日期格式字符串
:return:
* date_time_str: (string) 日期字符串
"""
if not date_time:
datetime_now = da... | def function[strftime, parameter[date_time, time_format]]:
constant[
将 datetime 对象转换为 str
:param:
* date_time: (obj) datetime 对象
* time_format: (sting) 日期格式字符串
:return:
* date_time_str: (string) 日期字符串
]
if <ast.UnaryOp object at 0x7da1... | keyword[def] identifier[strftime] ( identifier[date_time] = keyword[None] , identifier[time_format] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[date_time] :
identifier[datetime_now] = identifier[datetime] . identifier[now] ()
keyword[else] :
... | def strftime(date_time=None, time_format=None):
"""
将 datetime 对象转换为 str
:param:
* date_time: (obj) datetime 对象
* time_format: (sting) 日期格式字符串
:return:
* date_time_str: (string) 日期字符串
"""
if not date_time:
datetime_now = datetime.now()... |
def which(executable_name, env_var='PATH'):
"""Equivalent to ``which executable_name`` in a *nix environment.
Will return ``None`` if ``executable_name`` cannot be found in ``env_var``
or if ``env_var`` is not set. Otherwise will return the first match in
``env_var``.
Note: this function will like... | def function[which, parameter[executable_name, env_var]]:
constant[Equivalent to ``which executable_name`` in a *nix environment.
Will return ``None`` if ``executable_name`` cannot be found in ``env_var``
or if ``env_var`` is not set. Otherwise will return the first match in
``env_var``.
Note:... | keyword[def] identifier[which] ( identifier[executable_name] , identifier[env_var] = literal[string] ):
literal[string]
identifier[exec_fp] = keyword[None]
keyword[if] identifier[env_var] keyword[in] identifier[os] . identifier[environ] :
identifier[paths] = identifier[os] . identifier[e... | def which(executable_name, env_var='PATH'):
"""Equivalent to ``which executable_name`` in a *nix environment.
Will return ``None`` if ``executable_name`` cannot be found in ``env_var``
or if ``env_var`` is not set. Otherwise will return the first match in
``env_var``.
Note: this function will like... |
def get_parent_families(self, family_id):
"""Gets the parent families of the given ``id``.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` to
query
return: (osid.relationship.FamilyList) - the parent families of
the ``id``
raise: NotFound - ... | def function[get_parent_families, parameter[self, family_id]]:
constant[Gets the parent families of the given ``id``.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` to
query
return: (osid.relationship.FamilyList) - the parent families of
the ``id``
... | keyword[def] identifier[get_parent_families] ( identifier[self] , identifier[family_id] ):
literal[string]
keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_catalog_... | def get_parent_families(self, family_id):
"""Gets the parent families of the given ``id``.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` to
query
return: (osid.relationship.FamilyList) - the parent families of
the ``id``
raise: NotFound - a ``... |
def register (self, target):
""" Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and 'target' is not registered... | def function[register, parameter[self, target]]:
constant[ Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and ... | keyword[def] identifier[register] ( identifier[self] , identifier[target] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[target] , identifier[VirtualTarget] )
keyword[if] identifier[target] . identifier[path] ():
identifier[signature] = identifier[tar... | def register(self, target):
""" Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and 'target' is not registered.
... |
def clear(name):
'''
Clear the namespace from the register
USAGE:
.. code-block:: yaml
clearns:
reg.clear:
- name: myregister
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
if name in __reg__:
_... | def function[clear, parameter[name]]:
constant[
Clear the namespace from the register
USAGE:
.. code-block:: yaml
clearns:
reg.clear:
- name: myregister
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da1b1fa3610>, <ast.Constant object at... | keyword[def] identifier[clear] ( identifier[name] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : literal[string] ,
literal[string] : keyword[True] }
keyword[if] identifier[name] keyword[in] identifier[__reg__] :
... | def clear(name):
"""
Clear the namespace from the register
USAGE:
.. code-block:: yaml
clearns:
reg.clear:
- name: myregister
"""
ret = {'name': name, 'changes': {}, 'comment': '', 'result': True}
if name in __reg__:
__reg__[name].clear() # depends o... |
def get_page_kwargs(**kwargs):
"""Construct page and page size kwargs (if present)."""
page_kwargs = {}
page = kwargs.get("page")
if page is not None and page > 0:
page_kwargs["page"] = page
page_size = kwargs.get("page_size")
if page_size is not None and page_size > 0:
page_kw... | def function[get_page_kwargs, parameter[]]:
constant[Construct page and page size kwargs (if present).]
variable[page_kwargs] assign[=] dictionary[[], []]
variable[page] assign[=] call[name[kwargs].get, parameter[constant[page]]]
if <ast.BoolOp object at 0x7da1b1a3e8f0> begin[:]
... | keyword[def] identifier[get_page_kwargs] (** identifier[kwargs] ):
literal[string]
identifier[page_kwargs] ={}
identifier[page] = identifier[kwargs] . identifier[get] ( literal[string] )
keyword[if] identifier[page] keyword[is] keyword[not] keyword[None] keyword[and] identifier[page] > lit... | def get_page_kwargs(**kwargs):
"""Construct page and page size kwargs (if present)."""
page_kwargs = {}
page = kwargs.get('page')
if page is not None and page > 0:
page_kwargs['page'] = page # depends on [control=['if'], data=[]]
page_size = kwargs.get('page_size')
if page_size is not N... |
def read_source_models(fnames, converter, monitor):
"""
:param fnames:
list of source model files
:param converter:
a SourceConverter instance
:param monitor:
a :class:`openquake.performance.Monitor` instance
:yields:
SourceModel instances
"""
for fname in fna... | def function[read_source_models, parameter[fnames, converter, monitor]]:
constant[
:param fnames:
list of source model files
:param converter:
a SourceConverter instance
:param monitor:
a :class:`openquake.performance.Monitor` instance
:yields:
SourceModel instanc... | keyword[def] identifier[read_source_models] ( identifier[fnames] , identifier[converter] , identifier[monitor] ):
literal[string]
keyword[for] identifier[fname] keyword[in] identifier[fnames] :
keyword[if] identifier[fname] . identifier[endswith] (( literal[string] , literal[string] )):
... | def read_source_models(fnames, converter, monitor):
"""
:param fnames:
list of source model files
:param converter:
a SourceConverter instance
:param monitor:
a :class:`openquake.performance.Monitor` instance
:yields:
SourceModel instances
"""
for fname in fna... |
def _pythonized_comments(tokens):
"""
Similar to tokens but converts strings after a colon (:) to comments.
"""
is_after_colon = True
for token_type, token_text in tokens:
if is_after_colon and (token_type in pygments.token.String):
token_type = pygments.token.Comment
eli... | def function[_pythonized_comments, parameter[tokens]]:
constant[
Similar to tokens but converts strings after a colon (:) to comments.
]
variable[is_after_colon] assign[=] constant[True]
for taget[tuple[[<ast.Name object at 0x7da204623820>, <ast.Name object at 0x7da204623700>]]] in starr... | keyword[def] identifier[_pythonized_comments] ( identifier[tokens] ):
literal[string]
identifier[is_after_colon] = keyword[True]
keyword[for] identifier[token_type] , identifier[token_text] keyword[in] identifier[tokens] :
keyword[if] identifier[is_after_colon] keyword[and] ( identifier... | def _pythonized_comments(tokens):
"""
Similar to tokens but converts strings after a colon (:) to comments.
"""
is_after_colon = True
for (token_type, token_text) in tokens:
if is_after_colon and token_type in pygments.token.String:
token_type = pygments.token.Comment # depends ... |
def write_json_response(self, response):
""" write back json response """
self.write(tornado.escape.json_encode(response))
self.set_header("Content-Type", "application/json") | def function[write_json_response, parameter[self, response]]:
constant[ write back json response ]
call[name[self].write, parameter[call[name[tornado].escape.json_encode, parameter[name[response]]]]]
call[name[self].set_header, parameter[constant[Content-Type], constant[application/json]]] | keyword[def] identifier[write_json_response] ( identifier[self] , identifier[response] ):
literal[string]
identifier[self] . identifier[write] ( identifier[tornado] . identifier[escape] . identifier[json_encode] ( identifier[response] ))
identifier[self] . identifier[set_header] ( literal[string] , li... | def write_json_response(self, response):
""" write back json response """
self.write(tornado.escape.json_encode(response))
self.set_header('Content-Type', 'application/json') |
def perspective(img, startpoints, endpoints, interpolation=Image.BICUBIC):
"""Perform perspective transform of the given PIL Image.
Args:
img (PIL Image): Image to be transformed.
coeffs (tuple) : 8-tuple (a, b, c, d, e, f, g, h) which contains the coefficients.
for ... | def function[perspective, parameter[img, startpoints, endpoints, interpolation]]:
constant[Perform perspective transform of the given PIL Image.
Args:
img (PIL Image): Image to be transformed.
coeffs (tuple) : 8-tuple (a, b, c, d, e, f, g, h) which contains the coefficients.
... | keyword[def] identifier[perspective] ( identifier[img] , identifier[startpoints] , identifier[endpoints] , identifier[interpolation] = identifier[Image] . identifier[BICUBIC] ):
literal[string]
keyword[if] keyword[not] identifier[_is_pil_image] ( identifier[img] ):
keyword[raise] identifier[Typ... | def perspective(img, startpoints, endpoints, interpolation=Image.BICUBIC):
"""Perform perspective transform of the given PIL Image.
Args:
img (PIL Image): Image to be transformed.
coeffs (tuple) : 8-tuple (a, b, c, d, e, f, g, h) which contains the coefficients.
for ... |
def multipath_flush(device):
'''
Device-Mapper Multipath flush
CLI Example:
.. code-block:: bash
salt '*' devmap.multipath_flush mpath1
'''
if not os.path.exists(device):
return '{0} does not exist'.format(device)
cmd = 'multipath -f {0}'.format(device)
return __salt_... | def function[multipath_flush, parameter[device]]:
constant[
Device-Mapper Multipath flush
CLI Example:
.. code-block:: bash
salt '*' devmap.multipath_flush mpath1
]
if <ast.UnaryOp object at 0x7da20e74b1f0> begin[:]
return[call[constant[{0} does not exist].format, para... | keyword[def] identifier[multipath_flush] ( identifier[device] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[device] ):
keyword[return] literal[string] . identifier[format] ( identifier[device] )
identifier[cmd] = literal[st... | def multipath_flush(device):
"""
Device-Mapper Multipath flush
CLI Example:
.. code-block:: bash
salt '*' devmap.multipath_flush mpath1
"""
if not os.path.exists(device):
return '{0} does not exist'.format(device) # depends on [control=['if'], data=[]]
cmd = 'multipath -f... |
def get_nameserver_detail_output_show_nameserver_nameserver_permanent_portname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_nameserver_detail = ET.Element("get_nameserver_detail")
config = get_nameserver_detail
output = ET.SubElement(get_n... | def function[get_nameserver_detail_output_show_nameserver_nameserver_permanent_portname, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_nameserver_detail] assign[=] call[name[ET].Element, parame... | keyword[def] identifier[get_nameserver_detail_output_show_nameserver_nameserver_permanent_portname] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_nameserver_detail] = identifier[ET] ... | def get_nameserver_detail_output_show_nameserver_nameserver_permanent_portname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_nameserver_detail = ET.Element('get_nameserver_detail')
config = get_nameserver_detail
output = ET.SubElement(get_nameserver_detail, 'o... |
def generate_records(self, infile):
""" Process a file of rest and yield dictionaries """
state = 0
record = {}
for item in self.generate_lines(infile):
line = item['line']
heading = item['heading']
# any Markdown heading is just a capt... | def function[generate_records, parameter[self, infile]]:
constant[ Process a file of rest and yield dictionaries ]
variable[state] assign[=] constant[0]
variable[record] assign[=] dictionary[[], []]
for taget[name[item]] in starred[call[name[self].generate_lines, parameter[name[infile]]]... | keyword[def] identifier[generate_records] ( identifier[self] , identifier[infile] ):
literal[string]
identifier[state] = literal[int]
identifier[record] ={}
keyword[for] identifier[item] keyword[in] identifier[self] . identifier[generate_lines] ( identifier[infile] ):
... | def generate_records(self, infile):
""" Process a file of rest and yield dictionaries """
state = 0
record = {}
for item in self.generate_lines(infile):
line = item['line']
heading = item['heading']
# any Markdown heading is just a caption, no image
if heading:
... |
def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(Header, self).Serialize(writer)
writer.WriteByte(0) | def function[Serialize, parameter[self, writer]]:
constant[
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
]
call[call[name[super], parameter[name[Header], name[self]]].Serialize, parameter[name[writer]]]
call[name[writer].WriteByte, parameter[con... | keyword[def] identifier[Serialize] ( identifier[self] , identifier[writer] ):
literal[string]
identifier[super] ( identifier[Header] , identifier[self] ). identifier[Serialize] ( identifier[writer] )
identifier[writer] . identifier[WriteByte] ( literal[int] ) | def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(Header, self).Serialize(writer)
writer.WriteByte(0) |
def samtools_index(self, bam_file):
"""Index a bam file."""
cmd = self.tools.samtools + " index {0}".format(bam_file)
return cmd | def function[samtools_index, parameter[self, bam_file]]:
constant[Index a bam file.]
variable[cmd] assign[=] binary_operation[name[self].tools.samtools + call[constant[ index {0}].format, parameter[name[bam_file]]]]
return[name[cmd]] | keyword[def] identifier[samtools_index] ( identifier[self] , identifier[bam_file] ):
literal[string]
identifier[cmd] = identifier[self] . identifier[tools] . identifier[samtools] + literal[string] . identifier[format] ( identifier[bam_file] )
keyword[return] identifier[cmd] | def samtools_index(self, bam_file):
"""Index a bam file."""
cmd = self.tools.samtools + ' index {0}'.format(bam_file)
return cmd |
def _build_zmat(self, construction_table):
"""Create the Zmatrix from a construction table.
Args:
Construction table (pd.DataFrame):
Returns:
Zmat: A new instance of :class:`Zmat`.
"""
c_table = construction_table
default_cols = ['atom', 'b', 'bo... | def function[_build_zmat, parameter[self, construction_table]]:
constant[Create the Zmatrix from a construction table.
Args:
Construction table (pd.DataFrame):
Returns:
Zmat: A new instance of :class:`Zmat`.
]
variable[c_table] assign[=] name[constructio... | keyword[def] identifier[_build_zmat] ( identifier[self] , identifier[construction_table] ):
literal[string]
identifier[c_table] = identifier[construction_table]
identifier[default_cols] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[st... | def _build_zmat(self, construction_table):
"""Create the Zmatrix from a construction table.
Args:
Construction table (pd.DataFrame):
Returns:
Zmat: A new instance of :class:`Zmat`.
"""
c_table = construction_table
default_cols = ['atom', 'b', 'bond', 'a', 'a... |
def select_where(self, table, cols, pk_att, pk):
'''
SELECT with WHERE clause.
:param table: target table
:param cols: list of columns to select
:param pk_att: attribute for the where clause
:param pk: the id that the pk_att should match
:retu... | def function[select_where, parameter[self, table, cols, pk_att, pk]]:
constant[
SELECT with WHERE clause.
:param table: target table
:param cols: list of columns to select
:param pk_att: attribute for the where clause
:param pk: the id that the pk_att sho... | keyword[def] identifier[select_where] ( identifier[self] , identifier[table] , identifier[cols] , identifier[pk_att] , identifier[pk] ):
literal[string]
keyword[if] identifier[self] . identifier[orng_tables] :
identifier[data] =[]
keyword[for] identifier[ex] keyword[in]... | def select_where(self, table, cols, pk_att, pk):
"""
SELECT with WHERE clause.
:param table: target table
:param cols: list of columns to select
:param pk_att: attribute for the where clause
:param pk: the id that the pk_att should match
:return: ... |
def get(cls, resource_id):
"""Returns the class object identified by `resource_id`
Args:
resource_id (str): Unique EC2 Instance ID to load from database
Returns:
EC2 Instance object if found, else None
"""
res = Resource.get(resource_id)
return c... | def function[get, parameter[cls, resource_id]]:
constant[Returns the class object identified by `resource_id`
Args:
resource_id (str): Unique EC2 Instance ID to load from database
Returns:
EC2 Instance object if found, else None
]
variable[res] assign[=]... | keyword[def] identifier[get] ( identifier[cls] , identifier[resource_id] ):
literal[string]
identifier[res] = identifier[Resource] . identifier[get] ( identifier[resource_id] )
keyword[return] identifier[cls] ( identifier[res] ) keyword[if] identifier[res] keyword[else] keyword[None] | def get(cls, resource_id):
"""Returns the class object identified by `resource_id`
Args:
resource_id (str): Unique EC2 Instance ID to load from database
Returns:
EC2 Instance object if found, else None
"""
res = Resource.get(resource_id)
return cls(res) if r... |
def _RunAndWaitForVFSFileUpdate(self, path):
"""Runs a flow on the client, and waits for it to finish."""
client_id = rdf_client.GetClientURNFromPath(path)
# If we're not actually in a directory on a client, no need to run a flow.
if client_id is None:
return
flow_utils.UpdateVFSFileAndWait... | def function[_RunAndWaitForVFSFileUpdate, parameter[self, path]]:
constant[Runs a flow on the client, and waits for it to finish.]
variable[client_id] assign[=] call[name[rdf_client].GetClientURNFromPath, parameter[name[path]]]
if compare[name[client_id] is constant[None]] begin[:]
retur... | keyword[def] identifier[_RunAndWaitForVFSFileUpdate] ( identifier[self] , identifier[path] ):
literal[string]
identifier[client_id] = identifier[rdf_client] . identifier[GetClientURNFromPath] ( identifier[path] )
keyword[if] identifier[client_id] keyword[is] keyword[None] :
keyword[re... | def _RunAndWaitForVFSFileUpdate(self, path):
"""Runs a flow on the client, and waits for it to finish."""
client_id = rdf_client.GetClientURNFromPath(path)
# If we're not actually in a directory on a client, no need to run a flow.
if client_id is None:
return # depends on [control=['if'], data=... |
def _fsync_files(filenames):
"""Call fsync() a list of file names
The filenames should be absolute paths already.
"""
touched_directories = set()
mode = os.O_RDONLY
# Windows
if hasattr(os, 'O_BINARY'):
mode |= os.O_BINARY
for filename in filenames:
fd = os.open(file... | def function[_fsync_files, parameter[filenames]]:
constant[Call fsync() a list of file names
The filenames should be absolute paths already.
]
variable[touched_directories] assign[=] call[name[set], parameter[]]
variable[mode] assign[=] name[os].O_RDONLY
if call[name[hasattr], ... | keyword[def] identifier[_fsync_files] ( identifier[filenames] ):
literal[string]
identifier[touched_directories] = identifier[set] ()
identifier[mode] = identifier[os] . identifier[O_RDONLY]
keyword[if] identifier[hasattr] ( identifier[os] , literal[string] ):
identifier[mode] |... | def _fsync_files(filenames):
"""Call fsync() a list of file names
The filenames should be absolute paths already.
"""
touched_directories = set()
mode = os.O_RDONLY
# Windows
if hasattr(os, 'O_BINARY'):
mode |= os.O_BINARY # depends on [control=['if'], data=[]]
for filename in... |
def create_file(self, share_name, directory_name, file_name,
content_length, content_settings=None, metadata=None,
timeout=None):
'''
Creates a new file.
See create_file_from_* for high level functions that handle the
creation and upload of large ... | def function[create_file, parameter[self, share_name, directory_name, file_name, content_length, content_settings, metadata, timeout]]:
constant[
Creates a new file.
See create_file_from_* for high level functions that handle the
creation and upload of large files with automatic chunkin... | keyword[def] identifier[create_file] ( identifier[self] , identifier[share_name] , identifier[directory_name] , identifier[file_name] ,
identifier[content_length] , identifier[content_settings] = keyword[None] , identifier[metadata] = keyword[None] ,
identifier[timeout] = keyword[None] ):
literal[string]
... | def create_file(self, share_name, directory_name, file_name, content_length, content_settings=None, metadata=None, timeout=None):
"""
Creates a new file.
See create_file_from_* for high level functions that handle the
creation and upload of large files with automatic chunking and
pr... |
def decode_keys(store, encoding='utf-8'):
"""
If a dictionary has keys that are bytes decode them to a str.
Parameters
---------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are converted to ASCII stri... | def function[decode_keys, parameter[store, encoding]]:
constant[
If a dictionary has keys that are bytes decode them to a str.
Parameters
---------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are ... | keyword[def] identifier[decode_keys] ( identifier[store] , identifier[encoding] = literal[string] ):
literal[string]
identifier[keys] = identifier[store] . identifier[keys] ()
keyword[for] identifier[key] keyword[in] identifier[keys] :
keyword[if] identifier[hasattr] ( identifier[key] , l... | def decode_keys(store, encoding='utf-8'):
"""
If a dictionary has keys that are bytes decode them to a str.
Parameters
---------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are converted to ASCII stri... |
def distance_inches_ping(self):
"""
Measurement of the distance detected by the sensor,
in inches.
The sensor will take a single measurement then stop
broadcasting.
If you use this property too frequently (e.g. every
100msec), the sensor will sometimes lock up a... | def function[distance_inches_ping, parameter[self]]:
constant[
Measurement of the distance detected by the sensor,
in inches.
The sensor will take a single measurement then stop
broadcasting.
If you use this property too frequently (e.g. every
100msec), the sens... | keyword[def] identifier[distance_inches_ping] ( identifier[self] ):
literal[string]
identifier[self] . identifier[mode] = identifier[self] . identifier[MODE_US_SI_IN]
keyword[return] identifier[self] . identifier[value] ( literal[int] )* identifier[self] . identifier[_s... | def distance_inches_ping(self):
"""
Measurement of the distance detected by the sensor,
in inches.
The sensor will take a single measurement then stop
broadcasting.
If you use this property too frequently (e.g. every
100msec), the sensor will sometimes lock up and w... |
def url(self):
"""Returns the public URL for the given key."""
if self.is_public:
return '{0}/{1}/{2}'.format(
self.bucket._boto_s3.meta.client.meta.endpoint_url,
self.bucket.name,
self.name
)
else:
raise ValueEr... | def function[url, parameter[self]]:
constant[Returns the public URL for the given key.]
if name[self].is_public begin[:]
return[call[constant[{0}/{1}/{2}].format, parameter[name[self].bucket._boto_s3.meta.client.meta.endpoint_url, name[self].bucket.name, name[self].name]]] | keyword[def] identifier[url] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_public] :
keyword[return] literal[string] . identifier[format] (
identifier[self] . identifier[bucket] . identifier[_boto_s3] . identifier[meta] . identifier[c... | def url(self):
"""Returns the public URL for the given key."""
if self.is_public:
return '{0}/{1}/{2}'.format(self.bucket._boto_s3.meta.client.meta.endpoint_url, self.bucket.name, self.name) # depends on [control=['if'], data=[]]
else:
raise ValueError('{0!r} does not have the public-read A... |
def square_batch_region(data, region, bam_files, vrn_files, out_file):
"""Perform squaring of a batch in a supplied region, with input BAMs
"""
from bcbio.variation import sentieon, strelka2
if not utils.file_exists(out_file):
jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data)... | def function[square_batch_region, parameter[data, region, bam_files, vrn_files, out_file]]:
constant[Perform squaring of a batch in a supplied region, with input BAMs
]
from relative_module[bcbio.variation] import module[sentieon], module[strelka2]
if <ast.UnaryOp object at 0x7da1b1833700> begin... | keyword[def] identifier[square_batch_region] ( identifier[data] , identifier[region] , identifier[bam_files] , identifier[vrn_files] , identifier[out_file] ):
literal[string]
keyword[from] identifier[bcbio] . identifier[variation] keyword[import] identifier[sentieon] , identifier[strelka2]
keyword... | def square_batch_region(data, region, bam_files, vrn_files, out_file):
"""Perform squaring of a batch in a supplied region, with input BAMs
"""
from bcbio.variation import sentieon, strelka2
if not utils.file_exists(out_file):
jointcaller = tz.get_in(('config', 'algorithm', 'jointcaller'), data)... |
def polylinesFromBinImage(img, minimum_cluster_size=6,
remove_small_obj_size=3,
reconnect_size=3,
max_n_contours=None, max_len_contour=None,
copy=True):
'''
return a list of arrays of un-branching conto... | def function[polylinesFromBinImage, parameter[img, minimum_cluster_size, remove_small_obj_size, reconnect_size, max_n_contours, max_len_contour, copy]]:
constant[
return a list of arrays of un-branching contours
img -> (boolean) array
optional:
---------
minimum_cluster_size -> minimum nu... | keyword[def] identifier[polylinesFromBinImage] ( identifier[img] , identifier[minimum_cluster_size] = literal[int] ,
identifier[remove_small_obj_size] = literal[int] ,
identifier[reconnect_size] = literal[int] ,
identifier[max_n_contours] = keyword[None] , identifier[max_len_contour] = keyword[None] ,
identif... | def polylinesFromBinImage(img, minimum_cluster_size=6, remove_small_obj_size=3, reconnect_size=3, max_n_contours=None, max_len_contour=None, copy=True):
"""
return a list of arrays of un-branching contours
img -> (boolean) array
optional:
---------
minimum_cluster_size -> minimum number of pi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.