text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _on_connected(self, future):
"""Invoked when connections have been established. If the client is
in clustering mode, it will kick of the discovery step if needed. If
not, it will select the configured database.
:param future: The connection future
:type future: tornado.concu... | [
"def",
"_on_connected",
"(",
"self",
",",
"future",
")",
":",
"if",
"future",
".",
"exception",
"(",
")",
":",
"self",
".",
"_connect_future",
".",
"set_exception",
"(",
"future",
".",
"exception",
"(",
")",
")",
"return",
"conn",
"=",
"future",
".",
"... | 41.116279 | 17.44186 |
def transaction(self, connection=None, **kwargs):
"""
a simple context manager useful for when you want to wrap a bunch of db calls in a transaction
http://docs.python.org/2/library/contextlib.html
http://docs.python.org/release/2.5/whatsnew/pep-343.html
example --
w... | [
"def",
"transaction",
"(",
"self",
",",
"connection",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"connection",
"(",
"connection",
")",
"as",
"connection",
":",
"name",
"=",
"connection",
".",
"transaction_name",
"(",
")",
"conne... | 38.190476 | 15.52381 |
def redo_expansion_state(self, ignore_not_existing_rows=False):
""" Considers the tree to be collapsed and expand into all tree item with the flag set True """
def set_expansion_state(state_path):
state_row_iter = self.state_row_iter_dict_by_state_path[state_path]
if state_row_i... | [
"def",
"redo_expansion_state",
"(",
"self",
",",
"ignore_not_existing_rows",
"=",
"False",
")",
":",
"def",
"set_expansion_state",
"(",
"state_path",
")",
":",
"state_row_iter",
"=",
"self",
".",
"state_row_iter_dict_by_state_path",
"[",
"state_path",
"]",
"if",
"st... | 64.535714 | 33.642857 |
def initialize_app(flask_app, args):
"""Initialize the App."""
# Setup gourde with the args.
gourde.setup(args)
# Register a custom health check.
gourde.is_healthy = is_healthy
# Add an optional API
initialize_api(flask_app) | [
"def",
"initialize_app",
"(",
"flask_app",
",",
"args",
")",
":",
"# Setup gourde with the args.",
"gourde",
".",
"setup",
"(",
"args",
")",
"# Register a custom health check.",
"gourde",
".",
"is_healthy",
"=",
"is_healthy",
"# Add an optional API",
"initialize_api",
"... | 24.5 | 14.4 |
def sum_distances(self, indices, distance_matrix):
"""Calculate combinatorial distance between a select group of
trajectories, indicated by indices
Arguments
---------
indices : tuple
distance_matrix : numpy.ndarray (M,M)
Returns
-------
numpy.nd... | [
"def",
"sum_distances",
"(",
"self",
",",
"indices",
",",
"distance_matrix",
")",
":",
"combs_tup",
"=",
"np",
".",
"array",
"(",
"tuple",
"(",
"combinations",
"(",
"indices",
",",
"2",
")",
")",
")",
"# Put indices from tuples into two-dimensional array.",
"com... | 32.548387 | 22.483871 |
def calc_score(self, att_query, att_keys):
"""
Calculate Bahdanau score
:param att_query: b x t_q x n
:param att_keys: b x t_k x n
returns: b x t_q x t_k scores
"""
b, t_k, n = att_keys.size()
t_q = att_query.size(1)
att_query = att_query.unsqu... | [
"def",
"calc_score",
"(",
"self",
",",
"att_query",
",",
"att_keys",
")",
":",
"b",
",",
"t_k",
",",
"n",
"=",
"att_keys",
".",
"size",
"(",
")",
"t_q",
"=",
"att_query",
".",
"size",
"(",
"1",
")",
"att_query",
"=",
"att_query",
".",
"unsqueeze",
... | 29.153846 | 17.384615 |
def rel_path(name, available_tools):
"""
Extracts relative path to a tool (from the main cloned directory) out
of available_tools based on the name it is given
"""
if name == '@' or name == '.' or name == '/':
name = ''
multi_tool = '@' in name
for too... | [
"def",
"rel_path",
"(",
"name",
",",
"available_tools",
")",
":",
"if",
"name",
"==",
"'@'",
"or",
"name",
"==",
"'.'",
"or",
"name",
"==",
"'/'",
":",
"name",
"=",
"''",
"multi_tool",
"=",
"'@'",
"in",
"name",
"for",
"tool",
"in",
"available_tools",
... | 39 | 12.368421 |
def cumulative_gain_curve(y_true, y_score, pos_label=None):
"""This function generates the points necessary to plot the Cumulative Gain
Note: This implementation is restricted to the binary classification task.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_score... | [
"def",
"cumulative_gain_curve",
"(",
"y_true",
",",
"y_score",
",",
"pos_label",
"=",
"None",
")",
":",
"y_true",
",",
"y_score",
"=",
"np",
".",
"asarray",
"(",
"y_true",
")",
",",
"np",
".",
"asarray",
"(",
"y_score",
")",
"# ensure binary classification i... | 36.614035 | 22.54386 |
def conv2d(x_input, w_matrix):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME') | [
"def",
"conv2d",
"(",
"x_input",
",",
"w_matrix",
")",
":",
"return",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"x_input",
",",
"w_matrix",
",",
"strides",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"'SAME'",
")"
] | 58.333333 | 16.666667 |
def RegresarAOrigenCTGRechazado(self, numero_carta_de_porte, numero_ctg,
km_a_recorrer=None,
**kwargs):
"Al consultar los CTGs rechazados se puede Regresar a Origen"
ret = self.client.regresarAOrigenCTGRechazado(request=dict(
... | [
"def",
"RegresarAOrigenCTGRechazado",
"(",
"self",
",",
"numero_carta_de_porte",
",",
"numero_ctg",
",",
"km_a_recorrer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"regresarAOrigenCTGRechazado",
"(",
"request",
"=",
... | 51.095238 | 15.571429 |
def reshape_like_all_dims(a, b):
"""Reshapes a to match the shape of b."""
ret = tf.reshape(a, tf.shape(b))
if not tf.executing_eagerly():
ret.set_shape(b.get_shape())
return ret | [
"def",
"reshape_like_all_dims",
"(",
"a",
",",
"b",
")",
":",
"ret",
"=",
"tf",
".",
"reshape",
"(",
"a",
",",
"tf",
".",
"shape",
"(",
"b",
")",
")",
"if",
"not",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"ret",
".",
"set_shape",
"(",
"b",
... | 30.833333 | 9.666667 |
def count_of_user(user_id):
'''
Get the cound of views.
'''
return TabCollect.select(
TabCollect, TabPost.uid.alias('post_uid'),
TabPost.title.alias('post_title'),
TabPost.view_count.alias('post_view_count')
).where(
TabCollect.user... | [
"def",
"count_of_user",
"(",
"user_id",
")",
":",
"return",
"TabCollect",
".",
"select",
"(",
"TabCollect",
",",
"TabPost",
".",
"uid",
".",
"alias",
"(",
"'post_uid'",
")",
",",
"TabPost",
".",
"title",
".",
"alias",
"(",
"'post_title'",
")",
",",
"TabP... | 32 | 16.461538 |
def pty_wrapper_main():
"""
Main function of the pty wrapper script
"""
# make sure we can import _pty even if pyqode is not installed (this is the case in HackEdit where pyqode has
# been vendored).
sys.path.insert(0, os.path.dirname(__file__))
import _pty
# fixme: find a way to use a ... | [
"def",
"pty_wrapper_main",
"(",
")",
":",
"# make sure we can import _pty even if pyqode is not installed (this is the case in HackEdit where pyqode has",
"# been vendored).",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"__file_... | 35.454545 | 22 |
def mutapply(self, function, fieldname):
"""
Applies `function` in-place to the field name specified.
In other words, `mutapply` overwrites column `fieldname`
ith the results of applying `function` to each element of that column.
"""
self[fieldname] = self.apply(function... | [
"def",
"mutapply",
"(",
"self",
",",
"function",
",",
"fieldname",
")",
":",
"self",
"[",
"fieldname",
"]",
"=",
"self",
".",
"apply",
"(",
"function",
",",
"fieldname",
")"
] | 40.625 | 17.875 |
def cancel(self):
""" Cancel current statement
"""
conn = self._assert_open()
conn._try_activate_cursor(self)
self._session.cancel_if_pending() | [
"def",
"cancel",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"_assert_open",
"(",
")",
"conn",
".",
"_try_activate_cursor",
"(",
"self",
")",
"self",
".",
"_session",
".",
"cancel_if_pending",
"(",
")"
] | 29.666667 | 5.166667 |
def render_as_json(func):
"""
Decorator to render as JSON
:param func:
:return:
"""
if inspect.isclass(func):
setattr(func, "_renderer", json_renderer)
return func
else:
@functools.wraps(func)
def decorated_view(*args, **kwargs):
data = func(*args,... | [
"def",
"render_as_json",
"(",
"func",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"func",
")",
":",
"setattr",
"(",
"func",
",",
"\"_renderer\"",
",",
"json_renderer",
")",
"return",
"func",
"else",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
... | 26.4 | 12.133333 |
def build_status(self, _args):
"""Print the status of the specified build. """
print('{Style.BRIGHT}Bootstraps whose core components are probably '
'already built:{Style.RESET_ALL}'.format(Style=Out_Style))
bootstrap_dir = join(self.ctx.build_dir, 'bootstrap_builds')
if ex... | [
"def",
"build_status",
"(",
"self",
",",
"_args",
")",
":",
"print",
"(",
"'{Style.BRIGHT}Bootstraps whose core components are probably '",
"'already built:{Style.RESET_ALL}'",
".",
"format",
"(",
"Style",
"=",
"Out_Style",
")",
")",
"bootstrap_dir",
"=",
"join",
"(",
... | 53.074074 | 21.481481 |
def porosimetry(im, sizes=25, inlets=None, access_limited=True,
mode='hybrid'):
r"""
Performs a porosimetry simulution on the image
Parameters
----------
im : ND-array
An ND image of the porous material containing True values in the
pore space.
sizes : array_lik... | [
"def",
"porosimetry",
"(",
"im",
",",
"sizes",
"=",
"25",
",",
"inlets",
"=",
"None",
",",
"access_limited",
"=",
"True",
",",
"mode",
"=",
"'hybrid'",
")",
":",
"if",
"im",
".",
"ndim",
"!=",
"im",
".",
"squeeze",
"(",
")",
".",
"ndim",
":",
"wa... | 41.676692 | 24.225564 |
def handleRestartRequest(self, req: Request) -> None:
"""
Handles transaction of type POOL_RESTART
Can schedule or cancel restart to a newer
version at specified time
:param req:
"""
txn = req.operation
if txn[TXN_TYPE] != POOL_RESTART:
return... | [
"def",
"handleRestartRequest",
"(",
"self",
",",
"req",
":",
"Request",
")",
"->",
"None",
":",
"txn",
"=",
"req",
".",
"operation",
"if",
"txn",
"[",
"TXN_TYPE",
"]",
"!=",
"POOL_RESTART",
":",
"return",
"action",
"=",
"txn",
"[",
"ACTION",
"]",
"if",... | 32.967742 | 17.354839 |
def set_offload(devname, **kwargs):
'''
Changes the offload parameters and other features of the specified network device
CLI Example:
.. code-block:: bash
salt '*' ethtool.set_offload <devname> tcp_segmentation_offload=on
'''
for param, value in kwargs.items():
if param == '... | [
"def",
"set_offload",
"(",
"devname",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"param",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"param",
"==",
"'tcp_segmentation_offload'",
":",
"value",
"=",
"value",
"==",
"\"on\"",
"and",
"1... | 26.9 | 22.8 |
def __expand_cluster(self, index_point):
"""!
@brief Expands cluster from specified point in the input data space.
@param[in] index_point (list): Index of a point from the data.
@return (list) Return tuple of list of indexes that belong to the same cluster and list of poi... | [
"def",
"__expand_cluster",
"(",
"self",
",",
"index_point",
")",
":",
"cluster",
"=",
"None",
"self",
".",
"__visited",
"[",
"index_point",
"]",
"=",
"True",
"neighbors",
"=",
"self",
".",
"__neighbor_searcher",
"(",
"index_point",
")",
"if",
"len",
"(",
"... | 38.909091 | 23.666667 |
def all_patterns(name):
u"""
Accepts a string and returns a pattern of possible patterns involving that name
Called by simple_mapping_to_pattern for each name in the mapping it receives.
"""
# i_ denotes an import-like node
# u_ denotes a node that appears to be a usage of the name
if u'.' ... | [
"def",
"all_patterns",
"(",
"name",
")",
":",
"# i_ denotes an import-like node",
"# u_ denotes a node that appears to be a usage of the name",
"if",
"u'.'",
"in",
"name",
":",
"name",
",",
"attr",
"=",
"name",
".",
"split",
"(",
"u'.'",
",",
"1",
")",
"simple_name"... | 49 | 20.56 |
def guess_width(self):
"""auto fit column width"""
if len(self.header) <= 4:
nspace = 6
elif len(self.header) <= 6:
nspace = 5
else:
nspace = 4
ncol = len(self.header)
self._width = [nspace] * ncol
width = [0] * ncol
# ... | [
"def",
"guess_width",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"header",
")",
"<=",
"4",
":",
"nspace",
"=",
"6",
"elif",
"len",
"(",
"self",
".",
"header",
")",
"<=",
"6",
":",
"nspace",
"=",
"5",
"else",
":",
"nspace",
"=",
"4",
... | 30.9 | 12.333333 |
def _write_gml(G, path):
"""
Wrapper around nx.write_gml
"""
import networkx as nx
return nx.write_gml(G, path, stringizer=str) | [
"def",
"_write_gml",
"(",
"G",
",",
"path",
")",
":",
"import",
"networkx",
"as",
"nx",
"return",
"nx",
".",
"write_gml",
"(",
"G",
",",
"path",
",",
"stringizer",
"=",
"str",
")"
] | 23.666667 | 8 |
def sanitize_ssl(self):
"""Use local installed certificate file if available.
Tries to get system, then certifi, then the own
installed certificate file."""
if self["sslverify"] is True:
try:
self["sslverify"] = get_system_cert_file()
except ValueE... | [
"def",
"sanitize_ssl",
"(",
"self",
")",
":",
"if",
"self",
"[",
"\"sslverify\"",
"]",
"is",
"True",
":",
"try",
":",
"self",
"[",
"\"sslverify\"",
"]",
"=",
"get_system_cert_file",
"(",
")",
"except",
"ValueError",
":",
"try",
":",
"self",
"[",
"\"sslve... | 40.466667 | 13.066667 |
def reorder(self, dst_order, arr, src_order=None):
"""Reorder the output array to match that needed by the viewer."""
if dst_order is None:
dst_order = self.viewer.rgb_order
if src_order is None:
src_order = self.rgb_order
if src_order != dst_order:
ar... | [
"def",
"reorder",
"(",
"self",
",",
"dst_order",
",",
"arr",
",",
"src_order",
"=",
"None",
")",
":",
"if",
"dst_order",
"is",
"None",
":",
"dst_order",
"=",
"self",
".",
"viewer",
".",
"rgb_order",
"if",
"src_order",
"is",
"None",
":",
"src_order",
"=... | 38.2 | 13.2 |
def block_sep0(self, Y):
r"""Separate variable into component corresponding to
:math:`\mathbf{y}_0` in :math:`\mathbf{y}\;\;`.
"""
return Y[(slice(None),)*self.blkaxis + (slice(0, self.blkidx),)] | [
"def",
"block_sep0",
"(",
"self",
",",
"Y",
")",
":",
"return",
"Y",
"[",
"(",
"slice",
"(",
"None",
")",
",",
")",
"*",
"self",
".",
"blkaxis",
"+",
"(",
"slice",
"(",
"0",
",",
"self",
".",
"blkidx",
")",
",",
")",
"]"
] | 37.166667 | 17.166667 |
def _latex_(self):
r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^... | [
"def",
"_latex_",
"(",
"self",
")",
":",
"if",
"self",
".",
"allowed",
":",
"return",
"self",
".",
"e1",
".",
"_latex_",
"(",
")",
"+",
"'\\\\ \\\\rightarrow \\\\ '",
"+",
"self",
".",
"e2",
".",
"_latex_",
"(",
")",
"elif",
"not",
"self",
".",
"allo... | 41.411765 | 25.294118 |
def _add_install(self, context):
"""
generates install.sh and adds it to included files
"""
contents = self._render_template('install.sh', context)
self.config.setdefault('files', []) # file list might be empty
# add install.sh to list of included files
self._add... | [
"def",
"_add_install",
"(",
"self",
",",
"context",
")",
":",
"contents",
"=",
"self",
".",
"_render_template",
"(",
"'install.sh'",
",",
"context",
")",
"self",
".",
"config",
".",
"setdefault",
"(",
"'files'",
",",
"[",
"]",
")",
"# file list might be empt... | 35.75 | 13.083333 |
def datetimeobj_YmdHMS(value):
"""Convert timestamp string to a datetime object.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
A datetime object.
Raises:
Value... | [
"def",
"datetimeobj_YmdHMS",
"(",
"value",
")",
":",
"i",
"=",
"int",
"(",
"value",
")",
"S",
"=",
"i",
"M",
"=",
"S",
"//",
"100",
"H",
"=",
"M",
"//",
"100",
"d",
"=",
"H",
"//",
"100",
"m",
"=",
"d",
"//",
"100",
"Y",
"=",
"m",
"//",
"... | 22.296296 | 25.111111 |
def to_dict(self):
"""
Return the information from the pedigree file as a dictionary.
family id is key and a list with dictionarys for each individual
as value.
Returns:
families (dict): A dictionary with the families
"""
self.logger... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Return the information as a dictionary\"",
")",
"families",
"=",
"{",
"}",
"for",
"family_id",
"in",
"self",
".",
"families",
":",
"family",
"=",
"[",
"]",
"for",
"indivi... | 38.416667 | 20.916667 |
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
... | [
"def",
"loads",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"object_hook",
"=",
"None",
",",
"parse_float",
"=",
"None",
",",
"parse_int",
"=",
"None",
",",
"parse_constant",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if... | 44.795918 | 21.857143 |
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
defaul... | [
"def",
"query",
"(",
"method",
"=",
"'droplets'",
",",
"droplet_id",
"=",
"None",
",",
"command",
"=",
"None",
",",
"args",
"=",
"None",
",",
"http_method",
"=",
"'get'",
")",
":",
"base_path",
"=",
"six",
".",
"text_type",
"(",
"config",
".",
"get_clo... | 27.910714 | 23.803571 |
def git_sequence_editor_squash(fpath):
r"""
squashes wip messages
CommandLine:
python -m utool.util_git --exec-git_sequence_editor_squash
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> import utool as ut
>>> from utool.util_git import * # NOQA
>>> fpat... | [
"def",
"git_sequence_editor_squash",
"(",
"fpath",
")",
":",
"# print(sys.argv)",
"import",
"utool",
"as",
"ut",
"text",
"=",
"ut",
".",
"read_from",
"(",
"fpath",
")",
"# print('fpath = %r' % (fpath,))",
"print",
"(",
"text",
")",
"# Doesnt work because of fixed witd... | 38.950355 | 21.028369 |
def convert(dbus_obj):
"""Converts dbus_obj from dbus type to python type.
:param dbus_obj: dbus object.
:returns: dbus_obj in python type.
"""
_isinstance = partial(isinstance, dbus_obj)
ConvertType = namedtuple('ConvertType', 'pytype dbustypes')
pyint = ConvertType(int, (dbus.Byte, dbus.... | [
"def",
"convert",
"(",
"dbus_obj",
")",
":",
"_isinstance",
"=",
"partial",
"(",
"isinstance",
",",
"dbus_obj",
")",
"ConvertType",
"=",
"namedtuple",
"(",
"'ConvertType'",
",",
"'pytype dbustypes'",
")",
"pyint",
"=",
"ConvertType",
"(",
"int",
",",
"(",
"d... | 38.028571 | 18.257143 |
def self_aware(fn):
''' decorating a function with this allows it to
refer to itself as 'self' inside the function
body.
'''
if isgeneratorfunction(fn):
@wraps(fn)
def wrapper(*a,**k):
generator = fn(*a,**k)
if hasattr(
generator,
... | [
"def",
"self_aware",
"(",
"fn",
")",
":",
"if",
"isgeneratorfunction",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
":",
"generator",
"=",
"fn",
"(",
"*",
"a",
",",
"*",
"*",
"k"... | 28.407407 | 15 |
def _create_gitlab_runner_prometheus_instance(self, instance, init_config):
"""
Set up the gitlab_runner instance so it can be used in OpenMetricsBaseCheck
"""
# Mapping from Prometheus metrics names to Datadog ones
# For now it's a 1:1 mapping
allowed_metrics = init_conf... | [
"def",
"_create_gitlab_runner_prometheus_instance",
"(",
"self",
",",
"instance",
",",
"init_config",
")",
":",
"# Mapping from Prometheus metrics names to Datadog ones",
"# For now it's a 1:1 mapping",
"allowed_metrics",
"=",
"init_config",
".",
"get",
"(",
"'allowed_metrics'",
... | 45.269231 | 27.423077 |
def touch(self):
"""
Mark this update as complete.
"""
if self.marker_table_bound is None:
self.create_marker_table()
table = self.marker_table_bound
id_exists = self.exists()
with self.engine.begin() as conn:
if not id_exists:
... | [
"def",
"touch",
"(",
"self",
")",
":",
"if",
"self",
".",
"marker_table_bound",
"is",
"None",
":",
"self",
".",
"create_marker_table",
"(",
")",
"table",
"=",
"self",
".",
"marker_table_bound",
"id_exists",
"=",
"self",
".",
"exists",
"(",
")",
"with",
"... | 44.65 | 20.95 |
def getAllChildNodes(self):
'''
getAllChildNodes - Gets all the children, and their children,
and their children, and so on, all the way to the end as a TagCollection.
Use .childNodes for a regular list
@return TagCollection<AdvancedTag> - ... | [
"def",
"getAllChildNodes",
"(",
"self",
")",
":",
"ret",
"=",
"TagCollection",
"(",
")",
"# Scan all the children of this node",
"for",
"child",
"in",
"self",
".",
"children",
":",
"# Append each child",
"ret",
".",
"append",
"(",
"child",
")",
"# Append children'... | 31.666667 | 25.380952 |
def disk_usage(path):
"""Return free usage about the given path, in bytes.
Parameters
----------
path : str
Folder for which to return disk usage
Returns
-------
output : tuple
Tuple containing total space in the folder and currently
used space in the folder
""... | [
"def",
"disk_usage",
"(",
"path",
")",
":",
"st",
"=",
"os",
".",
"statvfs",
"(",
"path",
")",
"total",
"=",
"st",
".",
"f_blocks",
"*",
"st",
".",
"f_frsize",
"used",
"=",
"(",
"st",
".",
"f_blocks",
"-",
"st",
".",
"f_bfree",
")",
"*",
"st",
... | 23.263158 | 20.052632 |
def refresh_state_in_ec(self, ec_index):
'''Get the up-to-date state of the component in an execution context.
This function will update the state, rather than using the cached
value. This may take time, if the component is executing on a remote
node.
@param ec_index The index ... | [
"def",
"refresh_state_in_ec",
"(",
"self",
",",
"ec_index",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"ec_index",
">=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
":",
"ec_index",
"-=",
"len",
"(",
"self",
".",
"owned_ecs",
")",
"if",
"ec_ind... | 48.777778 | 25.814815 |
def marketplace(self):
"""
:returns: Version marketplace of preview
:rtype: twilio.rest.preview.marketplace.Marketplace
"""
if self._marketplace is None:
self._marketplace = Marketplace(self)
return self._marketplace | [
"def",
"marketplace",
"(",
"self",
")",
":",
"if",
"self",
".",
"_marketplace",
"is",
"None",
":",
"self",
".",
"_marketplace",
"=",
"Marketplace",
"(",
"self",
")",
"return",
"self",
".",
"_marketplace"
] | 33.625 | 8.125 |
def _get_all_merges(routing_table):
"""Get possible sets of entries to merge.
Yields
------
:py:class:`~.Merge`
"""
# Memorise entries that have been considered as part of a merge
considered_entries = set()
for i, entry in enumerate(routing_table):
# If we've already considered... | [
"def",
"_get_all_merges",
"(",
"routing_table",
")",
":",
"# Memorise entries that have been considered as part of a merge",
"considered_entries",
"=",
"set",
"(",
")",
"for",
"i",
",",
"entry",
"in",
"enumerate",
"(",
"routing_table",
")",
":",
"# If we've already consid... | 31.206897 | 19.551724 |
def extend_selection_to_next(self, what='word', direction='left'):
"""
Extend selection to next *what* ('word' or 'character')
toward *direction* ('left' or 'right')
"""
self.__move_cursor_anchor(what, direction, QTextCursor.KeepAnchor) | [
"def",
"extend_selection_to_next",
"(",
"self",
",",
"what",
"=",
"'word'",
",",
"direction",
"=",
"'left'",
")",
":",
"self",
".",
"__move_cursor_anchor",
"(",
"what",
",",
"direction",
",",
"QTextCursor",
".",
"KeepAnchor",
")"
] | 46 | 15.333333 |
def _remove(self, shard_name):
"""remove member from configuration"""
result = self.router_command("removeShard", shard_name, is_eval=False)
if result['ok'] == 1 and result['state'] == 'completed':
shard = self._shards.pop(shard_name)
if shard.get('isServer', False):
... | [
"def",
"_remove",
"(",
"self",
",",
"shard_name",
")",
":",
"result",
"=",
"self",
".",
"router_command",
"(",
"\"removeShard\"",
",",
"shard_name",
",",
"is_eval",
"=",
"False",
")",
"if",
"result",
"[",
"'ok'",
"]",
"==",
"1",
"and",
"result",
"[",
"... | 47.5 | 12.7 |
def hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp")
arp_entry = ET.SubEleme... | [
"def",
"hide_arp_holder_arp_entry_interfacetype_TenGigabitEthernet_TenGigabitEthernet",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_arp_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
... | 57.466667 | 27 |
def reduce(source, func, initializer=None):
"""Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when ... | [
"def",
"reduce",
"(",
"source",
",",
"func",
",",
"initializer",
"=",
"None",
")",
":",
"acc",
"=",
"accumulate",
".",
"raw",
"(",
"source",
",",
"func",
",",
"initializer",
")",
"return",
"select",
".",
"item",
".",
"raw",
"(",
"acc",
",",
"-",
"1... | 43.3 | 16.6 |
def nla_put_data(msg, attrtype, data):
"""Add abstract data as unspecific attribute to Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L527
Equivalent to nla_put() except that the length of the payload is derived from the bytearray data object.
Positional arguments:
... | [
"def",
"nla_put_data",
"(",
"msg",
",",
"attrtype",
",",
"data",
")",
":",
"return",
"nla_put",
"(",
"msg",
",",
"attrtype",
",",
"len",
"(",
"data",
")",
",",
"data",
")"
] | 35.75 | 21.6875 |
def recap(self, nc):
# type: (int) -> None
"""recap changes the maximum size limit of the dynamic table. It also
proceeds to a resize(), if the new size is lower than the previous one.
@param int nc: the new cap of the dynamic table (that is the maximum-maximum size) # noqa: E501
... | [
"def",
"recap",
"(",
"self",
",",
"nc",
")",
":",
"# type: (int) -> None",
"assert",
"(",
"nc",
">=",
"0",
")",
"t",
"=",
"self",
".",
"_dynamic_table_cap_size",
">",
"nc",
"self",
".",
"_dynamic_table_cap_size",
"=",
"nc",
"if",
"t",
":",
"# The RFC is no... | 40.133333 | 19.6 |
def ensure_coord_type(f):
"""
A decorator for class methods of the form
.. code-block:: python
Class.method(self, coords, **kwargs)
where ``coords`` is an :obj:`astropy.coordinates.SkyCoord` object.
The decorator raises a :obj:`TypeError` if the ``coords`` that gets passed to
``Class... | [
"def",
"ensure_coord_type",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"_wrapper_func",
"(",
"self",
",",
"coords",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"coords",
",",
"coordinates",
".",
"SkyCoord",
")",
":... | 35.724138 | 23.655172 |
def when_built(self):
"""
Returns a Deferred that is callback()'d (with this Circuit
instance) when this circuit hits BUILT.
If it's already BUILT when this is called, you get an
already-successful Deferred; otherwise, the state must change
to BUILT.
If the circ... | [
"def",
"when_built",
"(",
"self",
")",
":",
"# XXX note to self: we never do an errback; fix this behavior",
"if",
"self",
".",
"state",
"==",
"'BUILT'",
":",
"return",
"defer",
".",
"succeed",
"(",
"self",
")",
"return",
"self",
".",
"_when_built",
".",
"when_fir... | 38.6875 | 18.6875 |
def parseColors(colors, defaultColor):
"""
Parse command line color information.
@param colors: A C{list} of space separated "value color" strings, such as
["0.9 red", "0.75 rgb(23, 190, 207)", "0.1 #CF3CF3"].
@param defaultColor: The C{str} color to use for cells that do not reach
the ... | [
"def",
"parseColors",
"(",
"colors",
",",
"defaultColor",
")",
":",
"result",
"=",
"[",
"]",
"if",
"colors",
":",
"for",
"colorInfo",
"in",
"colors",
":",
"fields",
"=",
"colorInfo",
".",
"split",
"(",
"maxsplit",
"=",
"1",
")",
"if",
"len",
"(",
"fi... | 44.106383 | 21.340426 |
def read_stat():
"""
Returns the system stat information.
:returns: The system stat information.
:rtype: list
"""
data = []
with open("/proc/stat", "rb") as stat_file:
for line in stat_file:
cpu_stat = line.split()
if cpu_stat[0][:3] != b"cpu":
... | [
"def",
"read_stat",
"(",
")",
":",
"data",
"=",
"[",
"]",
"with",
"open",
"(",
"\"/proc/stat\"",
",",
"\"rb\"",
")",
"as",
"stat_file",
":",
"for",
"line",
"in",
"stat_file",
":",
"cpu_stat",
"=",
"line",
".",
"split",
"(",
")",
"if",
"cpu_stat",
"["... | 29.535714 | 14.107143 |
def repeater(call, args=None, kwargs=None, retries=4):
"""
repeat call x-times: docker API is just awesome
:param call: function
:param args: tuple, args for function
:param kwargs: dict, kwargs for function
:param retries: int, how many times we try?
:return: response of the call
"""
... | [
"def",
"repeater",
"(",
"call",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"retries",
"=",
"4",
")",
":",
"args",
"=",
"args",
"or",
"(",
")",
"kwargs",
"=",
"kwargs",
"or",
"{",
"}",
"t",
"=",
"1.0",
"for",
"x",
"in",
"range",
... | 31.125 | 13.958333 |
def srp1(*args,**kargs):
"""Send and receive packets at layer 2 and return only the first answer
nofilter: put 1 to avoid use of bpf filters
retry: if positive, how many times to resend unanswered packets
if negative, how many times to retry when no more packets are answered
timeout: how much time to ... | [
"def",
"srp1",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"not",
"\"timeout\"",
"in",
"kargs",
":",
"kargs",
"[",
"\"timeout\"",
"]",
"=",
"-",
"1",
"a",
",",
"b",
"=",
"srp",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"if"... | 39.882353 | 16.823529 |
def connect(self, hostname, family, hostaddr):
"""
Log new connections.
"""
self.client_ip = hostaddr[0]
self.client_port = hostaddr[1]
self.time_start = time.time()
logger.debug('<{}> Connect from {}[{}]:{}'.format(
self.id, hostname, self.client_ip,... | [
"def",
"connect",
"(",
"self",
",",
"hostname",
",",
"family",
",",
"hostaddr",
")",
":",
"self",
".",
"client_ip",
"=",
"hostaddr",
"[",
"0",
"]",
"self",
".",
"client_port",
"=",
"hostaddr",
"[",
"1",
"]",
"self",
".",
"time_start",
"=",
"time",
".... | 32.727273 | 10.909091 |
def rm_files(path, extension):
"""
Remove all files in the given directory with the given extension
:param str path: Directory
:param str extension: File type to remove
:return none:
"""
files = list_files(extension, path)
for file in files:
if file.endswith(extension):
... | [
"def",
"rm_files",
"(",
"path",
",",
"extension",
")",
":",
"files",
"=",
"list_files",
"(",
"extension",
",",
"path",
")",
"for",
"file",
"in",
"files",
":",
"if",
"file",
".",
"endswith",
"(",
"extension",
")",
":",
"os",
".",
"remove",
"(",
"os",
... | 27.538462 | 13.538462 |
def var(ctx, clear_target, clear_all):
"""Install variable data to /var/[lib,cache]/hfos"""
install_var(str(ctx.obj['instance']), clear_target, clear_all) | [
"def",
"var",
"(",
"ctx",
",",
"clear_target",
",",
"clear_all",
")",
":",
"install_var",
"(",
"str",
"(",
"ctx",
".",
"obj",
"[",
"'instance'",
"]",
")",
",",
"clear_target",
",",
"clear_all",
")"
] | 40 | 17 |
def _record_count(self):
"""
Get number of records in file.
This is maybe suboptimal because we have to seek to the end of
the file.
Side effect: returns file position to record_start.
"""
self.filepath_or_buffer.seek(0, 2)
total_records_length = (self.... | [
"def",
"_record_count",
"(",
"self",
")",
":",
"self",
".",
"filepath_or_buffer",
".",
"seek",
"(",
"0",
",",
"2",
")",
"total_records_length",
"=",
"(",
"self",
".",
"filepath_or_buffer",
".",
"tell",
"(",
")",
"-",
"self",
".",
"record_start",
")",
"if... | 30.527778 | 21.527778 |
def _parse_request(self, xml):
""" Parse a request with metadata information
:param xml: LXML Object
:type xml: Union[lxml.etree._Element]
"""
for node in xml.xpath(".//ti:groupname", namespaces=XPATH_NAMESPACES):
lang = node.get("xml:lang") or CtsText.DEFAULT_LANG
... | [
"def",
"_parse_request",
"(",
"self",
",",
"xml",
")",
":",
"for",
"node",
"in",
"xml",
".",
"xpath",
"(",
"\".//ti:groupname\"",
",",
"namespaces",
"=",
"XPATH_NAMESPACES",
")",
":",
"lang",
"=",
"node",
".",
"get",
"(",
"\"xml:lang\"",
")",
"or",
"CtsT... | 48.1875 | 26 |
def get_distinct_values_from_cols(self, l_col_list):
"""
returns the list of distinct combinations in a dataset
based on the columns in the list. Note that this is
currently implemented as MAX permutations of the combo
so it is not guarenteed to have values in each case.
... | [
"def",
"get_distinct_values_from_cols",
"(",
"self",
",",
"l_col_list",
")",
":",
"uniq_vals",
"=",
"[",
"]",
"for",
"l_col_name",
"in",
"l_col_list",
":",
"#print('col_name: ' + l_col_name) ",
"uniq_vals",
".",
"append",
"(",
"set",
"(",
"self",
".",
"get_col_d... | 38.730769 | 15.423077 |
def del_resource(self, service_name, resource_name, base_class=None):
"""
Deletes a resource class for a given service.
Fails silently if no connection is found in the cache.
:param service_name: The service a given ``Resource`` talks to. Ex.
``sqs``, ``sns``, ``dynamodb``,... | [
"def",
"del_resource",
"(",
"self",
",",
"service_name",
",",
"resource_name",
",",
"base_class",
"=",
"None",
")",
":",
"# Unlike ``get_resource``, this should be fire & forget.",
"# We don't really care, as long as it's not in the cache any longer.",
"try",
":",
"classpath",
... | 40.652174 | 22.043478 |
def _GetStat(self):
"""Retrieves a stat object.
Returns:
VFSStat: a stat object.
Raises:
BackEndError: when the encoded stream is missing.
"""
stat_object = vfs_stat.VFSStat()
# File data stat information.
stat_object.size = self.path_spec.range_size
# File entry type sta... | [
"def",
"_GetStat",
"(",
"self",
")",
":",
"stat_object",
"=",
"vfs_stat",
".",
"VFSStat",
"(",
")",
"# File data stat information.",
"stat_object",
".",
"size",
"=",
"self",
".",
"path_spec",
".",
"range_size",
"# File entry type stat information.",
"stat_object",
"... | 21.444444 | 19.222222 |
def render_impl(self, template, context, at_paths=None, **kwargs):
"""
Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search... | [
"def",
"render_impl",
"(",
"self",
",",
"template",
",",
"context",
",",
"at_paths",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Override the path to pass it to tenjin.Engine.",
"if",
"at_paths",
"is",
"not",
"None",
":",
"paths",
"=",
"at_paths",
"+",
... | 41.217391 | 20.347826 |
def retrieve_all(self, sids, default_none=False):
"""
Retrieve all assets in `sids`.
Parameters
----------
sids : iterable of int
Assets to retrieve.
default_none : bool
If True, return None for failed lookups.
If False, raise `SidsNot... | [
"def",
"retrieve_all",
"(",
"self",
",",
"sids",
",",
"default_none",
"=",
"False",
")",
":",
"sids",
"=",
"list",
"(",
"sids",
")",
"hits",
",",
"missing",
",",
"failures",
"=",
"{",
"}",
",",
"set",
"(",
")",
",",
"[",
"]",
"for",
"sid",
"in",
... | 32.477612 | 19.58209 |
def mapPriority(levelno):
"""Map logging levels to journald priorities.
Since Python log level numbers are "sparse", we have
to map numbers in between the standard levels too.
"""
if levelno <= _logging.DEBUG:
return LOG_DEBUG
elif levelno <= _logging.INFO:
... | [
"def",
"mapPriority",
"(",
"levelno",
")",
":",
"if",
"levelno",
"<=",
"_logging",
".",
"DEBUG",
":",
"return",
"LOG_DEBUG",
"elif",
"levelno",
"<=",
"_logging",
".",
"INFO",
":",
"return",
"LOG_INFO",
"elif",
"levelno",
"<=",
"_logging",
".",
"WARNING",
"... | 32.388889 | 11.277778 |
def interpolation_linear(x, x1, x2, y1, y2):
"""
Linear interpolation
returns (y2 - y1) / (x2 - x1) * (x - x1) + y1
"""
m = (y2 - y1) / (x2 - x1)
t = (x - x1)
return m * t + y1 | [
"def",
"interpolation_linear",
"(",
"x",
",",
"x1",
",",
"x2",
",",
"y1",
",",
"y2",
")",
":",
"m",
"=",
"(",
"y2",
"-",
"y1",
")",
"/",
"(",
"x2",
"-",
"x1",
")",
"t",
"=",
"(",
"x",
"-",
"x1",
")",
"return",
"m",
"*",
"t",
"+",
"y1"
] | 24.625 | 10.375 |
def com_google_fonts_check_hinting_impact(font, ttfautohint_stats):
"""Show hinting filesize impact.
Current implementation simply logs useful info
but there's no fail scenario for this checker."""
hinted = ttfautohint_stats["hinted_size"]
dehinted = ttfautohint_stats["dehinted_size"]
increase = hin... | [
"def",
"com_google_fonts_check_hinting_impact",
"(",
"font",
",",
"ttfautohint_stats",
")",
":",
"hinted",
"=",
"ttfautohint_stats",
"[",
"\"hinted_size\"",
"]",
"dehinted",
"=",
"ttfautohint_stats",
"[",
"\"dehinted_size\"",
"]",
"increase",
"=",
"hinted",
"-",
"dehi... | 33.935484 | 14.967742 |
def box_actions(results, times, N_matrix, ifprint):
"""
Finds actions, angles and frequencies for box orbit.
Takes a series of phase-space points from an orbit integration at times t and returns
L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below.
"""
if(ifprint):
... | [
"def",
"box_actions",
"(",
"results",
",",
"times",
",",
"N_matrix",
",",
"ifprint",
")",
":",
"if",
"(",
"ifprint",
")",
":",
"print",
"(",
"\"\\n=====\\nUsing triaxial harmonic toy potential\"",
")",
"t",
"=",
"time",
".",
"time",
"(",
")",
"# Find best toy ... | 34.7 | 26.85 |
def rename_local_untracked(self):
"""
Rename local untracked files that would require pulls
"""
# Find what files have been added!
new_upstream_files = self.find_upstream_changed('A')
for f in new_upstream_files:
if os.path.exists(f):
# If ther... | [
"def",
"rename_local_untracked",
"(",
"self",
")",
":",
"# Find what files have been added!",
"new_upstream_files",
"=",
"self",
".",
"find_upstream_changed",
"(",
"'A'",
")",
"for",
"f",
"in",
"new_upstream_files",
":",
"if",
"os",
".",
"path",
".",
"exists",
"("... | 50.6 | 16.866667 |
def get_input(context, conf):
"""Gets a user parameter, either from the console or from an outer
submodule/system
Assumes conf has name, default, prompt and debug
"""
name = conf['name']['value']
prompt = conf['prompt']['value']
default = conf['default']['value'] or conf['debug']['va... | [
"def",
"get_input",
"(",
"context",
",",
"conf",
")",
":",
"name",
"=",
"conf",
"[",
"'name'",
"]",
"[",
"'value'",
"]",
"prompt",
"=",
"conf",
"[",
"'prompt'",
"]",
"[",
"'value'",
"]",
"default",
"=",
"conf",
"[",
"'default'",
"]",
"[",
"'value'",
... | 31.95 | 17.6 |
def center_origin(self):
"""Sets the origin to the center of the image."""
self.set_origin(Vector2(self.image.get_width() / 2.0, self.image.get_height() / 2.0)) | [
"def",
"center_origin",
"(",
"self",
")",
":",
"self",
".",
"set_origin",
"(",
"Vector2",
"(",
"self",
".",
"image",
".",
"get_width",
"(",
")",
"/",
"2.0",
",",
"self",
".",
"image",
".",
"get_height",
"(",
")",
"/",
"2.0",
")",
")"
] | 58 | 23 |
def CountHuntOutputPluginLogEntries(self,
hunt_id,
output_plugin_id,
with_type=None,
cursor=None):
"""Counts hunt output plugin log entries."""
query = ("SELECT... | [
"def",
"CountHuntOutputPluginLogEntries",
"(",
"self",
",",
"hunt_id",
",",
"output_plugin_id",
",",
"with_type",
"=",
"None",
",",
"cursor",
"=",
"None",
")",
":",
"query",
"=",
"(",
"\"SELECT COUNT(*) \"",
"\"FROM flow_output_plugin_log_entries \"",
"\"FORCE INDEX (fl... | 37.047619 | 14.761905 |
def os_walk_pre_35(top, topdown=True, onerror=None, followlinks=False):
"""Pre Python 3.5 implementation of os.walk() that doesn't use scandir."""
islink, join, isdir = os.path.islink, os.path.join, os.path.isdir
try:
names = os.listdir(top)
except OSError as err:
if onerror is not None... | [
"def",
"os_walk_pre_35",
"(",
"top",
",",
"topdown",
"=",
"True",
",",
"onerror",
"=",
"None",
",",
"followlinks",
"=",
"False",
")",
":",
"islink",
",",
"join",
",",
"isdir",
"=",
"os",
".",
"path",
".",
"islink",
",",
"os",
".",
"path",
".",
"joi... | 29.925926 | 19.185185 |
def delete_snapshot(self, snapshot_id):
"""Remove a previously created snapshot."""
query = self.query_factory(
action="DeleteSnapshot", creds=self.creds, endpoint=self.endpoint,
other_params={"SnapshotId": snapshot_id})
d = query.submit()
return d.addCallback(sel... | [
"def",
"delete_snapshot",
"(",
"self",
",",
"snapshot_id",
")",
":",
"query",
"=",
"self",
".",
"query_factory",
"(",
"action",
"=",
"\"DeleteSnapshot\"",
",",
"creds",
"=",
"self",
".",
"creds",
",",
"endpoint",
"=",
"self",
".",
"endpoint",
",",
"other_p... | 48 | 12.142857 |
def _decrypt(private_key, ciphertext, padding):
"""
Decrypts RSA ciphertext using a private key
:param private_key:
A PrivateKey object
:param ciphertext:
The ciphertext - a byte string
:param padding:
The padding mode to use, specified as a kSecPadding*Key value
:rai... | [
"def",
"_decrypt",
"(",
"private_key",
",",
"ciphertext",
",",
"padding",
")",
":",
"if",
"not",
"isinstance",
"(",
"private_key",
",",
"PrivateKey",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n private_key must be an instance of the P... | 26.95 | 20.75 |
def do_set(parser, token):
'''Calls an arbitrary method on an object.'''
code = token.contents
firstspace = code.find(' ')
if firstspace >= 0:
code = code[firstspace+1:]
return Setter(code) | [
"def",
"do_set",
"(",
"parser",
",",
"token",
")",
":",
"code",
"=",
"token",
".",
"contents",
"firstspace",
"=",
"code",
".",
"find",
"(",
"' '",
")",
"if",
"firstspace",
">=",
"0",
":",
"code",
"=",
"code",
"[",
"firstspace",
"+",
"1",
":",
"]",
... | 28.142857 | 13.857143 |
def _mine_flush(self, load, skip_verify=False):
'''
Allow the minion to delete all of its own mine contents
'''
if not skip_verify and 'id' not in load:
return False
if self.opts.get('minion_data_cache', False) or self.opts.get('enforce_mine_cache', False):
... | [
"def",
"_mine_flush",
"(",
"self",
",",
"load",
",",
"skip_verify",
"=",
"False",
")",
":",
"if",
"not",
"skip_verify",
"and",
"'id'",
"not",
"in",
"load",
":",
"return",
"False",
"if",
"self",
".",
"opts",
".",
"get",
"(",
"'minion_data_cache'",
",",
... | 44.333333 | 25.444444 |
def get_syn_ids_by_lemma(self, lemma):
"""Returns a list of synset IDs based on a lemma"""
if not isinstance(lemma,unicode):
lemma = unicode(lemma,'utf-8')
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.de... | [
"def",
"get_syn_ids_by_lemma",
"(",
"self",
",",
"lemma",
")",
":",
"if",
"not",
"isinstance",
"(",
"lemma",
",",
"unicode",
")",
":",
"lemma",
"=",
"unicode",
"(",
"lemma",
",",
"'utf-8'",
")",
"http",
",",
"resp",
",",
"content",
"=",
"self",
".",
... | 30.861538 | 20.661538 |
def get(self, ring, angle):
"""Get RGB color tuple of color at index pixel"""
pixel = self.angleToPixel(angle, ring)
return self._get_base(pixel) | [
"def",
"get",
"(",
"self",
",",
"ring",
",",
"angle",
")",
":",
"pixel",
"=",
"self",
".",
"angleToPixel",
"(",
"angle",
",",
"ring",
")",
"return",
"self",
".",
"_get_base",
"(",
"pixel",
")"
] | 41.5 | 5.75 |
def _get_function_inputs(f, src_kwargs):
"""Filters inputs to be compatible with function `f`'s signature.
Args:
f: Function according to whose input signature we filter arguments.
src_kwargs: Keyword arguments to filter according to `f`.
Returns:
kwargs: Dict of key-value pairs in `src_kwargs` whic... | [
"def",
"_get_function_inputs",
"(",
"f",
",",
"src_kwargs",
")",
":",
"if",
"hasattr",
"(",
"f",
",",
"\"_func\"",
")",
":",
"# functions returned by tf.make_template",
"f",
"=",
"f",
".",
"_func",
"# pylint: disable=protected-access",
"try",
":",
"# getargspec was ... | 33.666667 | 21.952381 |
def exactly_n(l, n=1):
'''
Tests that exactly N items in an iterable are "truthy" (neither None,
False, nor 0).
'''
i = iter(l)
return all(any(i) for j in range(n)) and not any(i) | [
"def",
"exactly_n",
"(",
"l",
",",
"n",
"=",
"1",
")",
":",
"i",
"=",
"iter",
"(",
"l",
")",
"return",
"all",
"(",
"any",
"(",
"i",
")",
"for",
"j",
"in",
"range",
"(",
"n",
")",
")",
"and",
"not",
"any",
"(",
"i",
")"
] | 28.142857 | 25.571429 |
def check_directory(placeholders):
"""
Find out, and create if needed,
the directory in which the feed will be downloaded
"""
feed = placeholders.feed
args = feed.args
placeholders.directory = "This very directory" # wink, wink
placeholders.fullpath = os.path.join(
placeholders.... | [
"def",
"check_directory",
"(",
"placeholders",
")",
":",
"feed",
"=",
"placeholders",
".",
"feed",
"args",
"=",
"feed",
".",
"args",
"placeholders",
".",
"directory",
"=",
"\"This very directory\"",
"# wink, wink",
"placeholders",
".",
"fullpath",
"=",
"os",
"."... | 38.34375 | 11.09375 |
def _auth(self, load):
'''
Authenticate the client, use the sent public key to encrypt the AES key
which was generated at start up.
This method fires an event over the master event manager. The event is
tagged "auth" and returns a dict with information about the auth
eve... | [
"def",
"_auth",
"(",
"self",
",",
"load",
")",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"verify",
".",
"valid_id",
"(",
"self",
".",
"opts",
",",
"load",
"[",
"'id'",
"]",
")",
":",
"log",
".",
"info",
"(",
"'Authentication request from invalid id ... | 48.016807 | 20.072829 |
def disable_alarm_actions(self, alarm_names):
"""
Disables actions for the specified alarms.
:type alarms: list
:param alarms: List of alarm names.
"""
params = {}
self.build_list_params(params, alarm_names, 'AlarmNames.member.%s')
return self.get_status(... | [
"def",
"disable_alarm_actions",
"(",
"self",
",",
"alarm_names",
")",
":",
"params",
"=",
"{",
"}",
"self",
".",
"build_list_params",
"(",
"params",
",",
"alarm_names",
",",
"'AlarmNames.member.%s'",
")",
"return",
"self",
".",
"get_status",
"(",
"'DisableAlarmA... | 34.1 | 14.9 |
def config(data_folder=settings.data_folder,
logs_folder=settings.logs_folder,
imgs_folder=settings.imgs_folder,
cache_folder=settings.cache_folder,
use_cache=settings.use_cache,
log_file=settings.log_file,
log_console=settings.log_console,
lo... | [
"def",
"config",
"(",
"data_folder",
"=",
"settings",
".",
"data_folder",
",",
"logs_folder",
"=",
"settings",
".",
"logs_folder",
",",
"imgs_folder",
"=",
"settings",
".",
"imgs_folder",
",",
"cache_folder",
"=",
"settings",
".",
"cache_folder",
",",
"use_cache... | 38.652632 | 13.094737 |
def get_col_row_tot_array_from_data_record_array(array): # TODO: max ToT
'''Convert raw data array to column, row, and ToT array.
Parameters
----------
array : numpy.array
Raw data array.
Returns
-------
Tuple of arrays.
'''
def get_col_row_tot_1_array_from_dat... | [
"def",
"get_col_row_tot_array_from_data_record_array",
"(",
"array",
")",
":",
"# TODO: max ToT\r",
"def",
"get_col_row_tot_1_array_from_data_record_array",
"(",
"value",
")",
":",
"return",
"np",
".",
"right_shift",
"(",
"np",
".",
"bitwise_and",
"(",
"value",
",",
"... | 60.344828 | 48.275862 |
def enumerate_all(vars, e, bn):
"""Return the sum of those entries in P(vars | e{others})
consistent with e, where P is the joint distribution represented
by bn, and e{others} means e restricted to bn's other variables
(the ones other than vars). Parents must precede children in vars."""
if not vars... | [
"def",
"enumerate_all",
"(",
"vars",
",",
"e",
",",
"bn",
")",
":",
"if",
"not",
"vars",
":",
"return",
"1.0",
"Y",
",",
"rest",
"=",
"vars",
"[",
"0",
"]",
",",
"vars",
"[",
"1",
":",
"]",
"Ynode",
"=",
"bn",
".",
"variable_node",
"(",
"Y",
... | 43.142857 | 17.857143 |
def transpose(self, trans, scale="C"):
""" Transpose the chord
:param int trans: Transpose key
:param str scale: key scale
:return:
"""
if not isinstance(trans, int):
raise TypeError("Expected integers, not {}".format(type(trans)))
self._root = transp... | [
"def",
"transpose",
"(",
"self",
",",
"trans",
",",
"scale",
"=",
"\"C\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"trans",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected integers, not {}\"",
".",
"format",
"(",
"type",
"(",
"trans",
")",... | 35.307692 | 13.769231 |
def get_board_information(self, query_params=None):
'''
Get all information for this board. Returns a dictionary of values.
'''
return self.fetch_json(
uri_path='/boards/' + self.id,
query_params=query_params or {}
) | [
"def",
"get_board_information",
"(",
"self",
",",
"query_params",
"=",
"None",
")",
":",
"return",
"self",
".",
"fetch_json",
"(",
"uri_path",
"=",
"'/boards/'",
"+",
"self",
".",
"id",
",",
"query_params",
"=",
"query_params",
"or",
"{",
"}",
")"
] | 34.125 | 18.625 |
def OnBackView(self, event):
"""Request to move backward in the history"""
self.historyIndex -= 1
try:
self.RestoreHistory(self.history[self.historyIndex])
except IndexError, err:
self.SetStatusText(_('No further history available')) | [
"def",
"OnBackView",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"historyIndex",
"-=",
"1",
"try",
":",
"self",
".",
"RestoreHistory",
"(",
"self",
".",
"history",
"[",
"self",
".",
"historyIndex",
"]",
")",
"except",
"IndexError",
",",
"err",
":... | 40.428571 | 15.428571 |
async def probe_message(self, _message, context):
"""Handle a probe message.
See :meth:`AbstractDeviceAdapter.probe`.
"""
client_id = context.user_data
await self.probe(client_id) | [
"async",
"def",
"probe_message",
"(",
"self",
",",
"_message",
",",
"context",
")",
":",
"client_id",
"=",
"context",
".",
"user_data",
"await",
"self",
".",
"probe",
"(",
"client_id",
")"
] | 26.75 | 13.125 |
def matchingTokens(self, tokenArray):
'''Returns a list of tokens in the tokenArray that match this WordTemplate (the
method self.matches(token) returns True). Returns an empty list if no matching
tokens appear in the input list.
Parameters
----------
... | [
"def",
"matchingTokens",
"(",
"self",
",",
"tokenArray",
")",
":",
"assert",
"isinstance",
"(",
"tokenArray",
",",
"list",
")",
",",
"\"tokenArray should be list \"",
"+",
"str",
"(",
"tokenArray",
")",
"matchingTok",
"=",
"[",
"]",
"for",
"i",
"in",
"range"... | 43.470588 | 20.411765 |
def df_quantile(df, nb=100):
"""Returns the nb quantiles for datas in a dataframe
"""
quantiles = np.linspace(0, 1., nb)
res = pd.DataFrame()
for q in quantiles:
res = res.append(df.quantile(q), ignore_index=True)
return res | [
"def",
"df_quantile",
"(",
"df",
",",
"nb",
"=",
"100",
")",
":",
"quantiles",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1.",
",",
"nb",
")",
"res",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"for",
"q",
"in",
"quantiles",
":",
"res",
"=",
"res",... | 31.125 | 11.5 |
def parse_error(self, response):
"Parse an error response"
error_code = response.split(' ')[0]
if error_code in self.EXCEPTION_CLASSES:
response = response[len(error_code) + 1:]
return self.EXCEPTION_CLASSES[error_code](response)
return ResponseError(response) | [
"def",
"parse_error",
"(",
"self",
",",
"response",
")",
":",
"error_code",
"=",
"response",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"if",
"error_code",
"in",
"self",
".",
"EXCEPTION_CLASSES",
":",
"response",
"=",
"response",
"[",
"len",
"(",
"e... | 44.285714 | 9.142857 |
def failure_data(self):
'''Returns the failing step's data that happened during this solid's execution, if any'''
for result in itertools.chain(
self.input_expectations, self.output_expectations, self.transforms
):
if result.event_type == DagsterEventType.STEP_FAILURE:
... | [
"def",
"failure_data",
"(",
"self",
")",
":",
"for",
"result",
"in",
"itertools",
".",
"chain",
"(",
"self",
".",
"input_expectations",
",",
"self",
".",
"output_expectations",
",",
"self",
".",
"transforms",
")",
":",
"if",
"result",
".",
"event_type",
"=... | 51.285714 | 25.285714 |
def strippen(function):
"Decorator. Strip excess whitespace from return value."
def wrapper(*args, **kwargs):
return strip_strings(function(*args, **kwargs))
return wrapper | [
"def",
"strippen",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"strip_strings",
"(",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"wrapper"
] | 37.6 | 16 |
def set_file_license_comment(self, doc, text):
"""
Raises OrderError if no package or file defined.
Raises SPDXValueError if text is not free form text.
Raises CardinalityError if more than one per file.
"""
if self.has_package(doc) and self.has_file(doc):
if ... | [
"def",
"set_file_license_comment",
"(",
"self",
",",
"doc",
",",
"text",
")",
":",
"if",
"self",
".",
"has_package",
"(",
"doc",
")",
"and",
"self",
".",
"has_file",
"(",
"doc",
")",
":",
"if",
"not",
"self",
".",
"file_license_comment_set",
":",
"self",... | 44.941176 | 16.470588 |
def technical_words_from_shadow_contents(shadow_contents):
"""Get a set of technical words from :shadow_contents:.
:shadow_contents: is an array of shadow contents, as returned by
spellcheckable_and_shadow_contents.
"""
technical_words = set()
for line in shadow_contents:
# "Fix up" the... | [
"def",
"technical_words_from_shadow_contents",
"(",
"shadow_contents",
")",
":",
"technical_words",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"shadow_contents",
":",
"# \"Fix up\" the shadow line by replacing zeros with spaces.",
"line",
"=",
"\"\"",
".",
"join",
"(",
... | 41.533333 | 17.933333 |
def is_empty(self):
"""
A group of modules is considered empty if it has no children or if
all its children are empty.
>>> from admin_tools.dashboard.modules import DashboardModule, LinkList
>>> mod = Group()
>>> mod.is_empty()
True
>>> mod.children.appen... | [
"def",
"is_empty",
"(",
"self",
")",
":",
"if",
"super",
"(",
"Group",
",",
"self",
")",
".",
"is_empty",
"(",
")",
":",
"return",
"True",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"not",
"child",
".",
"is_empty",
"(",
")",
":",
"... | 32.32 | 17.84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.