code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def init_app(self, app):
"""
:param app: :class:`sanic.Sanic` instance to rate limit.
"""
self.enabled = app.config.setdefault(C.ENABLED, True)
self._swallow_errors = app.config.setdefault(
C.SWALLOW_ERRORS, self._swallow_errors
)
self._storage_options... | def function[init_app, parameter[self, app]]:
constant[
:param app: :class:`sanic.Sanic` instance to rate limit.
]
name[self].enabled assign[=] call[name[app].config.setdefault, parameter[name[C].ENABLED, constant[True]]]
name[self]._swallow_errors assign[=] call[name[app].config... | keyword[def] identifier[init_app] ( identifier[self] , identifier[app] ):
literal[string]
identifier[self] . identifier[enabled] = identifier[app] . identifier[config] . identifier[setdefault] ( identifier[C] . identifier[ENABLED] , keyword[True] )
identifier[self] . identifier[_swallow_er... | def init_app(self, app):
"""
:param app: :class:`sanic.Sanic` instance to rate limit.
"""
self.enabled = app.config.setdefault(C.ENABLED, True)
self._swallow_errors = app.config.setdefault(C.SWALLOW_ERRORS, self._swallow_errors)
self._storage_options.update(app.config.get(C.STORAGE_OPTIO... |
def calcLogSum(Vals, sigma):
'''
Returns the optimal value given the choice specific value functions Vals.
Parameters
----------
Vals : [numpy.array]
A numpy.array that holds choice specific values at common grid points.
sigma : float
A number that controls the variance of the ta... | def function[calcLogSum, parameter[Vals, sigma]]:
constant[
Returns the optimal value given the choice specific value functions Vals.
Parameters
----------
Vals : [numpy.array]
A numpy.array that holds choice specific values at common grid points.
sigma : float
A number that ... | keyword[def] identifier[calcLogSum] ( identifier[Vals] , identifier[sigma] ):
literal[string]
keyword[if] identifier[sigma] == literal[int] :
identifier[V] = identifier[np] . identifier[amax] ( identifier[Vals] , identifier[axis] = literal[int] )
keyword[return] identifier[V]... | def calcLogSum(Vals, sigma):
"""
Returns the optimal value given the choice specific value functions Vals.
Parameters
----------
Vals : [numpy.array]
A numpy.array that holds choice specific values at common grid points.
sigma : float
A number that controls the variance of the ta... |
def multiplied(*values):
"""
Returns the product of all supplied values. One or more *values* can be
specified. For example, to light a :class:`~gpiozero.PWMLED` as the product
(i.e. multiplication) of several potentiometers connected to an
:class:`~gpiozero.MCP3008`
ADC::
from gpiozero... | def function[multiplied, parameter[]]:
constant[
Returns the product of all supplied values. One or more *values* can be
specified. For example, to light a :class:`~gpiozero.PWMLED` as the product
(i.e. multiplication) of several potentiometers connected to an
:class:`~gpiozero.MCP3008`
ADC:... | keyword[def] identifier[multiplied] (* identifier[values] ):
literal[string]
identifier[values] =[ identifier[_normalize] ( identifier[v] ) keyword[for] identifier[v] keyword[in] identifier[values] ]
keyword[def] identifier[_product] ( identifier[it] ):
identifier[p] = literal[int]
... | def multiplied(*values):
"""
Returns the product of all supplied values. One or more *values* can be
specified. For example, to light a :class:`~gpiozero.PWMLED` as the product
(i.e. multiplication) of several potentiometers connected to an
:class:`~gpiozero.MCP3008`
ADC::
from gpiozero... |
def parse_veto_definer(veto_def_filename):
""" Parse a veto definer file from the filename and return a dictionary
indexed by ifo and veto definer category level.
Parameters
----------
veto_def_filename: str
The path to the veto definer file
Returns:
parsed_definition: dict
... | def function[parse_veto_definer, parameter[veto_def_filename]]:
constant[ Parse a veto definer file from the filename and return a dictionary
indexed by ifo and veto definer category level.
Parameters
----------
veto_def_filename: str
The path to the veto definer file
Returns:
... | keyword[def] identifier[parse_veto_definer] ( identifier[veto_def_filename] ):
literal[string]
keyword[from] identifier[glue] . identifier[ligolw] keyword[import] identifier[table] , identifier[lsctables] , identifier[utils] keyword[as] identifier[ligolw_utils]
keyword[from] identifier[glue] . ... | def parse_veto_definer(veto_def_filename):
""" Parse a veto definer file from the filename and return a dictionary
indexed by ifo and veto definer category level.
Parameters
----------
veto_def_filename: str
The path to the veto definer file
Returns:
parsed_definition: dict
... |
def components(self):
"""
Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame
"""
from pandas import DataFrame
columns = ['days', 'hours', 'm... | def function[components, parameter[self]]:
constant[
Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame
]
from relative_module[pandas] import module[Data... | keyword[def] identifier[components] ( identifier[self] ):
literal[string]
keyword[from] identifier[pandas] keyword[import] identifier[DataFrame]
identifier[columns] =[ literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , ... | def components(self):
"""
Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame
"""
from pandas import DataFrame
columns = ['days', 'hours', 'minutes', 'sec... |
def associations(self, association_resource):
"""Retrieve Association for this resource of the type in association_resource.
This method will return all *resources* (group, indicators, task, victims, etc) for this
resource that are associated with the provided association resource_type.
... | def function[associations, parameter[self, association_resource]]:
constant[Retrieve Association for this resource of the type in association_resource.
This method will return all *resources* (group, indicators, task, victims, etc) for this
resource that are associated with the provided associa... | keyword[def] identifier[associations] ( identifier[self] , identifier[association_resource] ):
literal[string]
identifier[resource] = identifier[self] . identifier[copy] ()
identifier[resource] . identifier[_request_entity] = identifier[association_resource] . identifier[api_entity]
... | def associations(self, association_resource):
"""Retrieve Association for this resource of the type in association_resource.
This method will return all *resources* (group, indicators, task, victims, etc) for this
resource that are associated with the provided association resource_type.
**... |
def _parse_hosts_inventory(self, inventory_path):
"""
Read all the available hosts inventory information into one big list
and parse it.
"""
hosts_contents = []
if os.path.isdir(inventory_path):
self.log.debug("Inventory path {} is a dir. Looking for inventory... | def function[_parse_hosts_inventory, parameter[self, inventory_path]]:
constant[
Read all the available hosts inventory information into one big list
and parse it.
]
variable[hosts_contents] assign[=] list[[]]
if call[name[os].path.isdir, parameter[name[inventory_path]]] ... | keyword[def] identifier[_parse_hosts_inventory] ( identifier[self] , identifier[inventory_path] ):
literal[string]
identifier[hosts_contents] =[]
keyword[if] identifier[os] . identifier[path] . identifier[isdir] ( identifier[inventory_path] ):
identifier[self] . identifier[lo... | def _parse_hosts_inventory(self, inventory_path):
"""
Read all the available hosts inventory information into one big list
and parse it.
"""
hosts_contents = []
if os.path.isdir(inventory_path):
self.log.debug('Inventory path {} is a dir. Looking for inventory files in that d... |
def open_file(self, path, line=None):
"""
Creates a new GenericCodeEdit, opens the requested file and adds it
to the tab widget.
:param path: Path of the file to open
:return The opened editor if open succeeded.
"""
editor = None
if path:
int... | def function[open_file, parameter[self, path, line]]:
constant[
Creates a new GenericCodeEdit, opens the requested file and adds it
to the tab widget.
:param path: Path of the file to open
:return The opened editor if open succeeded.
]
variable[editor] assign[=]... | keyword[def] identifier[open_file] ( identifier[self] , identifier[path] , identifier[line] = keyword[None] ):
literal[string]
identifier[editor] = keyword[None]
keyword[if] identifier[path] :
identifier[interpreter] , identifier[pyserver] , identifier[args] = identifier[sel... | def open_file(self, path, line=None):
"""
Creates a new GenericCodeEdit, opens the requested file and adds it
to the tab widget.
:param path: Path of the file to open
:return The opened editor if open succeeded.
"""
editor = None
if path:
(interpreter, pyser... |
def _get_focused_item(self):
""" Returns the currently focused item """
focused_model = self._selection.focus
if not focused_model:
return None
return self.canvas.get_view_for_model(focused_model) | def function[_get_focused_item, parameter[self]]:
constant[ Returns the currently focused item ]
variable[focused_model] assign[=] name[self]._selection.focus
if <ast.UnaryOp object at 0x7da1b1a5f7f0> begin[:]
return[constant[None]]
return[call[name[self].canvas.get_view_for_model, p... | keyword[def] identifier[_get_focused_item] ( identifier[self] ):
literal[string]
identifier[focused_model] = identifier[self] . identifier[_selection] . identifier[focus]
keyword[if] keyword[not] identifier[focused_model] :
keyword[return] keyword[None]
keyword[r... | def _get_focused_item(self):
""" Returns the currently focused item """
focused_model = self._selection.focus
if not focused_model:
return None # depends on [control=['if'], data=[]]
return self.canvas.get_view_for_model(focused_model) |
def euler(self):
"""TODO DEPRECATE THIS?"""
e_xyz = transformations.euler_from_matrix(self.rotation, 'sxyz')
return np.array([180.0 / np.pi * a for a in e_xyz]) | def function[euler, parameter[self]]:
constant[TODO DEPRECATE THIS?]
variable[e_xyz] assign[=] call[name[transformations].euler_from_matrix, parameter[name[self].rotation, constant[sxyz]]]
return[call[name[np].array, parameter[<ast.ListComp object at 0x7da1b12b5870>]]] | keyword[def] identifier[euler] ( identifier[self] ):
literal[string]
identifier[e_xyz] = identifier[transformations] . identifier[euler_from_matrix] ( identifier[self] . identifier[rotation] , literal[string] )
keyword[return] identifier[np] . identifier[array] ([ literal[int] / identifie... | def euler(self):
"""TODO DEPRECATE THIS?"""
e_xyz = transformations.euler_from_matrix(self.rotation, 'sxyz')
return np.array([180.0 / np.pi * a for a in e_xyz]) |
def h2e(string):
"""
Convert hangul to english. ('한영타' -> 'gksdudxk')
:param string: hangul that actually represent english string
:return: converted english string
"""
result = []
for c in string:
ccode = ord(c) # Character code
if 0x3131 <= ccode <= 0x3163: # Hangul Comp... | def function[h2e, parameter[string]]:
constant[
Convert hangul to english. ('한영타' -> 'gksdudxk')
:param string: hangul that actually represent english string
:return: converted english string
]
variable[result] assign[=] list[[]]
for taget[name[c]] in starred[name[string]] begin[... | keyword[def] identifier[h2e] ( identifier[string] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[c] keyword[in] identifier[string] :
identifier[ccode] = identifier[ord] ( identifier[c] )
keyword[if] literal[int] <= identifier[ccode] <= literal[int] :
... | def h2e(string):
"""
Convert hangul to english. ('한영타' -> 'gksdudxk')
:param string: hangul that actually represent english string
:return: converted english string
"""
result = []
for c in string:
ccode = ord(c) # Character code
if 12593 <= ccode <= 12643: # Hangul Compati... |
def run(self, **client_params):
"""
Actually creates the async job on the CARTO server
:param client_params: To be send to the CARTO API. See CARTO's
documentation depending on the subclass
you are using
:type client_param... | def function[run, parameter[self]]:
constant[
Actually creates the async job on the CARTO server
:param client_params: To be send to the CARTO API. See CARTO's
documentation depending on the subclass
you are using
:type cl... | keyword[def] identifier[run] ( identifier[self] ,** identifier[client_params] ):
literal[string]
keyword[try] :
identifier[self] . identifier[send] ( identifier[self] . identifier[get_collection_endpoint] (),
identifier[http_method] = literal[string] ,
** ident... | def run(self, **client_params):
"""
Actually creates the async job on the CARTO server
:param client_params: To be send to the CARTO API. See CARTO's
documentation depending on the subclass
you are using
:type client_params: k... |
def filter_genes_cv_deprecated(X, Ecutoff, cvFilter):
"""Filter genes by coefficient of variance and mean.
See `filter_genes_dispersion`.
Reference: Weinreb et al. (2017).
"""
if issparse(X):
raise ValueError('Not defined for sparse input. See `filter_genes_dispersion`.')
mean_filter =... | def function[filter_genes_cv_deprecated, parameter[X, Ecutoff, cvFilter]]:
constant[Filter genes by coefficient of variance and mean.
See `filter_genes_dispersion`.
Reference: Weinreb et al. (2017).
]
if call[name[issparse], parameter[name[X]]] begin[:]
<ast.Raise object at 0x7da18... | keyword[def] identifier[filter_genes_cv_deprecated] ( identifier[X] , identifier[Ecutoff] , identifier[cvFilter] ):
literal[string]
keyword[if] identifier[issparse] ( identifier[X] ):
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[mean_filter] = identifier[np] . identi... | def filter_genes_cv_deprecated(X, Ecutoff, cvFilter):
"""Filter genes by coefficient of variance and mean.
See `filter_genes_dispersion`.
Reference: Weinreb et al. (2017).
"""
if issparse(X):
raise ValueError('Not defined for sparse input. See `filter_genes_dispersion`.') # depends on [co... |
def magic_read(self,infile):
"""
reads a Magic template file, puts data in a list of dictionaries
"""
# print "calling magic_read(self, infile)", infile
hold,magic_data,magic_record,magic_keys=[],[],{},[]
try:
f=open(infile,"r")
except:
ret... | def function[magic_read, parameter[self, infile]]:
constant[
reads a Magic template file, puts data in a list of dictionaries
]
<ast.Tuple object at 0x7da1b01bfd00> assign[=] tuple[[<ast.List object at 0x7da1b01bff10>, <ast.List object at 0x7da1b01bfdc0>, <ast.Dict object at 0x7da1b01bf... | keyword[def] identifier[magic_read] ( identifier[self] , identifier[infile] ):
literal[string]
identifier[hold] , identifier[magic_data] , identifier[magic_record] , identifier[magic_keys] =[],[],{},[]
keyword[try] :
identifier[f] = identifier[open] ( identifier[infil... | def magic_read(self, infile):
"""
reads a Magic template file, puts data in a list of dictionaries
"""
# print "calling magic_read(self, infile)", infile
(hold, magic_data, magic_record, magic_keys) = ([], [], {}, [])
try:
f = open(infile, 'r') # depends on [control=['tr... |
def _set_char(self, x, y, char, fg=None, bg=None,
bgblend=_lib.TCOD_BKGND_SET):
"""
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the dra... | def function[_set_char, parameter[self, x, y, char, fg, bg, bgblend]]:
constant[
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use... | keyword[def] identifier[_set_char] ( identifier[self] , identifier[x] , identifier[y] , identifier[char] , identifier[fg] = keyword[None] , identifier[bg] = keyword[None] ,
identifier[bgblend] = identifier[_lib] . identifier[TCOD_BKGND_SET] ):
literal[string]
keyword[return] identifier[_... | def _set_char(self, x, y, char, fg=None, bg=None, bgblend=_lib.TCOD_BKGND_SET):
"""
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use ... |
def reverseCommit(self):
"""
Re-insert the previously deleted line.
"""
if self.markerPos is None:
return
# Remove the specified string from the same position in every line
# in between the mark and the cursor (inclusive).
col = min((self.markerPos[1... | def function[reverseCommit, parameter[self]]:
constant[
Re-insert the previously deleted line.
]
if compare[name[self].markerPos is constant[None]] begin[:]
return[None]
variable[col] assign[=] call[name[min], parameter[tuple[[<ast.Subscript object at 0x7da204960a30>, <as... | keyword[def] identifier[reverseCommit] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[markerPos] keyword[is] keyword[None] :
keyword[return]
identifier[col] = identifier[min] (( identifier[self] . identifier[mark... | def reverseCommit(self):
"""
Re-insert the previously deleted line.
"""
if self.markerPos is None:
return # depends on [control=['if'], data=[]]
# Remove the specified string from the same position in every line
# in between the mark and the cursor (inclusive).
col = min((se... |
def sample(self, initial_pos, num_adapt, num_samples, stepsize=None, return_type='dataframe'):
"""
Returns samples using No U Turn Sampler with dual averaging
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, ... | def function[sample, parameter[self, initial_pos, num_adapt, num_samples, stepsize, return_type]]:
constant[
Returns samples using No U Turn Sampler with dual averaging
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter ... | keyword[def] identifier[sample] ( identifier[self] , identifier[initial_pos] , identifier[num_adapt] , identifier[num_samples] , identifier[stepsize] = keyword[None] , identifier[return_type] = literal[string] ):
literal[string]
identifier[initial_pos] = identifier[_check_1d_array_object] ( identif... | def sample(self, initial_pos, num_adapt, num_samples, stepsize=None, return_type='dataframe'):
"""
Returns samples using No U Turn Sampler with dual averaging
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the ... |
def _round_multiple(x:int, mult:int=None)->int:
"Calc `x` to nearest multiple of `mult`."
return (int(x/mult+0.5)*mult) if mult is not None else x | def function[_round_multiple, parameter[x, mult]]:
constant[Calc `x` to nearest multiple of `mult`.]
return[<ast.IfExp object at 0x7da1b20284c0>] | keyword[def] identifier[_round_multiple] ( identifier[x] : identifier[int] , identifier[mult] : identifier[int] = keyword[None] )-> identifier[int] :
literal[string]
keyword[return] ( identifier[int] ( identifier[x] / identifier[mult] + literal[int] )* identifier[mult] ) keyword[if] identifier[mult] keyw... | def _round_multiple(x: int, mult: int=None) -> int:
"""Calc `x` to nearest multiple of `mult`."""
return int(x / mult + 0.5) * mult if mult is not None else x |
def _check_reimport(self, node, basename=None, level=None):
"""check if the import is necessary (i.e. not already done)"""
if not self.linter.is_message_enabled("reimported"):
return
frame = node.frame()
root = node.root()
contexts = [(frame, level)]
if root ... | def function[_check_reimport, parameter[self, node, basename, level]]:
constant[check if the import is necessary (i.e. not already done)]
if <ast.UnaryOp object at 0x7da1b03a43d0> begin[:]
return[None]
variable[frame] assign[=] call[name[node].frame, parameter[]]
variable[root] a... | keyword[def] identifier[_check_reimport] ( identifier[self] , identifier[node] , identifier[basename] = keyword[None] , identifier[level] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[linter] . identifier[is_message_enabled] ( literal[string] ):
... | def _check_reimport(self, node, basename=None, level=None):
"""check if the import is necessary (i.e. not already done)"""
if not self.linter.is_message_enabled('reimported'):
return # depends on [control=['if'], data=[]]
frame = node.frame()
root = node.root()
contexts = [(frame, level)]
... |
def get_worst_flag_level(self, flags):
'''
Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned.
'''
worst_flag_level = 0
for flag_level_name in flags:
flag_level = self.FLAG_LEVELS[flag_level_name]
... | def function[get_worst_flag_level, parameter[self, flags]]:
constant[
Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned.
]
variable[worst_flag_level] assign[=] constant[0]
for taget[name[flag_level_name]] in st... | keyword[def] identifier[get_worst_flag_level] ( identifier[self] , identifier[flags] ):
literal[string]
identifier[worst_flag_level] = literal[int]
keyword[for] identifier[flag_level_name] keyword[in] identifier[flags] :
identifier[flag_level] = identifier[self] . identifi... | def get_worst_flag_level(self, flags):
"""
Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned.
"""
worst_flag_level = 0
for flag_level_name in flags:
flag_level = self.FLAG_LEVELS[flag_level_name]
if flag_le... |
def handle_unhandled_exception(exc_type, exc_value, exc_traceback):
"""Handler for unhandled exceptions that will write to the logs"""
if issubclass(exc_type, KeyboardInterrupt):
# call the default excepthook saved at __excepthook__
sys.__excepthook__(exc_type, exc_value, exc_traceback)
... | def function[handle_unhandled_exception, parameter[exc_type, exc_value, exc_traceback]]:
constant[Handler for unhandled exceptions that will write to the logs]
if call[name[issubclass], parameter[name[exc_type], name[KeyboardInterrupt]]] begin[:]
call[name[sys].__excepthook__, parameter[... | keyword[def] identifier[handle_unhandled_exception] ( identifier[exc_type] , identifier[exc_value] , identifier[exc_traceback] ):
literal[string]
keyword[if] identifier[issubclass] ( identifier[exc_type] , identifier[KeyboardInterrupt] ):
identifier[sys] . identifier[__excepthook__] ( identi... | def handle_unhandled_exception(exc_type, exc_value, exc_traceback):
"""Handler for unhandled exceptions that will write to the logs"""
if issubclass(exc_type, KeyboardInterrupt):
# call the default excepthook saved at __excepthook__
sys.__excepthook__(exc_type, exc_value, exc_traceback)
... |
def reformat_pattern(pattern, compile=False):
'''
Apply the filters on user pattern to generate a new regular expression
pattern.
A user provided variable, should start with an alphabet, can be
alphanumeric and can have _.
'''
# User pattern: (w:<name>) --> Changes to (?P<name>\w)
rex_p... | def function[reformat_pattern, parameter[pattern, compile]]:
constant[
Apply the filters on user pattern to generate a new regular expression
pattern.
A user provided variable, should start with an alphabet, can be
alphanumeric and can have _.
]
variable[rex_pattern] assign[=] call[n... | keyword[def] identifier[reformat_pattern] ( identifier[pattern] , identifier[compile] = keyword[False] ):
literal[string]
identifier[rex_pattern] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[pattern] )
identifier[rex_pattern] = identifier[re] . identif... | def reformat_pattern(pattern, compile=False):
"""
Apply the filters on user pattern to generate a new regular expression
pattern.
A user provided variable, should start with an alphabet, can be
alphanumeric and can have _.
"""
# User pattern: (w:<name>) --> Changes to (?P<name>\w)
rex_p... |
def estimate_map(interface, state, label, inp):
"""Find the cluster `i` that is closest to the datapoint `e`."""
out = interface.output(0)
centers = {}
for row in inp:
row = row.strip().split(state["delimiter"])
if len(row) > 1:
x = [(0 if row[i] in state["missing_vals"] else... | def function[estimate_map, parameter[interface, state, label, inp]]:
constant[Find the cluster `i` that is closest to the datapoint `e`.]
variable[out] assign[=] call[name[interface].output, parameter[constant[0]]]
variable[centers] assign[=] dictionary[[], []]
for taget[name[row]] in st... | keyword[def] identifier[estimate_map] ( identifier[interface] , identifier[state] , identifier[label] , identifier[inp] ):
literal[string]
identifier[out] = identifier[interface] . identifier[output] ( literal[int] )
identifier[centers] ={}
keyword[for] identifier[row] keyword[in] identifier[i... | def estimate_map(interface, state, label, inp):
"""Find the cluster `i` that is closest to the datapoint `e`."""
out = interface.output(0)
centers = {}
for row in inp:
row = row.strip().split(state['delimiter'])
if len(row) > 1:
x = [0 if row[i] in state['missing_vals'] else ... |
def rand_ssn():
"""Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178
"""
return "%s-%s-%s" % (rand_str(3, string.digits),
rand_str(2, string.digits),
rand_str(4, string.digits)) | def function[rand_ssn, parameter[]]:
constant[Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178
]
return[binary_operation[constant[%s-%s-%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da1b23730a0>, <ast.Call object at 0x7da1b23b0310>, <ast.Call objec... | keyword[def] identifier[rand_ssn] ():
literal[string]
keyword[return] literal[string] %( identifier[rand_str] ( literal[int] , identifier[string] . identifier[digits] ),
identifier[rand_str] ( literal[int] , identifier[string] . identifier[digits] ),
identifier[rand_str] ( literal[int] , identif... | def rand_ssn():
"""Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178
"""
return '%s-%s-%s' % (rand_str(3, string.digits), rand_str(2, string.digits), rand_str(4, string.digits)) |
def get_padding(x, padding_value=0):
"""Return float tensor representing the padding values in x.
Args:
x: int tensor with any shape
padding_value: int value that
Returns:
flaot tensor with same shape as x containing values 0 or 1.
0 -> non-padding, 1 -> padding
"""
with tf.name_scope("pad... | def function[get_padding, parameter[x, padding_value]]:
constant[Return float tensor representing the padding values in x.
Args:
x: int tensor with any shape
padding_value: int value that
Returns:
flaot tensor with same shape as x containing values 0 or 1.
0 -> non-padding, 1 -> padding
... | keyword[def] identifier[get_padding] ( identifier[x] , identifier[padding_value] = literal[int] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
keyword[return] identifier[tf] . identifier[to_float] ( identifier[tf] . identifier[equal] ( identifier[x] , ident... | def get_padding(x, padding_value=0):
"""Return float tensor representing the padding values in x.
Args:
x: int tensor with any shape
padding_value: int value that
Returns:
flaot tensor with same shape as x containing values 0 or 1.
0 -> non-padding, 1 -> padding
"""
with tf.name_scope(... |
def from_pypirc(pypi_repository):
""" Load configuration from .pypirc file, cached to only run once """
ret = {}
pypirc_locations = PYPIRC_LOCATIONS
for pypirc_path in pypirc_locations:
pypirc_path = os.path.expanduser(pypirc_path)
if os.path.isfile(pypirc_path):
parser = con... | def function[from_pypirc, parameter[pypi_repository]]:
constant[ Load configuration from .pypirc file, cached to only run once ]
variable[ret] assign[=] dictionary[[], []]
variable[pypirc_locations] assign[=] name[PYPIRC_LOCATIONS]
for taget[name[pypirc_path]] in starred[name[pypirc_loca... | keyword[def] identifier[from_pypirc] ( identifier[pypi_repository] ):
literal[string]
identifier[ret] ={}
identifier[pypirc_locations] = identifier[PYPIRC_LOCATIONS]
keyword[for] identifier[pypirc_path] keyword[in] identifier[pypirc_locations] :
identifier[pypirc_path] = identifier[o... | def from_pypirc(pypi_repository):
""" Load configuration from .pypirc file, cached to only run once """
ret = {}
pypirc_locations = PYPIRC_LOCATIONS
for pypirc_path in pypirc_locations:
pypirc_path = os.path.expanduser(pypirc_path)
if os.path.isfile(pypirc_path):
parser = con... |
def window(iterable, size=2):
''' yields wondows of a given size '''
iterable = iter(iterable)
d = deque(islice(iterable, size-1), maxlen=size)
for _ in map(d.append, iterable):
yield tuple(d) | def function[window, parameter[iterable, size]]:
constant[ yields wondows of a given size ]
variable[iterable] assign[=] call[name[iter], parameter[name[iterable]]]
variable[d] assign[=] call[name[deque], parameter[call[name[islice], parameter[name[iterable], binary_operation[name[size] - consta... | keyword[def] identifier[window] ( identifier[iterable] , identifier[size] = literal[int] ):
literal[string]
identifier[iterable] = identifier[iter] ( identifier[iterable] )
identifier[d] = identifier[deque] ( identifier[islice] ( identifier[iterable] , identifier[size] - literal[int] ), identifier[max... | def window(iterable, size=2):
""" yields wondows of a given size """
iterable = iter(iterable)
d = deque(islice(iterable, size - 1), maxlen=size)
for _ in map(d.append, iterable):
yield tuple(d) # depends on [control=['for'], data=[]] |
def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for... | def function[get_items_of_type, parameter[self, item_type]]:
constant[
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
]... | keyword[def] identifier[get_items_of_type] ( identifier[self] , identifier[item_type] ):
literal[string]
keyword[return] ( identifier[item] keyword[for] identifier[item] keyword[in] identifier[self] . identifier[items] keyword[if] identifier[item] . identifier[get_type] ()== identifier[item_t... | def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in... |
def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port):
"""Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a
series product self-feedback.
"""
_, block_index = rhs.index_in_block(in_port)
rest = tuple(rest)
bs = rhs.block_structure
(nbefore, nblock, nafter) = ... | def function[_pull_out_unaffected_blocks_rhs, parameter[rest, rhs, out_port, in_port]]:
constant[Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a
series product self-feedback.
]
<ast.Tuple object at 0x7da20c9928c0> assign[=] call[name[rhs].index_in_block, parameter[name[in_... | keyword[def] identifier[_pull_out_unaffected_blocks_rhs] ( identifier[rest] , identifier[rhs] , identifier[out_port] , identifier[in_port] ):
literal[string]
identifier[_] , identifier[block_index] = identifier[rhs] . identifier[index_in_block] ( identifier[in_port] )
identifier[rest] = identifier[tup... | def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port):
"""Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a
series product self-feedback.
"""
(_, block_index) = rhs.index_in_block(in_port)
rest = tuple(rest)
bs = rhs.block_structure
(nbefore, nblock, nafter) ... |
def query_by_wiql(self, wiql, team_context=None, time_precision=None, top=None):
"""QueryByWiql.
[Preview API] Gets the results of the query given its WIQL.
:param :class:`<Wiql> <azure.devops.v5_1.work_item_tracking.models.Wiql>` wiql: The query containing the WIQL.
:param :class:`<Team... | def function[query_by_wiql, parameter[self, wiql, team_context, time_precision, top]]:
constant[QueryByWiql.
[Preview API] Gets the results of the query given its WIQL.
:param :class:`<Wiql> <azure.devops.v5_1.work_item_tracking.models.Wiql>` wiql: The query containing the WIQL.
:param :... | keyword[def] identifier[query_by_wiql] ( identifier[self] , identifier[wiql] , identifier[team_context] = keyword[None] , identifier[time_precision] = keyword[None] , identifier[top] = keyword[None] ):
literal[string]
identifier[project] = keyword[None]
identifier[team] = keyword[None]
... | def query_by_wiql(self, wiql, team_context=None, time_precision=None, top=None):
"""QueryByWiql.
[Preview API] Gets the results of the query given its WIQL.
:param :class:`<Wiql> <azure.devops.v5_1.work_item_tracking.models.Wiql>` wiql: The query containing the WIQL.
:param :class:`<TeamCont... |
def authors(self):
"""A list of namedtuples storing author information,
where each namedtuple corresponds to one author.
The information in each namedtuple is (name surname initials id url).
All entries are strings.
"""
out = []
order = 'name surname initials id u... | def function[authors, parameter[self]]:
constant[A list of namedtuples storing author information,
where each namedtuple corresponds to one author.
The information in each namedtuple is (name surname initials id url).
All entries are strings.
]
variable[out] assign[=] lis... | keyword[def] identifier[authors] ( identifier[self] ):
literal[string]
identifier[out] =[]
identifier[order] = literal[string]
identifier[auth] = identifier[namedtuple] ( literal[string] , identifier[order] )
keyword[for] identifier[author] keyword[in] identifier[self... | def authors(self):
"""A list of namedtuples storing author information,
where each namedtuple corresponds to one author.
The information in each namedtuple is (name surname initials id url).
All entries are strings.
"""
out = []
order = 'name surname initials id url'
auth... |
def gunzip(gzipfile, template=None, runas=None, options=None):
'''
Uses the gunzip command to unpack gzip files
template : None
Can be set to 'jinja' or another supported template engine to render
the command arguments before execution:
.. code-block:: bash
salt '*' ar... | def function[gunzip, parameter[gzipfile, template, runas, options]]:
constant[
Uses the gunzip command to unpack gzip files
template : None
Can be set to 'jinja' or another supported template engine to render
the command arguments before execution:
.. code-block:: bash
... | keyword[def] identifier[gunzip] ( identifier[gzipfile] , identifier[template] = keyword[None] , identifier[runas] = keyword[None] , identifier[options] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] ]
keyword[if] identifier[options] :
identifier[cmd] . identifier[appen... | def gunzip(gzipfile, template=None, runas=None, options=None):
"""
Uses the gunzip command to unpack gzip files
template : None
Can be set to 'jinja' or another supported template engine to render
the command arguments before execution:
.. code-block:: bash
salt '*' ar... |
def get_bool_data(self, copy=False):
"""
Parameters
----------
copy : boolean, default False
Whether to copy the blocks
"""
self._consolidate_inplace()
return self.combine([b for b in self.blocks if b.is_bool], copy) | def function[get_bool_data, parameter[self, copy]]:
constant[
Parameters
----------
copy : boolean, default False
Whether to copy the blocks
]
call[name[self]._consolidate_inplace, parameter[]]
return[call[name[self].combine, parameter[<ast.ListComp object... | keyword[def] identifier[get_bool_data] ( identifier[self] , identifier[copy] = keyword[False] ):
literal[string]
identifier[self] . identifier[_consolidate_inplace] ()
keyword[return] identifier[self] . identifier[combine] ([ identifier[b] keyword[for] identifier[b] keyword[in] identi... | def get_bool_data(self, copy=False):
"""
Parameters
----------
copy : boolean, default False
Whether to copy the blocks
"""
self._consolidate_inplace()
return self.combine([b for b in self.blocks if b.is_bool], copy) |
def spendables_for_address(self, address):
"""
Return a list of Spendable objects for the
given bitcoin address.
"""
URL = "%s/addr/%s/utxo" % (self.base_url, address)
r = json.loads(urlopen(URL).read().decode("utf8"))
spendables = []
for u in r:
... | def function[spendables_for_address, parameter[self, address]]:
constant[
Return a list of Spendable objects for the
given bitcoin address.
]
variable[URL] assign[=] binary_operation[constant[%s/addr/%s/utxo] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7d... | keyword[def] identifier[spendables_for_address] ( identifier[self] , identifier[address] ):
literal[string]
identifier[URL] = literal[string] %( identifier[self] . identifier[base_url] , identifier[address] )
identifier[r] = identifier[json] . identifier[loads] ( identifier[urlopen] ( iden... | def spendables_for_address(self, address):
"""
Return a list of Spendable objects for the
given bitcoin address.
"""
URL = '%s/addr/%s/utxo' % (self.base_url, address)
r = json.loads(urlopen(URL).read().decode('utf8'))
spendables = []
for u in r:
coin_value = btc_to_s... |
def iter_alignments(dataset, cognate_sets, column='Segments', method='library'):
"""
Function computes automatic alignments and writes them to file.
"""
if not isinstance(dataset, lingpy.basic.parser.QLCParser):
wordlist = _cldf2wordlist(dataset)
cognates = {r['Form_ID']: r for r in cogn... | def function[iter_alignments, parameter[dataset, cognate_sets, column, method]]:
constant[
Function computes automatic alignments and writes them to file.
]
if <ast.UnaryOp object at 0x7da1b236b940> begin[:]
variable[wordlist] assign[=] call[name[_cldf2wordlist], parameter[name[d... | keyword[def] identifier[iter_alignments] ( identifier[dataset] , identifier[cognate_sets] , identifier[column] = literal[string] , identifier[method] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[dataset] , identifier[lingpy] . identifier[basic] . ident... | def iter_alignments(dataset, cognate_sets, column='Segments', method='library'):
"""
Function computes automatic alignments and writes them to file.
"""
if not isinstance(dataset, lingpy.basic.parser.QLCParser):
wordlist = _cldf2wordlist(dataset)
cognates = {r['Form_ID']: r for r in cogn... |
def _find_widget_match(self, prop_name):
"""
Used to search ``self.view`` when :meth:`adapt` is not given a widget
name.
*prop_name* is the name of a property in the model.
Returns a string with the best match. Raises
:class:`TooManyCandidatesError` or ``ValueError`` wh... | def function[_find_widget_match, parameter[self, prop_name]]:
constant[
Used to search ``self.view`` when :meth:`adapt` is not given a widget
name.
*prop_name* is the name of a property in the model.
Returns a string with the best match. Raises
:class:`TooManyCandidates... | keyword[def] identifier[_find_widget_match] ( identifier[self] , identifier[prop_name] ):
literal[string]
identifier[names] =[]
keyword[for] identifier[wid_name] keyword[in] identifier[self] . identifier[view] :
keyword[if] identifier[wid_name] . identifi... | def _find_widget_match(self, prop_name):
"""
Used to search ``self.view`` when :meth:`adapt` is not given a widget
name.
*prop_name* is the name of a property in the model.
Returns a string with the best match. Raises
:class:`TooManyCandidatesError` or ``ValueError`` when n... |
def configurable(name_or_fn=None, module=None, whitelist=None, blacklist=None):
"""Decorator to make a function or class configurable.
This decorator registers the decorated function/class as configurable, which
allows its parameters to be supplied from the global configuration (i.e., set
through `bind_paramet... | def function[configurable, parameter[name_or_fn, module, whitelist, blacklist]]:
constant[Decorator to make a function or class configurable.
This decorator registers the decorated function/class as configurable, which
allows its parameters to be supplied from the global configuration (i.e., set
through ... | keyword[def] identifier[configurable] ( identifier[name_or_fn] = keyword[None] , identifier[module] = keyword[None] , identifier[whitelist] = keyword[None] , identifier[blacklist] = keyword[None] ):
literal[string]
identifier[decoration_target] = keyword[None]
keyword[if] identifier[callable] ( identifier... | def configurable(name_or_fn=None, module=None, whitelist=None, blacklist=None):
"""Decorator to make a function or class configurable.
This decorator registers the decorated function/class as configurable, which
allows its parameters to be supplied from the global configuration (i.e., set
through `bind_param... |
async def eventuallyAll(*coroFuncs: FlexFunc, # (use functools.partials if needed)
totalTimeout: float,
retryWait: float=0.1,
acceptableExceptions=None,
acceptableFails: int=0,
override_timeout_limit... | <ast.AsyncFunctionDef object at 0x7da2047ebcd0> | keyword[async] keyword[def] identifier[eventuallyAll] (* identifier[coroFuncs] : identifier[FlexFunc] ,
identifier[totalTimeout] : identifier[float] ,
identifier[retryWait] : identifier[float] = literal[int] ,
identifier[acceptableExceptions] = keyword[None] ,
identifier[acceptableFails] : identifier[int] = lite... | async def eventuallyAll(*coroFuncs: FlexFunc, totalTimeout: float, retryWait: float=0.1, acceptableExceptions=None, acceptableFails: int=0, override_timeout_limit=False): # (use functools.partials if needed)
# TODO: Bug when `acceptableFails` > 0 if the first check fails, it will
# exhaust the entire timeout.
... |
def _tokenize(self, text, token_class=None):
"""
Tokenizes a text
:Returns:
A `list` of tokens
"""
token_class = token_class or Token
tokens = {}
for i, match in enumerate(self.regex.finditer(text)):
value = match.group(0)
tr... | def function[_tokenize, parameter[self, text, token_class]]:
constant[
Tokenizes a text
:Returns:
A `list` of tokens
]
variable[token_class] assign[=] <ast.BoolOp object at 0x7da1b0babb80>
variable[tokens] assign[=] dictionary[[], []]
for taget[tuple[... | keyword[def] identifier[_tokenize] ( identifier[self] , identifier[text] , identifier[token_class] = keyword[None] ):
literal[string]
identifier[token_class] = identifier[token_class] keyword[or] identifier[Token]
identifier[tokens] ={}
keyword[for] identifier[i] , identifier... | def _tokenize(self, text, token_class=None):
"""
Tokenizes a text
:Returns:
A `list` of tokens
"""
token_class = token_class or Token
tokens = {}
for (i, match) in enumerate(self.regex.finditer(text)):
value = match.group(0)
try:
token = t... |
def hide_routemap_holder_route_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElement(hide_routemap_holder, "... | def function[hide_routemap_holder_route_map_name, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[hide_routemap_holder] assign[=] call[name[ET].SubElement, parameter[name[config], constant[hide-route... | keyword[def] identifier[hide_routemap_holder_route_map_name] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[hide_routemap_holder] = identifier[ET] . identifier[SubElement] ( identifier[co... | def hide_routemap_holder_route_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
hide_routemap_holder = ET.SubElement(config, 'hide-routemap-holder', xmlns='urn:brocade.com:mgmt:brocade-ip-policy')
route_map = ET.SubElement(hide_routemap_holder, 'route-map')
... |
async def oauth(request):
"""Oauth example."""
provider = request.match_info.get('provider')
client, _ = await app.ps.oauth.login(provider, request)
user, data = await client.user_info()
response = (
"<a href='/'>back</a><br/><br/>"
"<ul>"
"<li>ID: {u.id}</li>"
"<li>U... | <ast.AsyncFunctionDef object at 0x7da204347160> | keyword[async] keyword[def] identifier[oauth] ( identifier[request] ):
literal[string]
identifier[provider] = identifier[request] . identifier[match_info] . identifier[get] ( literal[string] )
identifier[client] , identifier[_] = keyword[await] identifier[app] . identifier[ps] . identifier[oauth] . ... | async def oauth(request):
"""Oauth example."""
provider = request.match_info.get('provider')
(client, _) = await app.ps.oauth.login(provider, request)
(user, data) = await client.user_info()
response = "<a href='/'>back</a><br/><br/><ul><li>ID: {u.id}</li><li>Username: {u.username}</li><li>First, la... |
def _split_regex(regex):
"""
Return an array of the URL split at each regex match like (?P<id>[\d]+)
Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/']
"""
if regex[0] == '^':
regex = regex[1:]
if regex[-1] == '$':
regex = regex[0:-1]
res... | def function[_split_regex, parameter[regex]]:
constant[
Return an array of the URL split at each regex match like (?P<id>[\d]+)
Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/']
]
if compare[call[name[regex]][constant[0]] equal[==] constant[^]] begin[:]... | keyword[def] identifier[_split_regex] ( identifier[regex] ):
literal[string]
keyword[if] identifier[regex] [ literal[int] ]== literal[string] :
identifier[regex] = identifier[regex] [ literal[int] :]
keyword[if] identifier[regex] [- literal[int] ]== literal[string] :
identifier[reg... | def _split_regex(regex):
"""
Return an array of the URL split at each regex match like (?P<id>[\\d]+)
Call with a regex of '^/foo/(?P<id>[\\d]+)/bar/$' and you will receive ['/foo/', '/bar/']
"""
if regex[0] == '^':
regex = regex[1:] # depends on [control=['if'], data=[]]
if regex[-1] =... |
def link_order_filter(self, column, modelview_name):
"""
Arguments are passed like:
_oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
"""
new_args = request.view_args.copy()
args = request.args.copy()
if ("_oc_" + modelview_name) in args:
... | def function[link_order_filter, parameter[self, column, modelview_name]]:
constant[
Arguments are passed like:
_oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
]
variable[new_args] assign[=] call[name[request].view_args.copy, parameter[]]
variable[args]... | keyword[def] identifier[link_order_filter] ( identifier[self] , identifier[column] , identifier[modelview_name] ):
literal[string]
identifier[new_args] = identifier[request] . identifier[view_args] . identifier[copy] ()
identifier[args] = identifier[request] . identifier[args] . identifier... | def link_order_filter(self, column, modelview_name):
"""
Arguments are passed like:
_oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
"""
new_args = request.view_args.copy()
args = request.args.copy()
if '_oc_' + modelview_name in args:
args['_oc_' + mod... |
def policy_present(name, rules):
'''
Ensure a Vault policy with the given name and rules is present.
name
The name of the policy
rules
Rules formatted as in-line HCL
.. code-block:: yaml
demo-policy:
vault.policy_present:
- name: foo/bar
... | def function[policy_present, parameter[name, rules]]:
constant[
Ensure a Vault policy with the given name and rules is present.
name
The name of the policy
rules
Rules formatted as in-line HCL
.. code-block:: yaml
demo-policy:
vault.policy_present:
... | keyword[def] identifier[policy_present] ( identifier[name] , identifier[rules] ):
literal[string]
identifier[url] = literal[string] . identifier[format] ( identifier[name] )
identifier[response] = identifier[__utils__] [ literal[string] ]( literal[string] , identifier[url] )
keyword[try] :
... | def policy_present(name, rules):
"""
Ensure a Vault policy with the given name and rules is present.
name
The name of the policy
rules
Rules formatted as in-line HCL
.. code-block:: yaml
demo-policy:
vault.policy_present:
- name: foo/bar
... |
def exec_scratch_virtualenv(args):
"""
goals:
- get any random site-packages off of the pythonpath
- ensure we can import virtualenv
- ensure that we're not using the interpreter that we may need to delete
- idempotency: do nothing if the above goals are already met
"""
s... | def function[exec_scratch_virtualenv, parameter[args]]:
constant[
goals:
- get any random site-packages off of the pythonpath
- ensure we can import virtualenv
- ensure that we're not using the interpreter that we may need to delete
- idempotency: do nothing if the above goal... | keyword[def] identifier[exec_scratch_virtualenv] ( identifier[args] ):
literal[string]
identifier[scratch] = identifier[Scratch] ()
keyword[if] keyword[not] identifier[exists] ( identifier[scratch] . identifier[python] ):
identifier[run] (( literal[string] , identifier[scratch] . identifier... | def exec_scratch_virtualenv(args):
"""
goals:
- get any random site-packages off of the pythonpath
- ensure we can import virtualenv
- ensure that we're not using the interpreter that we may need to delete
- idempotency: do nothing if the above goals are already met
"""
s... |
def list_guests(self, host_id, tags=None, cpus=None, memory=None, hostname=None,
domain=None, local_disk=None, nic_speed=None, public_ip=None,
private_ip=None, **kwargs):
"""Retrieve a list of all virtual servers on the dedicated host.
Example::
# Pr... | def function[list_guests, parameter[self, host_id, tags, cpus, memory, hostname, domain, local_disk, nic_speed, public_ip, private_ip]]:
constant[Retrieve a list of all virtual servers on the dedicated host.
Example::
# Print out a list of instances with 4 cpu cores in the host id 12345.
... | keyword[def] identifier[list_guests] ( identifier[self] , identifier[host_id] , identifier[tags] = keyword[None] , identifier[cpus] = keyword[None] , identifier[memory] = keyword[None] , identifier[hostname] = keyword[None] ,
identifier[domain] = keyword[None] , identifier[local_disk] = keyword[None] , identifier[ni... | def list_guests(self, host_id, tags=None, cpus=None, memory=None, hostname=None, domain=None, local_disk=None, nic_speed=None, public_ip=None, private_ip=None, **kwargs):
"""Retrieve a list of all virtual servers on the dedicated host.
Example::
# Print out a list of instances with 4 cpu cores... |
def _add_linux_ethernet(self, port_info, bridge_name):
"""
Use raw sockets on Linux.
If interface is a bridge we connect a tap to it
"""
interface = port_info["interface"]
if gns3server.utils.interfaces.is_interface_bridge(interface):
network_interfaces = [i... | def function[_add_linux_ethernet, parameter[self, port_info, bridge_name]]:
constant[
Use raw sockets on Linux.
If interface is a bridge we connect a tap to it
]
variable[interface] assign[=] call[name[port_info]][constant[interface]]
if call[name[gns3server].utils.inter... | keyword[def] identifier[_add_linux_ethernet] ( identifier[self] , identifier[port_info] , identifier[bridge_name] ):
literal[string]
identifier[interface] = identifier[port_info] [ literal[string] ]
keyword[if] identifier[gns3server] . identifier[utils] . identifier[interfaces] . identifi... | def _add_linux_ethernet(self, port_info, bridge_name):
"""
Use raw sockets on Linux.
If interface is a bridge we connect a tap to it
"""
interface = port_info['interface']
if gns3server.utils.interfaces.is_interface_bridge(interface):
network_interfaces = [interface['name'] ... |
def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs with base URI."""
storage_account_name = generous_parse_uri(base_uri).netloc
blobservice = get_blob_service(storage_account_name, config_path)
containers = blobservice.list_containers(include_metadata=True... | def function[list_dataset_uris, parameter[cls, base_uri, config_path]]:
constant[Return list containing URIs with base URI.]
variable[storage_account_name] assign[=] call[name[generous_parse_uri], parameter[name[base_uri]]].netloc
variable[blobservice] assign[=] call[name[get_blob_service], para... | keyword[def] identifier[list_dataset_uris] ( identifier[cls] , identifier[base_uri] , identifier[config_path] ):
literal[string]
identifier[storage_account_name] = identifier[generous_parse_uri] ( identifier[base_uri] ). identifier[netloc]
identifier[blobservice] = identifier[get_blob_se... | def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs with base URI."""
storage_account_name = generous_parse_uri(base_uri).netloc
blobservice = get_blob_service(storage_account_name, config_path)
containers = blobservice.list_containers(include_metadata=True)
uri_list = ... |
def match_function(self, args, kwargs, match_args=(), star_arg=None, kwd_args=(), dubstar_arg=None):
"""Matches a pattern-matching function."""
self.match_in_args_kwargs(match_args, args, kwargs, allow_star_args=star_arg is not None)
if star_arg is not None:
self.match(star_arg, args... | def function[match_function, parameter[self, args, kwargs, match_args, star_arg, kwd_args, dubstar_arg]]:
constant[Matches a pattern-matching function.]
call[name[self].match_in_args_kwargs, parameter[name[match_args], name[args], name[kwargs]]]
if compare[name[star_arg] is_not constant[None]] b... | keyword[def] identifier[match_function] ( identifier[self] , identifier[args] , identifier[kwargs] , identifier[match_args] =(), identifier[star_arg] = keyword[None] , identifier[kwd_args] =(), identifier[dubstar_arg] = keyword[None] ):
literal[string]
identifier[self] . identifier[match_in_args_kw... | def match_function(self, args, kwargs, match_args=(), star_arg=None, kwd_args=(), dubstar_arg=None):
"""Matches a pattern-matching function."""
self.match_in_args_kwargs(match_args, args, kwargs, allow_star_args=star_arg is not None)
if star_arg is not None:
self.match(star_arg, args + '[' + str(len... |
def register(self):
"""
Register via the method configured
:return:
"""
if self.register_method == "twine":
self.register_by_twine()
if self.register_method == "setup":
self.register_by_setup()
if self.register_method == "upload":
... | def function[register, parameter[self]]:
constant[
Register via the method configured
:return:
]
if compare[name[self].register_method equal[==] constant[twine]] begin[:]
call[name[self].register_by_twine, parameter[]]
if compare[name[self].register_method... | keyword[def] identifier[register] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[register_method] == literal[string] :
identifier[self] . identifier[register_by_twine] ()
keyword[if] identifier[self] . identifier[register_method] == literal[s... | def register(self):
"""
Register via the method configured
:return:
"""
if self.register_method == 'twine':
self.register_by_twine() # depends on [control=['if'], data=[]]
if self.register_method == 'setup':
self.register_by_setup() # depends on [control=['if'], dat... |
def lfprob (dfnum, dfden, F):
"""
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
"""
p = betai(0.5*dfden,... | def function[lfprob, parameter[dfnum, dfden, F]]:
constant[
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfw... | keyword[def] identifier[lfprob] ( identifier[dfnum] , identifier[dfden] , identifier[F] ):
literal[string]
identifier[p] = identifier[betai] ( literal[int] * identifier[dfden] , literal[int] * identifier[dfnum] , identifier[dfden] / identifier[float] ( identifier[dfden] + identifier[dfnum] * identifier[F] ... | def lfprob(dfnum, dfden, F):
"""
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
"""
p = betai(0.5 * dfden... |
def LogAccessWrapper(func):
"""Decorator that ensures that HTTP access is logged."""
def Wrapper(request, *args, **kwargs):
"""Wrapping function."""
try:
response = func(request, *args, **kwargs)
server_logging.LOGGER.LogHttpAdminUIAccess(request, response)
except Exception: # pylint: disa... | def function[LogAccessWrapper, parameter[func]]:
constant[Decorator that ensures that HTTP access is logged.]
def function[Wrapper, parameter[request]]:
constant[Wrapping function.]
<ast.Try object at 0x7da18bcc91e0>
return[name[response]]
return[name[Wrapper]] | keyword[def] identifier[LogAccessWrapper] ( identifier[func] ):
literal[string]
keyword[def] identifier[Wrapper] ( identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[response] = identifier[func] ( identifier[request] ,* identifier[arg... | def LogAccessWrapper(func):
"""Decorator that ensures that HTTP access is logged."""
def Wrapper(request, *args, **kwargs):
"""Wrapping function."""
try:
response = func(request, *args, **kwargs)
server_logging.LOGGER.LogHttpAdminUIAccess(request, response) # depends on... |
def collapse_user(fp):
"""
Converts a path back to ~/ from expanduser()
"""
home_dir = os.path.expanduser("~")
abs_path = os.path.abspath(fp)
return abs_path.replace(home_dir, "~") | def function[collapse_user, parameter[fp]]:
constant[
Converts a path back to ~/ from expanduser()
]
variable[home_dir] assign[=] call[name[os].path.expanduser, parameter[constant[~]]]
variable[abs_path] assign[=] call[name[os].path.abspath, parameter[name[fp]]]
return[call[name[abs_... | keyword[def] identifier[collapse_user] ( identifier[fp] ):
literal[string]
identifier[home_dir] = identifier[os] . identifier[path] . identifier[expanduser] ( literal[string] )
identifier[abs_path] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[fp] )
keyword[return] ident... | def collapse_user(fp):
"""
Converts a path back to ~/ from expanduser()
"""
home_dir = os.path.expanduser('~')
abs_path = os.path.abspath(fp)
return abs_path.replace(home_dir, '~') |
def create_data(step: 'projects.ProjectStep') -> STEP_DATA:
"""
Creates the data object that stores the step information in the notebook
results JavaScript file.
:param step:
Project step for which to create the data
:return:
Step data tuple containing scaffold data structure for th... | def function[create_data, parameter[step]]:
constant[
Creates the data object that stores the step information in the notebook
results JavaScript file.
:param step:
Project step for which to create the data
:return:
Step data tuple containing scaffold data structure for the step... | keyword[def] identifier[create_data] ( identifier[step] : literal[string] )-> identifier[STEP_DATA] :
literal[string]
keyword[return] identifier[STEP_DATA] (
identifier[name] = identifier[step] . identifier[definition] . identifier[name] ,
identifier[status] = identifier[step] . identifier[stat... | def create_data(step: 'projects.ProjectStep') -> STEP_DATA:
"""
Creates the data object that stores the step information in the notebook
results JavaScript file.
:param step:
Project step for which to create the data
:return:
Step data tuple containing scaffold data structure for th... |
def _get_all_files(self, path, *exclude):
'''
Walk implementation. Version in python 2.x and 3.x works differently.
'''
files = list()
dirs = list()
links = list()
if os.access(path, os.R_OK):
for obj in os.listdir(path):
obj = os.path... | def function[_get_all_files, parameter[self, path]]:
constant[
Walk implementation. Version in python 2.x and 3.x works differently.
]
variable[files] assign[=] call[name[list], parameter[]]
variable[dirs] assign[=] call[name[list], parameter[]]
variable[links] assign[=] ... | keyword[def] identifier[_get_all_files] ( identifier[self] , identifier[path] ,* identifier[exclude] ):
literal[string]
identifier[files] = identifier[list] ()
identifier[dirs] = identifier[list] ()
identifier[links] = identifier[list] ()
keyword[if] identifier[os] . id... | def _get_all_files(self, path, *exclude):
"""
Walk implementation. Version in python 2.x and 3.x works differently.
"""
files = list()
dirs = list()
links = list()
if os.access(path, os.R_OK):
for obj in os.listdir(path):
obj = os.path.join(path, obj)
... |
def matrix_undirected_weighted(user, interaction=None):
"""
Returns an undirected, weighted matrix for call, text and call duration
where an edge exists if the relationship is reciprocated.
"""
matrix = _interaction_matrix(user, interaction=interaction)
result = [[0 for _ in range(len(matrix))] ... | def function[matrix_undirected_weighted, parameter[user, interaction]]:
constant[
Returns an undirected, weighted matrix for call, text and call duration
where an edge exists if the relationship is reciprocated.
]
variable[matrix] assign[=] call[name[_interaction_matrix], parameter[name[user... | keyword[def] identifier[matrix_undirected_weighted] ( identifier[user] , identifier[interaction] = keyword[None] ):
literal[string]
identifier[matrix] = identifier[_interaction_matrix] ( identifier[user] , identifier[interaction] = identifier[interaction] )
identifier[result] =[[ literal[int] keyword... | def matrix_undirected_weighted(user, interaction=None):
"""
Returns an undirected, weighted matrix for call, text and call duration
where an edge exists if the relationship is reciprocated.
"""
matrix = _interaction_matrix(user, interaction=interaction)
result = [[0 for _ in range(len(matrix))] ... |
def _list_records(self, rtype=None, name=None, content=None):
"""
list all records
:param str rtype: type of record
:param str name: name of record
:param mixed content: value of record
:return list: list of found records
:raises Exception: on error
"""
... | def function[_list_records, parameter[self, rtype, name, content]]:
constant[
list all records
:param str rtype: type of record
:param str name: name of record
:param mixed content: value of record
:return list: list of found records
:raises Exception: on error
... | keyword[def] identifier[_list_records] ( identifier[self] , identifier[rtype] = keyword[None] , identifier[name] = keyword[None] , identifier[content] = keyword[None] ):
literal[string]
identifier[opts] ={ literal[string] : identifier[self] . identifier[_domain] }
keyword[if] identifier[r... | def _list_records(self, rtype=None, name=None, content=None):
"""
list all records
:param str rtype: type of record
:param str name: name of record
:param mixed content: value of record
:return list: list of found records
:raises Exception: on error
"""
o... |
def increment(self):
'''Increment the counter (overflow rolls back to 0).'''
for i in xrange(len(self._counter) - 1, -1, -1):
self._counter[i] += 1
if self._counter[i] < 256: break
# Carry the one
self._counter[i] = 0
# Overflow
else:
... | def function[increment, parameter[self]]:
constant[Increment the counter (overflow rolls back to 0).]
for taget[name[i]] in starred[call[name[xrange], parameter[binary_operation[call[name[len], parameter[name[self]._counter]] - constant[1]], <ast.UnaryOp object at 0x7da20c6e6140>, <ast.UnaryOp object at... | keyword[def] identifier[increment] ( identifier[self] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[xrange] ( identifier[len] ( identifier[self] . identifier[_counter] )- literal[int] ,- literal[int] ,- literal[int] ):
identifier[self] . identifier[_counter] ... | def increment(self):
"""Increment the counter (overflow rolls back to 0)."""
for i in xrange(len(self._counter) - 1, -1, -1):
self._counter[i] += 1
if self._counter[i] < 256:
break # depends on [control=['if'], data=[]]
# Carry the one
self._counter[i] = 0 # depends... |
def _terms(self):
""" Returns a list with the objects as terms. """
res = []
for sign, terms in self.terms.items():
for ID, lon in terms.items():
res.append(self.T(ID, sign))
return res | def function[_terms, parameter[self]]:
constant[ Returns a list with the objects as terms. ]
variable[res] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b11dc2e0>, <ast.Name object at 0x7da1b11dc520>]]] in starred[call[name[self].terms.items, parameter[]]] begin[:]
... | keyword[def] identifier[_terms] ( identifier[self] ):
literal[string]
identifier[res] =[]
keyword[for] identifier[sign] , identifier[terms] keyword[in] identifier[self] . identifier[terms] . identifier[items] ():
keyword[for] identifier[ID] , identifier[lon] keyword[in] ... | def _terms(self):
""" Returns a list with the objects as terms. """
res = []
for (sign, terms) in self.terms.items():
for (ID, lon) in terms.items():
res.append(self.T(ID, sign)) # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]]
return res |
def export(self, exporter=None, force_stroke=False):
"""
Export this SWF using the specified exporter.
When no exporter is passed in the default exporter used
is swf.export.SVGExporter.
Exporters should extend the swf.export.BaseExporter class.
@param ... | def function[export, parameter[self, exporter, force_stroke]]:
constant[
Export this SWF using the specified exporter.
When no exporter is passed in the default exporter used
is swf.export.SVGExporter.
Exporters should extend the swf.export.BaseExporter class.
... | keyword[def] identifier[export] ( identifier[self] , identifier[exporter] = keyword[None] , identifier[force_stroke] = keyword[False] ):
literal[string]
identifier[exporter] = identifier[SVGExporter] () keyword[if] identifier[exporter] keyword[is] keyword[None] keyword[else] identifier[exporte... | def export(self, exporter=None, force_stroke=False):
"""
Export this SWF using the specified exporter.
When no exporter is passed in the default exporter used
is swf.export.SVGExporter.
Exporters should extend the swf.export.BaseExporter class.
@param expo... |
def cell2code(cell, named_ranges):
"""Generate python code for the given cell"""
if cell.formula:
debug = False
# if 'OFFSET' in cell.formula or 'INDEX' in cell.formula:
# debug = True
# if debug:
# print 'FORMULA', cell.formula
ref = parse_cell_address(... | def function[cell2code, parameter[cell, named_ranges]]:
constant[Generate python code for the given cell]
if name[cell].formula begin[:]
variable[debug] assign[=] constant[False]
variable[ref] assign[=] <ast.IfExp object at 0x7da1b08602b0>
variable[sheet] ... | keyword[def] identifier[cell2code] ( identifier[cell] , identifier[named_ranges] ):
literal[string]
keyword[if] identifier[cell] . identifier[formula] :
identifier[debug] = keyword[False]
identifier[ref] = identifier[parse_cell_address] ( identifier... | def cell2code(cell, named_ranges):
"""Generate python code for the given cell"""
if cell.formula:
debug = False
# if 'OFFSET' in cell.formula or 'INDEX' in cell.formula:
# debug = True
# if debug:
# print 'FORMULA', cell.formula
ref = parse_cell_address(ce... |
def disassemble(self, code, lasti=-1, file=None):
"""Disassemble a code object."""
return self.disco(code, lasti, file) | def function[disassemble, parameter[self, code, lasti, file]]:
constant[Disassemble a code object.]
return[call[name[self].disco, parameter[name[code], name[lasti], name[file]]]] | keyword[def] identifier[disassemble] ( identifier[self] , identifier[code] , identifier[lasti] =- literal[int] , identifier[file] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[disco] ( identifier[code] , identifier[lasti] , identifier[file] ) | def disassemble(self, code, lasti=-1, file=None):
"""Disassemble a code object."""
return self.disco(code, lasti, file) |
def njsd_all(network, ref, query, file, verbose=True):
"""Compute transcriptome-wide nJSD between reference and query expression profiles.
Attribute:
network (str): File path to a network file.
ref (str): File path to a reference expression file.
query (str): File path to a query express... | def function[njsd_all, parameter[network, ref, query, file, verbose]]:
constant[Compute transcriptome-wide nJSD between reference and query expression profiles.
Attribute:
network (str): File path to a network file.
ref (str): File path to a reference expression file.
query (str): Fi... | keyword[def] identifier[njsd_all] ( identifier[network] , identifier[ref] , identifier[query] , identifier[file] , identifier[verbose] = keyword[True] ):
literal[string]
identifier[graph] , identifier[gene_set_total] = identifier[util] . identifier[parse_network] ( identifier[network] )
identifier[ref... | def njsd_all(network, ref, query, file, verbose=True):
"""Compute transcriptome-wide nJSD between reference and query expression profiles.
Attribute:
network (str): File path to a network file.
ref (str): File path to a reference expression file.
query (str): File path to a query express... |
def parse(self, fileobj, name_hint='', parser=None):
"""Fill from a file-like object."""
self.current_block = None # Reset current block
parser = parser or Parser()
for line in parser.parse(fileobj, name_hint=name_hint):
self.handle_line(line) | def function[parse, parameter[self, fileobj, name_hint, parser]]:
constant[Fill from a file-like object.]
name[self].current_block assign[=] constant[None]
variable[parser] assign[=] <ast.BoolOp object at 0x7da1b2346b60>
for taget[name[line]] in starred[call[name[parser].parse, parameter... | keyword[def] identifier[parse] ( identifier[self] , identifier[fileobj] , identifier[name_hint] = literal[string] , identifier[parser] = keyword[None] ):
literal[string]
identifier[self] . identifier[current_block] = keyword[None]
identifier[parser] = identifier[parser] keyword[or] iden... | def parse(self, fileobj, name_hint='', parser=None):
"""Fill from a file-like object."""
self.current_block = None # Reset current block
parser = parser or Parser()
for line in parser.parse(fileobj, name_hint=name_hint):
self.handle_line(line) # depends on [control=['for'], data=['line']] |
def rename(self, new_dirname=None, new_basename=None):
"""Rename the dirname, basename or their combinations.
**中文文档**
对文件的目录名, 文件夹名, 或它们的组合进行修改。
"""
if not new_basename:
new_basename = self.new_basename
if not new_dirname:
new_di... | def function[rename, parameter[self, new_dirname, new_basename]]:
constant[Rename the dirname, basename or their combinations.
**中文文档**
对文件的目录名, 文件夹名, 或它们的组合进行修改。
]
if <ast.UnaryOp object at 0x7da18f09d690> begin[:]
variable[new_basename] assign[... | keyword[def] identifier[rename] ( identifier[self] , identifier[new_dirname] = keyword[None] , identifier[new_basename] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[new_basename] :
identifier[new_basename] = identifier[self] . identifier[new_basename]
... | def rename(self, new_dirname=None, new_basename=None):
"""Rename the dirname, basename or their combinations.
**中文文档**
对文件的目录名, 文件夹名, 或它们的组合进行修改。
"""
if not new_basename:
new_basename = self.new_basename # depends on [control=['if'], data=[]]
if not new_dir... |
def reduce_data_frame_evenly_with_gaps (df, valcol, target_len, maxgap, **kwargs):
""""Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based on
gaps in one of the columns.
This function combines :func:`reduce_data_frame` with
:func:`slice_evenly_with_gaps`.
"""
return reduce... | def function[reduce_data_frame_evenly_with_gaps, parameter[df, valcol, target_len, maxgap]]:
constant["Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based on
gaps in one of the columns.
This function combines :func:`reduce_data_frame` with
:func:`slice_evenly_with_gaps`.
]... | keyword[def] identifier[reduce_data_frame_evenly_with_gaps] ( identifier[df] , identifier[valcol] , identifier[target_len] , identifier[maxgap] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[reduce_data_frame] ( identifier[df] ,
identifier[slice_evenly_with_gaps] ( identifier[df... | def reduce_data_frame_evenly_with_gaps(df, valcol, target_len, maxgap, **kwargs):
""""Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based on
gaps in one of the columns.
This function combines :func:`reduce_data_frame` with
:func:`slice_evenly_with_gaps`.
"""
return reduce_... |
def update_one(self, filter, update, upsert=False,
bypass_document_validation=False,
collation=None):
"""Update a single document matching the filter.
>>> for doc in db.test.find():
... print(doc)
...
{u'x': 1, u'_id': 0}
... | def function[update_one, parameter[self, filter, update, upsert, bypass_document_validation, collation]]:
constant[Update a single document matching the filter.
>>> for doc in db.test.find():
... print(doc)
...
{u'x': 1, u'_id': 0}
{u'x': 1, u'_id': 1}
... | keyword[def] identifier[update_one] ( identifier[self] , identifier[filter] , identifier[update] , identifier[upsert] = keyword[False] ,
identifier[bypass_document_validation] = keyword[False] ,
identifier[collation] = keyword[None] ):
literal[string]
identifier[common] . identifier[validate_is_m... | def update_one(self, filter, update, upsert=False, bypass_document_validation=False, collation=None):
"""Update a single document matching the filter.
>>> for doc in db.test.find():
... print(doc)
...
{u'x': 1, u'_id': 0}
{u'x': 1, u'_id': 1}
{u'x': 1... |
def create_new_example(self, foo='', a='', b=''):
"""Entity object factory."""
return create_new_example(foo=foo, a=a, b=b) | def function[create_new_example, parameter[self, foo, a, b]]:
constant[Entity object factory.]
return[call[name[create_new_example], parameter[]]] | keyword[def] identifier[create_new_example] ( identifier[self] , identifier[foo] = literal[string] , identifier[a] = literal[string] , identifier[b] = literal[string] ):
literal[string]
keyword[return] identifier[create_new_example] ( identifier[foo] = identifier[foo] , identifier[a] = identifier[... | def create_new_example(self, foo='', a='', b=''):
"""Entity object factory."""
return create_new_example(foo=foo, a=a, b=b) |
def _error_handler(data, unique_id):
"""Called when data first received
:param data: Received data
:param unique_id: Unique id
:return: True if error present
"""
if data.get('statusCode') == 'FAILURE':
logger.error('[Subscription: %s] %s: %s' % (unique_id, da... | def function[_error_handler, parameter[data, unique_id]]:
constant[Called when data first received
:param data: Received data
:param unique_id: Unique id
:return: True if error present
]
if compare[call[name[data].get, parameter[constant[statusCode]]] equal[==] constant[... | keyword[def] identifier[_error_handler] ( identifier[data] , identifier[unique_id] ):
literal[string]
keyword[if] identifier[data] . identifier[get] ( literal[string] )== literal[string] :
identifier[logger] . identifier[error] ( literal[string] %( identifier[unique_id] , identifier[d... | def _error_handler(data, unique_id):
"""Called when data first received
:param data: Received data
:param unique_id: Unique id
:return: True if error present
"""
if data.get('statusCode') == 'FAILURE':
logger.error('[Subscription: %s] %s: %s' % (unique_id, data.get('erro... |
def isdir(path, **kwargs):
"""Check if *path* is a directory"""
import os.path
return os.path.isdir(path, **kwargs) | def function[isdir, parameter[path]]:
constant[Check if *path* is a directory]
import module[os.path]
return[call[name[os].path.isdir, parameter[name[path]]]] | keyword[def] identifier[isdir] ( identifier[path] ,** identifier[kwargs] ):
literal[string]
keyword[import] identifier[os] . identifier[path]
keyword[return] identifier[os] . identifier[path] . identifier[isdir] ( identifier[path] ,** identifier[kwargs] ) | def isdir(path, **kwargs):
"""Check if *path* is a directory"""
import os.path
return os.path.isdir(path, **kwargs) |
def best_model(self):
"""Rebuilds the top scoring model from an optimisation.
Returns
-------
model: AMPAL
Returns an AMPAL model of the top scoring parameters.
Raises
------
AttributeError
Raises a name error if the optimiser has not bee... | def function[best_model, parameter[self]]:
constant[Rebuilds the top scoring model from an optimisation.
Returns
-------
model: AMPAL
Returns an AMPAL model of the top scoring parameters.
Raises
------
AttributeError
Raises a name error i... | keyword[def] identifier[best_model] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[raise] identifier[AttributeError] (
literal[string] )
identifier[model] = identifier[self] . i... | def best_model(self):
"""Rebuilds the top scoring model from an optimisation.
Returns
-------
model: AMPAL
Returns an AMPAL model of the top scoring parameters.
Raises
------
AttributeError
Raises a name error if the optimiser has not been ru... |
def get_vulnerability(
source,
sink,
triggers,
lattice,
cfg,
interactive,
blackbox_mapping
):
"""Get vulnerability between source and sink if it exists.
Uses triggers to find sanitisers.
Note: When a secondary node is in_constraint with the sink
but not the source... | def function[get_vulnerability, parameter[source, sink, triggers, lattice, cfg, interactive, blackbox_mapping]]:
constant[Get vulnerability between source and sink if it exists.
Uses triggers to find sanitisers.
Note: When a secondary node is in_constraint with the sink
but not the sourc... | keyword[def] identifier[get_vulnerability] (
identifier[source] ,
identifier[sink] ,
identifier[triggers] ,
identifier[lattice] ,
identifier[cfg] ,
identifier[interactive] ,
identifier[blackbox_mapping]
):
literal[string]
identifier[nodes_in_constraint] =[
identifier[secondary]
keyword[f... | def get_vulnerability(source, sink, triggers, lattice, cfg, interactive, blackbox_mapping):
"""Get vulnerability between source and sink if it exists.
Uses triggers to find sanitisers.
Note: When a secondary node is in_constraint with the sink
but not the source, the secondary is a save_N_LH... |
def init_with_context(self, context):
"""
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
"""
from admin_tools.menu.models import Bookmark
for b in Bookmark.objects.fil... | def function[init_with_context, parameter[self, context]]:
constant[
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
]
from relative_module[admin_tools.menu.models] import module[Bo... | keyword[def] identifier[init_with_context] ( identifier[self] , identifier[context] ):
literal[string]
keyword[from] identifier[admin_tools] . identifier[menu] . identifier[models] keyword[import] identifier[Bookmark]
keyword[for] identifier[b] keyword[in] identifier[Bookmark] . id... | def init_with_context(self, context):
"""
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
"""
from admin_tools.menu.models import Bookmark
for b in Bookmark.objects.filter(user=cont... |
def get_field(self, offset, length, format):
"""Returns unpacked Python struct array.
Args:
offset (int): offset to byte array within structure
length (int): how many bytes to unpack
format (str): Python struct format string for unpacking
See Also:
... | def function[get_field, parameter[self, offset, length, format]]:
constant[Returns unpacked Python struct array.
Args:
offset (int): offset to byte array within structure
length (int): how many bytes to unpack
format (str): Python struct format string for unpacking
... | keyword[def] identifier[get_field] ( identifier[self] , identifier[offset] , identifier[length] , identifier[format] ):
literal[string]
keyword[return] identifier[struct] . identifier[unpack] ( identifier[format] , identifier[self] . identifier[data] [ identifier[offset] : identifier[offset] + ide... | def get_field(self, offset, length, format):
"""Returns unpacked Python struct array.
Args:
offset (int): offset to byte array within structure
length (int): how many bytes to unpack
format (str): Python struct format string for unpacking
See Also:
h... |
def html_to_ssml(text):
"""
Replaces specific html tags with probable SSML counterparts.
"""
ssml_text = reduce(lambda x, y: x.replace(y, html_to_ssml_maps[y]), html_to_ssml_maps, text)
return ssml_text | def function[html_to_ssml, parameter[text]]:
constant[
Replaces specific html tags with probable SSML counterparts.
]
variable[ssml_text] assign[=] call[name[reduce], parameter[<ast.Lambda object at 0x7da1b11744f0>, name[html_to_ssml_maps], name[text]]]
return[name[ssml_text]] | keyword[def] identifier[html_to_ssml] ( identifier[text] ):
literal[string]
identifier[ssml_text] = identifier[reduce] ( keyword[lambda] identifier[x] , identifier[y] : identifier[x] . identifier[replace] ( identifier[y] , identifier[html_to_ssml_maps] [ identifier[y] ]), identifier[html_to_ssml_maps] , i... | def html_to_ssml(text):
"""
Replaces specific html tags with probable SSML counterparts.
"""
ssml_text = reduce(lambda x, y: x.replace(y, html_to_ssml_maps[y]), html_to_ssml_maps, text)
return ssml_text |
def VerifyRow(self, parser_mediator, row):
"""Verifies if a line of the file is in the expected format.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, str]): fields of a single row, as specified... | def function[VerifyRow, parameter[self, parser_mediator, row]]:
constant[Verifies if a line of the file is in the expected format.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, str]): field... | keyword[def] identifier[VerifyRow] ( identifier[self] , identifier[parser_mediator] , identifier[row] ):
literal[string]
keyword[try] :
identifier[time_elements_tuple] = identifier[self] . identifier[_GetTimeElementsTuple] ( identifier[row] [ literal[string] ])
keyword[except] ( identifier[Type... | def VerifyRow(self, parser_mediator, row):
"""Verifies if a line of the file is in the expected format.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, str]): fields of a single row, as specified... |
def _get_selection(self):
"Returns the index of the selected item (list for multiselect) or None"
if self.multiselect:
return self.wx_obj.GetSelections()
else:
sel = self.wx_obj.GetSelection()
if sel == wx.NOT_FOUND:
return None
... | def function[_get_selection, parameter[self]]:
constant[Returns the index of the selected item (list for multiselect) or None]
if name[self].multiselect begin[:]
return[call[name[self].wx_obj.GetSelections, parameter[]]] | keyword[def] identifier[_get_selection] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[multiselect] :
keyword[return] identifier[self] . identifier[wx_obj] . identifier[GetSelections] ()
keyword[else] :
identifier[sel] = ide... | def _get_selection(self):
"""Returns the index of the selected item (list for multiselect) or None"""
if self.multiselect:
return self.wx_obj.GetSelections() # depends on [control=['if'], data=[]]
else:
sel = self.wx_obj.GetSelection()
if sel == wx.NOT_FOUND:
return None... |
def read_stats(self, *stats):
""" Read port statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
"""
self.statistics = OrderedDict()
for port in self.ports:
port_stats = IxeStatTotal(port).get_attributes(FLAG_R... | def function[read_stats, parameter[self]]:
constant[ Read port statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
]
name[self].statistics assign[=] call[name[OrderedDict], parameter[]]
for taget[name[port]] in starred[nam... | keyword[def] identifier[read_stats] ( identifier[self] ,* identifier[stats] ):
literal[string]
identifier[self] . identifier[statistics] = identifier[OrderedDict] ()
keyword[for] identifier[port] keyword[in] identifier[self] . identifier[ports] :
identifier[port_stats] = i... | def read_stats(self, *stats):
""" Read port statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
"""
self.statistics = OrderedDict()
for port in self.ports:
port_stats = IxeStatTotal(port).get_attributes(FLAG_RDONLY, *stats)
... |
def _presize(self, size:int, val_xtra_size:int=32, scale:Tuple[float]=(0.08, 1.0), ratio:Tuple[float]=(0.75, 4./3.),
interpolation:int=2):
"Resize images to `size` using `RandomResizedCrop`, passing along `kwargs` to train transform"
return self.pre_transform(
tvt.RandomResizedCrop(size, sc... | def function[_presize, parameter[self, size, val_xtra_size, scale, ratio, interpolation]]:
constant[Resize images to `size` using `RandomResizedCrop`, passing along `kwargs` to train transform]
return[call[name[self].pre_transform, parameter[call[name[tvt].RandomResizedCrop, parameter[name[size]]], list[[<a... | keyword[def] identifier[_presize] ( identifier[self] , identifier[size] : identifier[int] , identifier[val_xtra_size] : identifier[int] = literal[int] , identifier[scale] : identifier[Tuple] [ identifier[float] ]=( literal[int] , literal[int] ), identifier[ratio] : identifier[Tuple] [ identifier[float] ]=( literal[in... | def _presize(self, size: int, val_xtra_size: int=32, scale: Tuple[float]=(0.08, 1.0), ratio: Tuple[float]=(0.75, 4.0 / 3.0), interpolation: int=2):
"""Resize images to `size` using `RandomResizedCrop`, passing along `kwargs` to train transform"""
return self.pre_transform(tvt.RandomResizedCrop(size, scale=scale... |
def require(self, product_type):
"""Schedules the tasks that produce product_type to be executed before the requesting task.
There must be at least one task that produces the required product type, or the
dependencies will not be satisfied.
:API: public
"""
self._dependencies.add(product_type)... | def function[require, parameter[self, product_type]]:
constant[Schedules the tasks that produce product_type to be executed before the requesting task.
There must be at least one task that produces the required product type, or the
dependencies will not be satisfied.
:API: public
]
cal... | keyword[def] identifier[require] ( identifier[self] , identifier[product_type] ):
literal[string]
identifier[self] . identifier[_dependencies] . identifier[add] ( identifier[product_type] )
identifier[self] . identifier[_context] . identifier[products] . identifier[require] ( identifier[product_type] ... | def require(self, product_type):
"""Schedules the tasks that produce product_type to be executed before the requesting task.
There must be at least one task that produces the required product type, or the
dependencies will not be satisfied.
:API: public
"""
self._dependencies.add(product_type)... |
def arc(document, bounding_rect, start, extent, style):
"arc, pieslice (filled), arc with chord (filled)"
(x1, y1, x2, y2) = bounding_rect
import math
cx = (x1 + x2)/2.0
cy = (y1 + y2)/2.0
rx = (x2 - x1)/2.0
ry = (y2 - y1)/2.0
start = math.radians(float(start))
extent = math.radians(float(extent))
# fr... | def function[arc, parameter[document, bounding_rect, start, extent, style]]:
constant[arc, pieslice (filled), arc with chord (filled)]
<ast.Tuple object at 0x7da1b0f44ac0> assign[=] name[bounding_rect]
import module[math]
variable[cx] assign[=] binary_operation[binary_operation[name[x1] + na... | keyword[def] identifier[arc] ( identifier[document] , identifier[bounding_rect] , identifier[start] , identifier[extent] , identifier[style] ):
literal[string]
( identifier[x1] , identifier[y1] , identifier[x2] , identifier[y2] )= identifier[bounding_rect]
keyword[import] identifier[math]
identifier[cx] =... | def arc(document, bounding_rect, start, extent, style):
"""arc, pieslice (filled), arc with chord (filled)"""
(x1, y1, x2, y2) = bounding_rect
import math
cx = (x1 + x2) / 2.0
cy = (y1 + y2) / 2.0
rx = (x2 - x1) / 2.0
ry = (y2 - y1) / 2.0
start = math.radians(float(start))
extent = m... |
def clear_marking(self):
"""Clear marking from image.
This does not clear loaded coordinates from memory."""
if self.marktag:
try:
self.canvas.delete_object_by_tag(self.marktag, redraw=False)
except Exception:
pass
if self.markhlta... | def function[clear_marking, parameter[self]]:
constant[Clear marking from image.
This does not clear loaded coordinates from memory.]
if name[self].marktag begin[:]
<ast.Try object at 0x7da18eb57d30>
if name[self].markhltag begin[:]
<ast.Try object at 0x7da18eb57dc0>
... | keyword[def] identifier[clear_marking] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[marktag] :
keyword[try] :
identifier[self] . identifier[canvas] . identifier[delete_object_by_tag] ( identifier[self] . identifier[marktag] , identif... | def clear_marking(self):
"""Clear marking from image.
This does not clear loaded coordinates from memory."""
if self.marktag:
try:
self.canvas.delete_object_by_tag(self.marktag, redraw=False) # depends on [control=['try'], data=[]]
except Exception:
pass # depen... |
def _depth_first_search(self, target_id, layer_id_list, node_list):
"""Search for all the layers and nodes down the path.
A recursive function to search all the layers and nodes between the node in the node_list
and the node with target_id."""
assert len(node_list) <= self.n_nodes
... | def function[_depth_first_search, parameter[self, target_id, layer_id_list, node_list]]:
constant[Search for all the layers and nodes down the path.
A recursive function to search all the layers and nodes between the node in the node_list
and the node with target_id.]
assert[compare[call... | keyword[def] identifier[_depth_first_search] ( identifier[self] , identifier[target_id] , identifier[layer_id_list] , identifier[node_list] ):
literal[string]
keyword[assert] identifier[len] ( identifier[node_list] )<= identifier[self] . identifier[n_nodes]
identifier[u] = identifier[nod... | def _depth_first_search(self, target_id, layer_id_list, node_list):
"""Search for all the layers and nodes down the path.
A recursive function to search all the layers and nodes between the node in the node_list
and the node with target_id."""
assert len(node_list) <= self.n_nodes
u = no... |
def quarterly(date=datetime.date.today()):
"""
Fixed at: 1/1, 4/1, 7/1, 10/1.
"""
return datetime.date(date.year, ((date.month - 1)//3) * 3 + 1, 1) | def function[quarterly, parameter[date]]:
constant[
Fixed at: 1/1, 4/1, 7/1, 10/1.
]
return[call[name[datetime].date, parameter[name[date].year, binary_operation[binary_operation[binary_operation[binary_operation[name[date].month - constant[1]] <ast.FloorDiv object at 0x7da2590d6bc0> constant[3]] * ... | keyword[def] identifier[quarterly] ( identifier[date] = identifier[datetime] . identifier[date] . identifier[today] ()):
literal[string]
keyword[return] identifier[datetime] . identifier[date] ( identifier[date] . identifier[year] ,(( identifier[date] . identifier[month] - literal[int] )// literal[int] )*... | def quarterly(date=datetime.date.today()):
"""
Fixed at: 1/1, 4/1, 7/1, 10/1.
"""
return datetime.date(date.year, (date.month - 1) // 3 * 3 + 1, 1) |
def set_alive(self):
"""Set alive, reachable, and reset attempts.
If we change state, raise a status brok update
alive, means the daemon is prenset in the system
reachable, means that the HTTP connection is valid
With this function we confirm that the daemon is reachable and, t... | def function[set_alive, parameter[self]]:
constant[Set alive, reachable, and reset attempts.
If we change state, raise a status brok update
alive, means the daemon is prenset in the system
reachable, means that the HTTP connection is valid
With this function we confirm that the... | keyword[def] identifier[set_alive] ( identifier[self] ):
literal[string]
identifier[was_alive] = identifier[self] . identifier[alive]
identifier[self] . identifier[alive] = keyword[True]
identifier[self] . identifier[reachable] = keyword[True]
identifier[self] . identi... | def set_alive(self):
"""Set alive, reachable, and reset attempts.
If we change state, raise a status brok update
alive, means the daemon is prenset in the system
reachable, means that the HTTP connection is valid
With this function we confirm that the daemon is reachable and, thus,... |
def execute_process_async(func, *args, **kwargs):
"""
Executes `func` in a separate process. Memory and other resources are not
available. This gives true concurrency at the cost of losing access to
these resources. `args` and `kwargs` are
"""
global _GIPC_EXECUTOR
if _GIPC_EXECUTOR is None:
_GIPC_EXE... | def function[execute_process_async, parameter[func]]:
constant[
Executes `func` in a separate process. Memory and other resources are not
available. This gives true concurrency at the cost of losing access to
these resources. `args` and `kwargs` are
]
<ast.Global object at 0x7da18f09f8e0>
if... | keyword[def] identifier[execute_process_async] ( identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[global] identifier[_GIPC_EXECUTOR]
keyword[if] identifier[_GIPC_EXECUTOR] keyword[is] keyword[None] :
identifier[_GIPC_EXECUTOR] = identifier[GIPCExecutor] (
... | def execute_process_async(func, *args, **kwargs):
"""
Executes `func` in a separate process. Memory and other resources are not
available. This gives true concurrency at the cost of losing access to
these resources. `args` and `kwargs` are
"""
global _GIPC_EXECUTOR
if _GIPC_EXECUTOR is None:
... |
def focus_next(self):
"""focus next message in depth first order"""
mid = self.get_selected_mid()
newpos = self._tree.next_position(mid)
if newpos is not None:
newpos = self._sanitize_position((newpos,))
self.body.set_focus(newpos) | def function[focus_next, parameter[self]]:
constant[focus next message in depth first order]
variable[mid] assign[=] call[name[self].get_selected_mid, parameter[]]
variable[newpos] assign[=] call[name[self]._tree.next_position, parameter[name[mid]]]
if compare[name[newpos] is_not constan... | keyword[def] identifier[focus_next] ( identifier[self] ):
literal[string]
identifier[mid] = identifier[self] . identifier[get_selected_mid] ()
identifier[newpos] = identifier[self] . identifier[_tree] . identifier[next_position] ( identifier[mid] )
keyword[if] identifier[newpos] ... | def focus_next(self):
"""focus next message in depth first order"""
mid = self.get_selected_mid()
newpos = self._tree.next_position(mid)
if newpos is not None:
newpos = self._sanitize_position((newpos,))
self.body.set_focus(newpos) # depends on [control=['if'], data=['newpos']] |
def set_params(self, targets=None):
'''Set the values of the parameters to the given target values.
Parameters
----------
targets : sequence of ndarray, optional
Arrays for setting the parameters of our model. If this is not
provided, the current best parameters ... | def function[set_params, parameter[self, targets]]:
constant[Set the values of the parameters to the given target values.
Parameters
----------
targets : sequence of ndarray, optional
Arrays for setting the parameters of our model. If this is not
provided, the cu... | keyword[def] identifier[set_params] ( identifier[self] , identifier[targets] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[targets] ,( identifier[list] , identifier[tuple] )):
identifier[targets] = identifier[self] . identifier[_best_... | def set_params(self, targets=None):
"""Set the values of the parameters to the given target values.
Parameters
----------
targets : sequence of ndarray, optional
Arrays for setting the parameters of our model. If this is not
provided, the current best parameters for ... |
def _add_action(self, notification, action, label, callback, *args):
"""
Show an action button button in mount notifications.
Note, this only works with some libnotify services.
"""
on_action_click = run_bg(lambda *_: callback(*args))
try:
# this is the corre... | def function[_add_action, parameter[self, notification, action, label, callback]]:
constant[
Show an action button button in mount notifications.
Note, this only works with some libnotify services.
]
variable[on_action_click] assign[=] call[name[run_bg], parameter[<ast.Lambda ob... | keyword[def] identifier[_add_action] ( identifier[self] , identifier[notification] , identifier[action] , identifier[label] , identifier[callback] ,* identifier[args] ):
literal[string]
identifier[on_action_click] = identifier[run_bg] ( keyword[lambda] * identifier[_] : identifier[callback] (* iden... | def _add_action(self, notification, action, label, callback, *args):
"""
Show an action button button in mount notifications.
Note, this only works with some libnotify services.
"""
on_action_click = run_bg(lambda *_: callback(*args))
try:
# this is the correct signature for... |
def specimens_extract(spec_file='specimens.txt', output_file='specimens.xls', landscape=False,
longtable=False, output_dir_path='.', input_dir_path='', latex=False):
"""
Extracts specimen results from a MagIC 3.0 format specimens.txt file.
Default output format is an Excel file.
t... | def function[specimens_extract, parameter[spec_file, output_file, landscape, longtable, output_dir_path, input_dir_path, latex]]:
constant[
Extracts specimen results from a MagIC 3.0 format specimens.txt file.
Default output format is an Excel file.
typeset with latex on your own computer.
Par... | keyword[def] identifier[specimens_extract] ( identifier[spec_file] = literal[string] , identifier[output_file] = literal[string] , identifier[landscape] = keyword[False] ,
identifier[longtable] = keyword[False] , identifier[output_dir_path] = literal[string] , identifier[input_dir_path] = literal[string] , identifie... | def specimens_extract(spec_file='specimens.txt', output_file='specimens.xls', landscape=False, longtable=False, output_dir_path='.', input_dir_path='', latex=False):
"""
Extracts specimen results from a MagIC 3.0 format specimens.txt file.
Default output format is an Excel file.
typeset with latex on y... |
def abort():
"""ABORT Section 9.2.8"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x29) # 00101001
c = RejectCause()
packet = a / b / c
return packet | def function[abort, parameter[]]:
constant[ABORT Section 9.2.8]
variable[a] assign[=] call[name[TpPd], parameter[]]
variable[b] assign[=] call[name[MessageType], parameter[]]
variable[c] assign[=] call[name[RejectCause], parameter[]]
variable[packet] assign[=] binary_operation[bi... | keyword[def] identifier[abort] ():
literal[string]
identifier[a] = identifier[TpPd] ( identifier[pd] = literal[int] )
identifier[b] = identifier[MessageType] ( identifier[mesType] = literal[int] )
identifier[c] = identifier[RejectCause] ()
identifier[packet] = identifier[a] / identifier[b] /... | def abort():
"""ABORT Section 9.2.8"""
a = TpPd(pd=5)
b = MessageType(mesType=41) # 00101001
c = RejectCause()
packet = a / b / c
return packet |
def visit_ClassDef(self, node): # pylint: disable=invalid-name
"""Visit top-level classes."""
# Resolve everything as root scope contains everything from the process module.
for base in node.bases:
# Cover `from resolwe.process import ...`.
if isinstance(base, ast.Name) ... | def function[visit_ClassDef, parameter[self, node]]:
constant[Visit top-level classes.]
for taget[name[base]] in starred[name[node].bases] begin[:]
if <ast.BoolOp object at 0x7da1b1a9f430> begin[:]
variable[base] assign[=] call[name[getattr], parameter[name[runtim... | keyword[def] identifier[visit_ClassDef] ( identifier[self] , identifier[node] ):
literal[string]
keyword[for] identifier[base] keyword[in] identifier[node] . identifier[bases] :
keyword[if] identifier[isinstance] ( identifier[base] , identifier[ast] . identifier[N... | def visit_ClassDef(self, node): # pylint: disable=invalid-name
'Visit top-level classes.'
# Resolve everything as root scope contains everything from the process module.
for base in node.bases:
# Cover `from resolwe.process import ...`.
if isinstance(base, ast.Name) and isinstance(base.ctx,... |
def verify(self, tool):
"""
check that the tool exists
"""
if os.path.isfile(tool['file']):
print('Toolbox: program exists = TOK :: ' + tool['file'])
return True
else:
print('Toolbox: program exists = FAIL :: ' + tool['file'])
retu... | def function[verify, parameter[self, tool]]:
constant[
check that the tool exists
]
if call[name[os].path.isfile, parameter[call[name[tool]][constant[file]]]] begin[:]
call[name[print], parameter[binary_operation[constant[Toolbox: program exists = TOK :: ] + call[name[to... | keyword[def] identifier[verify] ( identifier[self] , identifier[tool] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[isfile] ( identifier[tool] [ literal[string] ]):
identifier[print] ( literal[string] + identifier[tool] [ literal[string] ])
... | def verify(self, tool):
"""
check that the tool exists
"""
if os.path.isfile(tool['file']):
print('Toolbox: program exists = TOK :: ' + tool['file'])
return True # depends on [control=['if'], data=[]]
else:
print('Toolbox: program exists = FAIL :: ' + tool['file'])
... |
def ekappr(handle, segno):
"""
Append a new, empty record at the end of a specified E-kernel segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekappr_c.html
:param handle: File handle.
:type handle: int
:param segno: Segment number.
:type segno: int
:return: Number of ap... | def function[ekappr, parameter[handle, segno]]:
constant[
Append a new, empty record at the end of a specified E-kernel segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekappr_c.html
:param handle: File handle.
:type handle: int
:param segno: Segment number.
:type segno... | keyword[def] identifier[ekappr] ( identifier[handle] , identifier[segno] ):
literal[string]
identifier[handle] = identifier[ctypes] . identifier[c_int] ( identifier[handle] )
identifier[segno] = identifier[ctypes] . identifier[c_int] ( identifier[segno] )
identifier[recno] = identifier[ctypes] . ... | def ekappr(handle, segno):
"""
Append a new, empty record at the end of a specified E-kernel segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekappr_c.html
:param handle: File handle.
:type handle: int
:param segno: Segment number.
:type segno: int
:return: Number of ap... |
def update_milestone(self, milestone_id, title, deadline, party_id, notify,
move_upcoming_milestones=None,
move_upcoming_milestones_off_weekends=None):
"""
Modifies a single milestone. You can use this to shift the deadline of
a single milestone, and optionally shift the deadline... | def function[update_milestone, parameter[self, milestone_id, title, deadline, party_id, notify, move_upcoming_milestones, move_upcoming_milestones_off_weekends]]:
constant[
Modifies a single milestone. You can use this to shift the deadline of
a single milestone, and optionally shift the deadlin... | keyword[def] identifier[update_milestone] ( identifier[self] , identifier[milestone_id] , identifier[title] , identifier[deadline] , identifier[party_id] , identifier[notify] ,
identifier[move_upcoming_milestones] = keyword[None] ,
identifier[move_upcoming_milestones_off_weekends] = keyword[None] ):
litera... | def update_milestone(self, milestone_id, title, deadline, party_id, notify, move_upcoming_milestones=None, move_upcoming_milestones_off_weekends=None):
"""
Modifies a single milestone. You can use this to shift the deadline of
a single milestone, and optionally shift the deadlines of subsequent
... |
def run_getgist(filename, user, **kwargs):
"""Passes user inputs to GetGist() and calls get()"""
assume_yes = kwargs.get("yes_to_all")
getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes)
getgist.get() | def function[run_getgist, parameter[filename, user]]:
constant[Passes user inputs to GetGist() and calls get()]
variable[assume_yes] assign[=] call[name[kwargs].get, parameter[constant[yes_to_all]]]
variable[getgist] assign[=] call[name[GetGist], parameter[]]
call[name[getgist].get, para... | keyword[def] identifier[run_getgist] ( identifier[filename] , identifier[user] ,** identifier[kwargs] ):
literal[string]
identifier[assume_yes] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[getgist] = identifier[GetGist] ( identifier[user] = identifier[user] , identifier[filena... | def run_getgist(filename, user, **kwargs):
"""Passes user inputs to GetGist() and calls get()"""
assume_yes = kwargs.get('yes_to_all')
getgist = GetGist(user=user, filename=filename, assume_yes=assume_yes)
getgist.get() |
def strip_number(self):
"""The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
in... | def function[strip_number, parameter[self]]:
constant[The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`A... | keyword[def] identifier[strip_number] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[type] != identifier[EventType] . identifier[TABLET_PAD_STRIP] :
keyword[raise] identifier[AttributeError] ( identifier[_wrong_prop] . identifier[format] ( identifier[self] . identifier[t... | def strip_number(self):
"""The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
... |
def from_dict(cls, data):
"""
:type data: dict[str, str]
:rtype: satosa.internal.AuthenticationInformation
:param data: A dict representation of an AuthenticationInformation object
:return: An AuthenticationInformation object
"""
return cls(
auth_class... | def function[from_dict, parameter[cls, data]]:
constant[
:type data: dict[str, str]
:rtype: satosa.internal.AuthenticationInformation
:param data: A dict representation of an AuthenticationInformation object
:return: An AuthenticationInformation object
]
return[call[n... | keyword[def] identifier[from_dict] ( identifier[cls] , identifier[data] ):
literal[string]
keyword[return] identifier[cls] (
identifier[auth_class_ref] = identifier[data] . identifier[get] ( literal[string] ),
identifier[timestamp] = identifier[data] . identifier[get] ( literal[s... | def from_dict(cls, data):
"""
:type data: dict[str, str]
:rtype: satosa.internal.AuthenticationInformation
:param data: A dict representation of an AuthenticationInformation object
:return: An AuthenticationInformation object
"""
return cls(auth_class_ref=data.get('auth_c... |
def remove_root_repository(self, repository_id):
"""Removes a root repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: NotFound - ``repository_id`` not a root
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to ... | def function[remove_root_repository, parameter[self, repository_id]]:
constant[Removes a root repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: NotFound - ``repository_id`` not a root
raise: NullArgument - ``repository_id`` is ``null``
raise: O... | keyword[def] identifier[remove_root_repository] ( identifier[self] , identifier[repository_id] ):
literal[string]
keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_c... | def remove_root_repository(self, repository_id):
"""Removes a root repository.
arg: repository_id (osid.id.Id): the ``Id`` of a repository
raise: NotFound - ``repository_id`` not a root
raise: NullArgument - ``repository_id`` is ``null``
raise: OperationFailed - unable to comp... |
def rewrap(text, width=None):
"""
Rewrap text for output to the console.
Removes common indentation and rewraps paragraphs according to the console
width.
Line feeds between paragraphs preserved.
Formatting of paragraphs that starts with additional indentation
preserved.
"""
if wi... | def function[rewrap, parameter[text, width]]:
constant[
Rewrap text for output to the console.
Removes common indentation and rewraps paragraphs according to the console
width.
Line feeds between paragraphs preserved.
Formatting of paragraphs that starts with additional indentation
pre... | keyword[def] identifier[rewrap] ( identifier[text] , identifier[width] = keyword[None] ):
literal[string]
keyword[if] identifier[width] keyword[is] keyword[None] :
identifier[width] = literal[int]
identifier[text] = identifier[textwrap] . identifier[dedent] ( identifier[text] )... | def rewrap(text, width=None):
"""
Rewrap text for output to the console.
Removes common indentation and rewraps paragraphs according to the console
width.
Line feeds between paragraphs preserved.
Formatting of paragraphs that starts with additional indentation
preserved.
"""
if wid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.