text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _build_connstr(host, port, bucket):
"""
Converts a 1.x host:port specification to a connection string
"""
hostlist = []
if isinstance(host, (tuple, list)):
for curhost in host:
if isinstance(curhost, (list, tuple)):
hostlist.append(_fmthost(*curhost))
... | [
"def",
"_build_connstr",
"(",
"host",
",",
"port",
",",
"bucket",
")",
":",
"hostlist",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"host",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"for",
"curhost",
"in",
"host",
":",
"if",
"isinstance",
"(",
"cu... | 31.733333 | 0.002041 |
def _getPayload(self, record):
"""
The data that will be sent to the RESTful API
"""
try:
# top level payload items
d = record.__dict__
pid = d.pop('process', 'nopid')
tid = d.pop('thread', 'notid')
payload = {
... | [
"def",
"_getPayload",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"# top level payload items",
"d",
"=",
"record",
".",
"__dict__",
"pid",
"=",
"d",
".",
"pop",
"(",
"'process'",
",",
"'nopid'",
")",
"tid",
"=",
"d",
".",
"pop",
"(",
"'thread'",
... | 29.869565 | 0.001409 |
def _issubclass_2(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass, a.k.a pytypes.issubtype.
"""
if is_Tuple(superclass):
return _issubclass_Tuple(subclass, superclass, bound_Generic, bound_typevar... | [
"def",
"_issubclass_2",
"(",
"subclass",
",",
"superclass",
",",
"bound_Generic",
",",
"bound_typevars",
",",
"bound_typevars_readonly",
",",
"follow_fwd_refs",
",",
"_recursion_check",
")",
":",
"if",
"is_Tuple",
"(",
"superclass",
")",
":",
"return",
"_issubclass_... | 55.973684 | 0.009704 |
def _pastore16(ins):
''' Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
Use '*' for indirect store on 1st operand.
'''
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
... | [
"def",
"_pastore16",
"(",
"ins",
")",
":",
"output",
"=",
"_paddr",
"(",
"ins",
".",
"quad",
"[",
"1",
"]",
")",
"value",
"=",
"ins",
".",
"quad",
"[",
"2",
"]",
"if",
"value",
"[",
"0",
"]",
"==",
"'*'",
":",
"value",
"=",
"value",
"[",
"1",... | 23.37931 | 0.001416 |
def reset(self):
"""Reset before re-using the cell for another graph."""
self._init_counter = -1
self._counter = -1
if hasattr(self, '_cells'):
for cell in self._cells:
cell.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_init_counter",
"=",
"-",
"1",
"self",
".",
"_counter",
"=",
"-",
"1",
"if",
"hasattr",
"(",
"self",
",",
"'_cells'",
")",
":",
"for",
"cell",
"in",
"self",
".",
"_cells",
":",
"cell",
".",
"re... | 33.571429 | 0.008299 |
def deserialize_condition(self, workflow, start_node):
"""
Reads the conditional statement from the given node.
workflow -- the workflow with which the concurrence is associated
start_node -- the xml structure (xml.dom.minidom.Node)
"""
# Collect all information.
... | [
"def",
"deserialize_condition",
"(",
"self",
",",
"workflow",
",",
"start_node",
")",
":",
"# Collect all information.",
"condition",
"=",
"None",
"spec_name",
"=",
"None",
"for",
"node",
"in",
"start_node",
".",
"childNodes",
":",
"if",
"node",
".",
"nodeType",... | 42.032258 | 0.0015 |
def setFilepath(self, filepath):
"""
Sets the filepath text for this widget to the inputed path.
:param filepath | <str>
"""
if not filepath:
self._filepathEdit.setText('')
return
if self.normalizePath():
fi... | [
"def",
"setFilepath",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"not",
"filepath",
":",
"self",
".",
"_filepathEdit",
".",
"setText",
"(",
"''",
")",
"return",
"if",
"self",
".",
"normalizePath",
"(",
")",
":",
"filepath",
"=",
"os",
".",
"path",
... | 32 | 0.011385 |
def draw_clusters(data, clusters, noise = [], marker_descr = '.', hide_axes = False, axes = None, display_result = True):
"""!
@brief Displays clusters for data in 2D or 3D.
@param[in] data (list): Points that are described by coordinates represented.
@param[in] clusters (list): Clusters that ... | [
"def",
"draw_clusters",
"(",
"data",
",",
"clusters",
",",
"noise",
"=",
"[",
"]",
",",
"marker_descr",
"=",
"'.'",
",",
"hide_axes",
"=",
"False",
",",
"axes",
"=",
"None",
",",
"display_result",
"=",
"True",
")",
":",
"# Get dimension\r",
"dimension",
... | 41.35 | 0.026925 |
def __parse_results(self,results):
"""
The resolve server responds with some basic HTML formatting, where the actual
results are listed as an HTML list. The regular expression RE_RESULT captures
each entry
"""
reslist = []
cursor = 0
match = RE_RESULTS.se... | [
"def",
"__parse_results",
"(",
"self",
",",
"results",
")",
":",
"reslist",
"=",
"[",
"]",
"cursor",
"=",
"0",
"match",
"=",
"RE_RESULTS",
".",
"search",
"(",
"results",
",",
"cursor",
")",
"while",
"match",
":",
"doc",
"=",
"{",
"}",
"doc",
"[",
"... | 39.055556 | 0.013889 |
def handle_notification(self, data):
"""Handle JSONRPC notification."""
if data.get('method') in self._callbacks:
self._callbacks.get(data.get('method'))(data.get('params')) | [
"def",
"handle_notification",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"'method'",
")",
"in",
"self",
".",
"_callbacks",
":",
"self",
".",
"_callbacks",
".",
"get",
"(",
"data",
".",
"get",
"(",
"'method'",
")",
")",
"(",
... | 49.5 | 0.00995 |
def read_namespaced_config_map(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_config_map # noqa: E501
read the specified ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True... | [
"def",
"read_namespaced_config_map",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return... | 55.56 | 0.001415 |
def check(self, batch_size):
"""Returns True if the logging frequency has been met."""
self.increment(batch_size)
return self.unit_count >= self.config["log_train_every"] | [
"def",
"check",
"(",
"self",
",",
"batch_size",
")",
":",
"self",
".",
"increment",
"(",
"batch_size",
")",
"return",
"self",
".",
"unit_count",
">=",
"self",
".",
"config",
"[",
"\"log_train_every\"",
"]"
] | 47.75 | 0.010309 |
def _read(filepath_or_buffer: FilePathOrBuffer, kwds):
"""Generic reader of line files."""
encoding = kwds.get('encoding', None)
if encoding is not None:
encoding = re.sub('_', '-', encoding).lower()
kwds['encoding'] = encoding
compression = kwds.get('compression', 'infer')
compress... | [
"def",
"_read",
"(",
"filepath_or_buffer",
":",
"FilePathOrBuffer",
",",
"kwds",
")",
":",
"encoding",
"=",
"kwds",
".",
"get",
"(",
"'encoding'",
",",
"None",
")",
"if",
"encoding",
"is",
"not",
"None",
":",
"encoding",
"=",
"re",
".",
"sub",
"(",
"'_... | 30.916667 | 0.000653 |
def sync_auth_groups():
"""
Syncs auth groups according to settings.AUTH_GROUPS
:return:
"""
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from django.db.models import Q
for data in settings.AUTH_GROUPS:
g1 = Group.objects.get_or_creat... | [
"def",
"sync_auth_groups",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"from",
"django",
".",
"contrib",
".",
"auth",
".",
"models",
"import",
"Group",
",",
"Permission",
"from",
"django",
".",
"db",
".",
"models",
"import",
"Q",
... | 32.217391 | 0.001311 |
def _init_colors(self):
"""Init the Curses color layout."""
# Set curses options
try:
if hasattr(curses, 'start_color'):
curses.start_color()
if hasattr(curses, 'use_default_colors'):
curses.use_default_colors()
except Exception as... | [
"def",
"_init_colors",
"(",
"self",
")",
":",
"# Set curses options",
"try",
":",
"if",
"hasattr",
"(",
"curses",
",",
"'start_color'",
")",
":",
"curses",
".",
"start_color",
"(",
")",
"if",
"hasattr",
"(",
"curses",
",",
"'use_default_colors'",
")",
":",
... | 41.947368 | 0.000409 |
def to_json(self, data, labels=None):
"""
Will return a dict with Google JSON structure for charts
The Google structure::
{
cols: [{id:<COL_NAME>, label:<LABEL FOR COL>, type: <COL TYPE>}, ...]
rows: [{c: [{v: <COL VALUE}, ...], .... | [
"def",
"to_json",
"(",
"self",
",",
"data",
",",
"labels",
"=",
"None",
")",
":",
"labels",
"=",
"labels",
"or",
"dict",
"(",
")",
"json_data",
"=",
"dict",
"(",
")",
"json_data",
"[",
"\"cols\"",
"]",
"=",
"[",
"]",
"# Create Structure to identify the g... | 40.040816 | 0.00199 |
def pklc_fovcatalog_objectinfo(
pklcdir,
fovcatalog,
fovcatalog_columns=[0,1,2,
6,7,
8,9,
10,11,
13,14,15,16,
17,18,19,
20,21],
... | [
"def",
"pklc_fovcatalog_objectinfo",
"(",
"pklcdir",
",",
"fovcatalog",
",",
"fovcatalog_columns",
"=",
"[",
"0",
",",
"1",
",",
"2",
",",
"6",
",",
"7",
",",
"8",
",",
"9",
",",
"10",
",",
"11",
",",
"13",
",",
"14",
",",
"15",
",",
"16",
",",
... | 34.978723 | 0.008577 |
def _get_run_breadcrumbs(cls, source_type, data_object, task_attempt):
"""Create a path for a given file, in such a way
that files end up being organized and browsable by run
"""
# We cannot generate the path unless connect to a TaskAttempt
# and a run
if not task_attempt... | [
"def",
"_get_run_breadcrumbs",
"(",
"cls",
",",
"source_type",
",",
"data_object",
",",
"task_attempt",
")",
":",
"# We cannot generate the path unless connect to a TaskAttempt",
"# and a run",
"if",
"not",
"task_attempt",
":",
"return",
"[",
"]",
"# If multiple tasks exist... | 33.2 | 0.001672 |
def _image_url(array, fmt='png', mode="data", quality=90, domain=None):
"""Create a data URL representing an image from a PIL.Image.
Args:
image: a numpy
mode: presently only supports "data" for data URL
Returns:
URL representing image
"""
supported_modes = ("data")
if mode not in supported_mo... | [
"def",
"_image_url",
"(",
"array",
",",
"fmt",
"=",
"'png'",
",",
"mode",
"=",
"\"data\"",
",",
"quality",
"=",
"90",
",",
"domain",
"=",
"None",
")",
":",
"supported_modes",
"=",
"(",
"\"data\"",
")",
"if",
"mode",
"not",
"in",
"supported_modes",
":",... | 34.777778 | 0.010886 |
def non_argument_modifiers(role='ARG1', only_connecting=True):
"""
Return a function that finds non-argument modifier dependencies.
Args:
role (str): the role that is assigned to the dependency
only_connecting (bool): if `True`, only return dependencies
that connect separate com... | [
"def",
"non_argument_modifiers",
"(",
"role",
"=",
"'ARG1'",
",",
"only_connecting",
"=",
"True",
")",
":",
"def",
"func",
"(",
"xmrs",
",",
"deps",
")",
":",
"edges",
"=",
"[",
"]",
"for",
"src",
"in",
"deps",
":",
"for",
"_",
",",
"tgt",
"in",
"d... | 36.053571 | 0.000482 |
def get_crystal_field_spin(self, coordination: str = "oct",
spin_config: str = "high"):
"""
Calculate the crystal field spin based on coordination and spin
configuration. Only works for transition metal species.
Args:
coordination (str): Only o... | [
"def",
"get_crystal_field_spin",
"(",
"self",
",",
"coordination",
":",
"str",
"=",
"\"oct\"",
",",
"spin_config",
":",
"str",
"=",
"\"high\"",
")",
":",
"if",
"coordination",
"not",
"in",
"(",
"\"oct\"",
",",
"\"tet\"",
")",
"or",
"spin_config",
"not",
"i... | 41.538462 | 0.001357 |
def _GetTimelineItems(client_id, file_path):
"""Gets timeline items for a given client id and path."""
items = []
for file_path, stat_entry, _ in _GetTimelineStatEntries(
client_id, file_path, with_history=True):
# It may be that for a given timestamp only hash entry is available, we're
# skippin... | [
"def",
"_GetTimelineItems",
"(",
"client_id",
",",
"file_path",
")",
":",
"items",
"=",
"[",
"]",
"for",
"file_path",
",",
"stat_entry",
",",
"_",
"in",
"_GetTimelineStatEntries",
"(",
"client_id",
",",
"file_path",
",",
"with_history",
"=",
"True",
")",
":"... | 31.4 | 0.015887 |
def store(bank, key, data, cachedir):
'''
Store information in a file.
'''
base = os.path.join(cachedir, os.path.normpath(bank))
try:
os.makedirs(base)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise SaltCacheError(
'The cache directory, {0}... | [
"def",
"store",
"(",
"bank",
",",
"key",
",",
"data",
",",
"cachedir",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cachedir",
",",
"os",
".",
"path",
".",
"normpath",
"(",
"bank",
")",
")",
"try",
":",
"os",
".",
"makedirs",
"(... | 33.068966 | 0.001013 |
def clone(self, fp):
"""Clone this generator with the exact same options."""
return self.__class__(fp,
self._mangle_from_,
None, # Use policy setting, which we've adjusted
policy=self.policy) | [
"def",
"clone",
"(",
"self",
",",
"fp",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"fp",
",",
"self",
".",
"_mangle_from_",
",",
"None",
",",
"# Use policy setting, which we've adjusted",
"policy",
"=",
"self",
".",
"policy",
")"
] | 48.666667 | 0.010101 |
def get_cors_options(appInstance, *dicts):
"""
Compute CORS options for an application by combining the DEFAULT_OPTIONS,
the app's configuration-specified options and any dictionaries passed. The
last specified option wins.
"""
options = DEFAULT_OPTIONS.copy()
options.update(get_app_kwarg_di... | [
"def",
"get_cors_options",
"(",
"appInstance",
",",
"*",
"dicts",
")",
":",
"options",
"=",
"DEFAULT_OPTIONS",
".",
"copy",
"(",
")",
"options",
".",
"update",
"(",
"get_app_kwarg_dict",
"(",
"appInstance",
")",
")",
"if",
"dicts",
":",
"for",
"d",
"in",
... | 33.153846 | 0.002257 |
def get_tree(self, tgt_env):
'''
Return a tree object for the specified environment
'''
if not self.env_is_exposed(tgt_env):
return None
tgt_ref = self.ref(tgt_env)
if tgt_ref is None:
return None
for ref_type in self.ref_types:
... | [
"def",
"get_tree",
"(",
"self",
",",
"tgt_env",
")",
":",
"if",
"not",
"self",
".",
"env_is_exposed",
"(",
"tgt_env",
")",
":",
"return",
"None",
"tgt_ref",
"=",
"self",
".",
"ref",
"(",
"tgt_env",
")",
"if",
"tgt_ref",
"is",
"None",
":",
"return",
"... | 29.444444 | 0.002436 |
def is_continuous(self):
"""Boolean denoting whether the data collection is continuous."""
if self._validated_a_period is True and \
len(self.values) == len(self.header.analysis_period.months_int):
return True
else:
return False | [
"def",
"is_continuous",
"(",
"self",
")",
":",
"if",
"self",
".",
"_validated_a_period",
"is",
"True",
"and",
"len",
"(",
"self",
".",
"values",
")",
"==",
"len",
"(",
"self",
".",
"header",
".",
"analysis_period",
".",
"months_int",
")",
":",
"return",
... | 40.857143 | 0.010274 |
async def rt_unsubscribe(self):
"""Unsubscribe to Tibber rt subscription."""
if self._subscription_id is None:
_LOGGER.error("Not subscribed.")
return
await self._tibber_control.sub_manager.unsubscribe(self._subscription_id) | [
"async",
"def",
"rt_unsubscribe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subscription_id",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Not subscribed.\"",
")",
"return",
"await",
"self",
".",
"_tibber_control",
".",
"sub_manager",
".",
"unsubscrib... | 44.5 | 0.011029 |
def get_SCAT(points, low_bound, high_bound, x_max, y_max):
"""
runs SCAT test and returns boolean
"""
# iterate through all relevant points and see if any of them fall outside of your SCAT box
SCAT = True
for point in points:
result = in_SCAT_box(point[0], point[1], low_bound, high_bound... | [
"def",
"get_SCAT",
"(",
"points",
",",
"low_bound",
",",
"high_bound",
",",
"x_max",
",",
"y_max",
")",
":",
"# iterate through all relevant points and see if any of them fall outside of your SCAT box",
"SCAT",
"=",
"True",
"for",
"point",
"in",
"points",
":",
"result",... | 35.916667 | 0.011312 |
def make_auth_regex_str(etal, initial_surname_author=None, surname_initial_author=None):
"""
Returns a regular expression to be used to identify groups of author names in a citation.
This method contains patterns for default authors, so no arguments are needed for the
most reliable form of m... | [
"def",
"make_auth_regex_str",
"(",
"etal",
",",
"initial_surname_author",
"=",
"None",
",",
"surname_initial_author",
"=",
"None",
")",
":",
"if",
"not",
"initial_surname_author",
":",
"# Standard author, with a maximum of 6 initials, and a surname.",
"# The Initials MUST be up... | 53.031447 | 0.013853 |
def set_viewup(self, vector):
""" sets camera viewup vector """
if isinstance(vector, np.ndarray):
if vector.ndim != 1:
vector = vector.ravel()
self.camera.SetViewUp(vector)
self._render() | [
"def",
"set_viewup",
"(",
"self",
",",
"vector",
")",
":",
"if",
"isinstance",
"(",
"vector",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"vector",
".",
"ndim",
"!=",
"1",
":",
"vector",
"=",
"vector",
".",
"ravel",
"(",
")",
"self",
".",
"camera",
... | 34.571429 | 0.008065 |
def rdl_decomposition_rev(T, norm='reversible', mu=None):
r"""Decomposition into left and right eigenvectors for reversible
transition matrices.
Parameters
----------
T : (M, M) ndarray
Transition matrix
norm: {'standard', 'reversible'}
standard: (L'R) = Id, L[:,0] is a probabil... | [
"def",
"rdl_decomposition_rev",
"(",
"T",
",",
"norm",
"=",
"'reversible'",
",",
"mu",
"=",
"None",
")",
":",
"if",
"mu",
"is",
"None",
":",
"mu",
"=",
"stationary_distribution",
"(",
"T",
")",
"\"\"\" symmetrize T \"\"\"",
"smu",
"=",
"np",
".",
"sqrt",
... | 32.139241 | 0.001911 |
def trapezoid_transit_residual(transitparams, times, mags, errs):
'''
This returns the residual between the modelmags and the actual mags.
Parameters
----------
transitparams : list of float
This contains the transiting planet trapezoid model::
transitparams = [transitperiod (... | [
"def",
"trapezoid_transit_residual",
"(",
"transitparams",
",",
"times",
",",
"mags",
",",
"errs",
")",
":",
"modelmags",
",",
"phase",
",",
"ptimes",
",",
"pmags",
",",
"perrs",
"=",
"(",
"trapezoid_transit_func",
"(",
"transitparams",
",",
"times",
",",
"m... | 32.72093 | 0.00069 |
def mean(self, *args, **kwargs):
"""
Compute mean of groups, excluding missing values.
Returns
-------
pandas.Series or pandas.DataFrame
%(see_also)s
Examples
--------
>>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2],
... 'B'... | [
"def",
"mean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_groupby_func",
"(",
"'mean'",
",",
"args",
",",
"kwargs",
",",
"[",
"'numeric_only'",
"]",
")",
"try",
":",
"return",
"self",
".",
"_cython_agg_genera... | 27.12963 | 0.001976 |
def gaps(args):
"""
%prog gaps agpfile
Print out the distribution of gapsizes. Option --merge allows merging of
adjacent gaps which is used by tidy().
"""
from jcvi.graphics.histogram import loghistogram
p = OptionParser(gaps.__doc__)
p.add_option("--merge", dest="merge", default=False... | [
"def",
"gaps",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"graphics",
".",
"histogram",
"import",
"loghistogram",
"p",
"=",
"OptionParser",
"(",
"gaps",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--merge\"",
",",
"dest",
"=",
"\"merge\"",
",",... | 31.575 | 0.001919 |
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
... | [
"def",
"mean",
"(",
"l",
",",
"ignore_nan",
"=",
"False",
",",
"empty",
"=",
"0",
")",
":",
"l",
"=",
"iter",
"(",
"l",
")",
"if",
"ignore_nan",
":",
"l",
"=",
"ifilterfalse",
"(",
"np",
".",
"isnan",
",",
"l",
")",
"try",
":",
"n",
"=",
"1",... | 21.947368 | 0.009195 |
def parse_enum_type_definition(lexer: Lexer) -> EnumTypeDefinitionNode:
"""UnionTypeDefinition"""
start = lexer.token
description = parse_description(lexer)
expect_keyword(lexer, "enum")
name = parse_name(lexer)
directives = parse_directives(lexer, True)
values = parse_enum_values_definition... | [
"def",
"parse_enum_type_definition",
"(",
"lexer",
":",
"Lexer",
")",
"->",
"EnumTypeDefinitionNode",
":",
"start",
"=",
"lexer",
".",
"token",
"description",
"=",
"parse_description",
"(",
"lexer",
")",
"expect_keyword",
"(",
"lexer",
",",
"\"enum\"",
")",
"nam... | 32.733333 | 0.00198 |
def generate_hooked_command(cmd_name, cmd_cls, hooks):
"""
Returns a generated subclass of ``cmd_cls`` that runs the pre- and
post-command hooks for that command before and after the ``cmd_cls.run``
method.
"""
def run(self, orig_run=cmd_cls.run):
self.run_command_hooks('pre_hooks')
... | [
"def",
"generate_hooked_command",
"(",
"cmd_name",
",",
"cmd_cls",
",",
"hooks",
")",
":",
"def",
"run",
"(",
"self",
",",
"orig_run",
"=",
"cmd_cls",
".",
"run",
")",
":",
"self",
".",
"run_command_hooks",
"(",
"'pre_hooks'",
")",
"orig_run",
"(",
"self",... | 36.9375 | 0.00165 |
def get_transcoder():
"""Return the path to a transcoder (ffmpeg or avconv) with MP3 support."""
transcoders = ['ffmpeg', 'avconv']
transcoder_details = {}
for transcoder in transcoders:
command_path = shutil.which(transcoder)
if command_path is None:
transcoder_details[transcoder] = 'Not installed.'
co... | [
"def",
"get_transcoder",
"(",
")",
":",
"transcoders",
"=",
"[",
"'ffmpeg'",
",",
"'avconv'",
"]",
"transcoder_details",
"=",
"{",
"}",
"for",
"transcoder",
"in",
"transcoders",
":",
"command_path",
"=",
"shutil",
".",
"which",
"(",
"transcoder",
")",
"if",
... | 32.807692 | 0.027335 |
def _createShapelet(self,coeff):
"""
returns a shapelet array out of the coefficients *a, up to order l
:param num_l: order of shapelets
:type num_l: int.
:param coeff: shapelet coefficients
:type coeff: floats
:returns: complex array
:raises: AttributeE... | [
"def",
"_createShapelet",
"(",
"self",
",",
"coeff",
")",
":",
"n_coeffs",
"=",
"len",
"(",
"coeff",
")",
"num_l",
"=",
"self",
".",
"_get_num_l",
"(",
"n_coeffs",
")",
"shapelets",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_l",
"+",
"1",
",",
"num_l",
... | 29.114286 | 0.018993 |
def _first_batch(sock_info, db, coll, query, ntoreturn,
slave_ok, codec_options, read_preference, cmd, listeners):
"""Simple query helper for retrieving a first (and possibly only) batch."""
query = _Query(
0, db, coll, 0, query, None, codec_options,
read_preference, ntoreturn, ... | [
"def",
"_first_batch",
"(",
"sock_info",
",",
"db",
",",
"coll",
",",
"query",
",",
"ntoreturn",
",",
"slave_ok",
",",
"codec_options",
",",
"read_preference",
",",
"cmd",
",",
"listeners",
")",
":",
"query",
"=",
"_Query",
"(",
"0",
",",
"db",
",",
"c... | 34.727273 | 0.000509 |
def vtableEqual(a, objectStart, b):
"""vtableEqual compares an unwritten vtable to a written vtable."""
N.enforce_number(objectStart, N.UOffsetTFlags)
if len(a) * N.VOffsetTFlags.bytewidth != len(b):
return False
for i, elem in enumerate(a):
x = encode.Get(packer.voffset, b, i * N.VOf... | [
"def",
"vtableEqual",
"(",
"a",
",",
"objectStart",
",",
"b",
")",
":",
"N",
".",
"enforce_number",
"(",
"objectStart",
",",
"N",
".",
"UOffsetTFlags",
")",
"if",
"len",
"(",
"a",
")",
"*",
"N",
".",
"VOffsetTFlags",
".",
"bytewidth",
"!=",
"len",
"(... | 29.052632 | 0.001754 |
def download_url(self, remote_path, **kwargs):
"""返回目标文件可用的下载地址
:param remote_path: 每一项代表需要下载的文件路径
:type remote_path: str list
"""
def get_url(dlink):
return self.session.get(dlink,
headers=BAIDUPAN_HEADERS,
... | [
"def",
"download_url",
"(",
"self",
",",
"remote_path",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"get_url",
"(",
"dlink",
")",
":",
"return",
"self",
".",
"session",
".",
"get",
"(",
"dlink",
",",
"headers",
"=",
"BAIDUPAN_HEADERS",
",",
"stream",
"="... | 35.235294 | 0.001625 |
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
... | [
"def",
"_get_files_to_lint",
"(",
"self",
",",
"external_directories",
")",
":",
"all_f",
"=",
"[",
"]",
"for",
"external_dir",
"in",
"external_directories",
":",
"all_f",
".",
"extend",
"(",
"_all_files_matching_ext",
"(",
"external_dir",
",",
"\"py\"",
")",
")... | 35.5 | 0.00211 |
def close_filenos(preserve):
""" Close unprotected file descriptors
Close all open file descriptors that are not in preserve.
If ulimit -nofile is "unlimited", all is defined filenos <= 4096,
else all is <= the output of resource.getrlimit().
:param preserve: set with protected files
:type pr... | [
"def",
"close_filenos",
"(",
"preserve",
")",
":",
"maxfd",
"=",
"resource",
".",
"getrlimit",
"(",
"resource",
".",
"RLIMIT_NOFILE",
")",
"[",
"1",
"]",
"if",
"maxfd",
"==",
"resource",
".",
"RLIM_INFINITY",
":",
"maxfd",
"=",
"4096",
"for",
"fileno",
"... | 32.24 | 0.001205 |
def calc_qma_v1(self):
"""Calculate the discharge responses of the different MA processes.
Required derived parameters:
|Nmb|
|MA_Order|
|MA_Coefs|
Required log sequence:
|LogIn|
Calculated flux sequence:
|QMA|
Examples:
Assume there are three response func... | [
"def",
"calc_qma_v1",
"(",
"self",
")",
":",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"log",
"=",
"self",
".",
"sequences",
".",
"logs",
".",
"fast... | 30.830508 | 0.000533 |
def _set_config(self, config=None):
"""Set this component's initial configuration"""
if not config:
config = {}
try:
# pprint(self.configschema)
self.config = self.componentmodel(config)
# self.log("Config schema:", lvl=critical)
# ppr... | [
"def",
"_set_config",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"if",
"not",
"config",
":",
"config",
"=",
"{",
"}",
"try",
":",
"# pprint(self.configschema)",
"self",
".",
"config",
"=",
"self",
".",
"componentmodel",
"(",
"config",
")",
"# sel... | 37.614035 | 0.000909 |
def start(self):
"""Start the sensor.
"""
if rospy.get_name() == '/unnamed':
raise ValueError('Weight sensor must be run inside a ros node!')
self._weight_subscriber = rospy.Subscriber('weight_sensor/weights', Float32MultiArray, self._weights_callback)
self._running =... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"rospy",
".",
"get_name",
"(",
")",
"==",
"'/unnamed'",
":",
"raise",
"ValueError",
"(",
"'Weight sensor must be run inside a ros node!'",
")",
"self",
".",
"_weight_subscriber",
"=",
"rospy",
".",
"Subscriber",
"(",
... | 45.571429 | 0.009231 |
def validate_service(self, request, uid):
"""Validates the specs values from request for the service uid. Returns
a non-translated message if the validation failed."""
result = get_record_value(request, uid, 'result')
if not result:
# No result set for this service, dismiss
... | [
"def",
"validate_service",
"(",
"self",
",",
"request",
",",
"uid",
")",
":",
"result",
"=",
"get_record_value",
"(",
"request",
",",
"uid",
",",
"'result'",
")",
"if",
"not",
"result",
":",
"# No result set for this service, dismiss",
"return",
"None",
"if",
... | 45.961538 | 0.001639 |
def _refresh_cache(self):
"""Populate self._thumbnails."""
self._thumbnails = {}
metadatas = self.metadata_backend.get_thumbnails(self.source_image.name)
for metadata in metadatas:
self._thumbnails[metadata.size] = Thumbnail(metadata=metadata, storage=self.storage) | [
"def",
"_refresh_cache",
"(",
"self",
")",
":",
"self",
".",
"_thumbnails",
"=",
"{",
"}",
"metadatas",
"=",
"self",
".",
"metadata_backend",
".",
"get_thumbnails",
"(",
"self",
".",
"source_image",
".",
"name",
")",
"for",
"metadata",
"in",
"metadatas",
"... | 50.666667 | 0.012945 |
def queryByPortSensor(portiaConfig, edgeId, port, sensor, last=False, params={ 'from': None, 'to': None, 'order': None, 'precision': 'ms', 'limit': None }):
"""Returns a pandas data frame with the portia select resultset"""
header = {'Accept': 'text/csv'}
if last == False:
endpoint = '/select/devi... | [
"def",
"queryByPortSensor",
"(",
"portiaConfig",
",",
"edgeId",
",",
"port",
",",
"sensor",
",",
"last",
"=",
"False",
",",
"params",
"=",
"{",
"'from'",
":",
"None",
",",
"'to'",
":",
"None",
",",
"'order'",
":",
"None",
",",
"'precision'",
":",
"'ms'... | 41.4 | 0.018886 |
def main():
"""Main function for :command:`fabulous-image`."""
import optparse
parser = optparse.OptionParser()
parser.add_option(
"-w", "--width", dest="width", type="int", default=None,
help=("Width of printed image in characters. Default: %default"))
(options, args) = parser.pars... | [
"def",
"main",
"(",
")",
":",
"import",
"optparse",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"\"-w\"",
",",
"\"--width\"",
",",
"dest",
"=",
"\"width\"",
",",
"type",
"=",
"\"int\"",
",",
"default",
"=",... | 39.636364 | 0.002242 |
def check_docstrings(show_diff=False, config=None, mods=None):
"""
Check docstrings in module match the README.md
"""
readme = parse_readme()
modules_readme = core_module_docstrings(config=config)
warned = False
if create_readme(readme) != create_readme(modules_readme):
for module i... | [
"def",
"check_docstrings",
"(",
"show_diff",
"=",
"False",
",",
"config",
"=",
"None",
",",
"mods",
"=",
"None",
")",
":",
"readme",
"=",
"parse_readme",
"(",
")",
"modules_readme",
"=",
"core_module_docstrings",
"(",
"config",
"=",
"config",
")",
"warned",
... | 36.395349 | 0.001867 |
def isstream(obj):
"""Detect if `obj` is a stream.
We consider anything a stream that has the methods
- ``close()``
and either set of the following
- ``read()``, ``readline()``, ``readlines()``
- ``write()``, ``writeline()``, ``writelines()``
:Arguments:
*obj*
stream or ... | [
"def",
"isstream",
"(",
"obj",
")",
":",
"signature_methods",
"=",
"(",
"\"close\"",
",",
")",
"alternative_methods",
"=",
"(",
"(",
"\"read\"",
",",
"\"readline\"",
",",
"\"readlines\"",
")",
",",
"(",
"\"write\"",
",",
"\"writeline\"",
",",
"\"writelines\"",... | 24.846154 | 0.000993 |
def run(self):
'''
Execute the salt-cloud command line
'''
# Parse shell arguments
self.parse_args()
salt_master_user = self.config.get('user')
if salt_master_user is None:
salt_master_user = salt.utils.user.get_user()
if not check_user(salt_... | [
"def",
"run",
"(",
"self",
")",
":",
"# Parse shell arguments",
"self",
".",
"parse_args",
"(",
")",
"salt_master_user",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'user'",
")",
"if",
"salt_master_user",
"is",
"None",
":",
"salt_master_user",
"=",
"salt",... | 40.803922 | 0.000603 |
def rainbow(
self, text=None, fore=None, back=None, style=None,
freq=0.1, offset=30, spread=3.0,
linemode=True, movefactor=2, rgb_mode=False):
""" Make rainbow gradient text.
Arguments:
text : Text to make gradient.
... | [
"def",
"rainbow",
"(",
"self",
",",
"text",
"=",
"None",
",",
"fore",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
",",
"freq",
"=",
"0.1",
",",
"offset",
"=",
"30",
",",
"spread",
"=",
"3.0",
",",
"linemode",
"=",
"True",
... | 38.274194 | 0.000822 |
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
self.main.console.shell.refresh.connect(self.refresh_plugin)
iconsize = 24
self.toolbar.setIconSize(QSize(iconsize, iconsize))
... | [
"def",
"register_plugin",
"(",
"self",
")",
":",
"self",
".",
"redirect_stdio",
".",
"connect",
"(",
"self",
".",
"main",
".",
"redirect_internalshell_stdio",
")",
"self",
".",
"main",
".",
"console",
".",
"shell",
".",
"refresh",
".",
"connect",
"(",
"sel... | 50.142857 | 0.008403 |
def apply(self, resource):
"""
:param resource: Image
:return: Image
"""
if isinstance(resource, Image.Image):
return getattr(self, '_' + self.method)(resource)
else:
raise ValueError('Unsupported resource format: %s' % str(type(resource))) | [
"def",
"apply",
"(",
"self",
",",
"resource",
")",
":",
"if",
"isinstance",
"(",
"resource",
",",
"Image",
".",
"Image",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"'_'",
"+",
"self",
".",
"method",
")",
"(",
"resource",
")",
"else",
":",
"ra... | 33.777778 | 0.009615 |
def _addLink(self, dirTree, dirID, dirSeq, dirPath, name):
""" Add tree reference and name. (Hardlink). """
logger.debug("Link %d-%d-%d '%s%s'", dirTree, dirID, dirSeq, dirPath, name)
# assert dirTree != 0, (dirTree, dirID, dirSeq, dirPath, name)
assert (dirTree, dirID, dirSeq) not in s... | [
"def",
"_addLink",
"(",
"self",
",",
"dirTree",
",",
"dirID",
",",
"dirSeq",
",",
"dirPath",
",",
"name",
")",
":",
"logger",
".",
"debug",
"(",
"\"Link %d-%d-%d '%s%s'\"",
",",
"dirTree",
",",
"dirID",
",",
"dirSeq",
",",
"dirPath",
",",
"name",
")",
... | 67.625 | 0.009124 |
def get_ndv_b(b):
"""Get NoData value for GDAL band.
If NoDataValue is not set in the band,
extract upper left and lower right pixel values.
Otherwise assume NoDataValue is 0.
Parameters
----------
b : GDALRasterBand object
This is the input band.
Returns
-------
b... | [
"def",
"get_ndv_b",
"(",
"b",
")",
":",
"b_ndv",
"=",
"b",
".",
"GetNoDataValue",
"(",
")",
"if",
"b_ndv",
"is",
"None",
":",
"#Check ul pixel for ndv",
"ns",
"=",
"b",
".",
"XSize",
"nl",
"=",
"b",
".",
"YSize",
"ul",
"=",
"float",
"(",
"b",
".",
... | 25.439024 | 0.012004 |
def calc_and_store_post_estimation_results(results_dict,
estimator):
"""
Calculates and stores post-estimation results that require the use of the
systematic utility transformation functions or the various derivative
functions. Note that this function is only v... | [
"def",
"calc_and_store_post_estimation_results",
"(",
"results_dict",
",",
"estimator",
")",
":",
"# Store the final log-likelihood",
"final_log_likelihood",
"=",
"-",
"1",
"*",
"results_dict",
"[",
"\"fun\"",
"]",
"results_dict",
"[",
"\"final_log_likelihood\"",
"]",
"="... | 37.326733 | 0.000258 |
def string_class(cls):
"""Define __unicode__ and __str__ methods on the given class in Python 2.
The given class must define a __str__ method returning a unicode string,
otherwise a TypeError is raised.
Under Python 3, the class is returned as is.
"""
if not PY3:
if '__str__' not in cls... | [
"def",
"string_class",
"(",
"cls",
")",
":",
"if",
"not",
"PY3",
":",
"if",
"'__str__'",
"not",
"in",
"cls",
".",
"__dict__",
":",
"raise",
"TypeError",
"(",
"'the given class has no __str__ method'",
")",
"cls",
".",
"__unicode__",
",",
"cls",
".",
"__strin... | 40 | 0.00188 |
def show_tracebacks(self):
""" Show tracebacks """
if self.broker.tracebacks:
for tb in self.broker.tracebacks.values():
# tb = "Traceback {0}".format(str(tb))
self.logit(str(tb), self.pid, self.user, "insights-run", logging.ERROR) | [
"def",
"show_tracebacks",
"(",
"self",
")",
":",
"if",
"self",
".",
"broker",
".",
"tracebacks",
":",
"for",
"tb",
"in",
"self",
".",
"broker",
".",
"tracebacks",
".",
"values",
"(",
")",
":",
"# tb = \"Traceback {0}\".format(str(tb))",
"self",
".",
"logit",... | 47.666667 | 0.010309 |
def generate_password_link(self):
""" Generates a link to reset password """
self.password_link = self.generate_hash(50)
now = datetime.datetime.utcnow()
self.password_link_expires = now + datetime.timedelta(hours=24) | [
"def",
"generate_password_link",
"(",
"self",
")",
":",
"self",
".",
"password_link",
"=",
"self",
".",
"generate_hash",
"(",
"50",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"self",
".",
"password_link_expires",
"=",
"now",
"+"... | 49 | 0.008032 |
def load(filters="*.*", text='Select a file, FACEFACE!', default_directory='default_directory'):
"""
Pops up a dialog for opening a single file. Returns a string path or None.
"""
# make sure the filters contains "*.*" as an option!
if not '*' in filters.split(';'): filters = filters + ";;All files ... | [
"def",
"load",
"(",
"filters",
"=",
"\"*.*\"",
",",
"text",
"=",
"'Select a file, FACEFACE!'",
",",
"default_directory",
"=",
"'default_directory'",
")",
":",
"# make sure the filters contains \"*.*\" as an option!",
"if",
"not",
"'*'",
"in",
"filters",
".",
"split",
... | 38.541667 | 0.018987 |
def disco(bytecode_version, co, timestamp, out=sys.stdout,
is_pypy=False, magic_int=None, source_size=None,
header=True, asm_format=False, show_bytes=False,
dup_lines=False):
"""
diassembles and deparses a given code block 'co'
"""
assert iscode(co)
show_module_header... | [
"def",
"disco",
"(",
"bytecode_version",
",",
"co",
",",
"timestamp",
",",
"out",
"=",
"sys",
".",
"stdout",
",",
"is_pypy",
"=",
"False",
",",
"magic_int",
"=",
"None",
",",
"source_size",
"=",
"None",
",",
"header",
"=",
"True",
",",
"asm_format",
"=... | 32.2 | 0.00201 |
def set(clear=False, **defaults):
""" Set default parameters for :class:`lsqfit.nonlinear_fit`.
Use to set default values for parameters: ``svdcut``,
``debug``, ``tol``, ``maxit``, and ``fitter``. Can also set
parameters specific to the fitter specified by the ``fitter``
argumen... | [
"def",
"set",
"(",
"clear",
"=",
"False",
",",
"*",
"*",
"defaults",
")",
":",
"old_defaults",
"=",
"dict",
"(",
"nonlinear_fit",
".",
"DEFAULTS",
")",
"if",
"clear",
":",
"nonlinear_fit",
".",
"DEFAULTS",
"=",
"{",
"}",
"for",
"k",
"in",
"defaults",
... | 39.238095 | 0.001184 |
def api_server(connection, server_class):
"""
Establishes an API Server on the supplied connection
Arguments:
- connection (xbahn.connection.Connection)
- server_class (xbahn.api.Server)
Returns:
- server_class: server instance
"""
# run api server on connection
re... | [
"def",
"api_server",
"(",
"connection",
",",
"server_class",
")",
":",
"# run api server on connection",
"return",
"server_class",
"(",
"link",
"=",
"xbahn",
".",
"connection",
".",
"link",
".",
"Link",
"(",
"# use the connection to receive messages",
"receive",
"=",
... | 26.47619 | 0.001736 |
def ycoord(self):
"""The y coordinate :class:`xarray.Variable`"""
v = next(self.raw_data.psy.iter_base_variables)
return self.decoder.get_y(v, coords=self.data.coords) | [
"def",
"ycoord",
"(",
"self",
")",
":",
"v",
"=",
"next",
"(",
"self",
".",
"raw_data",
".",
"psy",
".",
"iter_base_variables",
")",
"return",
"self",
".",
"decoder",
".",
"get_y",
"(",
"v",
",",
"coords",
"=",
"self",
".",
"data",
".",
"coords",
"... | 47 | 0.010471 |
def main(argv=None):
"""
Command line entry point
"""
if not argv:
argv = sys.argv[1:]
parser = argparse.ArgumentParser(description=_HELP_TEXT)
parser.add_argument('input', nargs='?', default=None)
parser.add_argument('output', nargs='?', default=None)
parser.add_argument('--ver... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"not",
"argv",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"_HELP_TEXT",
")",
"parser",
".",
"add_argume... | 30.133333 | 0.001072 |
def stopLongPolling(self):
'''
Stop LongPolling thread
:return: none
'''
if(self.longPollThread.isAlive()):
self._stopLongPolling.set()
self.log.debug("set stop longpolling flag")
else:
self.log.warn("LongPolling thread already stopped")
return | [
"def",
"stopLongPolling",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"longPollThread",
".",
"isAlive",
"(",
")",
")",
":",
"self",
".",
"_stopLongPolling",
".",
"set",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"set stop longpolling flag\"",
... | 21.583333 | 0.051852 |
def remote_log_block_status_send(self, target_system, target_component, seqno, status, force_mavlink1=False):
'''
Send Status of each log block that autopilot board might have sent
target_system : System ID (uint8_t)
target_component ... | [
"def",
"remote_log_block_status_send",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"seqno",
",",
"status",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"remote_log_block_status_encode",
"(",
... | 60.545455 | 0.008876 |
def gain(self, gain_db=0.0, normalize=True, limiter=False, balance=None):
'''Apply amplification or attenuation to the audio signal.
Parameters
----------
gain_db : float, default=0.0
Gain adjustment in decibels (dB).
normalize : bool, default=True
If Tru... | [
"def",
"gain",
"(",
"self",
",",
"gain_db",
"=",
"0.0",
",",
"normalize",
"=",
"True",
",",
"limiter",
"=",
"False",
",",
"balance",
"=",
"None",
")",
":",
"if",
"not",
"is_number",
"(",
"gain_db",
")",
":",
"raise",
"ValueError",
"(",
"\"gain_db must ... | 36.288136 | 0.00091 |
def _setup_constants(alphabet=NAMESPACE_CHARACTERS,
max_length=MAX_NAMESPACE_LENGTH,
batch_size=NAMESPACE_BATCH_SIZE):
"""Calculate derived constant values. Only useful for testing."""
global NAMESPACE_CHARACTERS
global MAX_NAMESPACE_LENGTH
# pylint: disable=global-var... | [
"def",
"_setup_constants",
"(",
"alphabet",
"=",
"NAMESPACE_CHARACTERS",
",",
"max_length",
"=",
"MAX_NAMESPACE_LENGTH",
",",
"batch_size",
"=",
"NAMESPACE_BATCH_SIZE",
")",
":",
"global",
"NAMESPACE_CHARACTERS",
"global",
"MAX_NAMESPACE_LENGTH",
"# pylint: disable=global-var... | 33.139535 | 0.02454 |
def accumulate_nested_doc(nested_path, expr=IDENTITY):
"""
:param nested_path: THE PATH USED TO EXTRACT THE NESTED RECORDS
:param expr: FUNCTION USED ON THE NESTED OBJECT TO GET SPECIFIC VALUE
:return: THE DE_TYPED NESTED OBJECT ARRAY
"""
name = literal_field(nested_path)
def output(doc):
... | [
"def",
"accumulate_nested_doc",
"(",
"nested_path",
",",
"expr",
"=",
"IDENTITY",
")",
":",
"name",
"=",
"literal_field",
"(",
"nested_path",
")",
"def",
"output",
"(",
"doc",
")",
":",
"acc",
"=",
"[",
"]",
"for",
"h",
"in",
"doc",
".",
"inner_hits",
... | 37.285714 | 0.002491 |
def _get_sizes_checksums(checksums_path):
"""Returns {URL: (size, checksum)}s stored within file."""
checksums = {}
for line in _read_file(checksums_path).split('\n'):
if not line:
continue
# URL might have spaces inside, but size and checksum will not.
url, size, checksum = line.rsplit(' ', 2)
... | [
"def",
"_get_sizes_checksums",
"(",
"checksums_path",
")",
":",
"checksums",
"=",
"{",
"}",
"for",
"line",
"in",
"_read_file",
"(",
"checksums_path",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"not",
"line",
":",
"continue",
"# URL might have spaces insi... | 37.2 | 0.015748 |
def yum_group_install(**kwargs):
""" instals a yum group """
for grp in list(kwargs['groups']):
log_green("installing %s ..." % grp)
if 'repo' in kwargs:
repo = kwargs['repo']
sudo("yum groupinstall -y --quiet "
"--enablerepo=%s '%s'" % (repo, grp))
... | [
"def",
"yum_group_install",
"(",
"*",
"*",
"kwargs",
")",
":",
"for",
"grp",
"in",
"list",
"(",
"kwargs",
"[",
"'groups'",
"]",
")",
":",
"log_green",
"(",
"\"installing %s ...\"",
"%",
"grp",
")",
"if",
"'repo'",
"in",
"kwargs",
":",
"repo",
"=",
"kwa... | 42.333333 | 0.001927 |
def rm_command(
ignore_missing,
star_silent,
recursive,
enable_globs,
endpoint_plus_path,
label,
submission_id,
dry_run,
deadline,
skip_activation_check,
notify,
meow,
heartbeat,
polling_interval,
timeout,
timeout_exit_code,
):
"""
Executor for `gl... | [
"def",
"rm_command",
"(",
"ignore_missing",
",",
"star_silent",
",",
"recursive",
",",
"enable_globs",
",",
"endpoint_plus_path",
",",
"label",
",",
"submission_id",
",",
"dry_run",
",",
"deadline",
",",
"skip_activation_check",
",",
"notify",
",",
"meow",
",",
... | 26.469136 | 0.001799 |
def reset_highlights(self):
"""
Remove red outlines from all buttons
"""
for dtype in ["specimens", "samples", "sites", "locations", "ages"]:
wind = self.FindWindowByName(dtype + '_btn')
wind.Unbind(wx.EVT_PAINT, handler=self.highlight_button)
self.Refresh... | [
"def",
"reset_highlights",
"(",
"self",
")",
":",
"for",
"dtype",
"in",
"[",
"\"specimens\"",
",",
"\"samples\"",
",",
"\"sites\"",
",",
"\"locations\"",
",",
"\"ages\"",
"]",
":",
"wind",
"=",
"self",
".",
"FindWindowByName",
"(",
"dtype",
"+",
"'_btn'",
... | 42.454545 | 0.008386 |
def wait_for_server(pbclient=None, dc_id=None, serverid=None,
indicator='state', state='AVAILABLE', timeout=300):
'''
wait for a server/VM to reach a defined state for a specified time
indicator := {state|vmstate} specifies if server or VM stat is tested
state specifies the status th... | [
"def",
"wait_for_server",
"(",
"pbclient",
"=",
"None",
",",
"dc_id",
"=",
"None",
",",
"serverid",
"=",
"None",
",",
"indicator",
"=",
"'state'",
",",
"state",
"=",
"'AVAILABLE'",
",",
"timeout",
"=",
"300",
")",
":",
"if",
"pbclient",
"is",
"None",
"... | 39.172414 | 0.000859 |
def _eager_tasklet(tasklet):
"""Decorator to turn tasklet to run eagerly."""
@utils.wrapping(tasklet)
def eager_wrapper(*args, **kwds):
fut = tasklet(*args, **kwds)
_run_until_rpc()
return fut
return eager_wrapper | [
"def",
"_eager_tasklet",
"(",
"tasklet",
")",
":",
"@",
"utils",
".",
"wrapping",
"(",
"tasklet",
")",
"def",
"eager_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"fut",
"=",
"tasklet",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
... | 22.6 | 0.021277 |
def deprecated(text="", eos=""):
"""
Args:
text, eos: same as :func:`log_deprecated`.
Returns:
a decorator which deprecates the function.
Example:
.. code-block:: python
@deprecated("Explanation of what to do instead.", "2017-11-4")
def foo(...):
... | [
"def",
"deprecated",
"(",
"text",
"=",
"\"\"",
",",
"eos",
"=",
"\"\"",
")",
":",
"def",
"get_location",
"(",
")",
":",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"if",
"frame",
":",
"callstack",
"=",
"inspect",
".",
... | 27.6 | 0.001 |
def _importGenomeObjects(gtfFilePath, chroSet, genome, batchSize, verbose = 0) :
"""verbose must be an int [0, 4] for various levels of verbosity"""
class Store(object) :
def __init__(self, conf) :
self.conf = conf
self.chromosomes = {}
self.gen... | [
"def",
"_importGenomeObjects",
"(",
"gtfFilePath",
",",
"chroSet",
",",
"genome",
",",
"batchSize",
",",
"verbose",
"=",
"0",
")",
":",
"class",
"Store",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"conf",
")",
":",
"self",
".",
"conf... | 44.413223 | 0.017836 |
def get_mems(self, type):
"""Fetch all the memories of the supplied type"""
ret = ()
for m in self.mems:
if m.type == type:
ret += (m,)
return ret | [
"def",
"get_mems",
"(",
"self",
",",
"type",
")",
":",
"ret",
"=",
"(",
")",
"for",
"m",
"in",
"self",
".",
"mems",
":",
"if",
"m",
".",
"type",
"==",
"type",
":",
"ret",
"+=",
"(",
"m",
",",
")",
"return",
"ret"
] | 25 | 0.009662 |
def setColor( self, color ):
"""
Sets the color for this widget.
:param color | <QColor> || <str>
"""
self._color = QColor(color)
self.setAlternateColor(self._color.darker(110)) | [
"def",
"setColor",
"(",
"self",
",",
"color",
")",
":",
"self",
".",
"_color",
"=",
"QColor",
"(",
"color",
")",
"self",
".",
"setAlternateColor",
"(",
"self",
".",
"_color",
".",
"darker",
"(",
"110",
")",
")"
] | 29.875 | 0.020325 |
def _filter_dead_code(nodes: Iterable[ast.AST]) -> List[ast.AST]:
"""Return a list of body nodes, trimming out unreachable code (any
statements appearing after `break`, `continue`, and `return` nodes)."""
new_nodes: List[ast.AST] = []
for node in nodes:
if isinstance(node, (ast.Break, ast.Contin... | [
"def",
"_filter_dead_code",
"(",
"nodes",
":",
"Iterable",
"[",
"ast",
".",
"AST",
"]",
")",
"->",
"List",
"[",
"ast",
".",
"AST",
"]",
":",
"new_nodes",
":",
"List",
"[",
"ast",
".",
"AST",
"]",
"=",
"[",
"]",
"for",
"node",
"in",
"nodes",
":",
... | 43.3 | 0.002262 |
def out_of_bag_samples(self):
"""
Returns the out-of-bag samples list, inside a wrapper to keep track
of modifications.
"""
#TODO:replace with more a generic pass-through wrapper?
class O(object):
def __init__(self, tree):
self.tree = tree
... | [
"def",
"out_of_bag_samples",
"(",
"self",
")",
":",
"#TODO:replace with more a generic pass-through wrapper?",
"class",
"O",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"tree",
")",
":",
"self",
".",
"tree",
"=",
"tree",
"def",
"__len__",
"("... | 39.095238 | 0.009512 |
def solar_noon_utc(self, date, longitude):
"""Calculate solar noon time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
... | [
"def",
"solar_noon_utc",
"(",
"self",
",",
"date",
",",
"longitude",
")",
":",
"jc",
"=",
"self",
".",
"_jday_to_jcentury",
"(",
"self",
".",
"_julianday",
"(",
"date",
")",
")",
"eqtime",
"=",
"self",
".",
"_eq_of_time",
"(",
"jc",
")",
"timeUTC",
"="... | 29.555556 | 0.002183 |
def directory_cloud(self,directory,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000):
'''Creates a word cloud using files from a directory.
The color of the words correspond to the amount of documents the word occurs in.'''
worddict = assign_fonts(tuplecount(re... | [
"def",
"directory_cloud",
"(",
"self",
",",
"directory",
",",
"max_text_size",
"=",
"72",
",",
"min_text_size",
"=",
"12",
",",
"expand_width",
"=",
"50",
",",
"expand_height",
"=",
"50",
",",
"max_count",
"=",
"100000",
")",
":",
"worddict",
"=",
"assign_... | 61.384615 | 0.021592 |
def prettymetrics(self) -> str:
"""
Pretty printing for metrics
"""
rendered = ["{}: {}".format(*m) for m in self.metrics()]
return "\n ".join(rendered) | [
"def",
"prettymetrics",
"(",
"self",
")",
"->",
"str",
":",
"rendered",
"=",
"[",
"\"{}: {}\"",
".",
"format",
"(",
"*",
"m",
")",
"for",
"m",
"in",
"self",
".",
"metrics",
"(",
")",
"]",
"return",
"\"\\n \"",
".",
"join",
"(",
"rendered",
... | 33 | 0.009852 |
def nfa_complementation(nfa: dict) -> dict:
""" Returns a DFA reading the complemented language read by
input NFA.
Complement a nondeterministic automaton is possible
complementing the determinization of it.
The construction is effective, but it involves an exponential
blow-up, since determiniz... | [
"def",
"nfa_complementation",
"(",
"nfa",
":",
"dict",
")",
"->",
"dict",
":",
"determinized_nfa",
"=",
"nfa_determinization",
"(",
"nfa",
")",
"return",
"DFA",
".",
"dfa_complementation",
"(",
"determinized_nfa",
")"
] | 38.875 | 0.00157 |
def _expand(self, row, consumed_position, passed):
"""Add the arguments `(args, kw)` to `_walk` to the todo list."""
self._todo.append((row, consumed_position, passed)) | [
"def",
"_expand",
"(",
"self",
",",
"row",
",",
"consumed_position",
",",
"passed",
")",
":",
"self",
".",
"_todo",
".",
"append",
"(",
"(",
"row",
",",
"consumed_position",
",",
"passed",
")",
")"
] | 60.666667 | 0.01087 |
def geocode(
self,
query,
bounds=None,
country=None,
language=None,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
):
"""
Return a location point by address.
:param str query: The address or query you wish to g... | [
"def",
"geocode",
"(",
"self",
",",
"query",
",",
"bounds",
"=",
"None",
",",
"country",
"=",
"None",
",",
"language",
"=",
"None",
",",
"exactly_one",
"=",
"True",
",",
"timeout",
"=",
"DEFAULT_SENTINEL",
",",
")",
":",
"params",
"=",
"{",
"'key'",
... | 40.795699 | 0.001287 |
async def _connect(self, hostname, port, reconnect=False, password=None, encoding=pydle.protocol.DEFAULT_ENCODING, channels=[], tls=False, tls_verify=False, source_address=None):
""" Connect to IRC server, optionally over TLS. """
self.password = password
# Create connection if we can't reuse i... | [
"async",
"def",
"_connect",
"(",
"self",
",",
"hostname",
",",
"port",
",",
"reconnect",
"=",
"False",
",",
"password",
"=",
"None",
",",
"encoding",
"=",
"pydle",
".",
"protocol",
".",
"DEFAULT_ENCODING",
",",
"channels",
"=",
"[",
"]",
",",
"tls",
"=... | 48.722222 | 0.010067 |
def backbone_wu(CIJ, avgdeg):
'''
The network backbone contains the dominant connections in the network
and may be used to aid network visualization. This function computes
the backbone of a given weighted and undirected connection matrix CIJ,
using a minimum-spanning-tree based algorithm.
Para... | [
"def",
"backbone_wu",
"(",
"CIJ",
",",
"avgdeg",
")",
":",
"n",
"=",
"len",
"(",
"CIJ",
")",
"if",
"not",
"np",
".",
"all",
"(",
"CIJ",
"==",
"CIJ",
".",
"T",
")",
":",
"raise",
"BCTParamError",
"(",
"'backbone_wu can only be computed for undirected '",
... | 33.727273 | 0.001122 |
def update_fax(self, fax_id, payload_fax_modification, **kwargs): # noqa: E501
"""Modify fax record # noqa: E501
You can modify a fax record's comment or mark it as read # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please... | [
"def",
"update_fax",
"(",
"self",
",",
"fax_id",
",",
"payload_fax_modification",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
... | 47.409091 | 0.00188 |
def lucene_version(core_name=None):
'''
Gets the lucene version that solr is using. If you are running a multi-core
setup you should specify a core name since all the cores run under the same
servlet container, they will all have the same version.
core_name : str (None)
The name of the solr... | [
"def",
"lucene_version",
"(",
"core_name",
"=",
"None",
")",
":",
"ret",
"=",
"_get_return_dict",
"(",
")",
"# do we want to check for all the cores?",
"if",
"_get_none_or_value",
"(",
"core_name",
")",
"is",
"None",
"and",
"_check_for_cores",
"(",
")",
":",
"succ... | 38.658537 | 0.001231 |
def get_log_metric(
self,
metric_name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets a logs-based metric.
Example:
>>> from google.cloud import logging_v2
... | [
"def",
"get_log_metric",
"(",
"self",
",",
"metric_name",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"... | 38.555556 | 0.001756 |
def main(argv=None):
'''Command line options.'''
program_name = os.path.basename(sys.argv[0])
program_version = version
program_build_date = "%s" % __updated__
program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
#program_usage = '''usage: spam two eggs''' # option... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"program_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"program_version",
"=",
"version",
"program_build_date",
"=",
"\"%s\"",
"%",
"__updated__",
"program_... | 60.900415 | 0.010726 |
def from_mask(cls, mask):
"""Setup a regular-grid from a mask, wehere the center of every unmasked pixel gives the grid's (y,x) \
arc-second coordinates.
Parameters
-----------
mask : Mask
The mask whose unmasked pixels are used to setup the regular-pixel grid.
... | [
"def",
"from_mask",
"(",
"cls",
",",
"mask",
")",
":",
"array",
"=",
"grid_util",
".",
"regular_grid_1d_masked_from_mask_pixel_scales_and_origin",
"(",
"mask",
"=",
"mask",
",",
"pixel_scales",
"=",
"mask",
".",
"pixel_scales",
")",
"return",
"cls",
"(",
"array"... | 46.333333 | 0.010582 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.