code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def makeConstructor(self, originalConstructor, syntheticMemberList, doesConsumeArguments):
"""
:type syntheticMemberList: list(SyntheticMember)
:type doesConsumeArguments: bool
"""
# Original constructor's expected args.
originalConstructorExpectedArgList = []
doesExpectVariadic... | def function[makeConstructor, parameter[self, originalConstructor, syntheticMemberList, doesConsumeArguments]]:
constant[
:type syntheticMemberList: list(SyntheticMember)
:type doesConsumeArguments: bool
]
variable[originalConstructorExpectedArgList] assign[=] list[[]]
variable[doesExpec... | keyword[def] identifier[makeConstructor] ( identifier[self] , identifier[originalConstructor] , identifier[syntheticMemberList] , identifier[doesConsumeArguments] ):
literal[string]
identifier[originalConstructorExpectedArgList] =[]
identifier[doesExpectVariadicArgs] = keyword[Fa... | def makeConstructor(self, originalConstructor, syntheticMemberList, doesConsumeArguments):
"""
:type syntheticMemberList: list(SyntheticMember)
:type doesConsumeArguments: bool
"""
# Original constructor's expected args.
originalConstructorExpectedArgList = []
doesExpectVariadicArgs = False
... |
def symbols(self):
"""List of the coded symbols as strings, with special characters included."""
def _iter_symbols(symbol_values):
# The initial charset doesn't matter, as the start codes have the same symbol values in all charsets.
charset = 'A'
shift_charset = None... | def function[symbols, parameter[self]]:
constant[List of the coded symbols as strings, with special characters included.]
def function[_iter_symbols, parameter[symbol_values]]:
variable[charset] assign[=] constant[A]
variable[shift_charset] assign[=] constant[None]
... | keyword[def] identifier[symbols] ( identifier[self] ):
literal[string]
keyword[def] identifier[_iter_symbols] ( identifier[symbol_values] ):
identifier[charset] = literal[string]
identifier[shift_charset] = keyword[None]
keyword[for] identifier[s... | def symbols(self):
"""List of the coded symbols as strings, with special characters included."""
def _iter_symbols(symbol_values):
# The initial charset doesn't matter, as the start codes have the same symbol values in all charsets.
charset = 'A'
shift_charset = None
for symbol_... |
def get_dict(self, only_attributes=None, exclude_attributes=None, df_format=False):
"""Summarize the I-TASSER run in a dictionary containing modeling results and top predictions from COACH
Args:
only_attributes (str, list): Attributes that should be returned. If not provided, all are return... | def function[get_dict, parameter[self, only_attributes, exclude_attributes, df_format]]:
constant[Summarize the I-TASSER run in a dictionary containing modeling results and top predictions from COACH
Args:
only_attributes (str, list): Attributes that should be returned. If not provided, all... | keyword[def] identifier[get_dict] ( identifier[self] , identifier[only_attributes] = keyword[None] , identifier[exclude_attributes] = keyword[None] , identifier[df_format] = keyword[False] ):
literal[string]
identifier[to_exclude] =[ literal[string] , literal[string] , literal[string] , literal[st... | def get_dict(self, only_attributes=None, exclude_attributes=None, df_format=False):
"""Summarize the I-TASSER run in a dictionary containing modeling results and top predictions from COACH
Args:
only_attributes (str, list): Attributes that should be returned. If not provided, all are returned.
... |
def autoclean_cv(training_dataframe, testing_dataframe, drop_nans=False, copy=False,
encoder=None, encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function... | def function[autoclean_cv, parameter[training_dataframe, testing_dataframe, drop_nans, copy, encoder, encoder_kwargs, ignore_update_check]]:
constant[Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function takes cross-v... | keyword[def] identifier[autoclean_cv] ( identifier[training_dataframe] , identifier[testing_dataframe] , identifier[drop_nans] = keyword[False] , identifier[copy] = keyword[False] ,
identifier[encoder] = keyword[None] , identifier[encoder_kwargs] = keyword[None] , identifier[ignore_update_check] = keyword[False] ):
... | def autoclean_cv(training_dataframe, testing_dataframe, drop_nans=False, copy=False, encoder=None, encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function takes cross-vali... |
def read_plain(file_obj, type_, count):
"""Read `count` items `type` from the fo using the plain encoding."""
if count == 0:
return []
conv = DECODE_PLAIN[type_]
return conv(file_obj, count) | def function[read_plain, parameter[file_obj, type_, count]]:
constant[Read `count` items `type` from the fo using the plain encoding.]
if compare[name[count] equal[==] constant[0]] begin[:]
return[list[[]]]
variable[conv] assign[=] call[name[DECODE_PLAIN]][name[type_]]
return[call[na... | keyword[def] identifier[read_plain] ( identifier[file_obj] , identifier[type_] , identifier[count] ):
literal[string]
keyword[if] identifier[count] == literal[int] :
keyword[return] []
identifier[conv] = identifier[DECODE_PLAIN] [ identifier[type_] ]
keyword[return] identifier[conv] ( ... | def read_plain(file_obj, type_, count):
"""Read `count` items `type` from the fo using the plain encoding."""
if count == 0:
return [] # depends on [control=['if'], data=[]]
conv = DECODE_PLAIN[type_]
return conv(file_obj, count) |
def deconv2d(self, filter_size, output_channels, stride=1, padding='SAME', stoch=False, ladder=None,
activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, bn=True):
"""
2D Deconvolutional Layer
:param filter_size: int. assumes square filter
:param output_channels: int
... | def function[deconv2d, parameter[self, filter_size, output_channels, stride, padding, stoch, ladder, activation_fn, b_value, s_value, bn]]:
constant[
2D Deconvolutional Layer
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:pa... | keyword[def] identifier[deconv2d] ( identifier[self] , identifier[filter_size] , identifier[output_channels] , identifier[stride] = literal[int] , identifier[padding] = literal[string] , identifier[stoch] = keyword[False] , identifier[ladder] = keyword[None] ,
identifier[activation_fn] = identifier[tf] . identifier[... | def deconv2d(self, filter_size, output_channels, stride=1, padding='SAME', stoch=False, ladder=None, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, bn=True):
"""
2D Deconvolutional Layer
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: in... |
def update(self, statement):
"""
Update the provided statement.
"""
Statement = self.get_model('statement')
Tag = self.get_model('tag')
if hasattr(statement, 'id'):
statement.save()
else:
statement = Statement.objects.create(
... | def function[update, parameter[self, statement]]:
constant[
Update the provided statement.
]
variable[Statement] assign[=] call[name[self].get_model, parameter[constant[statement]]]
variable[Tag] assign[=] call[name[self].get_model, parameter[constant[tag]]]
if call[name[... | keyword[def] identifier[update] ( identifier[self] , identifier[statement] ):
literal[string]
identifier[Statement] = identifier[self] . identifier[get_model] ( literal[string] )
identifier[Tag] = identifier[self] . identifier[get_model] ( literal[string] )
keyword[if] identifie... | def update(self, statement):
"""
Update the provided statement.
"""
Statement = self.get_model('statement')
Tag = self.get_model('tag')
if hasattr(statement, 'id'):
statement.save() # depends on [control=['if'], data=[]]
else:
statement = Statement.objects.create(tex... |
def _create_archive(
self,
archive_name,
metadata):
'''
This adds an item in a DynamoDB table corresponding to a S3 object
Args
----
arhive_name: str
corresponds to the name of the Archive (e.g. )
Returns
-------
... | def function[_create_archive, parameter[self, archive_name, metadata]]:
constant[
This adds an item in a DynamoDB table corresponding to a S3 object
Args
----
arhive_name: str
corresponds to the name of the Archive (e.g. )
Returns
-------
Di... | keyword[def] identifier[_create_archive] (
identifier[self] ,
identifier[archive_name] ,
identifier[metadata] ):
literal[string]
identifier[archive_exists] = keyword[False]
keyword[try] :
identifier[self] . identifier[get_archive] ( identifier[archive_name] )
... | def _create_archive(self, archive_name, metadata):
"""
This adds an item in a DynamoDB table corresponding to a S3 object
Args
----
arhive_name: str
corresponds to the name of the Archive (e.g. )
Returns
-------
Dictionary with confirmation of u... |
def refkeys(self,fields):
"returns {ModelClass:list_of_pkey_tuples}. see syncschema.RefKey. Don't use this yet."
# todo doc: better explanation of what refkeys are and how fields plays in
dd=collections.defaultdict(list)
if any(f not in self.REFKEYS for f in fields): raise ValueError(fields,'not all... | def function[refkeys, parameter[self, fields]]:
constant[returns {ModelClass:list_of_pkey_tuples}. see syncschema.RefKey. Don't use this yet.]
variable[dd] assign[=] call[name[collections].defaultdict, parameter[name[list]]]
if call[name[any], parameter[<ast.GeneratorExp object at 0x7da1b15b3bb0... | keyword[def] identifier[refkeys] ( identifier[self] , identifier[fields] ):
literal[string]
identifier[dd] = identifier[collections] . identifier[defaultdict] ( identifier[list] )
keyword[if] identifier[any] ( identifier[f] keyword[not] keyword[in] identifier[self] . identifier[REFKEYS] ... | def refkeys(self, fields):
"""returns {ModelClass:list_of_pkey_tuples}. see syncschema.RefKey. Don't use this yet.""" # todo doc: better explanation of what refkeys are and how fields plays in
dd = collections.defaultdict(list)
if any((f not in self.REFKEYS for f in fields)):
raise ValueError(field... |
def start(self, stages=(1, 2)):
"""
Starts the processes or threads in the internal pool and the threads,
which manage the **worker pool** input and output queues. The
**starting mode** is split into **two stages**, which can be initiated
seperately. After the first stage the ... | def function[start, parameter[self, stages]]:
constant[
Starts the processes or threads in the internal pool and the threads,
which manage the **worker pool** input and output queues. The
**starting mode** is split into **two stages**, which can be initiated
seperately. After ... | keyword[def] identifier[start] ( identifier[self] , identifier[stages] =( literal[int] , literal[int] )):
literal[string]
keyword[if] literal[int] keyword[in] identifier[stages] :
keyword[if] keyword[not] identifier[self] . identifier[_started] . identifier[isSet] ():
... | def start(self, stages=(1, 2)):
"""
Starts the processes or threads in the internal pool and the threads,
which manage the **worker pool** input and output queues. The
**starting mode** is split into **two stages**, which can be initiated
seperately. After the first stage the **wo... |
def xml_to_json(element, definition, required=False):
# TODO document tuple - it looks little too complex
"""Convert XML (ElementTree) to dictionary from a definition schema.
Definition schema can be a simple string - XPath or @attribute for
direct extraction or a complex one described by
* dictio... | def function[xml_to_json, parameter[element, definition, required]]:
constant[Convert XML (ElementTree) to dictionary from a definition schema.
Definition schema can be a simple string - XPath or @attribute for
direct extraction or a complex one described by
* dictionary ``{key: 'xpath or @attribu... | keyword[def] identifier[xml_to_json] ( identifier[element] , identifier[definition] , identifier[required] = keyword[False] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[definition] , identifier[str] ) keyword[and] identifier[len] ( identifier[definition] )> literal[int] :
... | def xml_to_json(element, definition, required=False):
# TODO document tuple - it looks little too complex
"Convert XML (ElementTree) to dictionary from a definition schema.\n\n Definition schema can be a simple string - XPath or @attribute for\n direct extraction or a complex one described by\n\n * dic... |
def Sum(*args: BitVec) -> BitVec:
"""Create sum expression.
:return:
"""
raw = z3.Sum([a.raw for a in args])
annotations = [] # type: Annotations
bitvecfuncs = []
for bv in args:
annotations += bv.annotations
if isinstance(bv, BitVecFunc):
bitvecfuncs.append(bv... | def function[Sum, parameter[]]:
constant[Create sum expression.
:return:
]
variable[raw] assign[=] call[name[z3].Sum, parameter[<ast.ListComp object at 0x7da1b1ddcc10>]]
variable[annotations] assign[=] list[[]]
variable[bitvecfuncs] assign[=] list[[]]
for taget[name[bv]]... | keyword[def] identifier[Sum] (* identifier[args] : identifier[BitVec] )-> identifier[BitVec] :
literal[string]
identifier[raw] = identifier[z3] . identifier[Sum] ([ identifier[a] . identifier[raw] keyword[for] identifier[a] keyword[in] identifier[args] ])
identifier[annotations] =[]
identifie... | def Sum(*args: BitVec) -> BitVec:
"""Create sum expression.
:return:
"""
raw = z3.Sum([a.raw for a in args])
annotations = [] # type: Annotations
bitvecfuncs = []
for bv in args:
annotations += bv.annotations
if isinstance(bv, BitVecFunc):
bitvecfuncs.append(bv)... |
def samples(dataset='imagenet', index=0, batchsize=1, shape=(224, 224),
data_format='channels_last'):
''' Returns a batch of example images and the corresponding labels
Parameters
----------
dataset : string
The data set to load (options: imagenet, mnist, cifar10,
cifar100, ... | def function[samples, parameter[dataset, index, batchsize, shape, data_format]]:
constant[ Returns a batch of example images and the corresponding labels
Parameters
----------
dataset : string
The data set to load (options: imagenet, mnist, cifar10,
cifar100, fashionMNIST)
index... | keyword[def] identifier[samples] ( identifier[dataset] = literal[string] , identifier[index] = literal[int] , identifier[batchsize] = literal[int] , identifier[shape] =( literal[int] , literal[int] ),
identifier[data_format] = literal[string] ):
literal[string]
keyword[from] identifier[PIL] keyword[impo... | def samples(dataset='imagenet', index=0, batchsize=1, shape=(224, 224), data_format='channels_last'):
""" Returns a batch of example images and the corresponding labels
Parameters
----------
dataset : string
The data set to load (options: imagenet, mnist, cifar10,
cifar100, fashionMNIST... |
def _resolve_registered(self, event_handler, full_config) -> typing.Generator:
"""
Resolve registered filters
:param event_handler:
:param full_config:
:return:
"""
for record in self._registered:
filter_ = record.resolve(self._dispatcher, event_handl... | def function[_resolve_registered, parameter[self, event_handler, full_config]]:
constant[
Resolve registered filters
:param event_handler:
:param full_config:
:return:
]
for taget[name[record]] in starred[name[self]._registered] begin[:]
variable[... | keyword[def] identifier[_resolve_registered] ( identifier[self] , identifier[event_handler] , identifier[full_config] )-> identifier[typing] . identifier[Generator] :
literal[string]
keyword[for] identifier[record] keyword[in] identifier[self] . identifier[_registered] :
identifier[... | def _resolve_registered(self, event_handler, full_config) -> typing.Generator:
"""
Resolve registered filters
:param event_handler:
:param full_config:
:return:
"""
for record in self._registered:
filter_ = record.resolve(self._dispatcher, event_handler, full_con... |
def _match_data_sets(x,y):
"""
Makes sure everything is the same shape. "Intelligently".
"""
# Handle the None for x or y
if x is None:
# If x is none, y can be either [1,2] or [[1,2],[1,2]]
if _fun.is_iterable(y[0]):
# make an array of arrays to match
x = []... | def function[_match_data_sets, parameter[x, y]]:
constant[
Makes sure everything is the same shape. "Intelligently".
]
if compare[name[x] is constant[None]] begin[:]
if call[name[_fun].is_iterable, parameter[call[name[y]][constant[0]]]] begin[:]
variable[x... | keyword[def] identifier[_match_data_sets] ( identifier[x] , identifier[y] ):
literal[string]
keyword[if] identifier[x] keyword[is] keyword[None] :
keyword[if] identifier[_fun] . identifier[is_iterable] ( identifier[y] [ literal[int] ]):
identifier[x] =[]
... | def _match_data_sets(x, y):
"""
Makes sure everything is the same shape. "Intelligently".
"""
# Handle the None for x or y
if x is None:
# If x is none, y can be either [1,2] or [[1,2],[1,2]]
if _fun.is_iterable(y[0]):
# make an array of arrays to match
x = []... |
def fromJSON(value):
"""loads the GP object from a JSON string """
j = json.loads(value)
v = GPDate()
if "defaultValue" in j:
v.value = j['defaultValue']
else:
v.value = j['value']
if 'paramName' in j:
v.paramName = j['paramName']
... | def function[fromJSON, parameter[value]]:
constant[loads the GP object from a JSON string ]
variable[j] assign[=] call[name[json].loads, parameter[name[value]]]
variable[v] assign[=] call[name[GPDate], parameter[]]
if compare[constant[defaultValue] in name[j]] begin[:]
na... | keyword[def] identifier[fromJSON] ( identifier[value] ):
literal[string]
identifier[j] = identifier[json] . identifier[loads] ( identifier[value] )
identifier[v] = identifier[GPDate] ()
keyword[if] literal[string] keyword[in] identifier[j] :
identifier[v] . identif... | def fromJSON(value):
"""loads the GP object from a JSON string """
j = json.loads(value)
v = GPDate()
if 'defaultValue' in j:
v.value = j['defaultValue'] # depends on [control=['if'], data=['j']]
else:
v.value = j['value']
if 'paramName' in j:
v.paramName = j['paramName'... |
def plot_file_distances(dist_matrix):
"""
Plots dist_matrix
Parameters
----------
dist_matrix: np.ndarray
"""
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.matshow(dist_matrix, interpolation='nearest',
... | def function[plot_file_distances, parameter[dist_matrix]]:
constant[
Plots dist_matrix
Parameters
----------
dist_matrix: np.ndarray
]
import module[matplotlib.pyplot] as alias[plt]
variable[fig] assign[=] call[name[plt].figure, parameter[]]
variable[... | keyword[def] identifier[plot_file_distances] ( identifier[dist_matrix] ):
literal[string]
keyword[import] identifier[matplotlib] . identifier[pyplot] keyword[as] identifier[plt]
identifier[fig] = identifier[plt] . identifier[figure] ()
identifier[ax] = identifier[fig] . identi... | def plot_file_distances(dist_matrix):
"""
Plots dist_matrix
Parameters
----------
dist_matrix: np.ndarray
"""
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.matshow(dist_matrix, interpolation='nearest', cmap=plt.cm.get_cmap('P... |
def stddev(x, sample_axis=0, keepdims=False, name=None):
"""Estimate standard deviation using samples.
Given `N` samples of scalar valued random variable `X`, standard deviation may
be estimated as
```none
Stddev[X] := Sqrt[Var[X]],
Var[X] := N^{-1} sum_{n=1}^N (X_n - Xbar) Conj{(X_n - Xbar)},
Xbar := N... | def function[stddev, parameter[x, sample_axis, keepdims, name]]:
constant[Estimate standard deviation using samples.
Given `N` samples of scalar valued random variable `X`, standard deviation may
be estimated as
```none
Stddev[X] := Sqrt[Var[X]],
Var[X] := N^{-1} sum_{n=1}^N (X_n - Xbar) Conj{(X_n -... | keyword[def] identifier[stddev] ( identifier[x] , identifier[sample_axis] = literal[int] , identifier[keepdims] = keyword[False] , identifier[name] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . identifier[compat] . identifier[v1] . identifier[name_scope] ( identifier[name] , literal[string... | def stddev(x, sample_axis=0, keepdims=False, name=None):
"""Estimate standard deviation using samples.
Given `N` samples of scalar valued random variable `X`, standard deviation may
be estimated as
```none
Stddev[X] := Sqrt[Var[X]],
Var[X] := N^{-1} sum_{n=1}^N (X_n - Xbar) Conj{(X_n - Xbar)},
Xbar :=... |
def OnClearGlobals(self, event):
"""Clear globals event handler"""
msg = _("Deleting globals and reloading modules cannot be undone."
" Proceed?")
short_msg = _("Really delete globals and modules?")
choice = self.main_window.interfaces.get_warning_choice(msg, short_msg)... | def function[OnClearGlobals, parameter[self, event]]:
constant[Clear globals event handler]
variable[msg] assign[=] call[name[_], parameter[constant[Deleting globals and reloading modules cannot be undone. Proceed?]]]
variable[short_msg] assign[=] call[name[_], parameter[constant[Really delete g... | keyword[def] identifier[OnClearGlobals] ( identifier[self] , identifier[event] ):
literal[string]
identifier[msg] = identifier[_] ( literal[string]
literal[string] )
identifier[short_msg] = identifier[_] ( literal[string] )
identifier[choice] = identifier[self] . ident... | def OnClearGlobals(self, event):
"""Clear globals event handler"""
msg = _('Deleting globals and reloading modules cannot be undone. Proceed?')
short_msg = _('Really delete globals and modules?')
choice = self.main_window.interfaces.get_warning_choice(msg, short_msg)
if choice:
self.main_win... |
def search():
""" Search a movie on TMDB.
"""
redis_key = 's_%s' % request.args['query'].lower()
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached)
else:
try:
found = get_on_tmdb(u'/search/movie', query=request.args['query'])
movies =... | def function[search, parameter[]]:
constant[ Search a movie on TMDB.
]
variable[redis_key] assign[=] binary_operation[constant[s_%s] <ast.Mod object at 0x7da2590d6920> call[call[name[request].args][constant[query]].lower, parameter[]]]
variable[cached] assign[=] call[name[redis_ro_conn].get,... | keyword[def] identifier[search] ():
literal[string]
identifier[redis_key] = literal[string] % identifier[request] . identifier[args] [ literal[string] ]. identifier[lower] ()
identifier[cached] = identifier[redis_ro_conn] . identifier[get] ( identifier[redis_key] )
keyword[if] identifier[cached]... | def search():
""" Search a movie on TMDB.
"""
redis_key = 's_%s' % request.args['query'].lower()
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached) # depends on [control=['if'], data=[]]
else:
try:
found = get_on_tmdb(u'/search/movie', query=req... |
def next(self) -> mx.io.DataBatch:
"""
Returns the next batch from the data iterator.
"""
if not self.iter_next():
raise StopIteration
i, j = self.batch_indices[self.curr_batch_index]
self.curr_batch_index += 1
batch_size = self.bucket_batch_sizes[i]... | def function[next, parameter[self]]:
constant[
Returns the next batch from the data iterator.
]
if <ast.UnaryOp object at 0x7da1b1db3850> begin[:]
<ast.Raise object at 0x7da1b1db38e0>
<ast.Tuple object at 0x7da1b1db3100> assign[=] call[name[self].batch_indices][name[self]... | keyword[def] identifier[next] ( identifier[self] )-> identifier[mx] . identifier[io] . identifier[DataBatch] :
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[iter_next] ():
keyword[raise] identifier[StopIteration]
identifier[i] , identifier[j] = id... | def next(self) -> mx.io.DataBatch:
"""
Returns the next batch from the data iterator.
"""
if not self.iter_next():
raise StopIteration # depends on [control=['if'], data=[]]
(i, j) = self.batch_indices[self.curr_batch_index]
self.curr_batch_index += 1
batch_size = self.bucke... |
def get_password_gui(device, options):
"""Get the password to unlock a device from GUI."""
text = _('Enter password for {0.device_presentation}: ', device)
try:
return password_dialog(device.id_uuid, 'udiskie', text, options)
except RuntimeError:
return None | def function[get_password_gui, parameter[device, options]]:
constant[Get the password to unlock a device from GUI.]
variable[text] assign[=] call[name[_], parameter[constant[Enter password for {0.device_presentation}: ], name[device]]]
<ast.Try object at 0x7da207f02bc0> | keyword[def] identifier[get_password_gui] ( identifier[device] , identifier[options] ):
literal[string]
identifier[text] = identifier[_] ( literal[string] , identifier[device] )
keyword[try] :
keyword[return] identifier[password_dialog] ( identifier[device] . identifier[id_uuid] , literal[st... | def get_password_gui(device, options):
"""Get the password to unlock a device from GUI."""
text = _('Enter password for {0.device_presentation}: ', device)
try:
return password_dialog(device.id_uuid, 'udiskie', text, options) # depends on [control=['try'], data=[]]
except RuntimeError:
... |
def _children(self):
"""Yield all direct children of this object."""
if self.declarations:
yield self.declarations
if isinstance(self.condition, CodeExpression):
yield self.condition
if self.increment:
yield self.increment
for codeobj in self.b... | def function[_children, parameter[self]]:
constant[Yield all direct children of this object.]
if name[self].declarations begin[:]
<ast.Yield object at 0x7da18ede5ab0>
if call[name[isinstance], parameter[name[self].condition, name[CodeExpression]]] begin[:]
<ast.Yi... | keyword[def] identifier[_children] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[declarations] :
keyword[yield] identifier[self] . identifier[declarations]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[condition] , ide... | def _children(self):
"""Yield all direct children of this object."""
if self.declarations:
yield self.declarations # depends on [control=['if'], data=[]]
if isinstance(self.condition, CodeExpression):
yield self.condition # depends on [control=['if'], data=[]]
if self.increment:
... |
def circle(radius=None, center=None, **kwargs):
"""
Create a Path2D containing a single or multiple rectangles
with the specified bounds.
Parameters
--------------
bounds : (2, 2) float, or (m, 2, 2) float
Minimum XY, Maximum XY
Returns
-------------
rect : Path2D
Path ... | def function[circle, parameter[radius, center]]:
constant[
Create a Path2D containing a single or multiple rectangles
with the specified bounds.
Parameters
--------------
bounds : (2, 2) float, or (m, 2, 2) float
Minimum XY, Maximum XY
Returns
-------------
rect : Path2D
... | keyword[def] identifier[circle] ( identifier[radius] = keyword[None] , identifier[center] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[from] . identifier[path] keyword[import] identifier[Path2D]
keyword[if] identifier[center] keyword[is] keyword[None] :
identifier[... | def circle(radius=None, center=None, **kwargs):
"""
Create a Path2D containing a single or multiple rectangles
with the specified bounds.
Parameters
--------------
bounds : (2, 2) float, or (m, 2, 2) float
Minimum XY, Maximum XY
Returns
-------------
rect : Path2D
Path ... |
def add_cell_params(self, params, pos=None):
"""
Add cell of Python parameters
:param params: parameters to add
:return:
"""
self.params = params
cell_str = '# Parameters:\n'
for k, v in params.items():
cell_str += "{} = {}\n".format(k, repr(v... | def function[add_cell_params, parameter[self, params, pos]]:
constant[
Add cell of Python parameters
:param params: parameters to add
:return:
]
name[self].params assign[=] name[params]
variable[cell_str] assign[=] constant[# Parameters:
]
for taget[tuple[... | keyword[def] identifier[add_cell_params] ( identifier[self] , identifier[params] , identifier[pos] = keyword[None] ):
literal[string]
identifier[self] . identifier[params] = identifier[params]
identifier[cell_str] = literal[string]
keyword[for] identifier[k] , identifier[v] k... | def add_cell_params(self, params, pos=None):
"""
Add cell of Python parameters
:param params: parameters to add
:return:
"""
self.params = params
cell_str = '# Parameters:\n'
for (k, v) in params.items():
cell_str += '{} = {}\n'.format(k, repr(v)) # depends on [c... |
def make_key(table_name, objid):
"""Create an object key for storage."""
key = datastore.Key()
path = key.path_element.add()
path.kind = table_name
path.name = str(objid)
return key | def function[make_key, parameter[table_name, objid]]:
constant[Create an object key for storage.]
variable[key] assign[=] call[name[datastore].Key, parameter[]]
variable[path] assign[=] call[name[key].path_element.add, parameter[]]
name[path].kind assign[=] name[table_name]
name[... | keyword[def] identifier[make_key] ( identifier[table_name] , identifier[objid] ):
literal[string]
identifier[key] = identifier[datastore] . identifier[Key] ()
identifier[path] = identifier[key] . identifier[path_element] . identifier[add] ()
identifier[path] . identifier[kind] = identifier[table_... | def make_key(table_name, objid):
"""Create an object key for storage."""
key = datastore.Key()
path = key.path_element.add()
path.kind = table_name
path.name = str(objid)
return key |
def add_auth_attempt(self, auth_type, successful, **kwargs):
"""
:param username:
:param password:
:param auth_type: possible values:
plain: plaintext username/password
:return:
"""
entry = {'timestamp': datetime.utcnow(),
... | def function[add_auth_attempt, parameter[self, auth_type, successful]]:
constant[
:param username:
:param password:
:param auth_type: possible values:
plain: plaintext username/password
:return:
]
variable[entry] assign[=] dictionar... | keyword[def] identifier[add_auth_attempt] ( identifier[self] , identifier[auth_type] , identifier[successful] ,** identifier[kwargs] ):
literal[string]
identifier[entry] ={ literal[string] : identifier[datetime] . identifier[utcnow] (),
literal[string] : identifier[auth_type] ,
l... | def add_auth_attempt(self, auth_type, successful, **kwargs):
"""
:param username:
:param password:
:param auth_type: possible values:
plain: plaintext username/password
:return:
"""
entry = {'timestamp': datetime.utcnow(), 'auth': auth_type... |
def _raw_request(self, method_name, region, url, query_params):
"""
Sends a request through the BaseApi instance provided, injecting the provided endpoint_name
into the method call, so the caller doesn't have to.
:param string method_name: The name of the calling method
:param ... | def function[_raw_request, parameter[self, method_name, region, url, query_params]]:
constant[
Sends a request through the BaseApi instance provided, injecting the provided endpoint_name
into the method call, so the caller doesn't have to.
:param string method_name: The name of the cal... | keyword[def] identifier[_raw_request] ( identifier[self] , identifier[method_name] , identifier[region] , identifier[url] , identifier[query_params] ):
literal[string]
keyword[return] identifier[self] . identifier[_base_api] . identifier[raw_request] (
identifier[self] . identifier[_endpo... | def _raw_request(self, method_name, region, url, query_params):
"""
Sends a request through the BaseApi instance provided, injecting the provided endpoint_name
into the method call, so the caller doesn't have to.
:param string method_name: The name of the calling method
:param stri... |
def pipe_createrss(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that converts a source into an RSS stream. Not loopable.
"""
conf = DotDict(conf)
for item in _INPUT:
item = DotDict(item)
yield {
value: item.get(conf.get(key, **kwargs))
for ke... | def function[pipe_createrss, parameter[context, _INPUT, conf]]:
constant[An operator that converts a source into an RSS stream. Not loopable.
]
variable[conf] assign[=] call[name[DotDict], parameter[name[conf]]]
for taget[name[item]] in starred[name[_INPUT]] begin[:]
variabl... | keyword[def] identifier[pipe_createrss] ( identifier[context] = keyword[None] , identifier[_INPUT] = keyword[None] , identifier[conf] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[conf] = identifier[DotDict] ( identifier[conf] )
keyword[for] identifier[item] keyword[in] iden... | def pipe_createrss(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that converts a source into an RSS stream. Not loopable.
"""
conf = DotDict(conf)
for item in _INPUT:
item = DotDict(item)
yield {value: item.get(conf.get(key, **kwargs)) for (key, value) in RSS_FIELDS.it... |
def send_success_response(self, msgid, methodname):
"""Send a CIM-XML response message back to the WBEM server that
indicates success."""
resp_xml = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEEXPRSP(
cim_xml.EXPMETHODRESPONSE(
... | def function[send_success_response, parameter[self, msgid, methodname]]:
constant[Send a CIM-XML response message back to the WBEM server that
indicates success.]
variable[resp_xml] assign[=] call[name[cim_xml].CIM, parameter[call[name[cim_xml].MESSAGE, parameter[call[name[cim_xml].SIMPLEEXPRSP,... | keyword[def] identifier[send_success_response] ( identifier[self] , identifier[msgid] , identifier[methodname] ):
literal[string]
identifier[resp_xml] = identifier[cim_xml] . identifier[CIM] (
identifier[cim_xml] . identifier[MESSAGE] (
identifier[cim_xml] . identifier[SIMPLEEXPR... | def send_success_response(self, msgid, methodname):
"""Send a CIM-XML response message back to the WBEM server that
indicates success.""" # noqa: E123
resp_xml = cim_xml.CIM(cim_xml.MESSAGE(cim_xml.SIMPLEEXPRSP(cim_xml.EXPMETHODRESPONSE(methodname)), msgid, IMPLEMENTED_PROTOCOL_VERSION), IMPLEMENTED_CI... |
def unsubscribe(self, code_list, subtype_list):
"""
取消订阅
:param code_list: 取消订阅的股票代码列表
:param subtype_list: 取消订阅的类型,参见SubType
:return: (ret, err_message)
ret == RET_OK err_message为None
ret != RET_OK err_message为错误描述字符串
"""
ret, m... | def function[unsubscribe, parameter[self, code_list, subtype_list]]:
constant[
取消订阅
:param code_list: 取消订阅的股票代码列表
:param subtype_list: 取消订阅的类型,参见SubType
:return: (ret, err_message)
ret == RET_OK err_message为None
ret != RET_OK err_message为错误描述字符串
... | keyword[def] identifier[unsubscribe] ( identifier[self] , identifier[code_list] , identifier[subtype_list] ):
literal[string]
identifier[ret] , identifier[msg] , identifier[code_list] , identifier[subtype_list] = identifier[self] . identifier[_check_subscribe_param] ( identifier[code_list] , ident... | def unsubscribe(self, code_list, subtype_list):
"""
取消订阅
:param code_list: 取消订阅的股票代码列表
:param subtype_list: 取消订阅的类型,参见SubType
:return: (ret, err_message)
ret == RET_OK err_message为None
ret != RET_OK err_message为错误描述字符串
"""
(ret, msg, code... |
def _load(self, tree):
""" Run a LOAD statement """
filename = tree.load_file[0]
if filename[0] in ['"', "'"]:
filename = unwrap(filename)
if not os.path.exists(filename):
raise Exception("No such file %r" % filename)
batch = self.connection.batch_write(tr... | def function[_load, parameter[self, tree]]:
constant[ Run a LOAD statement ]
variable[filename] assign[=] call[name[tree].load_file][constant[0]]
if compare[call[name[filename]][constant[0]] in list[[<ast.Constant object at 0x7da2046230a0>, <ast.Constant object at 0x7da204622350>]]] begin[:]
... | keyword[def] identifier[_load] ( identifier[self] , identifier[tree] ):
literal[string]
identifier[filename] = identifier[tree] . identifier[load_file] [ literal[int] ]
keyword[if] identifier[filename] [ literal[int] ] keyword[in] [ literal[string] , literal[string] ]:
identi... | def _load(self, tree):
""" Run a LOAD statement """
filename = tree.load_file[0]
if filename[0] in ['"', "'"]:
filename = unwrap(filename) # depends on [control=['if'], data=[]]
if not os.path.exists(filename):
raise Exception('No such file %r' % filename) # depends on [control=['if'],... |
def close(self):
""" Closes the connection by removing the user from all rooms """
logging.debug('Closing for user {user}'.format(user=self.id.name))
self.id.release_name()
for room in self._rooms.values():
room.disconnect(self) | def function[close, parameter[self]]:
constant[ Closes the connection by removing the user from all rooms ]
call[name[logging].debug, parameter[call[constant[Closing for user {user}].format, parameter[]]]]
call[name[self].id.release_name, parameter[]]
for taget[name[room]] in starred[cal... | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[user] = identifier[self] . identifier[id] . identifier[name] ))
identifier[self] . identifier[id] . identifier[release_name] (... | def close(self):
""" Closes the connection by removing the user from all rooms """
logging.debug('Closing for user {user}'.format(user=self.id.name))
self.id.release_name()
for room in self._rooms.values():
room.disconnect(self) # depends on [control=['for'], data=['room']] |
def fuller(target, MA, MB, vA, vB, temperature='pore.temperature',
pressure='pore.pressure'):
r"""
Uses Fuller model to estimate diffusion coefficient for gases from first
principles at conditions of interest
Parameters
----------
target : OpenPNM Object
The object for which ... | def function[fuller, parameter[target, MA, MB, vA, vB, temperature, pressure]]:
constant[
Uses Fuller model to estimate diffusion coefficient for gases from first
principles at conditions of interest
Parameters
----------
target : OpenPNM Object
The object for which these values are... | keyword[def] identifier[fuller] ( identifier[target] , identifier[MA] , identifier[MB] , identifier[vA] , identifier[vB] , identifier[temperature] = literal[string] ,
identifier[pressure] = literal[string] ):
literal[string]
identifier[T] = identifier[target] [ identifier[temperature] ]
identifier[P... | def fuller(target, MA, MB, vA, vB, temperature='pore.temperature', pressure='pore.pressure'):
"""
Uses Fuller model to estimate diffusion coefficient for gases from first
principles at conditions of interest
Parameters
----------
target : OpenPNM Object
The object for which these values... |
def pop_frame(self):
"""
Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack
"""
self.frames.pop(0)
if len(self.frames) == 0:
raise Exception("stack ... | def function[pop_frame, parameter[self]]:
constant[
Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack
]
call[name[self].frames.pop, parameter[constant[0]]]
if ... | keyword[def] identifier[pop_frame] ( identifier[self] ):
literal[string]
identifier[self] . identifier[frames] . identifier[pop] ( literal[int] )
keyword[if] identifier[len] ( identifier[self] . identifier[frames] )== literal[int] :
keyword[raise] identifier[Exception] ( lit... | def pop_frame(self):
"""
Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack
"""
self.frames.pop(0)
if len(self.frames) == 0:
raise Exception('stack is exhausted') ... |
async def send(self, message: Message) -> None:
"""
Send ASGI websocket messages, ensuring valid state transitions.
"""
if self.application_state == WebSocketState.CONNECTING:
message_type = message["type"]
assert message_type in {"websocket.accept", "websocket.cl... | <ast.AsyncFunctionDef object at 0x7da1b000b8e0> | keyword[async] keyword[def] identifier[send] ( identifier[self] , identifier[message] : identifier[Message] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[application_state] == identifier[WebSocketState] . identifier[CONNECTING] :
identifier[message_typ... | async def send(self, message: Message) -> None:
"""
Send ASGI websocket messages, ensuring valid state transitions.
"""
if self.application_state == WebSocketState.CONNECTING:
message_type = message['type']
assert message_type in {'websocket.accept', 'websocket.close'}
if... |
def matplotlib_to_ginga_cmap(cm, name=None):
"""Convert matplotlib colormap to Ginga's."""
if name is None:
name = cm.name
arr = cm(np.arange(0, min_cmap_len) / np.float(min_cmap_len - 1))
clst = arr[:, 0:3]
return ColorMap(name, clst) | def function[matplotlib_to_ginga_cmap, parameter[cm, name]]:
constant[Convert matplotlib colormap to Ginga's.]
if compare[name[name] is constant[None]] begin[:]
variable[name] assign[=] name[cm].name
variable[arr] assign[=] call[name[cm], parameter[binary_operation[call[name[np].... | keyword[def] identifier[matplotlib_to_ginga_cmap] ( identifier[cm] , identifier[name] = keyword[None] ):
literal[string]
keyword[if] identifier[name] keyword[is] keyword[None] :
identifier[name] = identifier[cm] . identifier[name]
identifier[arr] = identifier[cm] ( identifier[np] . identi... | def matplotlib_to_ginga_cmap(cm, name=None):
"""Convert matplotlib colormap to Ginga's."""
if name is None:
name = cm.name # depends on [control=['if'], data=['name']]
arr = cm(np.arange(0, min_cmap_len) / np.float(min_cmap_len - 1))
clst = arr[:, 0:3]
return ColorMap(name, clst) |
def update_fmt_with_notebook_options(self, metadata):
"""Update format options with the values in the notebook metadata, and record those
options in the notebook metadata"""
# format options in notebook have precedence over that in fmt
for opt in _VALID_FORMAT_OPTIONS:
if opt... | def function[update_fmt_with_notebook_options, parameter[self, metadata]]:
constant[Update format options with the values in the notebook metadata, and record those
options in the notebook metadata]
for taget[name[opt]] in starred[name[_VALID_FORMAT_OPTIONS]] begin[:]
if compare[... | keyword[def] identifier[update_fmt_with_notebook_options] ( identifier[self] , identifier[metadata] ):
literal[string]
keyword[for] identifier[opt] keyword[in] identifier[_VALID_FORMAT_OPTIONS] :
keyword[if] identifier[opt] keyword[in] identifier[metadata] . identifier[g... | def update_fmt_with_notebook_options(self, metadata):
"""Update format options with the values in the notebook metadata, and record those
options in the notebook metadata"""
# format options in notebook have precedence over that in fmt
for opt in _VALID_FORMAT_OPTIONS:
if opt in metadata.get... |
def send_messages(cls, http_request, message_requests):
"""
Deduplicate any outgoing message requests, and send the remainder.
Args:
http_request: The HTTP request in whose response we want to embed the messages
message_requests: A list of undeduplicated messages in the ... | def function[send_messages, parameter[cls, http_request, message_requests]]:
constant[
Deduplicate any outgoing message requests, and send the remainder.
Args:
http_request: The HTTP request in whose response we want to embed the messages
message_requests: A list of unde... | keyword[def] identifier[send_messages] ( identifier[cls] , identifier[http_request] , identifier[message_requests] ):
literal[string]
identifier[deduplicated_messages] = identifier[set] ( identifier[message_requests] )
keyword[for] identifier[msg_type] , identifier[text] keyword[in] ide... | def send_messages(cls, http_request, message_requests):
"""
Deduplicate any outgoing message requests, and send the remainder.
Args:
http_request: The HTTP request in whose response we want to embed the messages
message_requests: A list of undeduplicated messages in the form... |
def produce_fake_hash(x):
"""
Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x.
"""
h = np.random.binomial(1, 0.5, (x.shape[0], 1024))
packed = np.packbits(h, axis=-1).view(np.uint64)
return zounds.ArrayWithUnits(
packed, [x.dimens... | def function[produce_fake_hash, parameter[x]]:
constant[
Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x.
]
variable[h] assign[=] call[name[np].random.binomial, parameter[constant[1], constant[0.5], tuple[[<ast.Subscript object at 0x7da1b... | keyword[def] identifier[produce_fake_hash] ( identifier[x] ):
literal[string]
identifier[h] = identifier[np] . identifier[random] . identifier[binomial] ( literal[int] , literal[int] ,( identifier[x] . identifier[shape] [ literal[int] ], literal[int] ))
identifier[packed] = identifier[np] . identifier... | def produce_fake_hash(x):
"""
Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x.
"""
h = np.random.binomial(1, 0.5, (x.shape[0], 1024))
packed = np.packbits(h, axis=-1).view(np.uint64)
return zounds.ArrayWithUnits(packed, [x.dimensions[0], ... |
def open_with_auth(url, opener=urllib.request.urlopen):
"""Open a urllib2 request, handling HTTP authentication"""
scheme, netloc, path, params, query, frag = urllib.parse.urlparse(url)
# Double scheme does not raise on Mac OS X as revealed by a
# failing test. We would expect "nonnumeric port". Refs ... | def function[open_with_auth, parameter[url, opener]]:
constant[Open a urllib2 request, handling HTTP authentication]
<ast.Tuple object at 0x7da20e9557b0> assign[=] call[name[urllib].parse.urlparse, parameter[name[url]]]
if call[name[netloc].endswith, parameter[constant[:]]] begin[:]
<ast... | keyword[def] identifier[open_with_auth] ( identifier[url] , identifier[opener] = identifier[urllib] . identifier[request] . identifier[urlopen] ):
literal[string]
identifier[scheme] , identifier[netloc] , identifier[path] , identifier[params] , identifier[query] , identifier[frag] = identifier[urllib] . i... | def open_with_auth(url, opener=urllib.request.urlopen):
"""Open a urllib2 request, handling HTTP authentication"""
(scheme, netloc, path, params, query, frag) = urllib.parse.urlparse(url)
# Double scheme does not raise on Mac OS X as revealed by a
# failing test. We would expect "nonnumeric port". Refs ... |
def ner_chunk(args):
"""Chunk named entities."""
chunker = NEChunker(lang=args.lang)
tag(chunker, args) | def function[ner_chunk, parameter[args]]:
constant[Chunk named entities.]
variable[chunker] assign[=] call[name[NEChunker], parameter[]]
call[name[tag], parameter[name[chunker], name[args]]] | keyword[def] identifier[ner_chunk] ( identifier[args] ):
literal[string]
identifier[chunker] = identifier[NEChunker] ( identifier[lang] = identifier[args] . identifier[lang] )
identifier[tag] ( identifier[chunker] , identifier[args] ) | def ner_chunk(args):
"""Chunk named entities."""
chunker = NEChunker(lang=args.lang)
tag(chunker, args) |
def add_profile(self, namespace, key, value, force=False):
""" Add profile information to this node at the DAX level
"""
try:
entry = dax.Profile(namespace, key, value)
self._dax_node.addProfile(entry)
except dax.DuplicateError:
if force:
... | def function[add_profile, parameter[self, namespace, key, value, force]]:
constant[ Add profile information to this node at the DAX level
]
<ast.Try object at 0x7da18f810940> | keyword[def] identifier[add_profile] ( identifier[self] , identifier[namespace] , identifier[key] , identifier[value] , identifier[force] = keyword[False] ):
literal[string]
keyword[try] :
identifier[entry] = identifier[dax] . identifier[Profile] ( identifier[namespace] , identifier[ke... | def add_profile(self, namespace, key, value, force=False):
""" Add profile information to this node at the DAX level
"""
try:
entry = dax.Profile(namespace, key, value)
self._dax_node.addProfile(entry) # depends on [control=['try'], data=[]]
except dax.DuplicateError:
if for... |
def setCurrentRegItem(self, regItem):
""" Sets the current item to the regItem
"""
check_class(regItem, ClassRegItem, allow_none=True)
self.tableView.setCurrentRegItem(regItem) | def function[setCurrentRegItem, parameter[self, regItem]]:
constant[ Sets the current item to the regItem
]
call[name[check_class], parameter[name[regItem], name[ClassRegItem]]]
call[name[self].tableView.setCurrentRegItem, parameter[name[regItem]]] | keyword[def] identifier[setCurrentRegItem] ( identifier[self] , identifier[regItem] ):
literal[string]
identifier[check_class] ( identifier[regItem] , identifier[ClassRegItem] , identifier[allow_none] = keyword[True] )
identifier[self] . identifier[tableView] . identifier[setCurrentRegItem... | def setCurrentRegItem(self, regItem):
""" Sets the current item to the regItem
"""
check_class(regItem, ClassRegItem, allow_none=True)
self.tableView.setCurrentRegItem(regItem) |
def parse_input(self):
'''Parse the listings.
Returns:
iter: A iterable of :class:`.ftp.ls.listing.FileEntry`
'''
if self._text:
lines = iter(self._text.splitlines())
elif self._file:
lines = self._file
else:
lines = ()
... | def function[parse_input, parameter[self]]:
constant[Parse the listings.
Returns:
iter: A iterable of :class:`.ftp.ls.listing.FileEntry`
]
if name[self]._text begin[:]
variable[lines] assign[=] call[name[iter], parameter[call[name[self]._text.splitlines, para... | keyword[def] identifier[parse_input] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_text] :
identifier[lines] = identifier[iter] ( identifier[self] . identifier[_text] . identifier[splitlines] ())
keyword[elif] identifier[self] . identifier... | def parse_input(self):
"""Parse the listings.
Returns:
iter: A iterable of :class:`.ftp.ls.listing.FileEntry`
"""
if self._text:
lines = iter(self._text.splitlines()) # depends on [control=['if'], data=[]]
elif self._file:
lines = self._file # depends on [contr... |
def loads(s, **kwargs):
"""Loads JSON object."""
try:
return _engine[0](s)
except _engine[2]:
# except_clause: 'except' [test ['as' NAME]] # grammar for py3x
# except_clause: 'except' [test [('as' | ',') test]] # grammar for py2x
why = sys.exc_info()[1]
raise JSONE... | def function[loads, parameter[s]]:
constant[Loads JSON object.]
<ast.Try object at 0x7da18f721d80> | keyword[def] identifier[loads] ( identifier[s] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
keyword[return] identifier[_engine] [ literal[int] ]( identifier[s] )
keyword[except] identifier[_engine] [ literal[int] ]:
identifier[why] = identifier[sys] . identi... | def loads(s, **kwargs):
"""Loads JSON object."""
try:
return _engine[0](s) # depends on [control=['try'], data=[]]
except _engine[2]:
# except_clause: 'except' [test ['as' NAME]] # grammar for py3x
# except_clause: 'except' [test [('as' | ',') test]] # grammar for py2x
why ... |
def top_i_answers(self, i):
"""获取排名在前几位的答案.
:param int i: 获取前几个
:return: 答案对象,返回生成器
:rtype: Answer.Iterable
"""
for j, a in enumerate(self.answers):
if j <= i - 1:
yield a
else:
return | def function[top_i_answers, parameter[self, i]]:
constant[获取排名在前几位的答案.
:param int i: 获取前几个
:return: 答案对象,返回生成器
:rtype: Answer.Iterable
]
for taget[tuple[[<ast.Name object at 0x7da20e9b24d0>, <ast.Name object at 0x7da20e9b1c60>]]] in starred[call[name[enumerate], paramete... | keyword[def] identifier[top_i_answers] ( identifier[self] , identifier[i] ):
literal[string]
keyword[for] identifier[j] , identifier[a] keyword[in] identifier[enumerate] ( identifier[self] . identifier[answers] ):
keyword[if] identifier[j] <= identifier[i] - literal[int] :
... | def top_i_answers(self, i):
"""获取排名在前几位的答案.
:param int i: 获取前几个
:return: 答案对象,返回生成器
:rtype: Answer.Iterable
"""
for (j, a) in enumerate(self.answers):
if j <= i - 1:
yield a # depends on [control=['if'], data=[]]
else:
return # depends o... |
def _Close(self):
"""Closes the file-like object."""
self._fsntfs_data_stream = None
self._fsntfs_file_entry = None
self._file_system.Close()
self._file_system = None | def function[_Close, parameter[self]]:
constant[Closes the file-like object.]
name[self]._fsntfs_data_stream assign[=] constant[None]
name[self]._fsntfs_file_entry assign[=] constant[None]
call[name[self]._file_system.Close, parameter[]]
name[self]._file_system assign[=] constant... | keyword[def] identifier[_Close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_fsntfs_data_stream] = keyword[None]
identifier[self] . identifier[_fsntfs_file_entry] = keyword[None]
identifier[self] . identifier[_file_system] . identifier[Close] ()
identifier[self] . ... | def _Close(self):
"""Closes the file-like object."""
self._fsntfs_data_stream = None
self._fsntfs_file_entry = None
self._file_system.Close()
self._file_system = None |
def get_action_list(self, page=1):
""" Получение списка событий
:param page: (опционально) номер страницы, начинается с 1
:param filter: todo
:return:
"""
kw = {}
if page:
kw['inum'] = page
actions, _ = self._call('getactionlist', **kw)
... | def function[get_action_list, parameter[self, page]]:
constant[ Получение списка событий
:param page: (опционально) номер страницы, начинается с 1
:param filter: todo
:return:
]
variable[kw] assign[=] dictionary[[], []]
if name[page] begin[:]
call[... | keyword[def] identifier[get_action_list] ( identifier[self] , identifier[page] = literal[int] ):
literal[string]
identifier[kw] ={}
keyword[if] identifier[page] :
identifier[kw] [ literal[string] ]= identifier[page]
identifier[actions] , identifier[_] = identifier[s... | def get_action_list(self, page=1):
""" Получение списка событий
:param page: (опционально) номер страницы, начинается с 1
:param filter: todo
:return:
"""
kw = {}
if page:
kw['inum'] = page # depends on [control=['if'], data=[]]
(actions, _) = self._call('getacti... |
def fwdl_status_output_fwdl_entries_blade_swbd(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_status
output = ET.SubElement(fwdl_status, "output")
fwdl_entries = ET.SubElement(output,... | def function[fwdl_status_output_fwdl_entries_blade_swbd, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[fwdl_status] assign[=] call[name[ET].Element, parameter[constant[fwdl_status]]]
variab... | keyword[def] identifier[fwdl_status_output_fwdl_entries_blade_swbd] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[fwdl_status] = identifier[ET] . identifier[Element] ( literal[string] )
... | def fwdl_status_output_fwdl_entries_blade_swbd(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
fwdl_status = ET.Element('fwdl_status')
config = fwdl_status
output = ET.SubElement(fwdl_status, 'output')
fwdl_entries = ET.SubElement(output, 'fwdl-entries')
bla... |
def find_block_end(row, line_list, sentinal, direction=1):
"""
Searches up and down until it finds the endpoints of a block Rectify
with find_paragraph_end in pyvim_funcs
"""
import re
row_ = row
line_ = line_list[row_]
flag1 = row_ == 0 or row_ == len(line_list) - 1
flag2 = re.match... | def function[find_block_end, parameter[row, line_list, sentinal, direction]]:
constant[
Searches up and down until it finds the endpoints of a block Rectify
with find_paragraph_end in pyvim_funcs
]
import module[re]
variable[row_] assign[=] name[row]
variable[line_] assign[=] cal... | keyword[def] identifier[find_block_end] ( identifier[row] , identifier[line_list] , identifier[sentinal] , identifier[direction] = literal[int] ):
literal[string]
keyword[import] identifier[re]
identifier[row_] = identifier[row]
identifier[line_] = identifier[line_list] [ identifier[row_] ]
... | def find_block_end(row, line_list, sentinal, direction=1):
"""
Searches up and down until it finds the endpoints of a block Rectify
with find_paragraph_end in pyvim_funcs
"""
import re
row_ = row
line_ = line_list[row_]
flag1 = row_ == 0 or row_ == len(line_list) - 1
flag2 = re.match... |
def generate(model_num):
"""Generates a new model name, given the model number."""
if model_num == 0:
new_name = 'bootstrap'
else:
new_name = random.choice(NAMES)
full_name = "%06d-%s" % (model_num, new_name)
return full_name | def function[generate, parameter[model_num]]:
constant[Generates a new model name, given the model number.]
if compare[name[model_num] equal[==] constant[0]] begin[:]
variable[new_name] assign[=] constant[bootstrap]
variable[full_name] assign[=] binary_operation[constant[%06d-%s]... | keyword[def] identifier[generate] ( identifier[model_num] ):
literal[string]
keyword[if] identifier[model_num] == literal[int] :
identifier[new_name] = literal[string]
keyword[else] :
identifier[new_name] = identifier[random] . identifier[choice] ( identifier[NAMES] )
identifi... | def generate(model_num):
"""Generates a new model name, given the model number."""
if model_num == 0:
new_name = 'bootstrap' # depends on [control=['if'], data=[]]
else:
new_name = random.choice(NAMES)
full_name = '%06d-%s' % (model_num, new_name)
return full_name |
def cancel_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success is
not guaranteed. Clients can use :meth:`get_oper... | def function[cancel_operation, parameter[self, name, retry, timeout]]:
constant[Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success is
not guaranteed. Clients can use :meth:`get_operation` or service-
specific... | keyword[def] identifier[cancel_operation] (
identifier[self] , identifier[name] , identifier[retry] = identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] , identifier[timeout] = identifier[gapic_v1] . identifier[method] . identifier[DEFAULT]
):
literal[string]
identifier[requ... | def cancel_operation(self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT):
"""Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success is
not guaranteed. Clients can use :meth:`get_operation` or service-... |
def getFileNameMime(self, requestedUrl, *args, **kwargs):
'''
Give a requested page (note: the arguments for this call are forwarded to getpage()),
return the content at the target URL, the filename for the target content, and
the mimetype for the content at the target URL, as a 3-tuple (pgctnt, hName, mime).
... | def function[getFileNameMime, parameter[self, requestedUrl]]:
constant[
Give a requested page (note: the arguments for this call are forwarded to getpage()),
return the content at the target URL, the filename for the target content, and
the mimetype for the content at the target URL, as a 3-tuple (pgctnt,... | keyword[def] identifier[getFileNameMime] ( identifier[self] , identifier[requestedUrl] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
keyword[raise] identifier[Exceptions] . identifier[ArgumentError] ( literal[string] , iden... | def getFileNameMime(self, requestedUrl, *args, **kwargs):
"""
Give a requested page (note: the arguments for this call are forwarded to getpage()),
return the content at the target URL, the filename for the target content, and
the mimetype for the content at the target URL, as a 3-tuple (pgctnt, hName, mime).... |
def uddc(udfunc, x, dx):
"""
SPICE private routine intended solely for the support of SPICE
routines. Users should not call this routine directly due to the
volatile nature of this routine.
This routine calculates the derivative of 'udfunc' with respect
to time for 'et', then determines if the ... | def function[uddc, parameter[udfunc, x, dx]]:
constant[
SPICE private routine intended solely for the support of SPICE
routines. Users should not call this routine directly due to the
volatile nature of this routine.
This routine calculates the derivative of 'udfunc' with respect
to time fo... | keyword[def] identifier[uddc] ( identifier[udfunc] , identifier[x] , identifier[dx] ):
literal[string]
identifier[x] = identifier[ctypes] . identifier[c_double] ( identifier[x] )
identifier[dx] = identifier[ctypes] . identifier[c_double] ( identifier[dx] )
identifier[isdescr] = identifier[ctypes]... | def uddc(udfunc, x, dx):
"""
SPICE private routine intended solely for the support of SPICE
routines. Users should not call this routine directly due to the
volatile nature of this routine.
This routine calculates the derivative of 'udfunc' with respect
to time for 'et', then determines if the ... |
def dok15_s(k15):
"""
calculates least-squares matrix for 15 measurements from Jelinek [1976]
"""
#
A, B = design(15) # get design matrix for 15 measurements
sbar = np.dot(B, k15) # get mean s
t = (sbar[0] + sbar[1] + sbar[2]) # trace
bulk = old_div(t, 3.) # bulk susceptibility
Kbar ... | def function[dok15_s, parameter[k15]]:
constant[
calculates least-squares matrix for 15 measurements from Jelinek [1976]
]
<ast.Tuple object at 0x7da204963730> assign[=] call[name[design], parameter[constant[15]]]
variable[sbar] assign[=] call[name[np].dot, parameter[name[B], name[k15]]]... | keyword[def] identifier[dok15_s] ( identifier[k15] ):
literal[string]
identifier[A] , identifier[B] = identifier[design] ( literal[int] )
identifier[sbar] = identifier[np] . identifier[dot] ( identifier[B] , identifier[k15] )
identifier[t] =( identifier[sbar] [ literal[int] ]+ identifier[sba... | def dok15_s(k15):
"""
calculates least-squares matrix for 15 measurements from Jelinek [1976]
"""
#
(A, B) = design(15) # get design matrix for 15 measurements
sbar = np.dot(B, k15) # get mean s
t = sbar[0] + sbar[1] + sbar[2] # trace
bulk = old_div(t, 3.0) # bulk susceptibility
... |
def adduser(username, password=None, shell='/bin/bash',
system_user=False, primary_group=None,
secondary_groups=None, uid=None, home_dir=None):
"""Add a user to the system.
Will log but otherwise succeed if the user already exists.
:param str username: Username to create
:param... | def function[adduser, parameter[username, password, shell, system_user, primary_group, secondary_groups, uid, home_dir]]:
constant[Add a user to the system.
Will log but otherwise succeed if the user already exists.
:param str username: Username to create
:param str password: Password for user; if... | keyword[def] identifier[adduser] ( identifier[username] , identifier[password] = keyword[None] , identifier[shell] = literal[string] ,
identifier[system_user] = keyword[False] , identifier[primary_group] = keyword[None] ,
identifier[secondary_groups] = keyword[None] , identifier[uid] = keyword[None] , identifier[ho... | def adduser(username, password=None, shell='/bin/bash', system_user=False, primary_group=None, secondary_groups=None, uid=None, home_dir=None):
"""Add a user to the system.
Will log but otherwise succeed if the user already exists.
:param str username: Username to create
:param str password: Password ... |
def post_message(session, thread_id, message):
"""
Add a message to a thread
"""
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
message_data = {
'message': message,
}
# POST /api/messages/0.1/threads/{thread_id}/messages/
endpoint = 'threads/{}/mes... | def function[post_message, parameter[session, thread_id, message]]:
constant[
Add a message to a thread
]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da1b0004cd0>], [<ast.Constant object at 0x7da1b0005ba0>]]
variable[message_data] assign[=] dictionary[[<ast.Constan... | keyword[def] identifier[post_message] ( identifier[session] , identifier[thread_id] , identifier[message] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string]
}
identifier[message_data] ={
literal[string] : identifier[message] ,
}
identifier[endpoin... | def post_message(session, thread_id, message):
"""
Add a message to a thread
"""
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
message_data = {'message': message}
# POST /api/messages/0.1/threads/{thread_id}/messages/
endpoint = 'threads/{}/messages'.format(thread_id)
r... |
def getCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
"""Creates a generator to perform one or more SNMP GET queries.
On each iteration, new SNMP GET request is send (:RFC:`1905#section-4.2.1`).
The iterator blocks waiting for response to arrive or error to occur.... | def function[getCmd, parameter[snmpEngine, authData, transportTarget, contextData]]:
constant[Creates a generator to perform one or more SNMP GET queries.
On each iteration, new SNMP GET request is send (:RFC:`1905#section-4.2.1`).
The iterator blocks waiting for response to arrive or error to occur.
... | keyword[def] identifier[getCmd] ( identifier[snmpEngine] , identifier[authData] , identifier[transportTarget] , identifier[contextData] ,
* identifier[varBinds] ,** identifier[options] ):
literal[string]
keyword[def] identifier[cbFun] ( identifier[snmpEngine] , identifier[sendRequestHandle] ,
i... | def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options):
"""Creates a generator to perform one or more SNMP GET queries.
On each iteration, new SNMP GET request is send (:RFC:`1905#section-4.2.1`).
The iterator blocks waiting for response to arrive or error to occur.
Param... |
def getElementConf(self, elementKw, raw=False):
""" return configuration for given element keyword,
e.g. getElementConf('Q01') should return dict: {u'k1': 0.0, u'l': 0.05}
:param elementKw: element keyword
"""
if raw is True:
try:
econf = self.... | def function[getElementConf, parameter[self, elementKw, raw]]:
constant[ return configuration for given element keyword,
e.g. getElementConf('Q01') should return dict: {u'k1': 0.0, u'l': 0.05}
:param elementKw: element keyword
]
if compare[name[raw] is constant[True]] beg... | keyword[def] identifier[getElementConf] ( identifier[self] , identifier[elementKw] , identifier[raw] = keyword[False] ):
literal[string]
keyword[if] identifier[raw] keyword[is] keyword[True] :
keyword[try] :
identifier[econf] = identifier[self] . identifier[all_elem... | def getElementConf(self, elementKw, raw=False):
""" return configuration for given element keyword,
e.g. getElementConf('Q01') should return dict: {u'k1': 0.0, u'l': 0.05}
:param elementKw: element keyword
"""
if raw is True:
try:
econf = self.all_elements.get... |
def _construct_email(self, email, **extra):
"""
Converts incoming data to properly structured dictionary.
"""
if isinstance(email, dict):
email = Email(manager=self._manager, **email)
elif isinstance(email, (MIMEText, MIMEMultipart)):
email = Email.from_mi... | def function[_construct_email, parameter[self, email]]:
constant[
Converts incoming data to properly structured dictionary.
]
if call[name[isinstance], parameter[name[email], name[dict]]] begin[:]
variable[email] assign[=] call[name[Email], parameter[]]
call[name[... | keyword[def] identifier[_construct_email] ( identifier[self] , identifier[email] ,** identifier[extra] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[email] , identifier[dict] ):
identifier[email] = identifier[Email] ( identifier[manager] = identifier[self] . ident... | def _construct_email(self, email, **extra):
"""
Converts incoming data to properly structured dictionary.
"""
if isinstance(email, dict):
email = Email(manager=self._manager, **email) # depends on [control=['if'], data=[]]
elif isinstance(email, (MIMEText, MIMEMultipart)):
e... |
def filter(self, filter_function):
"""Return a new Streamlet containing only the elements that satisfy filter_function
"""
from heronpy.streamlet.impl.filterbolt import FilterStreamlet
filter_streamlet = FilterStreamlet(filter_function, self)
self._add_child(filter_streamlet)
return filter_strea... | def function[filter, parameter[self, filter_function]]:
constant[Return a new Streamlet containing only the elements that satisfy filter_function
]
from relative_module[heronpy.streamlet.impl.filterbolt] import module[FilterStreamlet]
variable[filter_streamlet] assign[=] call[name[FilterStreamle... | keyword[def] identifier[filter] ( identifier[self] , identifier[filter_function] ):
literal[string]
keyword[from] identifier[heronpy] . identifier[streamlet] . identifier[impl] . identifier[filterbolt] keyword[import] identifier[FilterStreamlet]
identifier[filter_streamlet] = identifier[FilterStre... | def filter(self, filter_function):
"""Return a new Streamlet containing only the elements that satisfy filter_function
"""
from heronpy.streamlet.impl.filterbolt import FilterStreamlet
filter_streamlet = FilterStreamlet(filter_function, self)
self._add_child(filter_streamlet)
return filter_strea... |
def do_restart(self, line):
"""
Attempt to restart the bot.
"""
self.bot._frame = 0
self.bot._namespace.clear()
self.bot._namespace.update(self.bot._initial_namespace) | def function[do_restart, parameter[self, line]]:
constant[
Attempt to restart the bot.
]
name[self].bot._frame assign[=] constant[0]
call[name[self].bot._namespace.clear, parameter[]]
call[name[self].bot._namespace.update, parameter[name[self].bot._initial_namespace]] | keyword[def] identifier[do_restart] ( identifier[self] , identifier[line] ):
literal[string]
identifier[self] . identifier[bot] . identifier[_frame] = literal[int]
identifier[self] . identifier[bot] . identifier[_namespace] . identifier[clear] ()
identifier[self] . identifier[bot... | def do_restart(self, line):
"""
Attempt to restart the bot.
"""
self.bot._frame = 0
self.bot._namespace.clear()
self.bot._namespace.update(self.bot._initial_namespace) |
def connection(self):
"""The :class:`pika.BlockingConnection` for the current
thread. This property may change without notice.
"""
connection = getattr(self.state, "connection", None)
if connection is None:
connection = self.state.connection = pika.BlockingConnection... | def function[connection, parameter[self]]:
constant[The :class:`pika.BlockingConnection` for the current
thread. This property may change without notice.
]
variable[connection] assign[=] call[name[getattr], parameter[name[self].state, constant[connection], constant[None]]]
if co... | keyword[def] identifier[connection] ( identifier[self] ):
literal[string]
identifier[connection] = identifier[getattr] ( identifier[self] . identifier[state] , literal[string] , keyword[None] )
keyword[if] identifier[connection] keyword[is] keyword[None] :
identifier[connec... | def connection(self):
"""The :class:`pika.BlockingConnection` for the current
thread. This property may change without notice.
"""
connection = getattr(self.state, 'connection', None)
if connection is None:
connection = self.state.connection = pika.BlockingConnection(parameters=self... |
def GetRootKey(self):
"""Retrieves the root key.
Returns:
WinRegistryKey: Windows Registry root key or None if not available.
"""
regf_key = self._regf_file.get_root_key()
if not regf_key:
return None
return REGFWinRegistryKey(regf_key, key_path=self._key_path_prefix) | def function[GetRootKey, parameter[self]]:
constant[Retrieves the root key.
Returns:
WinRegistryKey: Windows Registry root key or None if not available.
]
variable[regf_key] assign[=] call[name[self]._regf_file.get_root_key, parameter[]]
if <ast.UnaryOp object at 0x7da2044c1ff0> b... | keyword[def] identifier[GetRootKey] ( identifier[self] ):
literal[string]
identifier[regf_key] = identifier[self] . identifier[_regf_file] . identifier[get_root_key] ()
keyword[if] keyword[not] identifier[regf_key] :
keyword[return] keyword[None]
keyword[return] identifier[REGFWinReg... | def GetRootKey(self):
"""Retrieves the root key.
Returns:
WinRegistryKey: Windows Registry root key or None if not available.
"""
regf_key = self._regf_file.get_root_key()
if not regf_key:
return None # depends on [control=['if'], data=[]]
return REGFWinRegistryKey(regf_key, key_... |
def security(self):
"""
Creates a reference to the Security operations for Portal
"""
url = self._url + "/security"
return _Security(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
... | def function[security, parameter[self]]:
constant[
Creates a reference to the Security operations for Portal
]
variable[url] assign[=] binary_operation[name[self]._url + constant[/security]]
return[call[name[_Security], parameter[]]] | keyword[def] identifier[security] ( identifier[self] ):
literal[string]
identifier[url] = identifier[self] . identifier[_url] + literal[string]
keyword[return] identifier[_Security] ( identifier[url] = identifier[url] ,
identifier[securityHandler] = identifier[self] . identifier... | def security(self):
"""
Creates a reference to the Security operations for Portal
"""
url = self._url + '/security'
return _Security(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) |
def of_project(project: 'projects.Project') -> dict:
"""
Returns the file status information for every file within the project
source directory and its shared library folders.
:param project:
The project for which the status information should be generated
:return:
A dictionary cont... | def function[of_project, parameter[project]]:
constant[
Returns the file status information for every file within the project
source directory and its shared library folders.
:param project:
The project for which the status information should be generated
:return:
A dictionary c... | keyword[def] identifier[of_project] ( identifier[project] : literal[string] )-> identifier[dict] :
literal[string]
identifier[source_directory] = identifier[project] . identifier[source_directory]
identifier[libraries_status] =[
{} keyword[if] identifier[d] . identifier[startswith] ( identifier... | def of_project(project: 'projects.Project') -> dict:
"""
Returns the file status information for every file within the project
source directory and its shared library folders.
:param project:
The project for which the status information should be generated
:return:
A dictionary cont... |
def alias_feed(name, alias):
"""write aliases to db"""
with Database("aliases") as db:
if alias in db:
print("Something has gone horribly wrong with your aliases! Try deleting the %s entry." % name)
return
else:
db[alias] = name | def function[alias_feed, parameter[name, alias]]:
constant[write aliases to db]
with call[name[Database], parameter[constant[aliases]]] begin[:]
if compare[name[alias] in name[db]] begin[:]
call[name[print], parameter[binary_operation[constant[Something has gone h... | keyword[def] identifier[alias_feed] ( identifier[name] , identifier[alias] ):
literal[string]
keyword[with] identifier[Database] ( literal[string] ) keyword[as] identifier[db] :
keyword[if] identifier[alias] keyword[in] identifier[db] :
identifier[print] ( literal[string] % ident... | def alias_feed(name, alias):
"""write aliases to db"""
with Database('aliases') as db:
if alias in db:
print('Something has gone horribly wrong with your aliases! Try deleting the %s entry.' % name)
return # depends on [control=['if'], data=[]]
else:
db[alias... |
def get_os_dist_info():
"""
Returns the distribution info
"""
distribution = platform.dist()
dist_name = distribution[0].lower()
dist_version_str = distribution[1]
if dist_name and dist_version_str:
return dist_name, dist_version_str
else:
return None, None | def function[get_os_dist_info, parameter[]]:
constant[
Returns the distribution info
]
variable[distribution] assign[=] call[name[platform].dist, parameter[]]
variable[dist_name] assign[=] call[call[name[distribution]][constant[0]].lower, parameter[]]
variable[dist_version_st... | keyword[def] identifier[get_os_dist_info] ():
literal[string]
identifier[distribution] = identifier[platform] . identifier[dist] ()
identifier[dist_name] = identifier[distribution] [ literal[int] ]. identifier[lower] ()
identifier[dist_version_str] = identifier[distribution] [ literal[int] ]
... | def get_os_dist_info():
"""
Returns the distribution info
"""
distribution = platform.dist()
dist_name = distribution[0].lower()
dist_version_str = distribution[1]
if dist_name and dist_version_str:
return (dist_name, dist_version_str) # depends on [control=['if'], data=[]]
... |
def partition_agent(host):
""" Partition a node from all network traffic except for SSH and loopback
:param hostname: host or IP of the machine to partition from the cluster
"""
network.save_iptables(host)
network.flush_all_rules(host)
network.allow_all_traffic(host)
network.run_iptabl... | def function[partition_agent, parameter[host]]:
constant[ Partition a node from all network traffic except for SSH and loopback
:param hostname: host or IP of the machine to partition from the cluster
]
call[name[network].save_iptables, parameter[name[host]]]
call[name[network].flus... | keyword[def] identifier[partition_agent] ( identifier[host] ):
literal[string]
identifier[network] . identifier[save_iptables] ( identifier[host] )
identifier[network] . identifier[flush_all_rules] ( identifier[host] )
identifier[network] . identifier[allow_all_traffic] ( identifier[host] )
... | def partition_agent(host):
""" Partition a node from all network traffic except for SSH and loopback
:param hostname: host or IP of the machine to partition from the cluster
"""
network.save_iptables(host)
network.flush_all_rules(host)
network.allow_all_traffic(host)
network.run_iptable... |
def _already_in_album(self,fullfile,pid,album_id):
"""Check to see if photo with given pid is already
in the album_id, returns true if this is the case
"""
logger.debug("fb: Checking if pid %s in album %s",pid,album_id)
pid_in_album=[]
# Get all photos in album
p... | def function[_already_in_album, parameter[self, fullfile, pid, album_id]]:
constant[Check to see if photo with given pid is already
in the album_id, returns true if this is the case
]
call[name[logger].debug, parameter[constant[fb: Checking if pid %s in album %s], name[pid], name[album_i... | keyword[def] identifier[_already_in_album] ( identifier[self] , identifier[fullfile] , identifier[pid] , identifier[album_id] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[pid] , identifier[album_id] )
identifier[pid_in_album] =[]
... | def _already_in_album(self, fullfile, pid, album_id):
"""Check to see if photo with given pid is already
in the album_id, returns true if this is the case
"""
logger.debug('fb: Checking if pid %s in album %s', pid, album_id)
pid_in_album = []
# Get all photos in album
photos = self.f... |
def _body_builder(self, kwargs):
"""
Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service.
"""
p = {
'action_name': self.name,
'service_type': self.service_type,
'arguments': '',
}
if kwargs:
... | def function[_body_builder, parameter[self, kwargs]]:
constant[
Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service.
]
variable[p] assign[=] dictionary[[<ast.Constant object at 0x7da1b1040d90>, <ast.Constant object at 0x7da1b10402b0>, <ast.Constant obj... | keyword[def] identifier[_body_builder] ( identifier[self] , identifier[kwargs] ):
literal[string]
identifier[p] ={
literal[string] : identifier[self] . identifier[name] ,
literal[string] : identifier[self] . identifier[service_type] ,
literal[string] : literal[string] ,
... | def _body_builder(self, kwargs):
"""
Helper method to construct the appropriate SOAP-body to call a
FritzBox-Service.
"""
p = {'action_name': self.name, 'service_type': self.service_type, 'arguments': ''}
if kwargs:
arguments = [self.argument_template % {'name': k, 'value': v... |
def update(self, title, key):
"""Update this key.
:param str title: (required), title of the key
:param str key: (required), text of the key file
:returns: bool
"""
json = None
if title and key:
data = {'title': title, 'key': key}
json = s... | def function[update, parameter[self, title, key]]:
constant[Update this key.
:param str title: (required), title of the key
:param str key: (required), text of the key file
:returns: bool
]
variable[json] assign[=] constant[None]
if <ast.BoolOp object at 0x7da1b0... | keyword[def] identifier[update] ( identifier[self] , identifier[title] , identifier[key] ):
literal[string]
identifier[json] = keyword[None]
keyword[if] identifier[title] keyword[and] identifier[key] :
identifier[data] ={ literal[string] : identifier[title] , literal[strin... | def update(self, title, key):
"""Update this key.
:param str title: (required), title of the key
:param str key: (required), text of the key file
:returns: bool
"""
json = None
if title and key:
data = {'title': title, 'key': key}
json = self._json(self._patc... |
def envelope(component, **kwargs):
"""
Create parameters for an envelope (usually will be attached to two stars solRad
that they can share a common-envelope)
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_component`
:parameter **kw... | def function[envelope, parameter[component]]:
constant[
Create parameters for an envelope (usually will be attached to two stars solRad
that they can share a common-envelope)
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_component`... | keyword[def] identifier[envelope] ( identifier[component] ,** identifier[kwargs] ):
literal[string]
identifier[params] =[]
identifier[params] +=[ identifier[FloatParameter] ( identifier[qualifier] = literal[string] , identifier[value] = identifier[kwargs] . identifier[get] ( literal[string] , literal... | def envelope(component, **kwargs):
"""
Create parameters for an envelope (usually will be attached to two stars solRad
that they can share a common-envelope)
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_component`
:parameter **kw... |
def unescape_LDAP(ldap_string):
# type: (str) -> str
# pylint: disable=C0103
"""
Unespaces an LDAP string
:param ldap_string: The string to unescape
:return: The unprotected string
"""
if ldap_string is None:
return None
if ESCAPE_CHARACTER not in ldap_string:
# No ... | def function[unescape_LDAP, parameter[ldap_string]]:
constant[
Unespaces an LDAP string
:param ldap_string: The string to unescape
:return: The unprotected string
]
if compare[name[ldap_string] is constant[None]] begin[:]
return[constant[None]]
if compare[name[ESCAPE_CHA... | keyword[def] identifier[unescape_LDAP] ( identifier[ldap_string] ):
literal[string]
keyword[if] identifier[ldap_string] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[if] identifier[ESCAPE_CHARACTER] keyword[not] keyword[in] identifier[ldap_string] :
... | def unescape_LDAP(ldap_string):
# type: (str) -> str
# pylint: disable=C0103
'\n Unespaces an LDAP string\n\n :param ldap_string: The string to unescape\n :return: The unprotected string\n '
if ldap_string is None:
return None # depends on [control=['if'], data=[]]
if ESCAPE_CHA... |
def get_manual(self, start, end):
"""Get forecasts for a manually selected time period."""
url = build_url(self.api_key, self.spot_id, self.fields,
self.unit, start, end)
return get_msw(url) | def function[get_manual, parameter[self, start, end]]:
constant[Get forecasts for a manually selected time period.]
variable[url] assign[=] call[name[build_url], parameter[name[self].api_key, name[self].spot_id, name[self].fields, name[self].unit, name[start], name[end]]]
return[call[name[get_msw], ... | keyword[def] identifier[get_manual] ( identifier[self] , identifier[start] , identifier[end] ):
literal[string]
identifier[url] = identifier[build_url] ( identifier[self] . identifier[api_key] , identifier[self] . identifier[spot_id] , identifier[self] . identifier[fields] ,
identifier[sel... | def get_manual(self, start, end):
"""Get forecasts for a manually selected time period."""
url = build_url(self.api_key, self.spot_id, self.fields, self.unit, start, end)
return get_msw(url) |
def intersect(self, *sets):
"""
Add a list of sets to the existing list of sets to check. Returns self
for chaining.
Each "set" represent a list of pk, the final goal is to return only pks
matching the intersection of all sets.
A "set" can be:
- a string: consider... | def function[intersect, parameter[self]]:
constant[
Add a list of sets to the existing list of sets to check. Returns self
for chaining.
Each "set" represent a list of pk, the final goal is to return only pks
matching the intersection of all sets.
A "set" can be:
... | keyword[def] identifier[intersect] ( identifier[self] ,* identifier[sets] ):
literal[string]
identifier[sets_] = identifier[set] ()
keyword[for] identifier[set_] keyword[in] identifier[sets] :
keyword[if] identifier[isinstance] ( identifier[set_] ,( identifier[list] , iden... | def intersect(self, *sets):
"""
Add a list of sets to the existing list of sets to check. Returns self
for chaining.
Each "set" represent a list of pk, the final goal is to return only pks
matching the intersection of all sets.
A "set" can be:
- a string: considered a... |
def execute(self, context):
"""Execute the python dataflow job."""
bucket_helper = GoogleCloudBucketHelper(
self.gcp_conn_id, self.delegate_to)
self.py_file = bucket_helper.google_cloud_to_local(self.py_file)
hook = DataFlowHook(gcp_conn_id=self.gcp_conn_id,
... | def function[execute, parameter[self, context]]:
constant[Execute the python dataflow job.]
variable[bucket_helper] assign[=] call[name[GoogleCloudBucketHelper], parameter[name[self].gcp_conn_id, name[self].delegate_to]]
name[self].py_file assign[=] call[name[bucket_helper].google_cloud_to_local... | keyword[def] identifier[execute] ( identifier[self] , identifier[context] ):
literal[string]
identifier[bucket_helper] = identifier[GoogleCloudBucketHelper] (
identifier[self] . identifier[gcp_conn_id] , identifier[self] . identifier[delegate_to] )
identifier[self] . identifier[py... | def execute(self, context):
"""Execute the python dataflow job."""
bucket_helper = GoogleCloudBucketHelper(self.gcp_conn_id, self.delegate_to)
self.py_file = bucket_helper.google_cloud_to_local(self.py_file)
hook = DataFlowHook(gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.... |
def get_manifest(self, asset_xml):
"""
Construct and return the xml manifest to deliver along with video file.
"""
# pylint: disable=E1101
manifest = '<?xml version="1.0" encoding="utf-8"?>'
manifest += '<publisher-upload-manifest publisher-id="%s" ' % \
self.... | def function[get_manifest, parameter[self, asset_xml]]:
constant[
Construct and return the xml manifest to deliver along with video file.
]
variable[manifest] assign[=] constant[<?xml version="1.0" encoding="utf-8"?>]
<ast.AugAssign object at 0x7da18ede4e50>
<ast.AugAssign object... | keyword[def] identifier[get_manifest] ( identifier[self] , identifier[asset_xml] ):
literal[string]
identifier[manifest] = literal[string]
identifier[manifest] += literal[string] % identifier[self] . identifier[publisher_id]
identifier[manifest] += literal[string] % ide... | def get_manifest(self, asset_xml):
"""
Construct and return the xml manifest to deliver along with video file.
"""
# pylint: disable=E1101
manifest = '<?xml version="1.0" encoding="utf-8"?>'
manifest += '<publisher-upload-manifest publisher-id="%s" ' % self.publisher_id
manifest += '... |
def get_console_info(kernel32, handle):
"""Get information about this current console window.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231
https://code.google.com/p/colorama/issues/detail?id=47
https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py
Windows 10... | def function[get_console_info, parameter[kernel32, handle]]:
constant[Get information about this current console window.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231
https://code.google.com/p/colorama/issues/detail?id=47
https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/te... | keyword[def] identifier[get_console_info] ( identifier[kernel32] , identifier[handle] ):
literal[string]
identifier[csbi] = identifier[ConsoleScreenBufferInfo] ()
identifier[lpcsbi] = identifier[ctypes] . identifier[byref] ( identifier[csbi] )
identifier[dword] = identifier[ctypes] . identif... | def get_console_info(kernel32, handle):
"""Get information about this current console window.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683231
https://code.google.com/p/colorama/issues/detail?id=47
https://bitbucket.org/pytest-dev/py/src/4617fe46/py/_io/terminalwriter.py
Windows 10... |
def GetEstimatedYear(self):
"""Retrieves an estimate of the year.
This function determines the year in the following manner:
* see if the user provided a preferred year;
* see if knowledge base defines a year e.g. derived from preprocessing;
* determine the year based on the file entry metadata;
... | def function[GetEstimatedYear, parameter[self]]:
constant[Retrieves an estimate of the year.
This function determines the year in the following manner:
* see if the user provided a preferred year;
* see if knowledge base defines a year e.g. derived from preprocessing;
* determine the year based... | keyword[def] identifier[GetEstimatedYear] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_preferred_year] :
keyword[return] identifier[self] . identifier[_preferred_year]
keyword[if] identifier[self] . identifier[_knowledge_base] . identifier[year... | def GetEstimatedYear(self):
"""Retrieves an estimate of the year.
This function determines the year in the following manner:
* see if the user provided a preferred year;
* see if knowledge base defines a year e.g. derived from preprocessing;
* determine the year based on the file entry metadata;
... |
def inst_repr(instance, fmt='str', public_only=True):
"""
Generate class instance signature from its __dict__
From python 3.6 dict is ordered and order of attributes will be preserved automatically
Args:
instance: class instance
fmt: ['json', 'str']
public_only: if display publi... | def function[inst_repr, parameter[instance, fmt, public_only]]:
constant[
Generate class instance signature from its __dict__
From python 3.6 dict is ordered and order of attributes will be preserved automatically
Args:
instance: class instance
fmt: ['json', 'str']
public_on... | keyword[def] identifier[inst_repr] ( identifier[instance] , identifier[fmt] = literal[string] , identifier[public_only] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[instance] , literal[string] ): keyword[return] literal[string]
keyword[if] identifi... | def inst_repr(instance, fmt='str', public_only=True):
"""
Generate class instance signature from its __dict__
From python 3.6 dict is ordered and order of attributes will be preserved automatically
Args:
instance: class instance
fmt: ['json', 'str']
public_only: if display publi... |
def _parse_custom_mpi_options(custom_mpi_options):
# type: (str) -> Tuple[argparse.Namespace, List[str]]
"""Parse custom MPI options provided by user. Known options default value will be overridden
and unknown options would be identified separately."""
parser = argparse.ArgumentParser()
parser.add_... | def function[_parse_custom_mpi_options, parameter[custom_mpi_options]]:
constant[Parse custom MPI options provided by user. Known options default value will be overridden
and unknown options would be identified separately.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
... | keyword[def] identifier[_parse_custom_mpi_options] ( identifier[custom_mpi_options] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ()
identifier[parser] . identifier[add_argument] ( literal[string] , identifier[default] = literal[string] , identifier[type] ... | def _parse_custom_mpi_options(custom_mpi_options):
# type: (str) -> Tuple[argparse.Namespace, List[str]]
'Parse custom MPI options provided by user. Known options default value will be overridden\n and unknown options would be identified separately.'
parser = argparse.ArgumentParser()
parser.add_argu... |
def add_actions(target, actions, insert_before=None):
"""Add actions to a QMenu or a QToolBar."""
previous_action = None
target_actions = list(target.actions())
if target_actions:
previous_action = target_actions[-1]
if previous_action.isSeparator():
previous_action = ... | def function[add_actions, parameter[target, actions, insert_before]]:
constant[Add actions to a QMenu or a QToolBar.]
variable[previous_action] assign[=] constant[None]
variable[target_actions] assign[=] call[name[list], parameter[call[name[target].actions, parameter[]]]]
if name[target_... | keyword[def] identifier[add_actions] ( identifier[target] , identifier[actions] , identifier[insert_before] = keyword[None] ):
literal[string]
identifier[previous_action] = keyword[None]
identifier[target_actions] = identifier[list] ( identifier[target] . identifier[actions] ())
keyword[if] ... | def add_actions(target, actions, insert_before=None):
"""Add actions to a QMenu or a QToolBar."""
previous_action = None
target_actions = list(target.actions())
if target_actions:
previous_action = target_actions[-1]
if previous_action.isSeparator():
previous_action = None #... |
def _back_compatible_gemini(conf_files, data):
"""Provide old install directory for configuration with GEMINI supplied tidy VCFs.
Handles new style (bcbio installed) and old style (GEMINI installed)
configuration and data locations.
"""
if vcfanno.is_human(data, builds=["37"]):
for f in con... | def function[_back_compatible_gemini, parameter[conf_files, data]]:
constant[Provide old install directory for configuration with GEMINI supplied tidy VCFs.
Handles new style (bcbio installed) and old style (GEMINI installed)
configuration and data locations.
]
if call[name[vcfanno].is_huma... | keyword[def] identifier[_back_compatible_gemini] ( identifier[conf_files] , identifier[data] ):
literal[string]
keyword[if] identifier[vcfanno] . identifier[is_human] ( identifier[data] , identifier[builds] =[ literal[string] ]):
keyword[for] identifier[f] keyword[in] identifier[conf_files] :
... | def _back_compatible_gemini(conf_files, data):
"""Provide old install directory for configuration with GEMINI supplied tidy VCFs.
Handles new style (bcbio installed) and old style (GEMINI installed)
configuration and data locations.
"""
if vcfanno.is_human(data, builds=['37']):
for f in con... |
def number(self):
# type: () -> int
""" Return this commits number.
This is the same as the total number of commits in history up until
this commit.
This value can be useful in some CI scenarios as it allows to track
progress on any given branch (although there can be t... | def function[number, parameter[self]]:
constant[ Return this commits number.
This is the same as the total number of commits in history up until
this commit.
This value can be useful in some CI scenarios as it allows to track
progress on any given branch (although there can be ... | keyword[def] identifier[number] ( identifier[self] ):
literal[string]
identifier[cmd] = literal[string] . identifier[format] ( identifier[self] . identifier[sha1] )
identifier[out] = identifier[shell] . identifier[run] ( identifier[cmd] , identifier[capture] = keyword[True] , identifier[n... | def number(self):
# type: () -> int
' Return this commits number.\n\n This is the same as the total number of commits in history up until\n this commit.\n\n This value can be useful in some CI scenarios as it allows to track\n progress on any given branch (although there can be two c... |
def kick(self, group_name, user):
""" https://api.slack.com/methods/groups.kick
"""
group_id = self.get_group_id(group_name)
self.params.update({
'channel': group_id,
'user': user,
})
return FromUrl('https://slack.com/api/groups.kick', self.... | def function[kick, parameter[self, group_name, user]]:
constant[ https://api.slack.com/methods/groups.kick
]
variable[group_id] assign[=] call[name[self].get_group_id, parameter[name[group_name]]]
call[name[self].params.update, parameter[dictionary[[<ast.Constant object at 0x7da1b1604be0... | keyword[def] identifier[kick] ( identifier[self] , identifier[group_name] , identifier[user] ):
literal[string]
identifier[group_id] = identifier[self] . identifier[get_group_id] ( identifier[group_name] )
identifier[self] . identifier[params] . identifier[update] ({
literal[strin... | def kick(self, group_name, user):
""" https://api.slack.com/methods/groups.kick
"""
group_id = self.get_group_id(group_name)
self.params.update({'channel': group_id, 'user': user})
return FromUrl('https://slack.com/api/groups.kick', self._requests)(data=self.params).post() |
def match_entry_line(str_to_match, regex_obj=MAIN_REGEX_OBJ):
"""Does a regex match of the mount entry string"""
match_obj = regex_obj.match(str_to_match)
if not match_obj:
error_message = ('Line "%s" is unrecognized by overlay4u. '
'This is only meant for use with Ubuntu Linux.')
... | def function[match_entry_line, parameter[str_to_match, regex_obj]]:
constant[Does a regex match of the mount entry string]
variable[match_obj] assign[=] call[name[regex_obj].match, parameter[name[str_to_match]]]
if <ast.UnaryOp object at 0x7da20e955b40> begin[:]
variable[error_me... | keyword[def] identifier[match_entry_line] ( identifier[str_to_match] , identifier[regex_obj] = identifier[MAIN_REGEX_OBJ] ):
literal[string]
identifier[match_obj] = identifier[regex_obj] . identifier[match] ( identifier[str_to_match] )
keyword[if] keyword[not] identifier[match_obj] :
identi... | def match_entry_line(str_to_match, regex_obj=MAIN_REGEX_OBJ):
"""Does a regex match of the mount entry string"""
match_obj = regex_obj.match(str_to_match)
if not match_obj:
error_message = 'Line "%s" is unrecognized by overlay4u. This is only meant for use with Ubuntu Linux.'
raise Unrecogni... |
def find_executable(executable, path=None):
"""Tries to find 'executable' in the directories listed in 'path'.
A string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']. Returns the complete filename or None if not found.
"""
if path is None:
path = os.environ['PATH']
path... | def function[find_executable, parameter[executable, path]]:
constant[Tries to find 'executable' in the directories listed in 'path'.
A string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']. Returns the complete filename or None if not found.
]
if compare[name[path]... | keyword[def] identifier[find_executable] ( identifier[executable] , identifier[path] = keyword[None] ):
literal[string]
keyword[if] identifier[path] keyword[is] keyword[None] :
identifier[path] = identifier[os] . identifier[environ] [ literal[string] ]
identifier[paths] = identifier[path] . identifi... | def find_executable(executable, path=None):
"""Tries to find 'executable' in the directories listed in 'path'.
A string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']. Returns the complete filename or None if not found.
"""
if path is None:
path = os.environ['PATH'... |
def remove_exclude_regions(orig_bed, base_file, items, remove_entire_feature=False):
"""Remove centromere and short end regions from an existing BED file of regions to target.
"""
from bcbio.structural import shared as sshared
out_bed = os.path.join("%s-noexclude.bed" % (utils.splitext_plus(base_file)[0... | def function[remove_exclude_regions, parameter[orig_bed, base_file, items, remove_entire_feature]]:
constant[Remove centromere and short end regions from an existing BED file of regions to target.
]
from relative_module[bcbio.structural] import module[shared]
variable[out_bed] assign[=] call[nam... | keyword[def] identifier[remove_exclude_regions] ( identifier[orig_bed] , identifier[base_file] , identifier[items] , identifier[remove_entire_feature] = keyword[False] ):
literal[string]
keyword[from] identifier[bcbio] . identifier[structural] keyword[import] identifier[shared] keyword[as] identifier[... | def remove_exclude_regions(orig_bed, base_file, items, remove_entire_feature=False):
"""Remove centromere and short end regions from an existing BED file of regions to target.
"""
from bcbio.structural import shared as sshared
out_bed = os.path.join('%s-noexclude.bed' % utils.splitext_plus(base_file)[0]... |
def main(args=None):
"""
Entry point for the tag CLI.
Isolated as a method so that the CLI can be called by other Python code
(e.g. for testing), in which case the arguments are passed to the function.
If no arguments are passed to the function, parse them from the command
line.
"""
if ... | def function[main, parameter[args]]:
constant[
Entry point for the tag CLI.
Isolated as a method so that the CLI can be called by other Python code
(e.g. for testing), in which case the arguments are passed to the function.
If no arguments are passed to the function, parse them from the command... | keyword[def] identifier[main] ( identifier[args] = keyword[None] ):
literal[string]
keyword[if] identifier[args] keyword[is] keyword[None] :
identifier[args] = identifier[tag] . identifier[cli] . identifier[parser] (). identifier[parse_args] ()
keyword[assert] identifier[args] . identifi... | def main(args=None):
"""
Entry point for the tag CLI.
Isolated as a method so that the CLI can be called by other Python code
(e.g. for testing), in which case the arguments are passed to the function.
If no arguments are passed to the function, parse them from the command
line.
"""
if ... |
def Copy(self, name=None):
"""Returns a copy of this Cdf.
Args:
name: string name for the new Cdf
"""
if name is None:
name = self.name
return Cdf(list(self.xs), list(self.ps), name) | def function[Copy, parameter[self, name]]:
constant[Returns a copy of this Cdf.
Args:
name: string name for the new Cdf
]
if compare[name[name] is constant[None]] begin[:]
variable[name] assign[=] name[self].name
return[call[name[Cdf], parameter[call[name... | keyword[def] identifier[Copy] ( identifier[self] , identifier[name] = keyword[None] ):
literal[string]
keyword[if] identifier[name] keyword[is] keyword[None] :
identifier[name] = identifier[self] . identifier[name]
keyword[return] identifier[Cdf] ( identifier[list] ( iden... | def Copy(self, name=None):
"""Returns a copy of this Cdf.
Args:
name: string name for the new Cdf
"""
if name is None:
name = self.name # depends on [control=['if'], data=['name']]
return Cdf(list(self.xs), list(self.ps), name) |
def File(self, path):
"""Returns a reference to a file with a given path on client's VFS."""
return vfs.FileRef(
client_id=self.client_id, path=path, context=self._context) | def function[File, parameter[self, path]]:
constant[Returns a reference to a file with a given path on client's VFS.]
return[call[name[vfs].FileRef, parameter[]]] | keyword[def] identifier[File] ( identifier[self] , identifier[path] ):
literal[string]
keyword[return] identifier[vfs] . identifier[FileRef] (
identifier[client_id] = identifier[self] . identifier[client_id] , identifier[path] = identifier[path] , identifier[context] = identifier[self] . identifier[... | def File(self, path):
"""Returns a reference to a file with a given path on client's VFS."""
return vfs.FileRef(client_id=self.client_id, path=path, context=self._context) |
def _handle_output(results_queue):
"""Scan output for exceptions
If there is an output from an add task collection call add it to the results.
:param results_queue: Queue containing results of attempted add_collection's
:type results_queue: collections.deque
:return: list of TaskAddResults
:rt... | def function[_handle_output, parameter[results_queue]]:
constant[Scan output for exceptions
If there is an output from an add task collection call add it to the results.
:param results_queue: Queue containing results of attempted add_collection's
:type results_queue: collections.deque
:return:... | keyword[def] identifier[_handle_output] ( identifier[results_queue] ):
literal[string]
identifier[results] =[]
keyword[while] identifier[results_queue] :
identifier[queue_item] = identifier[results_queue] . identifier[pop] ()
identifier[results] . identifier[append] ( identifier[que... | def _handle_output(results_queue):
"""Scan output for exceptions
If there is an output from an add task collection call add it to the results.
:param results_queue: Queue containing results of attempted add_collection's
:type results_queue: collections.deque
:return: list of TaskAddResults
:rt... |
def read(datapath, qt_app=None, dataplus_format=True, gui=False, start=0, stop=None, step=1, convert_to_gray=True,
series_number=None, dicom_expected=None, **kwargs):
"""Simple read function. Internally calls DataReader.Get3DData()"""
dr = DataReader()
return dr.Get3DData(datapath=datapath, qt_app=... | def function[read, parameter[datapath, qt_app, dataplus_format, gui, start, stop, step, convert_to_gray, series_number, dicom_expected]]:
constant[Simple read function. Internally calls DataReader.Get3DData()]
variable[dr] assign[=] call[name[DataReader], parameter[]]
return[call[name[dr].Get3DData,... | keyword[def] identifier[read] ( identifier[datapath] , identifier[qt_app] = keyword[None] , identifier[dataplus_format] = keyword[True] , identifier[gui] = keyword[False] , identifier[start] = literal[int] , identifier[stop] = keyword[None] , identifier[step] = literal[int] , identifier[convert_to_gray] = keyword[Tru... | def read(datapath, qt_app=None, dataplus_format=True, gui=False, start=0, stop=None, step=1, convert_to_gray=True, series_number=None, dicom_expected=None, **kwargs):
"""Simple read function. Internally calls DataReader.Get3DData()"""
dr = DataReader()
return dr.Get3DData(datapath=datapath, qt_app=qt_app, d... |
def run(self, row, **kwargs):
"""Methods takes a row and depending if a dict or list,
runs RML rules.
Args:
-----
row(Dict, List): Row from CSV Reader
"""
self.source = row
kwargs['output'] = self.__graph__()
super(CSVRowProcessor, self).run(*... | def function[run, parameter[self, row]]:
constant[Methods takes a row and depending if a dict or list,
runs RML rules.
Args:
-----
row(Dict, List): Row from CSV Reader
]
name[self].source assign[=] name[row]
call[name[kwargs]][constant[output]] assign... | keyword[def] identifier[run] ( identifier[self] , identifier[row] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[source] = identifier[row]
identifier[kwargs] [ literal[string] ]= identifier[self] . identifier[__graph__] ()
identifier[super] ( identifier[C... | def run(self, row, **kwargs):
"""Methods takes a row and depending if a dict or list,
runs RML rules.
Args:
-----
row(Dict, List): Row from CSV Reader
"""
self.source = row
kwargs['output'] = self.__graph__()
super(CSVRowProcessor, self).run(**kwargs)
ret... |
def min_pos(self):
'''Returns minimal positive value or None.'''
if self.__len__() == 0:
return ArgumentError('empty set has no minimum positive value.')
if self.contains(0):
return None
positive = [interval for interval in self.intervals
if in... | def function[min_pos, parameter[self]]:
constant[Returns minimal positive value or None.]
if compare[call[name[self].__len__, parameter[]] equal[==] constant[0]] begin[:]
return[call[name[ArgumentError], parameter[constant[empty set has no minimum positive value.]]]]
if call[name[self].c... | keyword[def] identifier[min_pos] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__len__] ()== literal[int] :
keyword[return] identifier[ArgumentError] ( literal[string] )
keyword[if] identifier[self] . identifier[contains] ( literal[int] ):
... | def min_pos(self):
"""Returns minimal positive value or None."""
if self.__len__() == 0:
return ArgumentError('empty set has no minimum positive value.') # depends on [control=['if'], data=[]]
if self.contains(0):
return None # depends on [control=['if'], data=[]]
positive = [interval ... |
def previous_unwrittable_on_col(view, coords):
"""Return position of the previous (in column) letter that is unwrittable"""
x, y = coords
miny = -1
for offset in range(y - 1, miny, -1):
letter = view[x, offset]
if letter not in REWRITABLE_LETTERS:
return offset
return Non... | def function[previous_unwrittable_on_col, parameter[view, coords]]:
constant[Return position of the previous (in column) letter that is unwrittable]
<ast.Tuple object at 0x7da20c6e7be0> assign[=] name[coords]
variable[miny] assign[=] <ast.UnaryOp object at 0x7da20c6e4ac0>
for taget[name[... | keyword[def] identifier[previous_unwrittable_on_col] ( identifier[view] , identifier[coords] ):
literal[string]
identifier[x] , identifier[y] = identifier[coords]
identifier[miny] =- literal[int]
keyword[for] identifier[offset] keyword[in] identifier[range] ( identifier[y] - literal[int] , i... | def previous_unwrittable_on_col(view, coords):
"""Return position of the previous (in column) letter that is unwrittable"""
(x, y) = coords
miny = -1
for offset in range(y - 1, miny, -1):
letter = view[x, offset]
if letter not in REWRITABLE_LETTERS:
return offset # depends o... |
async def destroy_models(self, *models, destroy_storage=False):
"""Destroy one or more models.
:param str *models: Names or UUIDs of models to destroy
:param bool destroy_storage: Whether or not to destroy storage when
destroying the models. Defaults to false.
"""
u... | <ast.AsyncFunctionDef object at 0x7da1b0ebe1a0> | keyword[async] keyword[def] identifier[destroy_models] ( identifier[self] ,* identifier[models] , identifier[destroy_storage] = keyword[False] ):
literal[string]
identifier[uuids] = keyword[await] identifier[self] . identifier[model_uuids] ()
identifier[models] =[ identifier[uuids] [ ide... | async def destroy_models(self, *models, destroy_storage=False):
"""Destroy one or more models.
:param str *models: Names or UUIDs of models to destroy
:param bool destroy_storage: Whether or not to destroy storage when
destroying the models. Defaults to false.
"""
uuids = a... |
def build_notification_message(template_context, template_configuration=None):
"""
Create HTML and plaintext message bodies for a notification.
We receive a context with data we can use to render, as well as an optional site
template configration - if we don't get a template configuration, we'll use th... | def function[build_notification_message, parameter[template_context, template_configuration]]:
constant[
Create HTML and plaintext message bodies for a notification.
We receive a context with data we can use to render, as well as an optional site
template configration - if we don't get a template c... | keyword[def] identifier[build_notification_message] ( identifier[template_context] , identifier[template_configuration] = keyword[None] ):
literal[string]
keyword[if] (
identifier[template_configuration] keyword[is] keyword[not] keyword[None] keyword[and]
identifier[template_configuration] .... | def build_notification_message(template_context, template_configuration=None):
"""
Create HTML and plaintext message bodies for a notification.
We receive a context with data we can use to render, as well as an optional site
template configration - if we don't get a template configuration, we'll use th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.