text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def plugged_usbs(multiple=True) -> map or dict:
"""
Gets the plugged-in USB Flash drives (pen-drives).
If multiple is true, it returns a map, and a dict otherwise.
If multiple is false, this method will raise a :class:`.NoUSBFound` if no USB is found.
"""
class FindPenDrives(object):
... | [
"def",
"plugged_usbs",
"(",
"multiple",
"=",
"True",
")",
"->",
"map",
"or",
"dict",
":",
"class",
"FindPenDrives",
"(",
"object",
")",
":",
"# From https://github.com/pyusb/pyusb/blob/master/docs/tutorial.rst",
"def",
"__init__",
"(",
"self",
",",
"class_",
")",
... | 38.224138 | 0.002199 |
def get_sdk_download_stream(self, rest_api_id,
api_gateway_stage=DEFAULT_STAGE_NAME,
sdk_type='javascript'):
# type: (str, str, str) -> file
"""Generate an SDK for a given SDK.
Returns a file like object that streams a zip contents... | [
"def",
"get_sdk_download_stream",
"(",
"self",
",",
"rest_api_id",
",",
"api_gateway_stage",
"=",
"DEFAULT_STAGE_NAME",
",",
"sdk_type",
"=",
"'javascript'",
")",
":",
"# type: (str, str, str) -> file",
"response",
"=",
"self",
".",
"_client",
"(",
"'apigateway'",
")"... | 38 | 0.009174 |
def update(self):
"""Update disk I/O stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Grab the stat using the psutil disk_io_counters method
... | [
"def",
"update",
"(",
"self",
")",
":",
"# Init new stats",
"stats",
"=",
"self",
".",
"get_init_value",
"(",
")",
"if",
"self",
".",
"input_method",
"==",
"'local'",
":",
"# Update stats using the standard system lib",
"# Grab the stat using the psutil disk_io_counters m... | 44.392405 | 0.001116 |
def load_device(self, serial=None):
"""Creates an AndroidDevice for the given serial number.
If no serial is given, it will read from the ANDROID_SERIAL
environmental variable. If the environmental variable is not set, then
it will read from 'adb devices' if there is only one.
"... | [
"def",
"load_device",
"(",
"self",
",",
"serial",
"=",
"None",
")",
":",
"serials",
"=",
"android_device",
".",
"list_adb_devices",
"(",
")",
"if",
"not",
"serials",
":",
"raise",
"Error",
"(",
"'No adb device found!'",
")",
"# No serial provided, try to pick up t... | 43.153846 | 0.001744 |
def _add_text_ngrams(self, witness, minimum, maximum):
"""Adds n-gram data from `witness` to the data store.
:param witness: witness to get n-grams from
:type witness: `WitnessText`
:param minimum: minimum n-gram size
:type minimum: `int`
:param maximum: maximum n-gram s... | [
"def",
"_add_text_ngrams",
"(",
"self",
",",
"witness",
",",
"minimum",
",",
"maximum",
")",
":",
"text_id",
"=",
"self",
".",
"_get_text_id",
"(",
"witness",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"'Adding n-grams ({} <= n <= {}) for {}'",
".",
"forma... | 42.136364 | 0.00211 |
def filter(self, relation_id=None, duedate__lt=None, duedate__gte=None,
**kwargs):
"""
A common query would be duedate__lt=date(2015, 1, 1) to get all
Receivables that are due in 2014 and earlier.
"""
if relation_id is not None:
# Filter by (relation) a... | [
"def",
"filter",
"(",
"self",
",",
"relation_id",
"=",
"None",
",",
"duedate__lt",
"=",
"None",
",",
"duedate__gte",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"relation_id",
"is",
"not",
"None",
":",
"# Filter by (relation) account_id. There doesn'... | 43.896552 | 0.002306 |
def random_draw(self, size=None):
"""Draw random samples of the hyperparameters.
Parameters
----------
size : None, int or array-like, optional
The number/shape of samples to draw. If None, only one sample is
returned. Default is None.
"""
... | [
"def",
"random_draw",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"return",
"scipy",
".",
"asarray",
"(",
"[",
"scipy",
".",
"stats",
".",
"lognorm",
".",
"rvs",
"(",
"s",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"em",
",",
"size",
"=",
"s... | 42.9 | 0.009132 |
def _get_mapper_spec(self):
"""Converts self to model.MapperSpec."""
# pylint: disable=g-import-not-at-top
from mapreduce import model
return model.MapperSpec(
handler_spec=util._obj_to_path(self.mapper),
input_reader_spec=util._obj_to_path(self.input_reader_cls),
params=self._g... | [
"def",
"_get_mapper_spec",
"(",
"self",
")",
":",
"# pylint: disable=g-import-not-at-top",
"from",
"mapreduce",
"import",
"model",
"return",
"model",
".",
"MapperSpec",
"(",
"handler_spec",
"=",
"util",
".",
"_obj_to_path",
"(",
"self",
".",
"mapper",
")",
",",
... | 39.727273 | 0.002237 |
def dump_ckan(m):
"""Create a groups and organization file"""
doc = MetapackDoc(cache=m.cache)
doc.new_section('Groups', 'Title Description Id Image_url'.split())
doc.new_section('Organizations', 'Title Description Id Image_url'.split())
c = RemoteCKAN(m.ckan_url, apikey=m.api_key)
for... | [
"def",
"dump_ckan",
"(",
"m",
")",
":",
"doc",
"=",
"MetapackDoc",
"(",
"cache",
"=",
"m",
".",
"cache",
")",
"doc",
".",
"new_section",
"(",
"'Groups'",
",",
"'Title Description Id Image_url'",
".",
"split",
"(",
")",
")",
"doc",
".",
"new_section",
"("... | 32.642857 | 0.002128 |
def forwards(self, orm):
"Write your forwards methods here."
samples = orm['samples.Sample'].objects.select_related('batch__project')
for sample in samples:
sample.project = sample.batch.project
sample.save() | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"samples",
"=",
"orm",
"[",
"'samples.Sample'",
"]",
".",
"objects",
".",
"select_related",
"(",
"'batch__project'",
")",
"for",
"sample",
"in",
"samples",
":",
"sample",
".",
"project",
"=",
"sample",
... | 41.833333 | 0.011719 |
def bearing_to_nearest_place(feature, parent):
"""If the impact layer has a distance field, it will return the bearing
to the nearest place in degrees.
e.g. bearing_to_nearest_place() -> 280
"""
_ = feature, parent # NOQA
layer = exposure_summary_layer()
if not layer:
return None
... | [
"def",
"bearing_to_nearest_place",
"(",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"layer",
"=",
"exposure_summary_layer",
"(",
")",
"if",
"not",
"layer",
":",
"return",
"None",
"index",
"=",
"layer",
".",
"fields",
"... | 25.473684 | 0.001992 |
def _check_values(self, value):
"""
Given a list of possible PK values, returns a QuerySet of the
corresponding objects. Raises a ValidationError if a given value is
invalid (not a valid PK, not in the queryset, etc.)
"""
key = self.to_field_name or 'pk'
# dedupli... | [
"def",
"_check_values",
"(",
"self",
",",
"value",
")",
":",
"key",
"=",
"self",
".",
"to_field_name",
"or",
"'pk'",
"# deduplicate given values to avoid creating many querysets or",
"# requiring the database backend deduplicate efficiently.",
"try",
":",
"value",
"=",
"fro... | 39.333333 | 0.001378 |
def ROC_AUC_analysis(adata,groupby,group=None, n_genes=100):
"""Calculate correlation matrix.
Calculate a correlation matrix for genes strored in sample annotation using rank_genes_groups.py
Parameters
----------
adata : :class:`~anndata.AnnData`
Ann... | [
"def",
"ROC_AUC_analysis",
"(",
"adata",
",",
"groupby",
",",
"group",
"=",
"None",
",",
"n_genes",
"=",
"100",
")",
":",
"if",
"group",
"is",
"None",
":",
"pass",
"# TODO: Loop over all groups instead of just taking one.",
"# Assume group takes an int value for one gro... | 39.852459 | 0.010036 |
def remove_tween(self, tween):
""""remove given tween without completing the motion or firing the on_complete"""
if tween.target in self.current_tweens and tween in self.current_tweens[tween.target]:
self.current_tweens[tween.target].remove(tween)
if not self.current_tweens[tween... | [
"def",
"remove_tween",
"(",
"self",
",",
"tween",
")",
":",
"if",
"tween",
".",
"target",
"in",
"self",
".",
"current_tweens",
"and",
"tween",
"in",
"self",
".",
"current_tweens",
"[",
"tween",
".",
"target",
"]",
":",
"self",
".",
"current_tweens",
"[",... | 63 | 0.010444 |
def maybe_profiled(profile_path):
"""A profiling context manager.
:param string profile_path: The path to write profile information to. If `None`, this will no-op.
"""
if not profile_path:
yield
return
import cProfile
profiler = cProfile.Profile()
try:
profiler.enable()
yield
finally:
... | [
"def",
"maybe_profiled",
"(",
"profile_path",
")",
":",
"if",
"not",
"profile_path",
":",
"yield",
"return",
"import",
"cProfile",
"profiler",
"=",
"cProfile",
".",
"Profile",
"(",
")",
"try",
":",
"profiler",
".",
"enable",
"(",
")",
"yield",
"finally",
"... | 29 | 0.015175 |
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value | [
"def",
"subtract_weeks",
"(",
"self",
",",
"weeks",
":",
"int",
")",
"->",
"datetime",
":",
"self",
".",
"value",
"=",
"self",
".",
"value",
"-",
"timedelta",
"(",
"weeks",
"=",
"weeks",
")",
"return",
"self",
".",
"value"
] | 48.5 | 0.010152 |
def reportMemory(k, options, field=None, isBytes=False):
""" Given k kilobytes, report back the correct format as string.
"""
if options.pretty:
return prettyMemory(int(k), field=field, isBytes=isBytes)
else:
if isBytes:
k /= 1024.
if field is not None:
re... | [
"def",
"reportMemory",
"(",
"k",
",",
"options",
",",
"field",
"=",
"None",
",",
"isBytes",
"=",
"False",
")",
":",
"if",
"options",
".",
"pretty",
":",
"return",
"prettyMemory",
"(",
"int",
"(",
"k",
")",
",",
"field",
"=",
"field",
",",
"isBytes",
... | 33.583333 | 0.002415 |
def query(self, expr, **kwargs):
"""Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied.
"""
d... | [
"def",
"query",
"(",
"self",
",",
"expr",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"gen_table_expr",
"(",
"table",
",",
"expr",
")",
":",
"resolver",
"=",
"{",
"name",
":",
"FakeSeries",
"(",
"dtype",
".",
"to_pandas_dtype",
"(",
")",
")",
"for",
... | 39.613139 | 0.001258 |
def should_not_sample_path(request):
"""Decided whether current request path should be sampled or not. This is
checked previous to `should_not_sample_route` and takes precedence.
:param: current active pyramid request
:returns: boolean whether current request path is blacklisted.
"""
blackliste... | [
"def",
"should_not_sample_path",
"(",
"request",
")",
":",
"blacklisted_paths",
"=",
"request",
".",
"registry",
".",
"settings",
".",
"get",
"(",
"'zipkin.blacklisted_paths'",
",",
"[",
"]",
")",
"# Only compile strings, since even recompiling existing",
"# compiled rege... | 41 | 0.00149 |
def shutdown(self, stop_process=False):
'''Shutdown the agency in gentel manner (terminate all the agents).'''
self.info("Agency.shutdown() called.")
return self._shutdown(stop_process=stop_process, gentle=True) | [
"def",
"shutdown",
"(",
"self",
",",
"stop_process",
"=",
"False",
")",
":",
"self",
".",
"info",
"(",
"\"Agency.shutdown() called.\"",
")",
"return",
"self",
".",
"_shutdown",
"(",
"stop_process",
"=",
"stop_process",
",",
"gentle",
"=",
"True",
")"
] | 58 | 0.008511 |
def next(self):
"""Next point in iteration
"""
if self.probability == 1:
x, y = next(self.scan)
else:
while True:
x, y = next(self.scan)
if random.random() <= self.probability: break
return x, y | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"probability",
"==",
"1",
":",
"x",
",",
"y",
"=",
"next",
"(",
"self",
".",
"scan",
")",
"else",
":",
"while",
"True",
":",
"x",
",",
"y",
"=",
"next",
"(",
"self",
".",
"scan",
")",
... | 28.1 | 0.010345 |
def asRGBA(self):
"""
Return image as RGBA pixels.
Greyscales are expanded into RGB triplets;
an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method except that
the *info* reflect the returned pixels, not the source image.
... | [
"def",
"asRGBA",
"(",
"self",
")",
":",
"width",
",",
"height",
",",
"pixels",
",",
"info",
"=",
"self",
".",
"asDirect",
"(",
")",
"if",
"info",
"[",
"'alpha'",
"]",
"and",
"not",
"info",
"[",
"'greyscale'",
"]",
":",
"return",
"width",
",",
"heig... | 35.303571 | 0.000984 |
def _iter_key_ranges(self):
"""Iterates over self._key_ranges, delegating to self._iter_key_range()."""
while True:
if self._current_key_range is None:
if self._key_ranges:
self._current_key_range = self._key_ranges.pop()
# The most recently popped key_range may be None, so con... | [
"def",
"_iter_key_ranges",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"_current_key_range",
"is",
"None",
":",
"if",
"self",
".",
"_key_ranges",
":",
"self",
".",
"_current_key_range",
"=",
"self",
".",
"_key_ranges",
".",
"pop",
"(",
... | 37.631579 | 0.013643 |
def from_httplib(ResponseCls, r, **response_kw):
"""
Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
... | [
"def",
"from_httplib",
"(",
"ResponseCls",
",",
"r",
",",
"*",
"*",
"response_kw",
")",
":",
"headers",
"=",
"r",
".",
"msg",
"if",
"not",
"isinstance",
"(",
"headers",
",",
"HTTPHeaderDict",
")",
":",
"if",
"PY3",
":",
"# Python 3",
"headers",
"=",
"H... | 38.740741 | 0.001866 |
def TimeFromTicks(ticks, tz=None):
"""Construct a DB-API time value from the given ticks value.
:type ticks: float
:param ticks:
a number of seconds since the epoch; see the documentation of the
standard Python time module for details.
:type tz: :class:`datetime.tzinfo`
:param tz: ... | [
"def",
"TimeFromTicks",
"(",
"ticks",
",",
"tz",
"=",
"None",
")",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"ticks",
",",
"tz",
"=",
"tz",
")",
"return",
"dt",
".",
"timetz",
"(",
")"
] | 31.875 | 0.001905 |
def _convert_to_list(self, value, delimiters):
"""
Return a list value translating from other types if necessary.
:param str value: The value to convert.
"""
if not value:
return []
if delimiters:
return [l.strip() for l in value.split(delimiters... | [
"def",
"_convert_to_list",
"(",
"self",
",",
"value",
",",
"delimiters",
")",
":",
"if",
"not",
"value",
":",
"return",
"[",
"]",
"if",
"delimiters",
":",
"return",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"value",
".",
"split",
"(",
"de... | 32.909091 | 0.010753 |
def generateExpectedList(numUniqueFeatures, numLocationsPerObject, maxNumObjects):
"""
Metric: How unique is each object's most unique feature? Calculate the
expected number of occurrences of an object's most unique feature.
"""
# We're choosing a location, checking its feature, and checking how many
# *oth... | [
"def",
"generateExpectedList",
"(",
"numUniqueFeatures",
",",
"numLocationsPerObject",
",",
"maxNumObjects",
")",
":",
"# We're choosing a location, checking its feature, and checking how many",
"# *other* occurrences there are of this feature. So we check n - 1 locations.",
"maxNumOtherLoca... | 45.888889 | 0.011862 |
def get_associated_profile_names(profile_path, result_role, org_vm, server,
include_classnames=False):
"""
Get the Associated profiles and return the string names (org:name:version)
for each profile as a list.
"""
insts = get_associated_profiles(profile_path, result_... | [
"def",
"get_associated_profile_names",
"(",
"profile_path",
",",
"result_role",
",",
"org_vm",
",",
"server",
",",
"include_classnames",
"=",
"False",
")",
":",
"insts",
"=",
"get_associated_profiles",
"(",
"profile_path",
",",
"result_role",
",",
"server",
")",
"... | 39.4 | 0.001653 |
def calculate(directory):
"""Split the tuple (obtained from scan) to separate files.
Alternately send full paths to the files in md5 and call it.
:param directory: tuple of files in the directory."""
# Set correct slashes for the OS
if sys.platform == 'windows':
slash = '\\'
... | [
"def",
"calculate",
"(",
"directory",
")",
":",
"# Set correct slashes for the OS\r",
"if",
"sys",
".",
"platform",
"==",
"'windows'",
":",
"slash",
"=",
"'\\\\'",
"elif",
"sys",
".",
"platform",
"==",
"'linux'",
":",
"slash",
"=",
"'/'",
"else",
":",
"print... | 35.619048 | 0.001302 |
def createDocument_(self, initDict = None) :
"create and returns a completely empty document or one populated with initDict"
if initDict is None :
initV = {}
else :
initV = initDict
return self.documentClass(self, initV) | [
"def",
"createDocument_",
"(",
"self",
",",
"initDict",
"=",
"None",
")",
":",
"if",
"initDict",
"is",
"None",
":",
"initV",
"=",
"{",
"}",
"else",
":",
"initV",
"=",
"initDict",
"return",
"self",
".",
"documentClass",
"(",
"self",
",",
"initV",
")"
] | 33.75 | 0.028881 |
def tile(self, ncols, nrows):
"""Automatically tile the panels of the figure.
This will re-arranged all elements of the figure (first in the
hierarchy) so that they will uniformly cover the figure area.
Parameters
----------
ncols, nrows : type
The number of... | [
"def",
"tile",
"(",
"self",
",",
"ncols",
",",
"nrows",
")",
":",
"dx",
"=",
"(",
"self",
".",
"width",
"/",
"ncols",
")",
".",
"to",
"(",
"'px'",
")",
".",
"value",
"dy",
"=",
"(",
"self",
".",
"height",
"/",
"nrows",
")",
".",
"to",
"(",
... | 29.517241 | 0.002262 |
def parse(self, media_page):
"""Parses the DOM and returns media attributes in the main-content area.
:type media_page: :class:`bs4.BeautifulSoup`
:param media_page: MAL media page's DOM
:rtype: dict
:return: media attributes.
"""
media_info = self.parse_sidebar(media_page)
try:
... | [
"def",
"parse",
"(",
"self",
",",
"media_page",
")",
":",
"media_info",
"=",
"self",
".",
"parse_sidebar",
"(",
"media_page",
")",
"try",
":",
"synopsis_elt",
"=",
"media_page",
".",
"find",
"(",
"u'h2'",
",",
"text",
"=",
"u'Synopsis'",
")",
".",
"paren... | 36.276923 | 0.014451 |
def get_ini(self, incl_unset=False):
"""Return the config dictionary in INI format
Args:
incl_unset (bool): include variables with no defaults.
Returns:
str: string of the config file in INI format
"""
configp = configparser.ConfigParser(allow_no_value=... | [
"def",
"get_ini",
"(",
"self",
",",
"incl_unset",
"=",
"False",
")",
":",
"configp",
"=",
"configparser",
".",
"ConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"configp",
".",
"read_dict",
"(",
"self",
".",
"_config",
")",
"with",
"StringIO",
"(",
... | 33.291667 | 0.002433 |
def value(self):
"""returns object as dictionary"""
return {
"type" : "simple",
"symbol" : self.symbol.value,
"label" : self.label,
"description" : self.description,
"rotationType": self.rotationType,
"rotationExpression"... | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"simple\"",
",",
"\"symbol\"",
":",
"self",
".",
"symbol",
".",
"value",
",",
"\"label\"",
":",
"self",
".",
"label",
",",
"\"description\"",
":",
"self",
".",
"description",
",",
... | 34.6 | 0.019718 |
def lrange(self, key, start, stop):
"""Emulate lrange."""
redis_list = self._get_list(key, 'LRANGE')
start, stop = self._translate_range(len(redis_list), start, stop)
return redis_list[start:stop + 1] | [
"def",
"lrange",
"(",
"self",
",",
"key",
",",
"start",
",",
"stop",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LRANGE'",
")",
"start",
",",
"stop",
"=",
"self",
".",
"_translate_range",
"(",
"len",
"(",
"redis_list",
"... | 45.6 | 0.008621 |
def _sparse_fit(self, X, strategy, missing_values, fill_value):
"""Fit the transformer on sparse data."""
mask_data = _get_mask(X.data, missing_values)
n_implicit_zeros = X.shape[0] - np.diff(X.indptr)
statistics = np.empty(X.shape[1])
if strategy == "constant":
# f... | [
"def",
"_sparse_fit",
"(",
"self",
",",
"X",
",",
"strategy",
",",
"missing_values",
",",
"fill_value",
")",
":",
"mask_data",
"=",
"_get_mask",
"(",
"X",
".",
"data",
",",
"missing_values",
")",
"n_implicit_zeros",
"=",
"X",
".",
"shape",
"[",
"0",
"]",... | 40.108108 | 0.001316 |
def delay(self, factor=1):
'returns True if delay satisfied'
acquired = CommandLog.semaphore.acquire(timeout=options.replay_wait*factor if not self.paused else None)
return acquired or not self.paused | [
"def",
"delay",
"(",
"self",
",",
"factor",
"=",
"1",
")",
":",
"acquired",
"=",
"CommandLog",
".",
"semaphore",
".",
"acquire",
"(",
"timeout",
"=",
"options",
".",
"replay_wait",
"*",
"factor",
"if",
"not",
"self",
".",
"paused",
"else",
"None",
")",... | 55.25 | 0.013393 |
def flairlist(self, limit=1000, after=None, before=None):
"""GETs flairlist for this subreddit. Calls :meth:`narwal.Reddit.flairlist`.
:param limit: max number of items to return
:param after: full id of user to return entries after
:param before: full id of user to return entr... | [
"def",
"flairlist",
"(",
"self",
",",
"limit",
"=",
"1000",
",",
"after",
"=",
"None",
",",
"before",
"=",
"None",
")",
":",
"return",
"self",
".",
"_reddit",
".",
"flairlist",
"(",
"self",
".",
"display_name",
",",
"limit",
"=",
"limit",
",",
"after... | 54.375 | 0.011312 |
def connected_components(edges,
min_len=1,
nodes=None,
engine=None):
"""
Find groups of connected nodes from an edge list.
Parameters
-----------
edges: (n,2) int, edges between nodes
nodes: (m, ) int, list of ... | [
"def",
"connected_components",
"(",
"edges",
",",
"min_len",
"=",
"1",
",",
"nodes",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"def",
"components_networkx",
"(",
")",
":",
"\"\"\"\n Find connected components using networkx\n \"\"\"",
"graph",
... | 34.976923 | 0.000214 |
def validate_digit(value, start, end):
'''validate if a digit is valid'''
if not str(value).isdigit() or int(value) < start or int(value) > end:
raise ValueError('%s must be a digit from %s to %s' % (value, start, end)) | [
"def",
"validate_digit",
"(",
"value",
",",
"start",
",",
"end",
")",
":",
"if",
"not",
"str",
"(",
"value",
")",
".",
"isdigit",
"(",
")",
"or",
"int",
"(",
"value",
")",
"<",
"start",
"or",
"int",
"(",
"value",
")",
">",
"end",
":",
"raise",
... | 58 | 0.008511 |
def _check_wait_input_flag(self):
"""
Returns a function to stop the search of the investigated node of the
ArciDispatch algorithm.
:return:
A function to stop the search.
:rtype: (bool, str) -> bool
"""
wf_pred = self._wf_pred # Namespace shortcuts... | [
"def",
"_check_wait_input_flag",
"(",
"self",
")",
":",
"wf_pred",
"=",
"self",
".",
"_wf_pred",
"# Namespace shortcuts.",
"pred",
"=",
"{",
"k",
":",
"set",
"(",
"v",
")",
".",
"issubset",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_pred",
".",
"items"... | 32.466667 | 0.001329 |
def hil_actuator_controls_send(self, time_usec, controls, mode, flags, force_mavlink1=False):
'''
Sent from autopilot to simulation. Hardware in the loop control
outputs (replacement for HIL_CONTROLS)
time_usec : Timestamp (microseconds si... | [
"def",
"hil_actuator_controls_send",
"(",
"self",
",",
"time_usec",
",",
"controls",
",",
"mode",
",",
"flags",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"hil_actuator_controls_encode",
"(",
"time_usec",
",... | 71.166667 | 0.009249 |
def event_listen_stop(self):
'''Stop event_listen() loop from e.g. another thread.
Does nothing if libpulse poll is not running yet, so might be racey with
event_listen() - be sure to call it in a loop until event_listen returns or something.'''
self._loop_stop = True
c.pa.mainloop_wakeup(self._loop) | [
"def",
"event_listen_stop",
"(",
"self",
")",
":",
"self",
".",
"_loop_stop",
"=",
"True",
"c",
".",
"pa",
".",
"mainloop_wakeup",
"(",
"self",
".",
"_loop",
")"
] | 51.5 | 0.025478 |
def delete(self):
"""
Delete a record from the database.
"""
if self._on_delete is not None:
return self._on_delete(self)
return self._query.delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"_on_delete",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_on_delete",
"(",
"self",
")",
"return",
"self",
".",
"_query",
".",
"delete",
"(",
")"
] | 24.375 | 0.009901 |
def check_requirements(requirement_files, strict=False, error_on_extras=False, verbose=False,
venv=None, do_colour=False):
"""
Given a list of requirements files, checks them against the installed
packages in the currentl environment. If any are missing, or do not fit
within the v... | [
"def",
"check_requirements",
"(",
"requirement_files",
",",
"strict",
"=",
"False",
",",
"error_on_extras",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"venv",
"=",
"None",
",",
"do_colour",
"=",
"False",
")",
":",
"colour",
"=",
"TextColours",
"(",
"... | 36.710843 | 0.001917 |
def update_permissions_for_group(apps, schema_editor):
'''
Update permissions for some users.
Give bulk-delete permissions to moderators.
Give edit permission to moderators and editors in order
to display 'Main' page in the explorer.
'''
db_alias = schema_editor.connection.alias
try:
... | [
"def",
"update_permissions_for_group",
"(",
"apps",
",",
"schema_editor",
")",
":",
"db_alias",
"=",
"schema_editor",
".",
"connection",
".",
"alias",
"try",
":",
"# Django 1.9",
"emit_post_migrate_signal",
"(",
"2",
",",
"False",
",",
"db_alias",
")",
"except",
... | 33.372549 | 0.000571 |
def iter_format_block(
self, text=None,
width=60, chars=False, fill=False, newlines=False,
append=None, prepend=None, strip_first=False, strip_last=False,
lstrip=False):
""" Iterate over lines in a formatted block of text.
This iterator allows you to p... | [
"def",
"iter_format_block",
"(",
"self",
",",
"text",
"=",
"None",
",",
"width",
"=",
"60",
",",
"chars",
"=",
"False",
",",
"fill",
"=",
"False",
",",
"newlines",
"=",
"False",
",",
"append",
"=",
"None",
",",
"prepend",
"=",
"None",
",",
"strip_fir... | 39.26 | 0.001491 |
def tables(self):
"""The complete list of SQL tables."""
self.own_connection.row_factory = sqlite3.Row
self.own_cursor.execute('SELECT name from sqlite_master where type="table";')
result = [x[0].encode('ascii') for x in self.own_cursor.fetchall()]
self.own_connection.row_factory... | [
"def",
"tables",
"(",
"self",
")",
":",
"self",
".",
"own_connection",
".",
"row_factory",
"=",
"sqlite3",
".",
"Row",
"self",
".",
"own_cursor",
".",
"execute",
"(",
"'SELECT name from sqlite_master where type=\"table\";'",
")",
"result",
"=",
"[",
"x",
"[",
... | 50.142857 | 0.008403 |
def _lookup_first(dictionary, key):
'''
Lookup the first value given a key. Returns the first value if the key
refers to a list or the value itself.
:param dict dictionary: The dictionary to search
:param str key: The key to get
:return: Returns the first value available for the key
:rtyp... | [
"def",
"_lookup_first",
"(",
"dictionary",
",",
"key",
")",
":",
"value",
"=",
"dictionary",
"[",
"key",
"]",
"if",
"type",
"(",
"value",
")",
"==",
"list",
":",
"return",
"value",
"[",
"0",
"]",
"else",
":",
"return",
"value"
] | 25.235294 | 0.002247 |
def trim_sample(data):
"""Trim from a sample with the provided trimming method.
Support methods: read_through.
"""
data = utils.to_single_data(data)
trim_reads = dd.get_trim_reads(data)
# this block is to maintain legacy configuration files
if not trim_reads:
logger.info("Skipping tr... | [
"def",
"trim_sample",
"(",
"data",
")",
":",
"data",
"=",
"utils",
".",
"to_single_data",
"(",
"data",
")",
"trim_reads",
"=",
"dd",
".",
"get_trim_reads",
"(",
"data",
")",
"# this block is to maintain legacy configuration files",
"if",
"not",
"trim_reads",
":",
... | 37.176471 | 0.001543 |
def fit(self, X, y=None):
""" Extract possible terms from documents """
self.unhasher.fit(self._get_terms_iter(X))
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"unhasher",
".",
"fit",
"(",
"self",
".",
"_get_terms_iter",
"(",
"X",
")",
")",
"return",
"self"
] | 36.75 | 0.013333 |
def sky_fraction(self):
"""
Sky fraction covered by the MOC
"""
pix_id = self._best_res_pixels()
nb_pix_filled = pix_id.size
return nb_pix_filled / float(3 << (2*(self.max_order + 1))) | [
"def",
"sky_fraction",
"(",
"self",
")",
":",
"pix_id",
"=",
"self",
".",
"_best_res_pixels",
"(",
")",
"nb_pix_filled",
"=",
"pix_id",
".",
"size",
"return",
"nb_pix_filled",
"/",
"float",
"(",
"3",
"<<",
"(",
"2",
"*",
"(",
"self",
".",
"max_order",
... | 32.285714 | 0.008621 |
async def get_sleep_timer_settings(self) -> List[Setting]:
"""Get sleep timer settings."""
return [
Setting.make(**x)
for x in await self.services["system"]["getSleepTimerSettings"]({})
] | [
"async",
"def",
"get_sleep_timer_settings",
"(",
"self",
")",
"->",
"List",
"[",
"Setting",
"]",
":",
"return",
"[",
"Setting",
".",
"make",
"(",
"*",
"*",
"x",
")",
"for",
"x",
"in",
"await",
"self",
".",
"services",
"[",
"\"system\"",
"]",
"[",
"\"... | 38.333333 | 0.008511 |
def largest_connected_component(volume):
"""Return the largest connected component of a 3D array.
Parameters
-----------
volume: numpy.array
3D boolean array.
Returns
--------
volume: numpy.array
3D boolean array with only one connected component.
"""
# We use asarr... | [
"def",
"largest_connected_component",
"(",
"volume",
")",
":",
"# We use asarray to be able to work with masked arrays.",
"volume",
"=",
"np",
".",
"asarray",
"(",
"volume",
")",
"labels",
",",
"num_labels",
"=",
"scn",
".",
"label",
"(",
"volume",
")",
"if",
"not... | 28.038462 | 0.001326 |
def install_requirements():
'''
Install cozy requirements
'''
helpers.cmd_exec(
'echo "cozy cozy/nodejs_apt_list text " | debconf-set-selections',
show_output=True)
helpers.cmd_exec('apt-get install -y cozy-apt-node-list', show_output=True)
helpers.cmd_exec('apt-get update', ... | [
"def",
"install_requirements",
"(",
")",
":",
"helpers",
".",
"cmd_exec",
"(",
"'echo \"cozy cozy/nodejs_apt_list text \" | debconf-set-selections'",
",",
"show_output",
"=",
"True",
")",
"helpers",
".",
"cmd_exec",
"(",
"'apt-get install -y cozy-apt-node-list'",
",",
"show... | 38.066667 | 0.001709 |
def send_mail(template_name, context, from_email, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, **kwargs):
"""
Easy wrapper for sending a single email message to a recipient list using
django template system.
It works almost the sa... | [
"def",
"send_mail",
"(",
"template_name",
",",
"context",
",",
"from_email",
",",
"recipient_list",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"*",
"*",
"kwargs",... | 34.234568 | 0.000351 |
def _base64_md5hash(buffer_object):
"""Get MD5 hash of bytes (as base64).
:type buffer_object: bytes buffer
:param buffer_object: Buffer containing bytes used to compute an MD5
hash (as base64).
:rtype: str
:returns: A base64 encoded digest of the MD5 hash.
"""
ha... | [
"def",
"_base64_md5hash",
"(",
"buffer_object",
")",
":",
"hash_obj",
"=",
"md5",
"(",
")",
"_write_buffer_to_hash",
"(",
"buffer_object",
",",
"hash_obj",
")",
"digest_bytes",
"=",
"hash_obj",
".",
"digest",
"(",
")",
"return",
"base64",
".",
"b64encode",
"("... | 32.214286 | 0.002155 |
def ask_for_input_with_prompt(cls, ui, prompt='', **options):
"""Ask user for written input with prompt"""
return cls.get_appropriate_helper(ui).ask_for_input_with_prompt(prompt=prompt, **options) | [
"def",
"ask_for_input_with_prompt",
"(",
"cls",
",",
"ui",
",",
"prompt",
"=",
"''",
",",
"*",
"*",
"options",
")",
":",
"return",
"cls",
".",
"get_appropriate_helper",
"(",
"ui",
")",
".",
"ask_for_input_with_prompt",
"(",
"prompt",
"=",
"prompt",
",",
"*... | 70 | 0.014151 |
def _hybrid_select_metrics(self, dup_bam, bait_file, target_file):
"""Generate metrics for hybrid selection efficiency.
"""
metrics = self._check_metrics_file(dup_bam, "hs_metrics")
if not file_exists(metrics):
with bed_to_interval(bait_file, dup_bam) as ready_bait:
... | [
"def",
"_hybrid_select_metrics",
"(",
"self",
",",
"dup_bam",
",",
"bait_file",
",",
"target_file",
")",
":",
"metrics",
"=",
"self",
".",
"_check_metrics_file",
"(",
"dup_bam",
",",
"\"hs_metrics\"",
")",
"if",
"not",
"file_exists",
"(",
"metrics",
")",
":",
... | 53.95 | 0.001821 |
def clear_tc(self, owner, data, clear_type):
"""Delete threat intel from ThreatConnect platform.
Args:
owner (str): The ThreatConnect owner.
data (dict): The data for the threat intel to clear.
clear_type (str): The type of clear action.
"""
batch = s... | [
"def",
"clear_tc",
"(",
"self",
",",
"owner",
",",
"data",
",",
"clear_type",
")",
":",
"batch",
"=",
"self",
".",
"tcex",
".",
"batch",
"(",
"owner",
",",
"action",
"=",
"'Delete'",
")",
"tc_type",
"=",
"data",
".",
"get",
"(",
"'type'",
")",
"pat... | 42.387755 | 0.001412 |
def forward_inference(self, variables, evidence=None, args=None):
"""
Forward inference method using belief propagation.
Parameters:
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict ... | [
"def",
"forward_inference",
"(",
"self",
",",
"variables",
",",
"evidence",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"variable_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"var",
"in",
"variables",
":",
"variable_dict",
"[",
"var",
"[",
"1... | 44.928571 | 0.002444 |
def _parallel_evolve(n_programs, parents, X, y, sample_weight, seeds, params):
"""Private function used to build a batch of programs within a job."""
n_samples, n_features = X.shape
# Unpack parameters
tournament_size = params['tournament_size']
function_set = params['function_set']
arities = pa... | [
"def",
"_parallel_evolve",
"(",
"n_programs",
",",
"parents",
",",
"X",
",",
"y",
",",
"sample_weight",
",",
"seeds",
",",
"params",
")",
":",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"# Unpack parameters",
"tournament_size",
"=",
"params",
"[... | 40.264957 | 0.000207 |
def _impl(lexer):
"""Return an Implies expression."""
p = _sumterm(lexer)
tok = next(lexer)
# SUMTERM '=>' IMPL
if isinstance(tok, OP_rarrow):
q = _impl(lexer)
return ('implies', p, q)
# SUMTERM '<=>' IMPL
elif isinstance(tok, OP_lrarrow):
q = _impl(lexer)
re... | [
"def",
"_impl",
"(",
"lexer",
")",
":",
"p",
"=",
"_sumterm",
"(",
"lexer",
")",
"tok",
"=",
"next",
"(",
"lexer",
")",
"# SUMTERM '=>' IMPL",
"if",
"isinstance",
"(",
"tok",
",",
"OP_rarrow",
")",
":",
"q",
"=",
"_impl",
"(",
"lexer",
")",
"return",... | 23.294118 | 0.002427 |
def path_shift(self, shift=1):
''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:param shift: The number of path fragments to shift. May be negative
to change the shift direction. (default: 1)
'''
script_name = self.environ.get('SCRIPT_N... | [
"def",
"path_shift",
"(",
"self",
",",
"shift",
"=",
"1",
")",
":",
"script_name",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"'SCRIPT_NAME'",
",",
"'/'",
")",
"self",
"[",
"'SCRIPT_NAME'",
"]",
",",
"self",
".",
"path",
"=",
"path_shift",
"(",
"s... | 49.111111 | 0.008889 |
def _get_index(self, value):
"""
Return the index of the given value in `state_values`.
Parameters
----------
value
Value to get the index for.
Returns
-------
idx : int
Index of `value`.
"""
error_msg = 'value {0... | [
"def",
"_get_index",
"(",
"self",
",",
"value",
")",
":",
"error_msg",
"=",
"'value {0} not found'",
".",
"format",
"(",
"value",
")",
"if",
"self",
".",
"state_values",
"is",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Integral",
... | 27.432432 | 0.001903 |
def estimate_hand_value(self, tiles, win_tile, melds=None, dora_indicators=None, config=None):
"""
:param tiles: array with 14 tiles in 136-tile format
:param win_tile: 136 format tile that caused win (ron or tsumo)
:param melds: array with Meld objects
:param dora_indicators: ar... | [
"def",
"estimate_hand_value",
"(",
"self",
",",
"tiles",
",",
"win_tile",
",",
"melds",
"=",
"None",
",",
"dora_indicators",
"=",
"None",
",",
"config",
"=",
"None",
")",
":",
"if",
"not",
"melds",
":",
"melds",
"=",
"[",
"]",
"if",
"not",
"dora_indica... | 42.409704 | 0.001863 |
def label_size(base, label_name=None, children=[], parents=[],
dependencies=[]):
"""
Function that returns a Formatoption class for modifying the fontsite
This function returns a :class:`~psyplot.plotter.Formatoption` instance
that modifies the size of the given `base` formatoption
... | [
"def",
"label_size",
"(",
"base",
",",
"label_name",
"=",
"None",
",",
"children",
"=",
"[",
"]",
",",
"parents",
"=",
"[",
"]",
",",
"dependencies",
"=",
"[",
"]",
")",
":",
"label_name",
"=",
"label_name",
"or",
"base",
".",
"key",
"cl_children",
"... | 28.859649 | 0.000588 |
def deduplicate(args):
"""
%prog deduplicate fastafile
Wraps `cd-hit-est` to remove duplicate sequences.
"""
p = OptionParser(deduplicate.__doc__)
p.set_align(pctid=96, pctcov=0)
p.add_option("--fast", default=False, action="store_true",
help="Place sequence in the first cl... | [
"def",
"deduplicate",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"deduplicate",
".",
"__doc__",
")",
"p",
".",
"set_align",
"(",
"pctid",
"=",
"96",
",",
"pctcov",
"=",
"0",
")",
"p",
".",
"add_option",
"(",
"\"--fast\"",
",",
"default",
"... | 33.690909 | 0.001049 |
def from_transitions(cls, initial_state, accepting_states, transition_function):
# type: (State, Set[State], NondeterministicTransitionFunction) -> NFA
"""
Initialize a DFA without explicitly specifying the set of states and the alphabet.
:param initial_state: the initial state.
... | [
"def",
"from_transitions",
"(",
"cls",
",",
"initial_state",
",",
"accepting_states",
",",
"transition_function",
")",
":",
"# type: (State, Set[State], NondeterministicTransitionFunction) -> NFA",
"states",
",",
"alphabet",
"=",
"_extract_states_from_nondeterministic_transition_fu... | 51.538462 | 0.010264 |
def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True):
"""
Parses the given text and yields tokens which represent words within
the given text. Tokens are assumed to be divided by any form of
whitespace character.
"""
if ngrams is None:
ngrams = 1
... | [
"def",
"word_tokenize",
"(",
"text",
",",
"stopwords",
"=",
"_stopwords",
",",
"ngrams",
"=",
"None",
",",
"min_length",
"=",
"0",
",",
"ignore_numeric",
"=",
"True",
")",
":",
"if",
"ngrams",
"is",
"None",
":",
"ngrams",
"=",
"1",
"text",
"=",
"re",
... | 36.043478 | 0.00235 |
def ziegler_nichols(self,ku,tu,control_type='pid'):
'''
ku = ultimate gain
tu = period of oscillation at ultimate gain
'''
converter = dict(
p = lambda ku,tu: (.5*ku, 0, 0),
pi = lambda ku,tu: (.45*ku, 1.2*(.45*ku)/tu, 0),
pd = lambda k... | [
"def",
"ziegler_nichols",
"(",
"self",
",",
"ku",
",",
"tu",
",",
"control_type",
"=",
"'pid'",
")",
":",
"converter",
"=",
"dict",
"(",
"p",
"=",
"lambda",
"ku",
",",
"tu",
":",
"(",
".5",
"*",
"ku",
",",
"0",
",",
"0",
")",
",",
"pi",
"=",
... | 48.4 | 0.040541 |
def doUpdate(self, timeout=1):
"""Do a software update of the Fritz Box if available.
:param float timeout: the timeout to wait for the action to be executed
:return: a list of if an update was available and the update state (bool, str)
:rtype: tuple(bool, str)
"""
names... | [
"def",
"doUpdate",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Fritz",
".",
"getServiceType",
"(",
"\"doUpdate\"",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
... | 43.076923 | 0.008741 |
def config_args(self, section='default'):
"""Loop through the configuration file and set all of our values.
Note:
that anything can be set as a "section" in the argument file. If a
section does not exist an empty dict will be returned.
:param section: ``str``
:retu... | [
"def",
"config_args",
"(",
"self",
",",
"section",
"=",
"'default'",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"2",
",",
"7",
",",
"0",
")",
":",
"parser",
"=",
"ConfigParser",
".",
"SafeConfigParser",
"(",
"allow_no_value",
"=",
"True",
"... | 33.882353 | 0.001688 |
def _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""
Collect invariants, preconditions and postconditions from the bases and decorate all the methods.
Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods a... | [
"def",
"_dbc_decorate_namespace",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"_collapse_invariants",
"(",
"bases",
"=",
"bases",
",",
"namespace",
"=",
"namespa... | 48.473684 | 0.00852 |
def get_distance_to(self, origin=None, other_atoms=None, sort=False):
"""Return a Cartesian with a column for the distance from origin.
"""
if origin is None:
origin = np.zeros(3)
elif pd.api.types.is_list_like(origin):
origin = np.array(origin, dtype='f8')
... | [
"def",
"get_distance_to",
"(",
"self",
",",
"origin",
"=",
"None",
",",
"other_atoms",
"=",
"None",
",",
"sort",
"=",
"False",
")",
":",
"if",
"origin",
"is",
"None",
":",
"origin",
"=",
"np",
".",
"zeros",
"(",
"3",
")",
"elif",
"pd",
".",
"api",
... | 37.333333 | 0.002176 |
def single_html(epub_file_path, html_out=sys.stdout, mathjax_version=None,
numchapters=None, includes=None):
"""Generate complete book HTML."""
epub = cnxepub.EPUB.from_file(epub_file_path)
if len(epub) != 1:
raise Exception('Expecting an epub with one book')
package = epub[0]
... | [
"def",
"single_html",
"(",
"epub_file_path",
",",
"html_out",
"=",
"sys",
".",
"stdout",
",",
"mathjax_version",
"=",
"None",
",",
"numchapters",
"=",
"None",
",",
"includes",
"=",
"None",
")",
":",
"epub",
"=",
"cnxepub",
".",
"EPUB",
".",
"from_file",
... | 35.9375 | 0.000847 |
def _connected(service):
'''
Verify if a connman service is connected
'''
state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State')
return state == 'online' or state == 'ready' | [
"def",
"_connected",
"(",
"service",
")",
":",
"state",
"=",
"pyconnman",
".",
"ConnService",
"(",
"os",
".",
"path",
".",
"join",
"(",
"SERVICE_PATH",
",",
"service",
")",
")",
".",
"get_property",
"(",
"'State'",
")",
"return",
"state",
"==",
"'online'... | 37 | 0.008811 |
def etree_to_text(tree,
guess_punct_space=True,
guess_layout=True,
newline_tags=NEWLINE_TAGS,
double_newline_tags=DOUBLE_NEWLINE_TAGS):
"""
Convert a html tree to text. Tree should be cleaned with
``html_text.html_text.cleaner.clean_htm... | [
"def",
"etree_to_text",
"(",
"tree",
",",
"guess_punct_space",
"=",
"True",
",",
"guess_layout",
"=",
"True",
",",
"newline_tags",
"=",
"NEWLINE_TAGS",
",",
"double_newline_tags",
"=",
"DOUBLE_NEWLINE_TAGS",
")",
":",
"chunks",
"=",
"[",
"]",
"_NEWLINE",
"=",
... | 34.690141 | 0.000395 |
def get_customs_properties_by_inheritance(self, obj):
"""
Get custom properties from the templates defined in this object
:param obj: the oject to search the property
:type obj: alignak.objects.item.Item
:return: list of custom properties
:rtype: list
"""
... | [
"def",
"get_customs_properties_by_inheritance",
"(",
"self",
",",
"obj",
")",
":",
"for",
"t_id",
"in",
"obj",
".",
"templates",
":",
"template",
"=",
"self",
".",
"templates",
"[",
"t_id",
"]",
"tpl_cv",
"=",
"self",
".",
"get_customs_properties_by_inheritance"... | 41.058824 | 0.0014 |
def update_state(self):
""" Update state with latest info from Wink API. """
response = self.api_interface.get_device_state(self, id_override=self.parent.object_id(),
type_override=self.parent.object_type())
self._update_state_from_respo... | [
"def",
"update_state",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"api_interface",
".",
"get_device_state",
"(",
"self",
",",
"id_override",
"=",
"self",
".",
"parent",
".",
"object_id",
"(",
")",
",",
"type_override",
"=",
"self",
".",
"parent",... | 65.8 | 0.012012 |
async def ask_async(self,
patch_stdout: bool = False,
kbi_msg: str = DEFAULT_KBI_MESSAGE) -> Any:
"""Ask the question using asyncio and return user response."""
if self.should_skip_question:
return self.default
try:
sys.st... | [
"async",
"def",
"ask_async",
"(",
"self",
",",
"patch_stdout",
":",
"bool",
"=",
"False",
",",
"kbi_msg",
":",
"str",
"=",
"DEFAULT_KBI_MESSAGE",
")",
"->",
"Any",
":",
"if",
"self",
".",
"should_skip_question",
":",
"return",
"self",
".",
"default",
"try"... | 34.428571 | 0.008081 |
def nest_map(control_iter, map_fn):
"""
Apply ``map_fn`` to the directories defined by ``control_iter``
For each control file in control_iter, map_fn is called with the directory
and control file contents as arguments.
Example::
>>> list(nest_map(['run1/control.json', 'run2/control.json']... | [
"def",
"nest_map",
"(",
"control_iter",
",",
"map_fn",
")",
":",
"def",
"fn",
"(",
"control_path",
")",
":",
"\"\"\"\n Read the control file, return the result of calling map_fn\n \"\"\"",
"with",
"open",
"(",
"control_path",
")",
"as",
"fp",
":",
"control... | 34.741935 | 0.000903 |
def to_pb(self):
"""Converts the row filter to a protobuf.
First converts to a :class:`.data_v2_pb2.ValueRange` and then uses
it to create a row filter protobuf.
:rtype: :class:`.data_v2_pb2.RowFilter`
:returns: The converted current object.
"""
value_range_kwar... | [
"def",
"to_pb",
"(",
"self",
")",
":",
"value_range_kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"start_value",
"is",
"not",
"None",
":",
"if",
"self",
".",
"inclusive_start",
":",
"key",
"=",
"\"start_value_closed\"",
"else",
":",
"key",
"=",
"\"start_value... | 36.88 | 0.002114 |
def _get_artifact_response(artifact):
"""Gets the response object for the given artifact.
This method may be overridden in environments that have a different way of
storing artifact files, such as on-disk or S3.
"""
response = flask.Response(
artifact.data,
mimetype=artifact.content... | [
"def",
"_get_artifact_response",
"(",
"artifact",
")",
":",
"response",
"=",
"flask",
".",
"Response",
"(",
"artifact",
".",
"data",
",",
"mimetype",
"=",
"artifact",
".",
"content_type",
")",
"response",
".",
"cache_control",
".",
"public",
"=",
"True",
"re... | 35 | 0.002141 |
def delete_changed(self, settings, key, user_data):
"""If the gconf var compat_delete be changed, this method
will be called and will change the binding configuration in
all terminals open.
"""
for i in self.guake.notebook_manager.iter_terminals():
i.set_delete_bindin... | [
"def",
"delete_changed",
"(",
"self",
",",
"settings",
",",
"key",
",",
"user_data",
")",
":",
"for",
"i",
"in",
"self",
".",
"guake",
".",
"notebook_manager",
".",
"iter_terminals",
"(",
")",
":",
"i",
".",
"set_delete_binding",
"(",
"self",
".",
"getEr... | 51.857143 | 0.00813 |
def get_write_subset(self, spec_type):
"""
Get a set of fields used to write the header; either 'record'
or 'signal' specification fields. Helper function for
`get_write_fields`. Gets the default required fields, the user
defined fields, and their dependencies.
Parameter... | [
"def",
"get_write_subset",
"(",
"self",
",",
"spec_type",
")",
":",
"if",
"spec_type",
"==",
"'record'",
":",
"write_fields",
"=",
"[",
"]",
"record_specs",
"=",
"RECORD_SPECS",
".",
"copy",
"(",
")",
"# Remove the n_seg requirement for single segment items",
"if",
... | 41.275862 | 0.001904 |
def exchange_declare(self, exchange, type, passive=False, durable=False,
auto_delete=True, nowait=False, arguments=None):
"""Declare exchange, create if needed
This method creates an exchange if it does not already exist,
and if the exchange exists, verifies that it is ... | [
"def",
"exchange_declare",
"(",
"self",
",",
"exchange",
",",
"type",
",",
"passive",
"=",
"False",
",",
"durable",
"=",
"False",
",",
"auto_delete",
"=",
"True",
",",
"nowait",
"=",
"False",
",",
"arguments",
"=",
"None",
")",
":",
"arguments",
"=",
"... | 34.657343 | 0.000588 |
def update(self, name=None, metadata=None):
"""
Updates this webhook. One or more of the parameters may be specified.
"""
return self.policy.update_webhook(self, name=name, metadata=metadata) | [
"def",
"update",
"(",
"self",
",",
"name",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"self",
".",
"policy",
".",
"update_webhook",
"(",
"self",
",",
"name",
"=",
"name",
",",
"metadata",
"=",
"metadata",
")"
] | 43.8 | 0.008969 |
def set_vim_style(theme):
"""Add style and compatibility with vim notebook extension"""
vim_jupyter_nbext = os.path.join(jupyter_nbext, 'vim_binding')
if not os.path.isdir(vim_jupyter_nbext):
os.makedirs(vim_jupyter_nbext)
vim_less = '@import "styles{}";\n'.format(''.join([os.sep, theme]))
... | [
"def",
"set_vim_style",
"(",
"theme",
")",
":",
"vim_jupyter_nbext",
"=",
"os",
".",
"path",
".",
"join",
"(",
"jupyter_nbext",
",",
"'vim_binding'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"vim_jupyter_nbext",
")",
":",
"os",
".",
"maked... | 35.045455 | 0.001263 |
def output_start_time(self, start_time_msec):
'''Log a start time in the log.
Params:
start_time_msec time (in milliseconds) since the absolute start time (the epoch)
'''
self.log.write("#[StartTime: %f (seconds since epoch), %s]\n" %
(float(start_time_... | [
"def",
"output_start_time",
"(",
"self",
",",
"start_time_msec",
")",
":",
"self",
".",
"log",
".",
"write",
"(",
"\"#[StartTime: %f (seconds since epoch), %s]\\n\"",
"%",
"(",
"float",
"(",
"start_time_msec",
")",
"/",
"1000.0",
",",
"datetime",
".",
"fromtimesta... | 51.25 | 0.009592 |
def blend_mode(self):
"""BlendMode: The blend mode used for drawing operations."""
blend_mode_ptr = ffi.new('int *')
lib.SDL_GetTextureBlendMode(self._ptr, blend_mode_ptr)
return BlendMode(blend_mode_ptr[0]) | [
"def",
"blend_mode",
"(",
"self",
")",
":",
"blend_mode_ptr",
"=",
"ffi",
".",
"new",
"(",
"'int *'",
")",
"lib",
".",
"SDL_GetTextureBlendMode",
"(",
"self",
".",
"_ptr",
",",
"blend_mode_ptr",
")",
"return",
"BlendMode",
"(",
"blend_mode_ptr",
"[",
"0",
... | 47 | 0.008368 |
def encode_dataset_coordinates(dataset):
"""Encode coordinates on the given dataset object into variable specific
and global attributes.
When possible, this is done according to CF conventions.
Parameters
----------
dataset : Dataset
Object to encode.
Returns
-------
varia... | [
"def",
"encode_dataset_coordinates",
"(",
"dataset",
")",
":",
"non_dim_coord_names",
"=",
"set",
"(",
"dataset",
".",
"coords",
")",
"-",
"set",
"(",
"dataset",
".",
"dims",
")",
"return",
"_encode_coordinates",
"(",
"dataset",
".",
"_variables",
",",
"datase... | 28.526316 | 0.001786 |
def i2m(self, pkt, p):
"""
Update the context with information from the built packet.
If no type was given at the record layer, we try to infer it.
"""
cur = b""
if isinstance(p, _GenericTLSSessionInheritance):
if pkt.type is None:
if isinstanc... | [
"def",
"i2m",
"(",
"self",
",",
"pkt",
",",
"p",
")",
":",
"cur",
"=",
"b\"\"",
"if",
"isinstance",
"(",
"p",
",",
"_GenericTLSSessionInheritance",
")",
":",
"if",
"pkt",
".",
"type",
"is",
"None",
":",
"if",
"isinstance",
"(",
"p",
",",
"TLSChangeCi... | 35.384615 | 0.002116 |
def start(self):
"""!
Start all receiving threads.
"""
if self.isThreadsRunning:
raise ThreadManagerException("Broker threads are already running")
self.isThreadsRunning = True
for client in self.clients:
threading.Thread(target = client).start() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"isThreadsRunning",
":",
"raise",
"ThreadManagerException",
"(",
"\"Broker threads are already running\"",
")",
"self",
".",
"isThreadsRunning",
"=",
"True",
"for",
"client",
"in",
"self",
".",
"clients",
... | 34.444444 | 0.012579 |
def register_memory():
"""Register an approximation of memory used by FTP server process
and all of its children.
"""
# XXX How to get a reliable representation of memory being used is
# not clear. (rss - shared) seems kind of ok but we might also use
# the private working set via get_memory_map... | [
"def",
"register_memory",
"(",
")",
":",
"# XXX How to get a reliable representation of memory being used is",
"# not clear. (rss - shared) seems kind of ok but we might also use",
"# the private working set via get_memory_maps().private*.",
"def",
"get_mem",
"(",
"proc",
")",
":",
"if",... | 36.782609 | 0.001152 |
def _generate_docstring_for_func(self, namespace, arg_data_type,
result_data_type=None, error_data_type=None,
overview=None, extra_request_args=None,
extra_return_arg=None, footer=None):
"""
Ge... | [
"def",
"_generate_docstring_for_func",
"(",
"self",
",",
"namespace",
",",
"arg_data_type",
",",
"result_data_type",
"=",
"None",
",",
"error_data_type",
"=",
"None",
",",
"overview",
"=",
"None",
",",
"extra_request_args",
"=",
"None",
",",
"extra_return_arg",
"=... | 48.455224 | 0.001962 |
def _auth(
self,
username,
password,
pkey,
key_filenames,
allow_agent,
look_for_keys,
gss_auth,
gss_kex,
gss_deleg_creds,
gss_host,
passphrase,
):
"""
Try, in order:
- The key(s) passed in, i... | [
"def",
"_auth",
"(",
"self",
",",
"username",
",",
"password",
",",
"pkey",
",",
"key_filenames",
",",
"allow_agent",
",",
"look_for_keys",
",",
"gss_auth",
",",
"gss_kex",
",",
"gss_deleg_creds",
",",
"gss_host",
",",
"passphrase",
",",
")",
":",
"saved_exc... | 36.415663 | 0.000483 |
def console_set_char_background(
con: tcod.console.Console,
x: int,
y: int,
col: Tuple[int, int, int],
flag: int = BKGND_SET,
) -> None:
"""Change the background color of x,y to col using a blend mode.
Args:
con (Console): Any Console instance.
x (int): Character x position ... | [
"def",
"console_set_char_background",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"col",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"flag",
":",
"int",
"=",
"BKGND_SET",... | 34.777778 | 0.001555 |
def rolling_window(a, window, pad=None):
"""
Returns (win, len(a)) rolling - window array of data.
Parameters
----------
a : array_like
Array to calculate the rolling window of
window : int
Description of `window`.
pad : same as dtype(a)
Description of `pad`.
Re... | [
"def",
"rolling_window",
"(",
"a",
",",
"window",
",",
"pad",
"=",
"None",
")",
":",
"shape",
"=",
"a",
".",
"shape",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"a",
".",
"shape",
"[",
"-",
"1",
"]",
"-",
"window",
"+",
"1",
",",
"window",
")",
"st... | 34.18 | 0.001138 |
def convert_scalar_add(net, node, model, builder):
"""Convert a scalar add layer from mxnet to coreml.
Parameters
----------
net: network
A mxnet network object.
node: layer
Node to convert.
model: model
An model for MXNet
builder: NeuralNetworkBuilder
A n... | [
"def",
"convert_scalar_add",
"(",
"net",
",",
"node",
",",
"model",
",",
"builder",
")",
":",
"import",
"numpy",
"as",
"_np",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",... | 27.4 | 0.018336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.