code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def symlink_exists(self, symlink):
"""Checks whether a symbolic link exists in the guest.
in symlink of type str
Path to the alleged symbolic link. Guest path style.
return exists of type bool
Returns @c true if the symbolic link exists. Returns @c false if it
... | def function[symlink_exists, parameter[self, symlink]]:
constant[Checks whether a symbolic link exists in the guest.
in symlink of type str
Path to the alleged symbolic link. Guest path style.
return exists of type bool
Returns @c true if the symbolic link exists. Ret... | keyword[def] identifier[symlink_exists] ( identifier[self] , identifier[symlink] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[symlink] , identifier[basestring] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[exists] ... | def symlink_exists(self, symlink):
"""Checks whether a symbolic link exists in the guest.
in symlink of type str
Path to the alleged symbolic link. Guest path style.
return exists of type bool
Returns @c true if the symbolic link exists. Returns @c false if it
... |
def op(
name,
labels,
predictions,
num_thresholds=None,
weights=None,
display_name=None,
description=None,
collections=None):
"""Create a PR curve summary op for a single binary classifier.
Computes true/false positive/negative values for the given `predictions`
against the ground... | def function[op, parameter[name, labels, predictions, num_thresholds, weights, display_name, description, collections]]:
constant[Create a PR curve summary op for a single binary classifier.
Computes true/false positive/negative values for the given `predictions`
against the ground truth `labels`, against ... | keyword[def] identifier[op] (
identifier[name] ,
identifier[labels] ,
identifier[predictions] ,
identifier[num_thresholds] = keyword[None] ,
identifier[weights] = keyword[None] ,
identifier[display_name] = keyword[None] ,
identifier[description] = keyword[None] ,
identifier[collections] = keyword[None] ):
... | def op(name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None, collections=None):
"""Create a PR curve summary op for a single binary classifier.
Computes true/false positive/negative values for the given `predictions`
against the ground truth `labels`, against a list... |
def add_dimension(dimension,**kwargs):
"""
Add the dimension defined into the object "dimension" to the DB
If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project
If the dimension exists emits an exception
"""
if numpy.isscalar(dim... | def function[add_dimension, parameter[dimension]]:
constant[
Add the dimension defined into the object "dimension" to the DB
If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project
If the dimension exists emits an exception
]
... | keyword[def] identifier[add_dimension] ( identifier[dimension] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[numpy] . identifier[isscalar] ( identifier[dimension] ):
identifier[dimension] ={ literal[string] : identifier[dimension] }
identifier[new_dimension] = identi... | def add_dimension(dimension, **kwargs):
"""
Add the dimension defined into the object "dimension" to the DB
If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project
If the dimension exists emits an exception
"""
if numpy.isscalar(di... |
def put_integration(restApiId=None, resourceId=None, httpMethod=None, type=None, integrationHttpMethod=None, uri=None, credentials=None, requestParameters=None, requestTemplates=None, passthroughBehavior=None, cacheNamespace=None, cacheKeyParameters=None, contentHandling=None):
"""
Represents a put integration.... | def function[put_integration, parameter[restApiId, resourceId, httpMethod, type, integrationHttpMethod, uri, credentials, requestParameters, requestTemplates, passthroughBehavior, cacheNamespace, cacheKeyParameters, contentHandling]]:
constant[
Represents a put integration.
See also: AWS API Documentati... | keyword[def] identifier[put_integration] ( identifier[restApiId] = keyword[None] , identifier[resourceId] = keyword[None] , identifier[httpMethod] = keyword[None] , identifier[type] = keyword[None] , identifier[integrationHttpMethod] = keyword[None] , identifier[uri] = keyword[None] , identifier[credentials] = keywor... | def put_integration(restApiId=None, resourceId=None, httpMethod=None, type=None, integrationHttpMethod=None, uri=None, credentials=None, requestParameters=None, requestTemplates=None, passthroughBehavior=None, cacheNamespace=None, cacheKeyParameters=None, contentHandling=None):
"""
Represents a put integration.... |
def check_shm():
""" Check /dev/shm right permissions
:return: None
"""
import stat
shm_path = '/dev/shm'
if os.name == 'posix' and os.path.exists(shm_path):
# We get the access rights, and we check them
mode = stat.S_IMODE(os.lstat(shm_path)[stat... | def function[check_shm, parameter[]]:
constant[ Check /dev/shm right permissions
:return: None
]
import module[stat]
variable[shm_path] assign[=] constant[/dev/shm]
if <ast.BoolOp object at 0x7da207f02650> begin[:]
variable[mode] assign[=] call[name[stat].S_I... | keyword[def] identifier[check_shm] ():
literal[string]
keyword[import] identifier[stat]
identifier[shm_path] = literal[string]
keyword[if] identifier[os] . identifier[name] == literal[string] keyword[and] identifier[os] . identifier[path] . identifier[exists] ( identifier[sh... | def check_shm():
""" Check /dev/shm right permissions
:return: None
"""
import stat
shm_path = '/dev/shm'
if os.name == 'posix' and os.path.exists(shm_path):
# We get the access rights, and we check them
mode = stat.S_IMODE(os.lstat(shm_path)[stat.ST_MODE])
if no... |
def string(self) -> str:
"""Return str(self)."""
start, end = self._span
return self._lststr[0][start:end] | def function[string, parameter[self]]:
constant[Return str(self).]
<ast.Tuple object at 0x7da20c991990> assign[=] name[self]._span
return[call[call[name[self]._lststr][constant[0]]][<ast.Slice object at 0x7da1b025d060>]] | keyword[def] identifier[string] ( identifier[self] )-> identifier[str] :
literal[string]
identifier[start] , identifier[end] = identifier[self] . identifier[_span]
keyword[return] identifier[self] . identifier[_lststr] [ literal[int] ][ identifier[start] : identifier[end] ] | def string(self) -> str:
"""Return str(self)."""
(start, end) = self._span
return self._lststr[0][start:end] |
def get_mask_selection(self, selection, out=None, fields=None):
"""Retrieve a selection of individual items, by providing a Boolean array of the
same shape as the array against which the selection is being made, where True
values indicate a selected item.
Parameters
----------
... | def function[get_mask_selection, parameter[self, selection, out, fields]]:
constant[Retrieve a selection of individual items, by providing a Boolean array of the
same shape as the array against which the selection is being made, where True
values indicate a selected item.
Parameters
... | keyword[def] identifier[get_mask_selection] ( identifier[self] , identifier[selection] , identifier[out] = keyword[None] , identifier[fields] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_cache_metadata] :
identifier[self] . iden... | def get_mask_selection(self, selection, out=None, fields=None):
"""Retrieve a selection of individual items, by providing a Boolean array of the
same shape as the array against which the selection is being made, where True
values indicate a selected item.
Parameters
----------
... |
def set_voltage(self, volt, ramp=False):
"""Sets the output voltage of monsoon.
Args:
volt: Voltage to set the output to.
ramp: If true, the output voltage will be increased gradually to
prevent tripping Monsoon overvoltage.
"""
if ramp:
... | def function[set_voltage, parameter[self, volt, ramp]]:
constant[Sets the output voltage of monsoon.
Args:
volt: Voltage to set the output to.
ramp: If true, the output voltage will be increased gradually to
prevent tripping Monsoon overvoltage.
]
... | keyword[def] identifier[set_voltage] ( identifier[self] , identifier[volt] , identifier[ramp] = keyword[False] ):
literal[string]
keyword[if] identifier[ramp] :
identifier[self] . identifier[mon] . identifier[RampVoltage] ( identifier[self] . identifier[mon] . identifier[start_voltage... | def set_voltage(self, volt, ramp=False):
"""Sets the output voltage of monsoon.
Args:
volt: Voltage to set the output to.
ramp: If true, the output voltage will be increased gradually to
prevent tripping Monsoon overvoltage.
"""
if ramp:
self.mon.... |
def run(self, messages):
"""Returns some analytics about this autograder run."""
statistics = {}
statistics['time'] = str(datetime.now())
statistics['time-utc'] = str(datetime.utcnow())
statistics['unlock'] = self.args.unlock
if self.args.question:
statistics... | def function[run, parameter[self, messages]]:
constant[Returns some analytics about this autograder run.]
variable[statistics] assign[=] dictionary[[], []]
call[name[statistics]][constant[time]] assign[=] call[name[str], parameter[call[name[datetime].now, parameter[]]]]
call[name[statist... | keyword[def] identifier[run] ( identifier[self] , identifier[messages] ):
literal[string]
identifier[statistics] ={}
identifier[statistics] [ literal[string] ]= identifier[str] ( identifier[datetime] . identifier[now] ())
identifier[statistics] [ literal[string] ]= identifier[str]... | def run(self, messages):
"""Returns some analytics about this autograder run."""
statistics = {}
statistics['time'] = str(datetime.now())
statistics['time-utc'] = str(datetime.utcnow())
statistics['unlock'] = self.args.unlock
if self.args.question:
statistics['question'] = [t.name for t ... |
def negated(input_words, include_nt=True):
"""
Determine if input contains negation words
"""
input_words = [str(w).lower() for w in input_words]
neg_words = []
neg_words.extend(NEGATE)
for word in neg_words:
if word in input_words:
return True
if include_nt:
... | def function[negated, parameter[input_words, include_nt]]:
constant[
Determine if input contains negation words
]
variable[input_words] assign[=] <ast.ListComp object at 0x7da1b20555d0>
variable[neg_words] assign[=] list[[]]
call[name[neg_words].extend, parameter[name[NEGATE]]]
... | keyword[def] identifier[negated] ( identifier[input_words] , identifier[include_nt] = keyword[True] ):
literal[string]
identifier[input_words] =[ identifier[str] ( identifier[w] ). identifier[lower] () keyword[for] identifier[w] keyword[in] identifier[input_words] ]
identifier[neg_words] =[]
i... | def negated(input_words, include_nt=True):
"""
Determine if input contains negation words
"""
input_words = [str(w).lower() for w in input_words]
neg_words = []
neg_words.extend(NEGATE)
for word in neg_words:
if word in input_words:
return True # depends on [control=['if... |
def opt_display(self, display):
""" Set value for display option """
key = get_enum_key(display, DISPLAYS)
if key is not None:
self.conf["display"] = key
self.display = DISPLAYS[key]
print("Set display %r" % key)
else:
print("Unknown displa... | def function[opt_display, parameter[self, display]]:
constant[ Set value for display option ]
variable[key] assign[=] call[name[get_enum_key], parameter[name[display], name[DISPLAYS]]]
if compare[name[key] is_not constant[None]] begin[:]
call[name[self].conf][constant[display]] a... | keyword[def] identifier[opt_display] ( identifier[self] , identifier[display] ):
literal[string]
identifier[key] = identifier[get_enum_key] ( identifier[display] , identifier[DISPLAYS] )
keyword[if] identifier[key] keyword[is] keyword[not] keyword[None] :
identifier[self] ... | def opt_display(self, display):
""" Set value for display option """
key = get_enum_key(display, DISPLAYS)
if key is not None:
self.conf['display'] = key
self.display = DISPLAYS[key]
print('Set display %r' % key) # depends on [control=['if'], data=['key']]
else:
print('U... |
def cdpop():
"""
Return the last directory.
Returns absolute path to new working directory.
"""
if len(_cdhist) >= 1:
old = _cdhist.pop() # Pop from history.
os.chdir(old)
return old
else:
return pwd() | def function[cdpop, parameter[]]:
constant[
Return the last directory.
Returns absolute path to new working directory.
]
if compare[call[name[len], parameter[name[_cdhist]]] greater_or_equal[>=] constant[1]] begin[:]
variable[old] assign[=] call[name[_cdhist].pop, parameter[... | keyword[def] identifier[cdpop] ():
literal[string]
keyword[if] identifier[len] ( identifier[_cdhist] )>= literal[int] :
identifier[old] = identifier[_cdhist] . identifier[pop] ()
identifier[os] . identifier[chdir] ( identifier[old] )
keyword[return] identifier[old]
keywor... | def cdpop():
"""
Return the last directory.
Returns absolute path to new working directory.
"""
if len(_cdhist) >= 1:
old = _cdhist.pop() # Pop from history.
os.chdir(old)
return old # depends on [control=['if'], data=[]]
else:
return pwd() |
def security():
"""View for security page."""
sessions = SessionActivity.query_by_user(
user_id=current_user.get_id()
).all()
master_session = None
for index, session in enumerate(sessions):
if SessionActivity.is_current(session.sid_s):
master_session = session
... | def function[security, parameter[]]:
constant[View for security page.]
variable[sessions] assign[=] call[call[name[SessionActivity].query_by_user, parameter[]].all, parameter[]]
variable[master_session] assign[=] constant[None]
for taget[tuple[[<ast.Name object at 0x7da1b1a1e4a0>, <ast.N... | keyword[def] identifier[security] ():
literal[string]
identifier[sessions] = identifier[SessionActivity] . identifier[query_by_user] (
identifier[user_id] = identifier[current_user] . identifier[get_id] ()
). identifier[all] ()
identifier[master_session] = keyword[None]
keyword[for] id... | def security():
"""View for security page."""
sessions = SessionActivity.query_by_user(user_id=current_user.get_id()).all()
master_session = None
for (index, session) in enumerate(sessions):
if SessionActivity.is_current(session.sid_s):
master_session = session
del sessio... |
def starts_expanded(name):
"""Return True if directory is a parent of initial cwd."""
if name is '/':
return True
l = name.split(dir_sep())
if len(l) > len(_initial_cwd):
return False
if l != _initial_cwd[:len(l)]:
return False
return True | def function[starts_expanded, parameter[name]]:
constant[Return True if directory is a parent of initial cwd.]
if compare[name[name] is constant[/]] begin[:]
return[constant[True]]
variable[l] assign[=] call[name[name].split, parameter[call[name[dir_sep], parameter[]]]]
if compar... | keyword[def] identifier[starts_expanded] ( identifier[name] ):
literal[string]
keyword[if] identifier[name] keyword[is] literal[string] :
keyword[return] keyword[True]
identifier[l] = identifier[name] . identifier[split] ( identifier[dir_sep] ())
keyword[if] identifier[len] ( ide... | def starts_expanded(name):
"""Return True if directory is a parent of initial cwd."""
if name is '/':
return True # depends on [control=['if'], data=[]]
l = name.split(dir_sep())
if len(l) > len(_initial_cwd):
return False # depends on [control=['if'], data=[]]
if l != _initial_cwd... |
def import_datatable(self, l_datatable, schema='datatable', col_key=0):
"""
import a datatable (grid) by using the schema:table:column as keys.
e.g. Sample input ( via cls_database.py -> test.csv)
TERM,GENDER,ID,tot1,tot2
5320,M,78,18,66
1310,M,78,10,12
L... | def function[import_datatable, parameter[self, l_datatable, schema, col_key]]:
constant[
import a datatable (grid) by using the schema:table:column as keys.
e.g. Sample input ( via cls_database.py -> test.csv)
TERM,GENDER,ID,tot1,tot2
5320,M,78,18,66
1310,M,78,10,12
... | keyword[def] identifier[import_datatable] ( identifier[self] , identifier[l_datatable] , identifier[schema] = literal[string] , identifier[col_key] = literal[int] ):
literal[string]
identifier[key] = literal[string]
identifier[hdr] = identifier[l_datatable] . identifier[get_header] ()
... | def import_datatable(self, l_datatable, schema='datatable', col_key=0):
"""
import a datatable (grid) by using the schema:table:column as keys.
e.g. Sample input ( via cls_database.py -> test.csv)
TERM,GENDER,ID,tot1,tot2
5320,M,78,18,66
1310,M,78,10,12
Loads... |
def duplicateAnalysis(analysis):
"""
Duplicate an analysis consist on creating a new analysis with
the same analysis service for the same sample. It is used in
order to reduce the error procedure probability because both
results must be similar.
:base: the analysis object used as the creation ba... | def function[duplicateAnalysis, parameter[analysis]]:
constant[
Duplicate an analysis consist on creating a new analysis with
the same analysis service for the same sample. It is used in
order to reduce the error procedure probability because both
results must be similar.
:base: the analysis... | keyword[def] identifier[duplicateAnalysis] ( identifier[analysis] ):
literal[string]
identifier[ar] = identifier[analysis] . identifier[aq_parent]
identifier[kw] = identifier[analysis] . identifier[getKeyword] ()
identifier[cnt] =[ identifier[x] keyword[for] identifier[x] keyword[in... | def duplicateAnalysis(analysis):
"""
Duplicate an analysis consist on creating a new analysis with
the same analysis service for the same sample. It is used in
order to reduce the error procedure probability because both
results must be similar.
:base: the analysis object used as the creation ba... |
def conv2d_fixed_padding(inputs,
filters,
kernel_size,
strides,
data_format="channels_first",
use_td=False,
targeting_rate=None,
keep_prob=None,
... | def function[conv2d_fixed_padding, parameter[inputs, filters, kernel_size, strides, data_format, use_td, targeting_rate, keep_prob, is_training]]:
constant[Strided 2-D convolution with explicit padding.
The padding is consistent and is based only on `kernel_size`, not on the
dimensions of `inputs` (as oppo... | keyword[def] identifier[conv2d_fixed_padding] ( identifier[inputs] ,
identifier[filters] ,
identifier[kernel_size] ,
identifier[strides] ,
identifier[data_format] = literal[string] ,
identifier[use_td] = keyword[False] ,
identifier[targeting_rate] = keyword[None] ,
identifier[keep_prob] = keyword[None] ,
iden... | def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format='channels_first', use_td=False, targeting_rate=None, keep_prob=None, is_training=None):
"""Strided 2-D convolution with explicit padding.
The padding is consistent and is based only on `kernel_size`, not on the
dimensions of `inputs` (... |
def selection_range(self):
"""
Returns the selected lines boundaries (start line, end line)
:return: tuple(int, int)
"""
editor = self._editor
doc = editor.document()
start = doc.findBlock(
editor.textCursor().selectionStart()).blockNumber()
e... | def function[selection_range, parameter[self]]:
constant[
Returns the selected lines boundaries (start line, end line)
:return: tuple(int, int)
]
variable[editor] assign[=] name[self]._editor
variable[doc] assign[=] call[name[editor].document, parameter[]]
variab... | keyword[def] identifier[selection_range] ( identifier[self] ):
literal[string]
identifier[editor] = identifier[self] . identifier[_editor]
identifier[doc] = identifier[editor] . identifier[document] ()
identifier[start] = identifier[doc] . identifier[findBlock] (
identif... | def selection_range(self):
"""
Returns the selected lines boundaries (start line, end line)
:return: tuple(int, int)
"""
editor = self._editor
doc = editor.document()
start = doc.findBlock(editor.textCursor().selectionStart()).blockNumber()
end = doc.findBlock(editor.textCur... |
def addSynonym(
self, class_id, synonym, synonym_type=None):
"""
Add the synonym as a property of the class cid.
Assume it is an exact synonym, unless otherwise specified
:param g:
:param cid: class id
:param synonym: the literal synonym label
:param s... | def function[addSynonym, parameter[self, class_id, synonym, synonym_type]]:
constant[
Add the synonym as a property of the class cid.
Assume it is an exact synonym, unless otherwise specified
:param g:
:param cid: class id
:param synonym: the literal synonym label
... | keyword[def] identifier[addSynonym] (
identifier[self] , identifier[class_id] , identifier[synonym] , identifier[synonym_type] = keyword[None] ):
literal[string]
keyword[if] identifier[synonym_type] keyword[is] keyword[None] :
identifier[synonym_type] = identifier[self] . identifi... | def addSynonym(self, class_id, synonym, synonym_type=None):
"""
Add the synonym as a property of the class cid.
Assume it is an exact synonym, unless otherwise specified
:param g:
:param cid: class id
:param synonym: the literal synonym label
:param synonym_type: the ... |
def make_spindles(events, power_peaks, powers, dat_det, dat_orig, time,
s_freq):
"""Create dict for each spindle, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples, and peak frequency
power_peaks... | def function[make_spindles, parameter[events, power_peaks, powers, dat_det, dat_orig, time, s_freq]]:
constant[Create dict for each spindle, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples, and peak frequency
... | keyword[def] identifier[make_spindles] ( identifier[events] , identifier[power_peaks] , identifier[powers] , identifier[dat_det] , identifier[dat_orig] , identifier[time] ,
identifier[s_freq] ):
literal[string]
identifier[i] , identifier[events] = identifier[_remove_duplicate] ( identifier[events] , ident... | def make_spindles(events, power_peaks, powers, dat_det, dat_orig, time, s_freq):
"""Create dict for each spindle, based on events of time points.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples, and peak frequency
power_peaks : ndarray (dtype=... |
def temp_path(file_name=None):
"""
Gets a temp path.
Kwargs:
file_name (str) : if file name is specified, it gets appended to the temp dir.
Usage::
temp_file_path = temp_path("myfile")
copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfile'
"""
if file_... | def function[temp_path, parameter[file_name]]:
constant[
Gets a temp path.
Kwargs:
file_name (str) : if file name is specified, it gets appended to the temp dir.
Usage::
temp_file_path = temp_path("myfile")
copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfi... | keyword[def] identifier[temp_path] ( identifier[file_name] = keyword[None] ):
literal[string]
keyword[if] identifier[file_name] keyword[is] keyword[None] :
identifier[file_name] = identifier[generate_timestamped_string] ( literal[string] )
keyword[return] identifier[os] . identifier[pat... | def temp_path(file_name=None):
"""
Gets a temp path.
Kwargs:
file_name (str) : if file name is specified, it gets appended to the temp dir.
Usage::
temp_file_path = temp_path("myfile")
copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfile'
"""
if file_n... |
def _from_dict(cls, _dict):
"""Initialize a ValueCollection object from a json dictionary."""
args = {}
if 'values' in _dict:
args['values'] = [
Value._from_dict(x) for x in (_dict.get('values'))
]
else:
raise ValueError(
... | def function[_from_dict, parameter[cls, _dict]]:
constant[Initialize a ValueCollection object from a json dictionary.]
variable[args] assign[=] dictionary[[], []]
if compare[constant[values] in name[_dict]] begin[:]
call[name[args]][constant[values]] assign[=] <ast.ListComp objec... | keyword[def] identifier[_from_dict] ( identifier[cls] , identifier[_dict] ):
literal[string]
identifier[args] ={}
keyword[if] literal[string] keyword[in] identifier[_dict] :
identifier[args] [ literal[string] ]=[
identifier[Value] . identifier[_from_dict] ( ide... | def _from_dict(cls, _dict):
"""Initialize a ValueCollection object from a json dictionary."""
args = {}
if 'values' in _dict:
args['values'] = [Value._from_dict(x) for x in _dict.get('values')] # depends on [control=['if'], data=['_dict']]
else:
raise ValueError("Required property 'valu... |
def find_root_tex_document(base_dir="."):
"""Find the tex article in the current directory that can be considered
a root. We do this by searching contents for ``'\documentclass'``.
Parameters
----------
base_dir : str
Directory to search for LaTeX documents, relative to the current
... | def function[find_root_tex_document, parameter[base_dir]]:
constant[Find the tex article in the current directory that can be considered
a root. We do this by searching contents for ``'\documentclass'``.
Parameters
----------
base_dir : str
Directory to search for LaTeX documents, relat... | keyword[def] identifier[find_root_tex_document] ( identifier[base_dir] = literal[string] ):
literal[string]
identifier[log] = identifier[logging] . identifier[getLogger] ( identifier[__name__] )
keyword[for] identifier[tex_path] keyword[in] identifier[iter_tex_documents] ( identifier[base_dir] = id... | def find_root_tex_document(base_dir='.'):
"""Find the tex article in the current directory that can be considered
a root. We do this by searching contents for ``'\\documentclass'``.
Parameters
----------
base_dir : str
Directory to search for LaTeX documents, relative to the current
... |
def tcalc(nf, p):
"""
t-table for nf degrees of freedom (95% confidence)
"""
#
if p == .05:
if nf > 2:
t = 4.3027
if nf > 3:
t = 3.1824
if nf > 4:
t = 2.7765
if nf > 5:
t = 2.5706
if nf > 6:
t = 2.4469
... | def function[tcalc, parameter[nf, p]]:
constant[
t-table for nf degrees of freedom (95% confidence)
]
if compare[name[p] equal[==] constant[0.05]] begin[:]
if compare[name[nf] greater[>] constant[2]] begin[:]
variable[t] assign[=] constant[4.3027]
... | keyword[def] identifier[tcalc] ( identifier[nf] , identifier[p] ):
literal[string]
keyword[if] identifier[p] == literal[int] :
keyword[if] identifier[nf] > literal[int] :
identifier[t] = literal[int]
keyword[if] identifier[nf] > literal[int] :
identifier... | def tcalc(nf, p):
"""
t-table for nf degrees of freedom (95% confidence)
"""
#
if p == 0.05:
if nf > 2:
t = 4.3027 # depends on [control=['if'], data=[]]
if nf > 3:
t = 3.1824 # depends on [control=['if'], data=[]]
if nf > 4:
t = 2.7765 ... |
def _use_color(msg, ansi_fmt, output_stream):
'''
Based on :data:`~exhale.configs.alwaysColorize`, returns the colorized or
non-colorized output when ``output_stream`` is not a TTY (e.g. redirecting
to a file).
**Parameters**
``msg`` (str)
The message that is going to be printed... | def function[_use_color, parameter[msg, ansi_fmt, output_stream]]:
constant[
Based on :data:`~exhale.configs.alwaysColorize`, returns the colorized or
non-colorized output when ``output_stream`` is not a TTY (e.g. redirecting
to a file).
**Parameters**
``msg`` (str)
The mess... | keyword[def] identifier[_use_color] ( identifier[msg] , identifier[ansi_fmt] , identifier[output_stream] ):
literal[string]
keyword[if] identifier[configs] . identifier[_on_rtd] keyword[or] ( keyword[not] identifier[configs] . identifier[alwaysColorize] keyword[and] keyword[not] identifier[output_str... | def _use_color(msg, ansi_fmt, output_stream):
"""
Based on :data:`~exhale.configs.alwaysColorize`, returns the colorized or
non-colorized output when ``output_stream`` is not a TTY (e.g. redirecting
to a file).
**Parameters**
``msg`` (str)
The message that is going to be printed... |
def systemInformationType13():
"""SYSTEM INFORMATION TYPE 13 Section 9.1.43a"""
a = L2PseudoLength(l2pLength=0x00)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x0) # 00000000
d = Si13RestOctets()
packet = a / b / c / d
return packet | def function[systemInformationType13, parameter[]]:
constant[SYSTEM INFORMATION TYPE 13 Section 9.1.43a]
variable[a] assign[=] call[name[L2PseudoLength], parameter[]]
variable[b] assign[=] call[name[TpPd], parameter[]]
variable[c] assign[=] call[name[MessageType], parameter[]]
va... | keyword[def] identifier[systemInformationType13] ():
literal[string]
identifier[a] = identifier[L2PseudoLength] ( identifier[l2pLength] = literal[int] )
identifier[b] = identifier[TpPd] ( identifier[pd] = literal[int] )
identifier[c] = identifier[MessageType] ( identifier[mesType] = literal[int] ... | def systemInformationType13():
"""SYSTEM INFORMATION TYPE 13 Section 9.1.43a"""
a = L2PseudoLength(l2pLength=0)
b = TpPd(pd=6)
c = MessageType(mesType=0) # 00000000
d = Si13RestOctets()
packet = a / b / c / d
return packet |
def moving_frequency(self, data_frame):
"""
This method returns moving frequency
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return diff_mov_freq: frequency
:rtype diff_mov_freq: float
"""
f = []
for ... | def function[moving_frequency, parameter[self, data_frame]]:
constant[
This method returns moving frequency
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return diff_mov_freq: frequency
:rtype diff_mov_freq: float
]
... | keyword[def] identifier[moving_frequency] ( identifier[self] , identifier[data_frame] ):
literal[string]
identifier[f] =[]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] ,( identifier[data_frame] . identifier[td] [- literal[int] ]. identifier[astype] ( literal[s... | def moving_frequency(self, data_frame):
"""
This method returns moving frequency
:param data_frame: the data frame
:type data_frame: pandas.DataFrame
:return diff_mov_freq: frequency
:rtype diff_mov_freq: float
"""
f = []
for i in range(0... |
def print_hex(data):
"""Debugging method to print out frames in hex."""
hex_msg = ""
for c in data:
hex_msg += "\\x" + format(c, "02x")
_LOGGER.debug(hex_msg) | def function[print_hex, parameter[data]]:
constant[Debugging method to print out frames in hex.]
variable[hex_msg] assign[=] constant[]
for taget[name[c]] in starred[name[data]] begin[:]
<ast.AugAssign object at 0x7da2041d86d0>
call[name[_LOGGER].debug, parameter[name[hex_msg]]] | keyword[def] identifier[print_hex] ( identifier[data] ):
literal[string]
identifier[hex_msg] = literal[string]
keyword[for] identifier[c] keyword[in] identifier[data] :
identifier[hex_msg] += literal[string] + identifier[format] ( identifier[c] , literal[string] )
identifier[_LOGGER]... | def print_hex(data):
"""Debugging method to print out frames in hex."""
hex_msg = ''
for c in data:
hex_msg += '\\x' + format(c, '02x') # depends on [control=['for'], data=['c']]
_LOGGER.debug(hex_msg) |
def get_object_executor(obj, green_mode=None):
"""Returns the proper executor for the given object.
If the object has *_executors* and *_green_mode* members it returns
the submit callable for the executor corresponding to the green_mode.
Otherwise it returns the global executor for the given green_mode... | def function[get_object_executor, parameter[obj, green_mode]]:
constant[Returns the proper executor for the given object.
If the object has *_executors* and *_green_mode* members it returns
the submit callable for the executor corresponding to the green_mode.
Otherwise it returns the global executo... | keyword[def] identifier[get_object_executor] ( identifier[obj] , identifier[green_mode] = keyword[None] ):
literal[string]
keyword[if] identifier[green_mode] keyword[is] keyword[None] :
identifier[green_mode] = identifier[get_object_green_mode] ( identifier[obj] )
identifier[... | def get_object_executor(obj, green_mode=None):
"""Returns the proper executor for the given object.
If the object has *_executors* and *_green_mode* members it returns
the submit callable for the executor corresponding to the green_mode.
Otherwise it returns the global executor for the given green_mode... |
def make_model(self, use_name_as_key=False, include_mods=False,
include_complexes=False):
"""Assemble the graph from the assembler's list of INDRA Statements.
Parameters
----------
use_name_as_key : boolean
If True, uses the name of the agent as the key to... | def function[make_model, parameter[self, use_name_as_key, include_mods, include_complexes]]:
constant[Assemble the graph from the assembler's list of INDRA Statements.
Parameters
----------
use_name_as_key : boolean
If True, uses the name of the agent as the key to the nodes... | keyword[def] identifier[make_model] ( identifier[self] , identifier[use_name_as_key] = keyword[False] , identifier[include_mods] = keyword[False] ,
identifier[include_complexes] = keyword[False] ):
literal[string]
identifier[self] . identifier[graph] = identifier[nx] . identifier[DiGraph] ()
... | def make_model(self, use_name_as_key=False, include_mods=False, include_complexes=False):
"""Assemble the graph from the assembler's list of INDRA Statements.
Parameters
----------
use_name_as_key : boolean
If True, uses the name of the agent as the key to the nodes in
... |
def config_start(args):
'''Invoke a task (method configuration), on given entity in given space'''
# Try to use call caching (job avoidance)? Flexibly accept range of answers
cache = getattr(args, "cache", True)
cache = cache is True or (cache.lower() in ["y", "true", "yes", "t", "1"])
if not arg... | def function[config_start, parameter[args]]:
constant[Invoke a task (method configuration), on given entity in given space]
variable[cache] assign[=] call[name[getattr], parameter[name[args], constant[cache], constant[True]]]
variable[cache] assign[=] <ast.BoolOp object at 0x7da1b1a2d0c0>
... | keyword[def] identifier[config_start] ( identifier[args] ):
literal[string]
identifier[cache] = identifier[getattr] ( identifier[args] , literal[string] , keyword[True] )
identifier[cache] = identifier[cache] keyword[is] keyword[True] keyword[or] ( identifier[cache] . identifier[lower] () key... | def config_start(args):
"""Invoke a task (method configuration), on given entity in given space"""
# Try to use call caching (job avoidance)? Flexibly accept range of answers
cache = getattr(args, 'cache', True)
cache = cache is True or cache.lower() in ['y', 'true', 'yes', 't', '1']
if not args.na... |
def sql_reset(app, style, connection):
"Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module."
return sql_delete(app, style, connection) + sql_all(app, style, connection) | def function[sql_reset, parameter[app, style, connection]]:
constant[Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module.]
return[binary_operation[call[name[sql_delete], parameter[name[app], name[style], name[connection]]] + call[name[sql_all], parameter[name[app], name[sty... | keyword[def] identifier[sql_reset] ( identifier[app] , identifier[style] , identifier[connection] ):
literal[string]
keyword[return] identifier[sql_delete] ( identifier[app] , identifier[style] , identifier[connection] )+ identifier[sql_all] ( identifier[app] , identifier[style] , identifier[connection] ) | def sql_reset(app, style, connection):
"""Returns a list of the DROP TABLE SQL, then the CREATE TABLE SQL, for the given module."""
return sql_delete(app, style, connection) + sql_all(app, style, connection) |
def _get_intermediate_file(self, name, machine_and_compiler_dependent=True, binary=False,
fp=True):
"""
Create or open intermediate file (may be used for caching).
Will replace files older than kernel file, machine file or kerncraft version.
:param machin... | def function[_get_intermediate_file, parameter[self, name, machine_and_compiler_dependent, binary, fp]]:
constant[
Create or open intermediate file (may be used for caching).
Will replace files older than kernel file, machine file or kerncraft version.
:param machine_and_compiler_depen... | keyword[def] identifier[_get_intermediate_file] ( identifier[self] , identifier[name] , identifier[machine_and_compiler_dependent] = keyword[True] , identifier[binary] = keyword[False] ,
identifier[fp] = keyword[True] ):
literal[string]
keyword[if] identifier[self] . identifier[_filename] :
... | def _get_intermediate_file(self, name, machine_and_compiler_dependent=True, binary=False, fp=True):
"""
Create or open intermediate file (may be used for caching).
Will replace files older than kernel file, machine file or kerncraft version.
:param machine_and_compiler_dependent: set to Fa... |
def create_api_model(restApiId, modelName, modelDescription, schema, contentType='application/json',
region=None, key=None, keyid=None, profile=None):
'''
Create a new model in a given API with a given schema, currently only contentType supported is
'application/json'
CLI Example:
... | def function[create_api_model, parameter[restApiId, modelName, modelDescription, schema, contentType, region, key, keyid, profile]]:
constant[
Create a new model in a given API with a given schema, currently only contentType supported is
'application/json'
CLI Example:
.. code-block:: bash
... | keyword[def] identifier[create_api_model] ( identifier[restApiId] , identifier[modelName] , identifier[modelDescription] , identifier[schema] , identifier[contentType] = literal[string] ,
identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = ... | def create_api_model(restApiId, modelName, modelDescription, schema, contentType='application/json', region=None, key=None, keyid=None, profile=None):
"""
Create a new model in a given API with a given schema, currently only contentType supported is
'application/json'
CLI Example:
.. code-block:: ... |
def has_transition(self, state):
"""
Lookup if any transition exists from current model state using current method
"""
if state in self.transitions:
return True
if '*' in self.transitions:
return True
if '+' in self.transitions and self.transitio... | def function[has_transition, parameter[self, state]]:
constant[
Lookup if any transition exists from current model state using current method
]
if compare[name[state] in name[self].transitions] begin[:]
return[constant[True]]
if compare[constant[*] in name[self].transitio... | keyword[def] identifier[has_transition] ( identifier[self] , identifier[state] ):
literal[string]
keyword[if] identifier[state] keyword[in] identifier[self] . identifier[transitions] :
keyword[return] keyword[True]
keyword[if] literal[string] keyword[in] identifier[se... | def has_transition(self, state):
"""
Lookup if any transition exists from current model state using current method
"""
if state in self.transitions:
return True # depends on [control=['if'], data=[]]
if '*' in self.transitions:
return True # depends on [control=['if'], data... |
def get(self, key, filepath):
"""Get configuration parameter.
Reads 'key' configuration parameter from the configuration file given
in 'filepath'. Configuration parameter in 'key' must follow the schema
<section>.<option> .
:param key: key to get
:param filepath: config... | def function[get, parameter[self, key, filepath]]:
constant[Get configuration parameter.
Reads 'key' configuration parameter from the configuration file given
in 'filepath'. Configuration parameter in 'key' must follow the schema
<section>.<option> .
:param key: key to get
... | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[filepath] ):
literal[string]
keyword[if] keyword[not] identifier[filepath] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
keyword[if] keyword[not] identifier[self] . identifier[... | def get(self, key, filepath):
"""Get configuration parameter.
Reads 'key' configuration parameter from the configuration file given
in 'filepath'. Configuration parameter in 'key' must follow the schema
<section>.<option> .
:param key: key to get
:param filepath: configurat... |
def option_in_select(browser, select_name, option):
"""
Returns the Element specified by @option or None
Looks at the real <select> not the select2 widget, since that doesn't
create the DOM until we click on it.
"""
select = find_field(browser, 'select', select_name)
assert select, "Cannot... | def function[option_in_select, parameter[browser, select_name, option]]:
constant[
Returns the Element specified by @option or None
Looks at the real <select> not the select2 widget, since that doesn't
create the DOM until we click on it.
]
variable[select] assign[=] call[name[find_fiel... | keyword[def] identifier[option_in_select] ( identifier[browser] , identifier[select_name] , identifier[option] ):
literal[string]
identifier[select] = identifier[find_field] ( identifier[browser] , literal[string] , identifier[select_name] )
keyword[assert] identifier[select] , literal[string] . ide... | def option_in_select(browser, select_name, option):
"""
Returns the Element specified by @option or None
Looks at the real <select> not the select2 widget, since that doesn't
create the DOM until we click on it.
"""
select = find_field(browser, 'select', select_name)
assert select, "Cannot ... |
def _getitem(self, key):
"""Return specified page of series from cache or file."""
key = int(key)
if key < 0:
key %= self._len
if len(self._pages) == 1 and 0 < key < self._len:
index = self._pages[0].index
return self.parent.pages._getitem(index + key)... | def function[_getitem, parameter[self, key]]:
constant[Return specified page of series from cache or file.]
variable[key] assign[=] call[name[int], parameter[name[key]]]
if compare[name[key] less[<] constant[0]] begin[:]
<ast.AugAssign object at 0x7da1b1859810>
if <ast.BoolOp obj... | keyword[def] identifier[_getitem] ( identifier[self] , identifier[key] ):
literal[string]
identifier[key] = identifier[int] ( identifier[key] )
keyword[if] identifier[key] < literal[int] :
identifier[key] %= identifier[self] . identifier[_len]
keyword[if] identifie... | def _getitem(self, key):
"""Return specified page of series from cache or file."""
key = int(key)
if key < 0:
key %= self._len # depends on [control=['if'], data=['key']]
if len(self._pages) == 1 and 0 < key < self._len:
index = self._pages[0].index
return self.parent.pages._get... |
def add_permission(content_type, permission):
"""
Adds the passed in permission to that content type. Note that the permission passed
in should be a single word, or verb. The proper 'codename' will be generated from that.
"""
# build our permission slug
codename = "%s_%s" % (content_type.model... | def function[add_permission, parameter[content_type, permission]]:
constant[
Adds the passed in permission to that content type. Note that the permission passed
in should be a single word, or verb. The proper 'codename' will be generated from that.
]
variable[codename] assign[=] binary_ope... | keyword[def] identifier[add_permission] ( identifier[content_type] , identifier[permission] ):
literal[string]
identifier[codename] = literal[string] %( identifier[content_type] . identifier[model] , identifier[permission] )
keyword[if] keyword[not] identifier[Permission] . identifi... | def add_permission(content_type, permission):
"""
Adds the passed in permission to that content type. Note that the permission passed
in should be a single word, or verb. The proper 'codename' will be generated from that.
"""
# build our permission slug
codename = '%s_%s' % (content_type.model... |
def pci_lookup_name1(
access: (IN, ctypes.POINTER(pci_access)),
buf: (IN, ctypes.c_char_p),
size: (IN, ctypes.c_int),
flags: (IN, ctypes.c_int),
arg1: (IN, ctypes.c_int),
) -> ctypes.c_char_p:
"""
Conversion of PCI ID's to names (according to the pci.ids file).
char *pci_lookup_name(
... | def function[pci_lookup_name1, parameter[access, buf, size, flags, arg1]]:
constant[
Conversion of PCI ID's to names (according to the pci.ids file).
char *pci_lookup_name(
struct pci_access *a, char *buf, int size, int flags, ...
) PCI_ABI;
This is a variant of pci_lookup_name() that ... | keyword[def] identifier[pci_lookup_name1] (
identifier[access] :( identifier[IN] , identifier[ctypes] . identifier[POINTER] ( identifier[pci_access] )),
identifier[buf] :( identifier[IN] , identifier[ctypes] . identifier[c_char_p] ),
identifier[size] :( identifier[IN] , identifier[ctypes] . identifier[c_int] ),
i... | def pci_lookup_name1(access: (IN, ctypes.POINTER(pci_access)), buf: (IN, ctypes.c_char_p), size: (IN, ctypes.c_int), flags: (IN, ctypes.c_int), arg1: (IN, ctypes.c_int)) -> ctypes.c_char_p:
"""
Conversion of PCI ID's to names (according to the pci.ids file).
char *pci_lookup_name(
struct pci_access... |
def LinShuReductionFactor(axiPot,R,sigmar,nonaxiPot=None,
k=None,m=None,OmegaP=None):
"""
NAME:
LinShuReductionFactor
PURPOSE:
Calculate the Lin & Shu (1966) reduction factor: the reduced linear response of a kinematically-warm stellar disk to a perturbation
I... | def function[LinShuReductionFactor, parameter[axiPot, R, sigmar, nonaxiPot, k, m, OmegaP]]:
constant[
NAME:
LinShuReductionFactor
PURPOSE:
Calculate the Lin & Shu (1966) reduction factor: the reduced linear response of a kinematically-warm stellar disk to a perturbation
INPUT:
... | keyword[def] identifier[LinShuReductionFactor] ( identifier[axiPot] , identifier[R] , identifier[sigmar] , identifier[nonaxiPot] = keyword[None] ,
identifier[k] = keyword[None] , identifier[m] = keyword[None] , identifier[OmegaP] = keyword[None] ):
literal[string]
identifier[axiPot] = identifier[flatten] ... | def LinShuReductionFactor(axiPot, R, sigmar, nonaxiPot=None, k=None, m=None, OmegaP=None):
"""
NAME:
LinShuReductionFactor
PURPOSE:
Calculate the Lin & Shu (1966) reduction factor: the reduced linear response of a kinematically-warm stellar disk to a perturbation
INPUT:
axiPot ... |
def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Check if this is a webservice request
self.json_worker = (bool(getattr(self.request, "authtoken", False))) or (self.json is True)
self.__authtoken = (bool(getattr(self... | def function[dispatch, parameter[self, request]]:
constant[
Entry point for this class, here we decide basic stuff
]
name[self].json_worker assign[=] <ast.BoolOp object at 0x7da1b0d24c40>
name[self].__authtoken assign[=] call[name[bool], parameter[call[name[getattr], parameter[na... | keyword[def] identifier[dispatch] ( identifier[self] , identifier[request] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[json_worker] =( identifier[bool] ( identifier[getattr] ( identifier[self] . identifier[request] , literal[string] , keyword[False] ))) keyword... | def dispatch(self, request, **kwargs):
"""
Entry point for this class, here we decide basic stuff
"""
# Check if this is a webservice request
self.json_worker = bool(getattr(self.request, 'authtoken', False)) or self.json is True
self.__authtoken = bool(getattr(self.request, 'authtoken',... |
def optimized_binary_search_lower(tab, logsize):
"""Binary search in a table using bit operations
:param tab: boolean monotone table
of size :math:`2^\\textrm{logsize}`
with tab[0] = False
:param int logsize:
:returns: last i such that not tab[i]
:complexity: O(logsize)
"""
lo... | def function[optimized_binary_search_lower, parameter[tab, logsize]]:
constant[Binary search in a table using bit operations
:param tab: boolean monotone table
of size :math:`2^\textrm{logsize}`
with tab[0] = False
:param int logsize:
:returns: last i such that not tab[i]
:complex... | keyword[def] identifier[optimized_binary_search_lower] ( identifier[tab] , identifier[logsize] ):
literal[string]
identifier[lo] = literal[int]
identifier[intervalsize] =( literal[int] << identifier[logsize] )>> literal[int]
keyword[while] identifier[intervalsize] > literal[int] :
key... | def optimized_binary_search_lower(tab, logsize):
"""Binary search in a table using bit operations
:param tab: boolean monotone table
of size :math:`2^\\textrm{logsize}`
with tab[0] = False
:param int logsize:
:returns: last i such that not tab[i]
:complexity: O(logsize)
"""
lo... |
def binary_shrink(image, iterations=-1):
"""Shrink an image by repeatedly removing pixels which have partners
above, to the left, to the right and below until the image doesn't change
image - binary image to be manipulated
iterations - # of times to shrink, -1 to shrink until idempotent... | def function[binary_shrink, parameter[image, iterations]]:
constant[Shrink an image by repeatedly removing pixels which have partners
above, to the left, to the right and below until the image doesn't change
image - binary image to be manipulated
iterations - # of times to shrink, -... | keyword[def] identifier[binary_shrink] ( identifier[image] , identifier[iterations] =- literal[int] ):
literal[string]
keyword[global] identifier[erode_table] , identifier[binary_shrink_ulr_table] , identifier[binary_shrink_lrl_table]
keyword[global] identifier[binary_shrink_urb_table] , identifier... | def binary_shrink(image, iterations=-1):
"""Shrink an image by repeatedly removing pixels which have partners
above, to the left, to the right and below until the image doesn't change
image - binary image to be manipulated
iterations - # of times to shrink, -1 to shrink until idempotent... |
def estimate_column_scales(
self,
X_centered,
row_scales):
"""
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
... | def function[estimate_column_scales, parameter[self, X_centered, row_scales]]:
constant[
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
row_sca... | keyword[def] identifier[estimate_column_scales] (
identifier[self] ,
identifier[X_centered] ,
identifier[row_scales] ):
literal[string]
identifier[n_rows] , identifier[n_cols] = identifier[X_centered] . identifier[shape]
identifier[row_scales] = identifier[np] . identifier[asarray] ( i... | def estimate_column_scales(self, X_centered, row_scales):
"""
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
row_scale[i] ** 2
}
""... |
def get_docker_tag(platform: str, registry: str) -> str:
""":return: docker tag to be used for the container"""
platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform)
if not registry:
registry = "mxnet_local"
return "{0}/{1}".format(registry, p... | def function[get_docker_tag, parameter[platform, registry]]:
constant[:return: docker tag to be used for the container]
variable[platform] assign[=] <ast.IfExp object at 0x7da1b2064880>
if <ast.UnaryOp object at 0x7da1b2066710> begin[:]
variable[registry] assign[=] constant[mxnet... | keyword[def] identifier[get_docker_tag] ( identifier[platform] : identifier[str] , identifier[registry] : identifier[str] )-> identifier[str] :
literal[string]
identifier[platform] = identifier[platform] keyword[if] identifier[any] ( identifier[x] keyword[in] identifier[platform] keyword[for] identif... | def get_docker_tag(platform: str, registry: str) -> str:
""":return: docker tag to be used for the container"""
platform = platform if any((x in platform for x in ['build.', 'publish.'])) else 'build.{}'.format(platform)
if not registry:
registry = 'mxnet_local' # depends on [control=['if'], data=[... |
def _build_shebang(self, executable, post_interp):
"""
Build a shebang line. In the simple case (on Windows, or a shebang line
which is not too long or contains spaces) use a simple formulation for
the shebang. Otherwise, use /bin/sh as the executable, with a contrived
shebang wh... | def function[_build_shebang, parameter[self, executable, post_interp]]:
constant[
Build a shebang line. In the simple case (on Windows, or a shebang line
which is not too long or contains spaces) use a simple formulation for
the shebang. Otherwise, use /bin/sh as the executable, with a c... | keyword[def] identifier[_build_shebang] ( identifier[self] , identifier[executable] , identifier[post_interp] ):
literal[string]
keyword[if] identifier[os] . identifier[name] != literal[string] :
identifier[simple_shebang] = keyword[True]
keyword[else] :
... | def _build_shebang(self, executable, post_interp):
"""
Build a shebang line. In the simple case (on Windows, or a shebang line
which is not too long or contains spaces) use a simple formulation for
the shebang. Otherwise, use /bin/sh as the executable, with a contrived
shebang which ... |
def sanity_updates_after_move(self, oldpath, newpath):
"""
Updates the list of sql statements needed after moving nodes.
1. :attr:`depth` updates *ONLY* needed by mysql databases (*sigh*)
2. update the number of children of parent nodes
"""
if (
self.node... | def function[sanity_updates_after_move, parameter[self, oldpath, newpath]]:
constant[
Updates the list of sql statements needed after moving nodes.
1. :attr:`depth` updates *ONLY* needed by mysql databases (*sigh*)
2. update the number of children of parent nodes
]
if <a... | keyword[def] identifier[sanity_updates_after_move] ( identifier[self] , identifier[oldpath] , identifier[newpath] ):
literal[string]
keyword[if] (
identifier[self] . identifier[node_cls] . identifier[get_database_vendor] ( literal[string] )== literal[string] keyword[and]
identif... | def sanity_updates_after_move(self, oldpath, newpath):
"""
Updates the list of sql statements needed after moving nodes.
1. :attr:`depth` updates *ONLY* needed by mysql databases (*sigh*)
2. update the number of children of parent nodes
"""
if self.node_cls.get_database_vendor('... |
def __get_exception_message(self):
""" This method extracts the message from an exception if there
was an exception that occurred during the test, assuming
that the exception was in a try/except block and not thrown. """
exception_info = sys.exc_info()[1]
if hasattr(excep... | def function[__get_exception_message, parameter[self]]:
constant[ This method extracts the message from an exception if there
was an exception that occurred during the test, assuming
that the exception was in a try/except block and not thrown. ]
variable[exception_info] assign[=]... | keyword[def] identifier[__get_exception_message] ( identifier[self] ):
literal[string]
identifier[exception_info] = identifier[sys] . identifier[exc_info] ()[ literal[int] ]
keyword[if] identifier[hasattr] ( identifier[exception_info] , literal[string] ):
identifier[exc_messa... | def __get_exception_message(self):
""" This method extracts the message from an exception if there
was an exception that occurred during the test, assuming
that the exception was in a try/except block and not thrown. """
exception_info = sys.exc_info()[1]
if hasattr(exception_info, '... |
def send(self, use_open_peers=True, queue=True, **kw):
"""
send a transaction immediately. Failed transactions are picked up by the TxBroadcaster
:param ip: specific peer IP to send tx to
:param port: port of specific peer
:param use_open_peers: use Arky's broadcast method
... | def function[send, parameter[self, use_open_peers, queue]]:
constant[
send a transaction immediately. Failed transactions are picked up by the TxBroadcaster
:param ip: specific peer IP to send tx to
:param port: port of specific peer
:param use_open_peers: use Arky's broadcast m... | keyword[def] identifier[send] ( identifier[self] , identifier[use_open_peers] = keyword[True] , identifier[queue] = keyword[True] ,** identifier[kw] ):
literal[string]
keyword[if] keyword[not] identifier[use_open_peers] :
identifier[ip] = identifier[kw] . identifier[get] ( literal[s... | def send(self, use_open_peers=True, queue=True, **kw):
"""
send a transaction immediately. Failed transactions are picked up by the TxBroadcaster
:param ip: specific peer IP to send tx to
:param port: port of specific peer
:param use_open_peers: use Arky's broadcast method
"... |
def parse_branchset(self, branchset_node, depth, number, validate):
"""
Create :class:`BranchSet` object using data in ``branchset_node``.
:param branchset_node:
``etree.Element`` object with tag "logicTreeBranchSet".
:param depth:
The sequential number of branch... | def function[parse_branchset, parameter[self, branchset_node, depth, number, validate]]:
constant[
Create :class:`BranchSet` object using data in ``branchset_node``.
:param branchset_node:
``etree.Element`` object with tag "logicTreeBranchSet".
:param depth:
The ... | keyword[def] identifier[parse_branchset] ( identifier[self] , identifier[branchset_node] , identifier[depth] , identifier[number] , identifier[validate] ):
literal[string]
identifier[uncertainty_type] = identifier[branchset_node] . identifier[attrib] . identifier[get] ( literal[string] )
i... | def parse_branchset(self, branchset_node, depth, number, validate):
"""
Create :class:`BranchSet` object using data in ``branchset_node``.
:param branchset_node:
``etree.Element`` object with tag "logicTreeBranchSet".
:param depth:
The sequential number of branchset'... |
def message(self, tree, spins, subtheta, auxvars):
"""Determine the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
auxvars (dict): The auxiliar... | def function[message, parameter[self, tree, spins, subtheta, auxvars]]:
constant[Determine the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
a... | keyword[def] identifier[message] ( identifier[self] , identifier[tree] , identifier[spins] , identifier[subtheta] , identifier[auxvars] ):
literal[string]
identifier[energy_sources] = identifier[set] ()
keyword[for] identifier[v] , identifier[children] keyword[in] identifier[tree] . ide... | def message(self, tree, spins, subtheta, auxvars):
"""Determine the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
auxvars (dict): The auxiliary va... |
def _init():
"""Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
"""
preferred = os.getenv("QT_PREFERRED_BINDING")
verbose = os.... | def function[_init, parameter[]]:
constant[Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
]
variable[preferred] assign[=] c... | keyword[def] identifier[_init] ():
literal[string]
identifier[preferred] = identifier[os] . identifier[getenv] ( literal[string] )
identifier[verbose] = identifier[os] . identifier[getenv] ( literal[string] ) keyword[is] keyword[not] keyword[None]
keyword[if] identifier[preferred] :
... | def _init():
"""Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
"""
preferred = os.getenv('QT_PREFERRED_BINDING')
verbose = os.g... |
def generatePlugins(widgetPath = None, buildPath = None):
"""
Generates all the plugin files for the system and imports them.
:param widgetPath | <str> || None
buildPath | <str> || None
"""
if widgetPath is None:
widgetPath = WIDGET_PATH
if b... | def function[generatePlugins, parameter[widgetPath, buildPath]]:
constant[
Generates all the plugin files for the system and imports them.
:param widgetPath | <str> || None
buildPath | <str> || None
]
if compare[name[widgetPath] is constant[None]] begin[:]
... | keyword[def] identifier[generatePlugins] ( identifier[widgetPath] = keyword[None] , identifier[buildPath] = keyword[None] ):
literal[string]
keyword[if] identifier[widgetPath] keyword[is] keyword[None] :
identifier[widgetPath] = identifier[WIDGET_PATH]
keyword[if] identifier[buildP... | def generatePlugins(widgetPath=None, buildPath=None):
"""
Generates all the plugin files for the system and imports them.
:param widgetPath | <str> || None
buildPath | <str> || None
"""
if widgetPath is None:
widgetPath = WIDGET_PATH # depends on [control=['if'], ... |
def _format_select(formatter, name):
"""Modify the query selector by applying any formatters to it.
Parameters
----------
formatter : str
Hyphen-delimited formatter string where formatters are
applied inside-out, e.g. the formatter string
SEC_TO_MICRO-INTEGER-FORMAT_UTC_USEC applie... | def function[_format_select, parameter[formatter, name]]:
constant[Modify the query selector by applying any formatters to it.
Parameters
----------
formatter : str
Hyphen-delimited formatter string where formatters are
applied inside-out, e.g. the formatter string
SEC_TO_MICRO... | keyword[def] identifier[_format_select] ( identifier[formatter] , identifier[name] ):
literal[string]
keyword[for] identifier[caster] keyword[in] identifier[formatter] . identifier[split] ( literal[string] ):
keyword[if] identifier[caster] == literal[string] :
identifier[name] = ... | def _format_select(formatter, name):
"""Modify the query selector by applying any formatters to it.
Parameters
----------
formatter : str
Hyphen-delimited formatter string where formatters are
applied inside-out, e.g. the formatter string
SEC_TO_MICRO-INTEGER-FORMAT_UTC_USEC applie... |
def p_path_sum(self, p):
""" path_sum : ctx_path
| path_sum PLUS ctx_path"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[3]] | def function[p_path_sum, parameter[self, p]]:
constant[ path_sum : ctx_path
| path_sum PLUS ctx_path]
if compare[call[name[len], parameter[name[p]]] equal[==] constant[2]] begin[:]
call[name[p]][constant[0]] assign[=] list[[<ast.Subscript object at 0x7da1b0285150>]] | keyword[def] identifier[p_path_sum] ( identifier[self] , identifier[p] ):
literal[string]
keyword[if] identifier[len] ( identifier[p] )== literal[int] :
identifier[p] [ literal[int] ]=[ identifier[p] [ literal[int] ]]
keyword[else] :
identifier[p] [ literal[int] ... | def p_path_sum(self, p):
""" path_sum : ctx_path
| path_sum PLUS ctx_path"""
if len(p) == 2:
p[0] = [p[1]] # depends on [control=['if'], data=[]]
else:
p[0] = p[1] + [p[3]] |
def _update_from_file(self, filename):
""" Helper method to update an existing configuration with the values from a file.
Loads a configuration file and replaces all values in the existing configuration
dictionary with the values from the file.
Args:
filename (str): The pat... | def function[_update_from_file, parameter[self, filename]]:
constant[ Helper method to update an existing configuration with the values from a file.
Loads a configuration file and replaces all values in the existing configuration
dictionary with the values from the file.
Args:
... | keyword[def] identifier[_update_from_file] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[filename] ):
keyword[try] :
keyword[with] identifier[open] ( identifier[filename] ,... | def _update_from_file(self, filename):
""" Helper method to update an existing configuration with the values from a file.
Loads a configuration file and replaces all values in the existing configuration
dictionary with the values from the file.
Args:
filename (str): The path an... |
def package_regex_filter(config, message, pattern=None, *args, **kw):
""" All packages matching a regular expression
Use this rule to include messages that relate to packages that match
particular regular expressions
(*i.e., (maven|javapackages-tools|maven-surefire)*).
"""
pattern = kw.get('pa... | def function[package_regex_filter, parameter[config, message, pattern]]:
constant[ All packages matching a regular expression
Use this rule to include messages that relate to packages that match
particular regular expressions
(*i.e., (maven|javapackages-tools|maven-surefire)*).
]
variab... | keyword[def] identifier[package_regex_filter] ( identifier[config] , identifier[message] , identifier[pattern] = keyword[None] ,* identifier[args] ,** identifier[kw] ):
literal[string]
identifier[pattern] = identifier[kw] . identifier[get] ( literal[string] , identifier[pattern] )
keyword[if] identi... | def package_regex_filter(config, message, pattern=None, *args, **kw):
""" All packages matching a regular expression
Use this rule to include messages that relate to packages that match
particular regular expressions
(*i.e., (maven|javapackages-tools|maven-surefire)*).
"""
pattern = kw.get('pat... |
def tdecode(pkt, *args):
"""Run tshark to decode and display the packet. If no args defined uses -V"""
if not args:
args = [ "-V" ]
fname = get_temp_file()
wrpcap(fname,[pkt])
subprocess.call(["tshark", "-r", fname] + list(args)) | def function[tdecode, parameter[pkt]]:
constant[Run tshark to decode and display the packet. If no args defined uses -V]
if <ast.UnaryOp object at 0x7da1b12abeb0> begin[:]
variable[args] assign[=] list[[<ast.Constant object at 0x7da1b12aa1a0>]]
variable[fname] assign[=] call[name... | keyword[def] identifier[tdecode] ( identifier[pkt] ,* identifier[args] ):
literal[string]
keyword[if] keyword[not] identifier[args] :
identifier[args] =[ literal[string] ]
identifier[fname] = identifier[get_temp_file] ()
identifier[wrpcap] ( identifier[fname] ,[ identifier[pkt] ])
i... | def tdecode(pkt, *args):
"""Run tshark to decode and display the packet. If no args defined uses -V"""
if not args:
args = ['-V'] # depends on [control=['if'], data=[]]
fname = get_temp_file()
wrpcap(fname, [pkt])
subprocess.call(['tshark', '-r', fname] + list(args)) |
def wrapper(vertices_resources, vertices_applications,
nets, net_keys,
machine, constraints=[],
reserve_monitor=True, align_sdram=True,
place=default_place, place_kwargs={},
allocate=default_allocate, allocate_kwargs={},
route=default_route, route_... | def function[wrapper, parameter[vertices_resources, vertices_applications, nets, net_keys, machine, constraints, reserve_monitor, align_sdram, place, place_kwargs, allocate, allocate_kwargs, route, route_kwargs, core_resource, sdram_resource]]:
constant[Wrapper for core place-and-route tasks for the common case... | keyword[def] identifier[wrapper] ( identifier[vertices_resources] , identifier[vertices_applications] ,
identifier[nets] , identifier[net_keys] ,
identifier[machine] , identifier[constraints] =[],
identifier[reserve_monitor] = keyword[True] , identifier[align_sdram] = keyword[True] ,
identifier[place] = identifie... | def wrapper(vertices_resources, vertices_applications, nets, net_keys, machine, constraints=[], reserve_monitor=True, align_sdram=True, place=default_place, place_kwargs={}, allocate=default_allocate, allocate_kwargs={}, route=default_route, route_kwargs={}, core_resource=Cores, sdram_resource=SDRAM):
"""Wrapper fo... |
def clone(self, ignore=()):
"""
Clone this dag using a set of substitutions.
Traverse the dag in topological order.
"""
nodes = [
clone(node, self.substitutions, ignore)
for node in toposorted(self.nodes, self.edges)
]
return DAG(nodes=no... | def function[clone, parameter[self, ignore]]:
constant[
Clone this dag using a set of substitutions.
Traverse the dag in topological order.
]
variable[nodes] assign[=] <ast.ListComp object at 0x7da1b0c3ef20>
return[call[call[name[DAG], parameter[]].build_edges, parameter[]]... | keyword[def] identifier[clone] ( identifier[self] , identifier[ignore] =()):
literal[string]
identifier[nodes] =[
identifier[clone] ( identifier[node] , identifier[self] . identifier[substitutions] , identifier[ignore] )
keyword[for] identifier[node] keyword[in] identifier[topo... | def clone(self, ignore=()):
"""
Clone this dag using a set of substitutions.
Traverse the dag in topological order.
"""
nodes = [clone(node, self.substitutions, ignore) for node in toposorted(self.nodes, self.edges)]
return DAG(nodes=nodes, substitutions=self.substitutions).build_e... |
def exit_enable_mode(self, exit_command=""):
"""Exit enable mode.
:param exit_command: Command that exits the session from privileged mode
:type exit_command: str
"""
output = ""
if self.check_enable_mode():
self.write_channel(self.normalize_cmd(exit_command)... | def function[exit_enable_mode, parameter[self, exit_command]]:
constant[Exit enable mode.
:param exit_command: Command that exits the session from privileged mode
:type exit_command: str
]
variable[output] assign[=] constant[]
if call[name[self].check_enable_mode, parame... | keyword[def] identifier[exit_enable_mode] ( identifier[self] , identifier[exit_command] = literal[string] ):
literal[string]
identifier[output] = literal[string]
keyword[if] identifier[self] . identifier[check_enable_mode] ():
identifier[self] . identifier[write_channel] ( i... | def exit_enable_mode(self, exit_command=''):
"""Exit enable mode.
:param exit_command: Command that exits the session from privileged mode
:type exit_command: str
"""
output = ''
if self.check_enable_mode():
self.write_channel(self.normalize_cmd(exit_command))
output... |
def _extract_features(self):
"""
Extracts and sets the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
# If it's ssh, we can handle it
if parsed_line.get('program') == 'sshd':
result = self._parse... | def function[_extract_features, parameter[self]]:
constant[
Extracts and sets the feature data from the log file necessary for a reduction
]
for taget[name[parsed_line]] in starred[name[self].parsed_lines] begin[:]
if compare[call[name[parsed_line].get, parameter[constant... | keyword[def] identifier[_extract_features] ( identifier[self] ):
literal[string]
keyword[for] identifier[parsed_line] keyword[in] identifier[self] . identifier[parsed_lines] :
keyword[if] identifier[parsed_line] . identifier[get] ( literal[string] )== literal[string] :
... | def _extract_features(self):
"""
Extracts and sets the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
# If it's ssh, we can handle it
if parsed_line.get('program') == 'sshd':
result = self._parse_auth_message(parsed_... |
def _do_batched_write_command(
namespace, operation, command, docs, check_keys, opts, ctx):
"""Batched write commands entry point."""
if ctx.sock_info.compression_context:
return _batched_write_command_compressed(
namespace, operation, command, docs, check_keys, opts, ctx)
return... | def function[_do_batched_write_command, parameter[namespace, operation, command, docs, check_keys, opts, ctx]]:
constant[Batched write commands entry point.]
if name[ctx].sock_info.compression_context begin[:]
return[call[name[_batched_write_command_compressed], parameter[name[namespace], name[o... | keyword[def] identifier[_do_batched_write_command] (
identifier[namespace] , identifier[operation] , identifier[command] , identifier[docs] , identifier[check_keys] , identifier[opts] , identifier[ctx] ):
literal[string]
keyword[if] identifier[ctx] . identifier[sock_info] . identifier[compression_context... | def _do_batched_write_command(namespace, operation, command, docs, check_keys, opts, ctx):
"""Batched write commands entry point."""
if ctx.sock_info.compression_context:
return _batched_write_command_compressed(namespace, operation, command, docs, check_keys, opts, ctx) # depends on [control=['if'], d... |
def setbit(self, name, offset, value):
"""
Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
"""
value = value and 1 or 0
return self.execute_command('SETBIT', name, offset, value) | def function[setbit, parameter[self, name, offset, value]]:
constant[
Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
]
variable[value] assign[=] <ast.BoolOp object at 0x7da18dc9b820>
return[call[name[self].execute_... | keyword[def] identifier[setbit] ( identifier[self] , identifier[name] , identifier[offset] , identifier[value] ):
literal[string]
identifier[value] = identifier[value] keyword[and] literal[int] keyword[or] literal[int]
keyword[return] identifier[self] . identifier[execute_command] ( ... | def setbit(self, name, offset, value):
"""
Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
"""
value = value and 1 or 0
return self.execute_command('SETBIT', name, offset, value) |
def _z(self, x):
"""Standardize input `x` to a unit normal."""
with tf.name_scope("standardize"):
return (x - self.loc) / self.scale | def function[_z, parameter[self, x]]:
constant[Standardize input `x` to a unit normal.]
with call[name[tf].name_scope, parameter[constant[standardize]]] begin[:]
return[binary_operation[binary_operation[name[x] - name[self].loc] / name[self].scale]] | keyword[def] identifier[_z] ( identifier[self] , identifier[x] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
keyword[return] ( identifier[x] - identifier[self] . identifier[loc] )/ identifier[self] . identifier[scale] | def _z(self, x):
"""Standardize input `x` to a unit normal."""
with tf.name_scope('standardize'):
return (x - self.loc) / self.scale # depends on [control=['with'], data=[]] |
def default(self, obj, **kwargs):
"""Handles the adapting of special types from mongo"""
if isinstance(obj, datetime.datetime):
return time.mktime(obj.timetuple())
if isinstance(obj, Timestamp):
return obj.time
if isinstance(obj, ObjectId):
return ob... | def function[default, parameter[self, obj]]:
constant[Handles the adapting of special types from mongo]
if call[name[isinstance], parameter[name[obj], name[datetime].datetime]] begin[:]
return[call[name[time].mktime, parameter[call[name[obj].timetuple, parameter[]]]]]
if call[name[isinst... | keyword[def] identifier[default] ( identifier[self] , identifier[obj] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[datetime] . identifier[datetime] ):
keyword[return] identifier[time] . identifier[mktime] ( identifier[obj... | def default(self, obj, **kwargs):
"""Handles the adapting of special types from mongo"""
if isinstance(obj, datetime.datetime):
return time.mktime(obj.timetuple()) # depends on [control=['if'], data=[]]
if isinstance(obj, Timestamp):
return obj.time # depends on [control=['if'], data=[]]
... |
def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None):
"""This is used by the interact() method.
"""
while self.isalive():
r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
if self.child_fd in r:
da... | def function[__interact_copy, parameter[self, escape_character, input_filter, output_filter]]:
constant[This is used by the interact() method.
]
while call[name[self].isalive, parameter[]] begin[:]
<ast.Tuple object at 0x7da1b021c160> assign[=] call[name[self].__select, parameter... | keyword[def] identifier[__interact_copy] ( identifier[self] , identifier[escape_character] = keyword[None] , identifier[input_filter] = keyword[None] , identifier[output_filter] = keyword[None] ):
literal[string]
keyword[while] identifier[self] . identifier[isalive] ():
identifier[r... | def __interact_copy(self, escape_character=None, input_filter=None, output_filter=None):
"""This is used by the interact() method.
"""
while self.isalive():
(r, w, e) = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
if self.child_fd in r:
data = self.__interact_rea... |
def pair(self):
""" Return tuple (address, port), where address is a string (empty string if self.address() is None) and
port is an integer (zero if self.port() is None). Mainly, this tuple is used with python socket module
(like in bind method)
:return: 2 value tuple of str and int.
"""
address = str(self... | def function[pair, parameter[self]]:
constant[ Return tuple (address, port), where address is a string (empty string if self.address() is None) and
port is an integer (zero if self.port() is None). Mainly, this tuple is used with python socket module
(like in bind method)
:return: 2 value tuple of str an... | keyword[def] identifier[pair] ( identifier[self] ):
literal[string]
identifier[address] = identifier[str] ( identifier[self] . identifier[__address] ) keyword[if] identifier[self] . identifier[__address] keyword[is] keyword[not] keyword[None] keyword[else] literal[string]
identifier[port] = identifie... | def pair(self):
""" Return tuple (address, port), where address is a string (empty string if self.address() is None) and
port is an integer (zero if self.port() is None). Mainly, this tuple is used with python socket module
(like in bind method)
:return: 2 value tuple of str and int.
"""
address = str(... |
def generate_config(directory):
"""
Generate default config file
"""
default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.yml")
target_config_path = os.path.abspath(os.path.join(directory, 'config.yml'))
shutil.copy(default_config, target_config_path)
six.print_... | def function[generate_config, parameter[directory]]:
constant[
Generate default config file
]
variable[default_config] assign[=] call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[call[name[os].path.realpath, parameter[name[__file__]]]]], constant[config.yml]]]
vari... | keyword[def] identifier[generate_config] ( identifier[directory] ):
literal[string]
identifier[default_config] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[realpath] ( identifier[__file__] )... | def generate_config(directory):
"""
Generate default config file
"""
default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.yml')
target_config_path = os.path.abspath(os.path.join(directory, 'config.yml'))
shutil.copy(default_config, target_config_path)
six.print_... |
def register_lookup_handler(lookup_type, handler_or_path):
"""Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler
"""
handler = handler_or_path
if isinstance(handler_or_path, ba... | def function[register_lookup_handler, parameter[lookup_type, handler_or_path]]:
constant[Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler
]
variable[handler] assign[=] na... | keyword[def] identifier[register_lookup_handler] ( identifier[lookup_type] , identifier[handler_or_path] ):
literal[string]
identifier[handler] = identifier[handler_or_path]
keyword[if] identifier[isinstance] ( identifier[handler_or_path] , identifier[basestring] ):
identifier[handler] = id... | def register_lookup_handler(lookup_type, handler_or_path):
"""Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler
"""
handler = handler_or_path
if isinstance(handler_or_path, ba... |
def add_simple_link(self, issue, object):
"""Add a simple remote link from an issue to web resource.
This avoids the admin access problems from add_remote_link by just
using a simple object and presuming all fields are correct and not
requiring more complex ``application`` data.... | def function[add_simple_link, parameter[self, issue, object]]:
constant[Add a simple remote link from an issue to web resource.
This avoids the admin access problems from add_remote_link by just
using a simple object and presuming all fields are correct and not
requiring more co... | keyword[def] identifier[add_simple_link] ( identifier[self] , identifier[issue] , identifier[object] ):
literal[string]
identifier[data] ={ literal[string] : identifier[object] }
identifier[url] = identifier[self] . identifier[_get_url] ( literal[string] + identifier[str] ( identifier[issu... | def add_simple_link(self, issue, object):
"""Add a simple remote link from an issue to web resource.
This avoids the admin access problems from add_remote_link by just
using a simple object and presuming all fields are correct and not
requiring more complex ``application`` data.
... |
def add_mag_drift_unit_vectors_ecef(inst, steps=None, max_steps=40000, step_size=10.,
ref_height=120.):
"""Adds unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in ECEF coordinates.
Parameters
... | def function[add_mag_drift_unit_vectors_ecef, parameter[inst, steps, max_steps, step_size, ref_height]]:
constant[Adds unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in ECEF coordinates.
Parameters
----------
inst :... | keyword[def] identifier[add_mag_drift_unit_vectors_ecef] ( identifier[inst] , identifier[steps] = keyword[None] , identifier[max_steps] = literal[int] , identifier[step_size] = literal[int] ,
identifier[ref_height] = literal[int] ):
literal[string]
identifier[zvx] , identifier[zvy] , identifier[zvz]... | def add_mag_drift_unit_vectors_ecef(inst, steps=None, max_steps=40000, step_size=10.0, ref_height=120.0):
"""Adds unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in ECEF coordinates.
Parameters
----------
inst : pysat.In... |
def region_size(im):
r"""
Replace each voxel with size of region to which it belongs
Parameters
----------
im : ND-array
Either a boolean image wtih ``True`` indicating the features of
interest, in which case ``scipy.ndimage.label`` will be applied to
find regions, or a grey... | def function[region_size, parameter[im]]:
constant[
Replace each voxel with size of region to which it belongs
Parameters
----------
im : ND-array
Either a boolean image wtih ``True`` indicating the features of
interest, in which case ``scipy.ndimage.label`` will be applied to
... | keyword[def] identifier[region_size] ( identifier[im] ):
literal[string]
keyword[if] identifier[im] . identifier[dtype] == identifier[bool] :
identifier[im] = identifier[spim] . identifier[label] ( identifier[im] )[ literal[int] ]
identifier[counts] = identifier[sp] . identifier[bincount] ( ... | def region_size(im):
"""
Replace each voxel with size of region to which it belongs
Parameters
----------
im : ND-array
Either a boolean image wtih ``True`` indicating the features of
interest, in which case ``scipy.ndimage.label`` will be applied to
find regions, or a greys... |
def pretty_print_list_info(num_results, page_info=None, suffix=None):
"""Pretty print list info, with pagination, for user display."""
num_results_fg = "green" if num_results else "red"
num_results_text = click.style(str(num_results), fg=num_results_fg)
if page_info and page_info.is_valid:
page... | def function[pretty_print_list_info, parameter[num_results, page_info, suffix]]:
constant[Pretty print list info, with pagination, for user display.]
variable[num_results_fg] assign[=] <ast.IfExp object at 0x7da1b19d8ac0>
variable[num_results_text] assign[=] call[name[click].style, parameter[cal... | keyword[def] identifier[pretty_print_list_info] ( identifier[num_results] , identifier[page_info] = keyword[None] , identifier[suffix] = keyword[None] ):
literal[string]
identifier[num_results_fg] = literal[string] keyword[if] identifier[num_results] keyword[else] literal[string]
identifier[num_r... | def pretty_print_list_info(num_results, page_info=None, suffix=None):
"""Pretty print list info, with pagination, for user display."""
num_results_fg = 'green' if num_results else 'red'
num_results_text = click.style(str(num_results), fg=num_results_fg)
if page_info and page_info.is_valid:
page_... |
def is_empty(self, resource):
"""Test if there is no document for resource.
:param resource: resource name
"""
args = self._es_args(resource)
res = self.elastic(resource).count(body={'query': {'match_all': {}}}, **args)
return res.get('count', 0) == 0 | def function[is_empty, parameter[self, resource]]:
constant[Test if there is no document for resource.
:param resource: resource name
]
variable[args] assign[=] call[name[self]._es_args, parameter[name[resource]]]
variable[res] assign[=] call[call[name[self].elastic, parameter[n... | keyword[def] identifier[is_empty] ( identifier[self] , identifier[resource] ):
literal[string]
identifier[args] = identifier[self] . identifier[_es_args] ( identifier[resource] )
identifier[res] = identifier[self] . identifier[elastic] ( identifier[resource] ). identifier[count] ( identifi... | def is_empty(self, resource):
"""Test if there is no document for resource.
:param resource: resource name
"""
args = self._es_args(resource)
res = self.elastic(resource).count(body={'query': {'match_all': {}}}, **args)
return res.get('count', 0) == 0 |
def _get_id(self):
"""Getter because using the id property from within was not working"""
ret = None
row = self.row
if row:
ret = row["id"]
return ret | def function[_get_id, parameter[self]]:
constant[Getter because using the id property from within was not working]
variable[ret] assign[=] constant[None]
variable[row] assign[=] name[self].row
if name[row] begin[:]
variable[ret] assign[=] call[name[row]][constant[id]]
... | keyword[def] identifier[_get_id] ( identifier[self] ):
literal[string]
identifier[ret] = keyword[None]
identifier[row] = identifier[self] . identifier[row]
keyword[if] identifier[row] :
identifier[ret] = identifier[row] [ literal[string] ]
keyword[re... | def _get_id(self):
"""Getter because using the id property from within was not working"""
ret = None
row = self.row
if row:
ret = row['id'] # depends on [control=['if'], data=[]]
return ret |
def __reorganize_geo(self):
"""
Concat geo value and units, and reorganize the rest
References geo data from self.noaa_data_sorted
Places new data into self.noaa_geo temporarily, and then back into self.noaa_data_sorted.
:return:
"""
logger_lpd_noaa.info("enter re... | def function[__reorganize_geo, parameter[self]]:
constant[
Concat geo value and units, and reorganize the rest
References geo data from self.noaa_data_sorted
Places new data into self.noaa_geo temporarily, and then back into self.noaa_data_sorted.
:return:
]
call[... | keyword[def] identifier[__reorganize_geo] ( identifier[self] ):
literal[string]
identifier[logger_lpd_noaa] . identifier[info] ( literal[string] )
keyword[try] :
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[self] . identifier[noaa_data_sorted]... | def __reorganize_geo(self):
"""
Concat geo value and units, and reorganize the rest
References geo data from self.noaa_data_sorted
Places new data into self.noaa_geo temporarily, and then back into self.noaa_data_sorted.
:return:
"""
logger_lpd_noaa.info('enter reorganize... |
def duration(self):
""" Returns task's current duration in minutes.
"""
if not self._loaded:
return 0
delta = datetime.datetime.now() - self._start_time
total_secs = (delta.microseconds +
(delta.seconds + delta.days * 24 * 3600) *
... | def function[duration, parameter[self]]:
constant[ Returns task's current duration in minutes.
]
if <ast.UnaryOp object at 0x7da1b134b400> begin[:]
return[constant[0]]
variable[delta] assign[=] binary_operation[call[name[datetime].datetime.now, parameter[]] - name[self]._star... | keyword[def] identifier[duration] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_loaded] :
keyword[return] literal[int]
identifier[delta] = identifier[datetime] . identifier[datetime] . identifier[now] ()- identifier[self] .... | def duration(self):
""" Returns task's current duration in minutes.
"""
if not self._loaded:
return 0 # depends on [control=['if'], data=[]]
delta = datetime.datetime.now() - self._start_time
total_secs = (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10 ** 6) / 10... |
def deprecated(version, version_removed):
'''This is a decorator which can be used to mark functions
as deprecated.
It will result in a warning being emitted when the function is used.'''
def __wrapper(func, *args, **kwargs):
'''Warn the user, and then proceed.'''
code = six.get_functi... | def function[deprecated, parameter[version, version_removed]]:
constant[This is a decorator which can be used to mark functions
as deprecated.
It will result in a warning being emitted when the function is used.]
def function[__wrapper, parameter[func]]:
constant[Warn the user, ... | keyword[def] identifier[deprecated] ( identifier[version] , identifier[version_removed] ):
literal[string]
keyword[def] identifier[__wrapper] ( identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[code] = identifier[six] . identifier[get_function_co... | def deprecated(version, version_removed):
"""This is a decorator which can be used to mark functions
as deprecated.
It will result in a warning being emitted when the function is used."""
def __wrapper(func, *args, **kwargs):
"""Warn the user, and then proceed."""
code = six.get_functi... |
def get_profile_name(org_vm, profile_inst):
"""
Get the org, name, and version from the profile instance and
return them as a tuple.
Returns: tuple of org, name, vers
Raises:
TypeError: if invalid property type
ValueError: If property value outside range
"""
try:
org = o... | def function[get_profile_name, parameter[org_vm, profile_inst]]:
constant[
Get the org, name, and version from the profile instance and
return them as a tuple.
Returns: tuple of org, name, vers
Raises:
TypeError: if invalid property type
ValueError: If property value outside range
... | keyword[def] identifier[get_profile_name] ( identifier[org_vm] , identifier[profile_inst] ):
literal[string]
keyword[try] :
identifier[org] = identifier[org_vm] . identifier[tovalues] ( identifier[profile_inst] [ literal[string] ])
identifier[name] = identifier[profile_inst] [ literal[str... | def get_profile_name(org_vm, profile_inst):
"""
Get the org, name, and version from the profile instance and
return them as a tuple.
Returns: tuple of org, name, vers
Raises:
TypeError: if invalid property type
ValueError: If property value outside range
"""
try:
org = o... |
def ParseObjs(self, objs, expression):
"""Parse one or more objects by testing if it has matching stat results.
Args:
objs: An iterable of objects that should be checked.
expression: A StatFilter expression, e.g.:
"uid:>0 gid:=0 file_type:link"
Yields:
matching objects.
"""
... | def function[ParseObjs, parameter[self, objs, expression]]:
constant[Parse one or more objects by testing if it has matching stat results.
Args:
objs: An iterable of objects that should be checked.
expression: A StatFilter expression, e.g.:
"uid:>0 gid:=0 file_type:link"
Yields:
... | keyword[def] identifier[ParseObjs] ( identifier[self] , identifier[objs] , identifier[expression] ):
literal[string]
identifier[self] . identifier[Validate] ( identifier[expression] )
keyword[for] identifier[obj] keyword[in] identifier[objs] :
keyword[if] keyword[not] identifier[isinstance... | def ParseObjs(self, objs, expression):
"""Parse one or more objects by testing if it has matching stat results.
Args:
objs: An iterable of objects that should be checked.
expression: A StatFilter expression, e.g.:
"uid:>0 gid:=0 file_type:link"
Yields:
matching objects.
"""
... |
def cdata(text):
"""Wraps the input `text` in a ``<![CDATA[ ]]>`` block.
If the text contains CDATA sections already, they are stripped and replaced
by the application of an outer-most CDATA block.
Args:
text: A string to wrap in a CDATA block.
Returns:
The `text` value wrapped in... | def function[cdata, parameter[text]]:
constant[Wraps the input `text` in a ``<![CDATA[ ]]>`` block.
If the text contains CDATA sections already, they are stripped and replaced
by the application of an outer-most CDATA block.
Args:
text: A string to wrap in a CDATA block.
Returns:
... | keyword[def] identifier[cdata] ( identifier[text] ):
literal[string]
keyword[if] keyword[not] identifier[text] :
keyword[return] identifier[text]
keyword[if] identifier[is_cdata] ( identifier[text] ):
identifier[text] = identifier[strip_cdata] ( identifier[text] )
identif... | def cdata(text):
"""Wraps the input `text` in a ``<![CDATA[ ]]>`` block.
If the text contains CDATA sections already, they are stripped and replaced
by the application of an outer-most CDATA block.
Args:
text: A string to wrap in a CDATA block.
Returns:
The `text` value wrapped in... |
def decorate_disabled(self):
""" Return True if this decoration must be omitted, otherwise - False.
This class searches for tags values in environment variable
(:attr:`.Verifier.__environment_var__`), Derived class can implement any logic
:return: bool
"""
if len(self._tags) == 0:
return False
if sel... | def function[decorate_disabled, parameter[self]]:
constant[ Return True if this decoration must be omitted, otherwise - False.
This class searches for tags values in environment variable
(:attr:`.Verifier.__environment_var__`), Derived class can implement any logic
:return: bool
]
if compare[ca... | keyword[def] identifier[decorate_disabled] ( identifier[self] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[_tags] )== literal[int] :
keyword[return] keyword[False]
keyword[if] identifier[self] . identifier[_env_var] keyword[not] keyword[in] identifier[os] . iden... | def decorate_disabled(self):
""" Return True if this decoration must be omitted, otherwise - False.
This class searches for tags values in environment variable
(:attr:`.Verifier.__environment_var__`), Derived class can implement any logic
:return: bool
"""
if len(self._tags) == 0:
return False ... |
def _roundSlist(slist):
""" Rounds a signed list over the last element and removes it. """
slist[-1] = 60 if slist[-1] >= 30 else 0
for i in range(len(slist)-1, 1, -1):
if slist[i] == 60:
slist[i] = 0
slist[i-1] += 1
return slist[:-1] | def function[_roundSlist, parameter[slist]]:
constant[ Rounds a signed list over the last element and removes it. ]
call[name[slist]][<ast.UnaryOp object at 0x7da1b11a2a70>] assign[=] <ast.IfExp object at 0x7da1b11a24d0>
for taget[name[i]] in starred[call[name[range], parameter[binary_operation[... | keyword[def] identifier[_roundSlist] ( identifier[slist] ):
literal[string]
identifier[slist] [- literal[int] ]= literal[int] keyword[if] identifier[slist] [- literal[int] ]>= literal[int] keyword[else] literal[int]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( i... | def _roundSlist(slist):
""" Rounds a signed list over the last element and removes it. """
slist[-1] = 60 if slist[-1] >= 30 else 0
for i in range(len(slist) - 1, 1, -1):
if slist[i] == 60:
slist[i] = 0
slist[i - 1] += 1 # depends on [control=['if'], data=[]] # depends on [... |
def fn_int16(self, value):
"""
Return the value cast to an 16-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... | def function[fn_int16, parameter[self, value]]:
constant[
Return the value cast to an 16-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
]
if <ast.BoolOp object at 0x7da18f58da50> ... | keyword[def] identifier[fn_int16] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[is_ndarray] ( identifier[value] ) keyword[or] identifier[isinstance] ( identifier[value] ,( identifier[list] , identifier[tuple] )):
keyword[return] identifier[self] .... | def fn_int16(self, value):
"""
Return the value cast to an 16-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return s... |
def p_var_decl_ini(p):
""" var_decl : DIM idlist typedef EQ expr
| CONST idlist typedef EQ expr
"""
p[0] = None
if len(p[2]) != 1:
syntax_error(p.lineno(1),
"Initialized variables must be declared one by one.")
return
if p[5] is None:
re... | def function[p_var_decl_ini, parameter[p]]:
constant[ var_decl : DIM idlist typedef EQ expr
| CONST idlist typedef EQ expr
]
call[name[p]][constant[0]] assign[=] constant[None]
if compare[call[name[len], parameter[call[name[p]][constant[2]]]] not_equal[!=] constant[1]] begin... | keyword[def] identifier[p_var_decl_ini] ( identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= keyword[None]
keyword[if] identifier[len] ( identifier[p] [ literal[int] ])!= literal[int] :
identifier[syntax_error] ( identifier[p] . identifier[lineno] ( literal[int] ),
li... | def p_var_decl_ini(p):
""" var_decl : DIM idlist typedef EQ expr
| CONST idlist typedef EQ expr
"""
p[0] = None
if len(p[2]) != 1:
syntax_error(p.lineno(1), 'Initialized variables must be declared one by one.')
return # depends on [control=['if'], data=[]]
if p[5] i... |
def get_attribute_data(attr_ids, node_ids, **kwargs):
"""
For a given attribute or set of attributes, return all the resources and
resource scenarios in the network
"""
node_attrs = db.DBSession.query(ResourceAttr).\
options(joinedload_all('attr')... | def function[get_attribute_data, parameter[attr_ids, node_ids]]:
constant[
For a given attribute or set of attributes, return all the resources and
resource scenarios in the network
]
variable[node_attrs] assign[=] call[call[call[call[name[db].DBSession.query, parameter[name[Resourc... | keyword[def] identifier[get_attribute_data] ( identifier[attr_ids] , identifier[node_ids] ,** identifier[kwargs] ):
literal[string]
identifier[node_attrs] = identifier[db] . identifier[DBSession] . identifier[query] ( identifier[ResourceAttr] ). identifier[options] ( identifier[joinedload_all] ( literal[st... | def get_attribute_data(attr_ids, node_ids, **kwargs):
"""
For a given attribute or set of attributes, return all the resources and
resource scenarios in the network
"""
node_attrs = db.DBSession.query(ResourceAttr).options(joinedload_all('attr')).filter(ResourceAttr.node_id.in_(node_ids), R... |
def hup_hook(signal_or_callable=signal.SIGTERM, verbose=False):
"""
Register a signal handler for `signal.SIGHUP` that checks for modified
files and only acts if at least one modified file is found.
@type signal_or_callable: str, int or callable
@param signal_or_callable: You can pass either a sign... | def function[hup_hook, parameter[signal_or_callable, verbose]]:
constant[
Register a signal handler for `signal.SIGHUP` that checks for modified
files and only acts if at least one modified file is found.
@type signal_or_callable: str, int or callable
@param signal_or_callable: You can pass eit... | keyword[def] identifier[hup_hook] ( identifier[signal_or_callable] = identifier[signal] . identifier[SIGTERM] , identifier[verbose] = keyword[False] ):
literal[string]
keyword[def] identifier[handle_hup] ( identifier[signum] , identifier[frame] ):
identifier[changed] = identifier[modified] ... | def hup_hook(signal_or_callable=signal.SIGTERM, verbose=False):
"""
Register a signal handler for `signal.SIGHUP` that checks for modified
files and only acts if at least one modified file is found.
@type signal_or_callable: str, int or callable
@param signal_or_callable: You can pass either a sign... |
def getMessage(self):
"""Returns a colorized log message based on the log level.
If the platform is windows the original message will be returned
without colorization windows escape codes are crazy.
:returns: ``str``
"""
msg = str(self.msg)
if self.args:
... | def function[getMessage, parameter[self]]:
constant[Returns a colorized log message based on the log level.
If the platform is windows the original message will be returned
without colorization windows escape codes are crazy.
:returns: ``str``
]
variable[msg] assign[=] ... | keyword[def] identifier[getMessage] ( identifier[self] ):
literal[string]
identifier[msg] = identifier[str] ( identifier[self] . identifier[msg] )
keyword[if] identifier[self] . identifier[args] :
identifier[msg] = identifier[msg] % identifier[self] . identifier[args]
... | def getMessage(self):
"""Returns a colorized log message based on the log level.
If the platform is windows the original message will be returned
without colorization windows escape codes are crazy.
:returns: ``str``
"""
msg = str(self.msg)
if self.args:
msg = msg %... |
def _read_field(self):
'''
Read a single byte for field type, then read the value.
'''
ftype = self._input[self._pos]
self._pos += 1
reader = self.field_type_map.get(ftype)
if reader:
return reader(self)
raise Reader.FieldError('Unknown field... | def function[_read_field, parameter[self]]:
constant[
Read a single byte for field type, then read the value.
]
variable[ftype] assign[=] call[name[self]._input][name[self]._pos]
<ast.AugAssign object at 0x7da18f09d030>
variable[reader] assign[=] call[name[self].field_type_ma... | keyword[def] identifier[_read_field] ( identifier[self] ):
literal[string]
identifier[ftype] = identifier[self] . identifier[_input] [ identifier[self] . identifier[_pos] ]
identifier[self] . identifier[_pos] += literal[int]
identifier[reader] = identifier[self] . identifier[fie... | def _read_field(self):
"""
Read a single byte for field type, then read the value.
"""
ftype = self._input[self._pos]
self._pos += 1
reader = self.field_type_map.get(ftype)
if reader:
return reader(self) # depends on [control=['if'], data=[]]
raise Reader.FieldError('Unk... |
def filter_styles(style, group, other_groups, blacklist=[]):
"""
Filters styles which are specific to a particular artist, e.g.
for a GraphPlot this will filter options specific to the nodes and
edges.
Arguments
---------
style: dict
Dictionary of styles and values
group: str
... | def function[filter_styles, parameter[style, group, other_groups, blacklist]]:
constant[
Filters styles which are specific to a particular artist, e.g.
for a GraphPlot this will filter options specific to the nodes and
edges.
Arguments
---------
style: dict
Dictionary of styles ... | keyword[def] identifier[filter_styles] ( identifier[style] , identifier[group] , identifier[other_groups] , identifier[blacklist] =[]):
literal[string]
identifier[group] = identifier[group] + literal[string]
identifier[filtered] ={}
keyword[for] identifier[k] , identifier[v] keyword[in] ident... | def filter_styles(style, group, other_groups, blacklist=[]):
"""
Filters styles which are specific to a particular artist, e.g.
for a GraphPlot this will filter options specific to the nodes and
edges.
Arguments
---------
style: dict
Dictionary of styles and values
group: str
... |
def task_pause_info(task_id):
"""
Executor for `globus task pause-info`
"""
client = get_client()
res = client.task_pause_info(task_id)
def _custom_text_format(res):
explicit_pauses = [
field
for field in EXPLICIT_PAUSE_MSG_FIELDS
# n.b. some keys are... | def function[task_pause_info, parameter[task_id]]:
constant[
Executor for `globus task pause-info`
]
variable[client] assign[=] call[name[get_client], parameter[]]
variable[res] assign[=] call[name[client].task_pause_info, parameter[name[task_id]]]
def function[_custom_text_forma... | keyword[def] identifier[task_pause_info] ( identifier[task_id] ):
literal[string]
identifier[client] = identifier[get_client] ()
identifier[res] = identifier[client] . identifier[task_pause_info] ( identifier[task_id] )
keyword[def] identifier[_custom_text_format] ( identifier[res] ):
... | def task_pause_info(task_id):
"""
Executor for `globus task pause-info`
"""
client = get_client()
res = client.task_pause_info(task_id)
def _custom_text_format(res):
# n.b. some keys are absent for completed tasks
explicit_pauses = [field for field in EXPLICIT_PAUSE_MSG_FIELDS i... |
def StartHuntFlowOnClient(client_id, hunt_id):
"""Starts a flow corresponding to a given hunt on a given client."""
hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
hunt_obj = CompleteHuntIfExpirationTimeReached(hunt_obj)
# There may be a little race between foreman rules being removed and
# foreman sche... | def function[StartHuntFlowOnClient, parameter[client_id, hunt_id]]:
constant[Starts a flow corresponding to a given hunt on a given client.]
variable[hunt_obj] assign[=] call[name[data_store].REL_DB.ReadHuntObject, parameter[name[hunt_id]]]
variable[hunt_obj] assign[=] call[name[CompleteHuntIfEx... | keyword[def] identifier[StartHuntFlowOnClient] ( identifier[client_id] , identifier[hunt_id] ):
literal[string]
identifier[hunt_obj] = identifier[data_store] . identifier[REL_DB] . identifier[ReadHuntObject] ( identifier[hunt_id] )
identifier[hunt_obj] = identifier[CompleteHuntIfExpirationTimeReached] ( id... | def StartHuntFlowOnClient(client_id, hunt_id):
"""Starts a flow corresponding to a given hunt on a given client."""
hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
hunt_obj = CompleteHuntIfExpirationTimeReached(hunt_obj)
# There may be a little race between foreman rules being removed and
# for... |
def create_socket(self):
"""Create a socket for the daemon, depending on the directory location.
Args:
config_dir (str): The absolute path to the config directory used by the daemon.
Returns:
socket.socket: The daemon socket. Clients connect to this socket.
"""... | def function[create_socket, parameter[self]]:
constant[Create a socket for the daemon, depending on the directory location.
Args:
config_dir (str): The absolute path to the config directory used by the daemon.
Returns:
socket.socket: The daemon socket. Clients connect t... | keyword[def] identifier[create_socket] ( identifier[self] ):
literal[string]
identifier[socket_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[config_dir] , literal[string] )
keyword[try] :
keyword[if] identifier[os] . ide... | def create_socket(self):
"""Create a socket for the daemon, depending on the directory location.
Args:
config_dir (str): The absolute path to the config directory used by the daemon.
Returns:
socket.socket: The daemon socket. Clients connect to this socket.
"""
... |
def stat_article_detail_list(self, page=1, start_date=str(date.today()+timedelta(days=-30)), end_date=str(date.today())):
"""
获取图文分析数据
返回JSON示例 ::
{
"hasMore": true, // 说明是否可以增加 page 页码来获取数据
"data": [
{
"i... | def function[stat_article_detail_list, parameter[self, page, start_date, end_date]]:
constant[
获取图文分析数据
返回JSON示例 ::
{
"hasMore": true, // 说明是否可以增加 page 页码来获取数据
"data": [
{
"index": [
... | keyword[def] identifier[stat_article_detail_list] ( identifier[self] , identifier[page] = literal[int] , identifier[start_date] = identifier[str] ( identifier[date] . identifier[today] ()+ identifier[timedelta] ( identifier[days] =- literal[int] )), identifier[end_date] = identifier[str] ( identifier[date] . identifi... | def stat_article_detail_list(self, page=1, start_date=str(date.today() + timedelta(days=-30)), end_date=str(date.today())):
"""
获取图文分析数据
返回JSON示例 ::
{
"hasMore": true, // 说明是否可以增加 page 页码来获取数据
"data": [
{
"ind... |
def truncate(s: str, length: int = DEFAULT_CURTAIL) -> str:
"""
Truncate a string and add an ellipsis (three dots) to the end if it was too long
:param s: string to possibly truncate
:param length: length to truncate the string to
"""
if len(s) > length:
s = s[: length - 1] + '…'
re... | def function[truncate, parameter[s, length]]:
constant[
Truncate a string and add an ellipsis (three dots) to the end if it was too long
:param s: string to possibly truncate
:param length: length to truncate the string to
]
if compare[call[name[len], parameter[name[s]]] greater[>] name... | keyword[def] identifier[truncate] ( identifier[s] : identifier[str] , identifier[length] : identifier[int] = identifier[DEFAULT_CURTAIL] )-> identifier[str] :
literal[string]
keyword[if] identifier[len] ( identifier[s] )> identifier[length] :
identifier[s] = identifier[s] [: identifier[length] - ... | def truncate(s: str, length: int=DEFAULT_CURTAIL) -> str:
"""
Truncate a string and add an ellipsis (three dots) to the end if it was too long
:param s: string to possibly truncate
:param length: length to truncate the string to
"""
if len(s) > length:
s = s[:length - 1] + '…' # depend... |
def get_if_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in human readable form. If no global address is found,
None is returned.
"""
return next((x[0] for x in in6_getifaddr()
if x[2] == iff and x[1] == IPV6_ADDR_GLOBAL), None) | def function[get_if_addr6, parameter[iff]]:
constant[
Returns the main global unicast address associated with provided
interface, in human readable form. If no global address is found,
None is returned.
]
return[call[name[next], parameter[<ast.GeneratorExp object at 0x7da1b21aeaa0>, constant... | keyword[def] identifier[get_if_addr6] ( identifier[iff] ):
literal[string]
keyword[return] identifier[next] (( identifier[x] [ literal[int] ] keyword[for] identifier[x] keyword[in] identifier[in6_getifaddr] ()
keyword[if] identifier[x] [ literal[int] ]== identifier[iff] keyword[and] identifier[... | def get_if_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in human readable form. If no global address is found,
None is returned.
"""
return next((x[0] for x in in6_getifaddr() if x[2] == iff and x[1] == IPV6_ADDR_GLOBAL), None) |
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex) | def function[confirm, parameter[self, question, default, true_answer_regex]]:
constant[
Confirm a question with the user.
]
return[call[name[self]._io.confirm, parameter[name[question], name[default], name[true_answer_regex]]]] | keyword[def] identifier[confirm] ( identifier[self] , identifier[question] , identifier[default] = keyword[False] , identifier[true_answer_regex] = literal[string] ):
literal[string]
keyword[return] identifier[self] . identifier[_io] . identifier[confirm] ( identifier[question] , identifier[defaul... | def confirm(self, question, default=False, true_answer_regex='(?i)^y'):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex) |
def adj_nodes_ali(ali_nodes):
"""Adjust details specific to AliCloud."""
for node in ali_nodes:
node.cloud = "alicloud"
node.cloud_disp = "AliCloud"
node.private_ips = ip_to_str(node.extra['vpc_attributes']['private_ip_address'])
node.public_ips = ip_to_str(node.public_ips)
... | def function[adj_nodes_ali, parameter[ali_nodes]]:
constant[Adjust details specific to AliCloud.]
for taget[name[node]] in starred[name[ali_nodes]] begin[:]
name[node].cloud assign[=] constant[alicloud]
name[node].cloud_disp assign[=] constant[AliCloud]
na... | keyword[def] identifier[adj_nodes_ali] ( identifier[ali_nodes] ):
literal[string]
keyword[for] identifier[node] keyword[in] identifier[ali_nodes] :
identifier[node] . identifier[cloud] = literal[string]
identifier[node] . identifier[cloud_disp] = literal[string]
identifier[n... | def adj_nodes_ali(ali_nodes):
"""Adjust details specific to AliCloud."""
for node in ali_nodes:
node.cloud = 'alicloud'
node.cloud_disp = 'AliCloud'
node.private_ips = ip_to_str(node.extra['vpc_attributes']['private_ip_address'])
node.public_ips = ip_to_str(node.public_ips)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.