text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def remove(self):
"""Remove all documents matching the selector criteria.
"""
self.__bulk.add_delete(self.__selector, _DELETE_ALL,
collation=self.__collation) | [
"def",
"remove",
"(",
"self",
")",
":",
"self",
".",
"__bulk",
".",
"add_delete",
"(",
"self",
".",
"__selector",
",",
"_DELETE_ALL",
",",
"collation",
"=",
"self",
".",
"__collation",
")"
] | 41.8 | 12.2 |
def vars_to_array(self):
"""
Convert `self.vars` to a numpy array
Returns
-------
numpy.array
"""
logger.warn('This function is deprecated. You can inspect `self.np_vars` directly as NumPy arrays '
'without conversion.')
if not self.v... | [
"def",
"vars_to_array",
"(",
"self",
")",
":",
"logger",
".",
"warn",
"(",
"'This function is deprecated. You can inspect `self.np_vars` directly as NumPy arrays '",
"'without conversion.'",
")",
"if",
"not",
"self",
".",
"vars",
":",
"return",
"None",
"vars_matrix",
"=",... | 27.5 | 23.3 |
def write_title(self, title: str, title_color: str = YELLOW, hyphen_line_color: str = WHITE):
"""
Prints title with hyphen line underneath it.
:param title: The title to print.
:param title_color: The title text color (default is yellow).
:param hyphen_line_color: The hyphen lin... | [
"def",
"write_title",
"(",
"self",
",",
"title",
":",
"str",
",",
"title_color",
":",
"str",
"=",
"YELLOW",
",",
"hyphen_line_color",
":",
"str",
"=",
"WHITE",
")",
":",
"self",
".",
"write_line",
"(",
"title_color",
"+",
"title",
")",
"self",
".",
"wr... | 46.3 | 20.1 |
def pformat(obj, verbose=False):
"""Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj) | [
"def",
"pformat",
"(",
"obj",
",",
"verbose",
"=",
"False",
")",
":",
"try",
":",
"from",
"pretty",
"import",
"pretty",
"return",
"pretty",
"(",
"obj",
",",
"verbose",
"=",
"verbose",
")",
"except",
"ImportError",
":",
"from",
"pprint",
"import",
"pforma... | 29.7 | 10.5 |
def __hook_dll(self, event):
"""
Hook the requested API calls (in self.apiHooks).
This method is called automatically whenever a DLL is loaded.
"""
debug = event.debug
pid = event.get_pid()
for hook_api_stub in self.__get_hooks_for_dll(event):
hook_... | [
"def",
"__hook_dll",
"(",
"self",
",",
"event",
")",
":",
"debug",
"=",
"event",
".",
"debug",
"pid",
"=",
"event",
".",
"get_pid",
"(",
")",
"for",
"hook_api_stub",
"in",
"self",
".",
"__get_hooks_for_dll",
"(",
"event",
")",
":",
"hook_api_stub",
".",
... | 33.6 | 14.2 |
def build_spec(user, repo, sha=None, prov=None, extraMetadata=[]):
"""Build grlc specification for the given github user / repo."""
loader = grlc.utils.getLoader(user, repo, sha=sha, prov=prov)
files = loader.fetchFiles()
raw_repo_uri = loader.getRawRepoUri()
# Fetch all .rq files
items = []
... | [
"def",
"build_spec",
"(",
"user",
",",
"repo",
",",
"sha",
"=",
"None",
",",
"prov",
"=",
"None",
",",
"extraMetadata",
"=",
"[",
"]",
")",
":",
"loader",
"=",
"grlc",
".",
"utils",
".",
"getLoader",
"(",
"user",
",",
"repo",
",",
"sha",
"=",
"sh... | 45.275 | 27.275 |
def params(self):
"""Current interpolation parameter dictionary"""
par = {"radius": self.radius,
"sphere_index": self.sphere_index,
"pha_offset": self.pha_offset,
"center": [self.posx_offset, self.posy_offset]
}
return par | [
"def",
"params",
"(",
"self",
")",
":",
"par",
"=",
"{",
"\"radius\"",
":",
"self",
".",
"radius",
",",
"\"sphere_index\"",
":",
"self",
".",
"sphere_index",
",",
"\"pha_offset\"",
":",
"self",
".",
"pha_offset",
",",
"\"center\"",
":",
"[",
"self",
".",... | 37.375 | 13.375 |
def overrides(method):
'''
Meant to be used as
class B:
@overrides(A.m1)
def m1(self):
pass
'''
def wrapper(func):
if func.__name__ != method.__name__:
msg = "Wrong @override: %r expected, but overwriting %r."
msg = msg % (func.__name_... | [
"def",
"overrides",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"if",
"func",
".",
"__name__",
"!=",
"method",
".",
"__name__",
":",
"msg",
"=",
"\"Wrong @override: %r expected, but overwriting %r.\"",
"msg",
"=",
"msg",
"%",
"(",
"func... | 22.571429 | 22.190476 |
def search(description, all=False):
"""
Gets a list of :class:`language_tags.Subtag.Subtag` objects where the description matches.
:param description: a string or compiled regular expression. For example: ``search(re.compile('\d{4}'))`` if the
description of the returned subtag must... | [
"def",
"search",
"(",
"description",
",",
"all",
"=",
"False",
")",
":",
"# If the input query is all lowercase, make a case-insensitive match.",
"if",
"isinstance",
"(",
"description",
",",
"str",
")",
":",
"list_to_string",
"=",
"lambda",
"l",
":",
"', '",
".",
... | 54.939394 | 33.848485 |
def content(self, output=None, str_output=None, **kwargs):
"""Searches for `output` regex within HTML page. kwargs are passed to BeautifulSoup's find function to filter for tags."""
if self.response.mimetype != "text/html":
raise Failure(_("expected request to return HTML, but it returned {}... | [
"def",
"content",
"(",
"self",
",",
"output",
"=",
"None",
",",
"str_output",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"response",
".",
"mimetype",
"!=",
"\"text/html\"",
":",
"raise",
"Failure",
"(",
"_",
"(",
"\"expected req... | 51.3125 | 23.9375 |
def check_bucket_exists(self, bucket: str) -> bool:
"""
Checks if bucket with specified name exists.
:param bucket: the bucket to be checked.
:return: true if specified bucket exists.
"""
exists = True
try:
self.s3_client.head_bucket(Bucket=bucket)
... | [
"def",
"check_bucket_exists",
"(",
"self",
",",
"bucket",
":",
"str",
")",
"->",
"bool",
":",
"exists",
"=",
"True",
"try",
":",
"self",
".",
"s3_client",
".",
"head_bucket",
"(",
"Bucket",
"=",
"bucket",
")",
"except",
"botocore",
".",
"exceptions",
"."... | 40.4375 | 14.4375 |
def _get_environs(self, prefix: str = None) -> dict:
"""
Fetches set environment variables if such exist, via the :func:`~notifiers.utils.helpers.dict_from_environs`
Searches for `[PREFIX_NAME]_[PROVIDER_NAME]_[ARGUMENT]` for each of the arguments defined in the schema
:param prefix: Th... | [
"def",
"_get_environs",
"(",
"self",
",",
"prefix",
":",
"str",
"=",
"None",
")",
"->",
"dict",
":",
"if",
"not",
"prefix",
":",
"log",
".",
"debug",
"(",
"\"using default environ prefix\"",
")",
"prefix",
"=",
"DEFAULT_ENVIRON_PREFIX",
"return",
"dict_from_en... | 54.416667 | 28.916667 |
def delete(self, historics_id):
""" Delete one specified playback query. If the query is currently running, stop it.
status_code is set to 204 on success
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsdelete
:param historics_id: playbac... | [
"def",
"delete",
"(",
"self",
",",
"historics_id",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'delete'",
",",
"data",
"=",
"dict",
"(",
"id",
"=",
"historics_id",
")",
")"
] | 49.428571 | 26.928571 |
def get_all_publications(return_namedtuples=True):
"""
Get list publications from all available source.
Args:
return_namedtuples (bool, default True): Convert :class:`.Publication`
structures to namedtuples (used in AMQP
communication).
Ret... | [
"def",
"get_all_publications",
"(",
"return_namedtuples",
"=",
"True",
")",
":",
"sources",
"=",
"[",
"ben_cz",
".",
"get_publications",
",",
"grada_cz",
".",
"get_publications",
",",
"cpress_cz",
".",
"get_publications",
",",
"zonerpress_cz",
".",
"get_publications... | 28.193548 | 20.322581 |
def extend_children(self, parent, wanted_children, child_class, child_glossary=None):
"""
Extend the number of children so that the parent object contains wanted children.
No child will be removed if wanted_children is smaller than the current number of children.
"""
from cms.api... | [
"def",
"extend_children",
"(",
"self",
",",
"parent",
",",
"wanted_children",
",",
"child_class",
",",
"child_glossary",
"=",
"None",
")",
":",
"from",
"cms",
".",
"api",
"import",
"add_plugin",
"current_children",
"=",
"parent",
".",
"get_num_children",
"(",
... | 55.25 | 23.083333 |
def record_ce_entries(self):
# type: () -> bytes
'''
Return a string representing the Rock Ridge entries in the Continuation Entry.
Parameters:
None.
Returns:
A string representing the Rock Ridge entry.
'''
if not self._initialized:
... | [
"def",
"record_ce_entries",
"(",
"self",
")",
":",
"# type: () -> bytes",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'Rock Ridge extension not yet initialized'",
")",
"return",
"self",
".",
"_record",
... | 31.428571 | 25.857143 |
def save_user(self, request, user, form, commit=True):
"""
Saves a new `User` instance using information provided in the
signup form.
"""
from .utils import user_username, user_email, user_field
data = form.cleaned_data
first_name = data.get('first_name')
... | [
"def",
"save_user",
"(",
"self",
",",
"request",
",",
"user",
",",
"form",
",",
"commit",
"=",
"True",
")",
":",
"from",
".",
"utils",
"import",
"user_username",
",",
"user_email",
",",
"user_field",
"data",
"=",
"form",
".",
"cleaned_data",
"first_name",
... | 34.75 | 12.892857 |
def rosenbrock(x, y, a=1, b=100):
"""Bigger is better; global optimum at x=a, y=a**2"""
return -1 * ((a - x)**2 + b * (y - x**2)**2) | [
"def",
"rosenbrock",
"(",
"x",
",",
"y",
",",
"a",
"=",
"1",
",",
"b",
"=",
"100",
")",
":",
"return",
"-",
"1",
"*",
"(",
"(",
"a",
"-",
"x",
")",
"**",
"2",
"+",
"b",
"*",
"(",
"y",
"-",
"x",
"**",
"2",
")",
"**",
"2",
")"
] | 46 | 5 |
def attenuation_curve(signal, resp, fs, calf, smooth_pts=99):
"""
Calculate an attenuation roll-off curve, from a signal and its recording
:param signal: ouput signal delivered to the generation hardware
:type signal: numpy.ndarray
:param resp: recording of given signal, as recieved from microp... | [
"def",
"attenuation_curve",
"(",
"signal",
",",
"resp",
",",
"fs",
",",
"calf",
",",
"smooth_pts",
"=",
"99",
")",
":",
"# remove dc offset",
"y",
"=",
"resp",
"-",
"np",
".",
"mean",
"(",
"resp",
")",
"x",
"=",
"signal",
"# frequencies present in calibrat... | 31.108696 | 19.282609 |
def create_tx(network, spendables, payables, fee="standard", lock_time=0, version=1):
"""
This function provides the easiest way to create an unsigned transaction.
All coin values are in satoshis.
:param spendables: a list of Spendable objects, which act as inputs.
Each item in the list can be... | [
"def",
"create_tx",
"(",
"network",
",",
"spendables",
",",
"payables",
",",
"fee",
"=",
"\"standard\"",
",",
"lock_time",
"=",
"0",
",",
"version",
"=",
"1",
")",
":",
"Tx",
"=",
"network",
".",
"tx",
"def",
"_fix_spendable",
"(",
"s",
")",
":",
"if... | 41.55 | 25.45 |
def to_sympy_matrix(value):
"""
Converts value to a `sympy.Matrix` object, if possible.
Leaves the value as `sympy.Matrix` if it already was
:param value: value to convert
:return:
:rtype: `sympy.Matrix`
"""
if isinstance(value, sympy.Matrix):
return value
try:
return... | [
"def",
"to_sympy_matrix",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"sympy",
".",
"Matrix",
")",
":",
"return",
"value",
"try",
":",
"return",
"sympy",
".",
"Matrix",
"(",
"value",
")",
"except",
"ValueError",
"as",
"original_exception... | 37.88 | 16.68 |
def moderate_view(self, request, object_id, extra_context=None):
"""
Handles moderate object tool through a somewhat hacky changelist view
whose queryset is altered via CommentAdmin.get_changelist to only list
comments for the object under review.
"""
opts = self.model._m... | [
"def",
"moderate_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"extra_context",
"=",
"None",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"app_label",
"=",
"opts",
".",
"app_label",
"view",
"=",
"CommentAdmin",
"(",
"model",
"=... | 36.333333 | 19.666667 |
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict:
.. code-block:: python
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_a... | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"versions_as_list",
")",
"# not yet implemented or not applicable",
"if",
"any",
"(",
... | 30.82 | 19.3 |
async def get_entry(self, entry):
"""
GET /api/entries/{entry}.{_format}
Retrieve a single entry
:param entry: \w+ an integer The Entry ID
:return data related to the ext
"""
params = {'access_token': self.token}
url = '/api/entries/{entry}.{ext}'.format... | [
"async",
"def",
"get_entry",
"(",
"self",
",",
"entry",
")",
":",
"params",
"=",
"{",
"'access_token'",
":",
"self",
".",
"token",
"}",
"url",
"=",
"'/api/entries/{entry}.{ext}'",
".",
"format",
"(",
"entry",
"=",
"entry",
",",
"ext",
"=",
"self",
".",
... | 34 | 13.384615 |
def _fill_function(*args):
"""Fills in the rest of function data into the skeleton function object
The skeleton itself is create by _make_skel_func().
"""
if len(args) == 2:
func = args[0]
state = args[1]
elif len(args) == 5:
# Backwards compat for cloudpickle v0.4.0, after ... | [
"def",
"_fill_function",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"func",
"=",
"args",
"[",
"0",
"]",
"state",
"=",
"args",
"[",
"1",
"]",
"elif",
"len",
"(",
"args",
")",
"==",
"5",
":",
"# Backwards compat for ... | 39.185185 | 18.333333 |
def set_params(w, src):
"""
Set source parameters.
"""
params = extract_source_params(src)
# this is done because for characteristic sources geometry is in
# 'surface' attribute
params.update(extract_geometry_params(src))
mfd_pars, rate_pars = extract_mfd_params(src)
params.update(m... | [
"def",
"set_params",
"(",
"w",
",",
"src",
")",
":",
"params",
"=",
"extract_source_params",
"(",
"src",
")",
"# this is done because for characteristic sources geometry is in",
"# 'surface' attribute",
"params",
".",
"update",
"(",
"extract_geometry_params",
"(",
"src",
... | 28.428571 | 17.357143 |
def write_job(self,fh):
"""
Write the DAG entry for this node's job to the DAG file descriptor.
@param fh: descriptor of open DAG file.
"""
if isinstance(self.job(),CondorDAGManJob):
# create an external subdag from this dag
fh.write( ' '.join(
['SUBDAG EXTERNAL', self.__name, se... | [
"def",
"write_job",
"(",
"self",
",",
"fh",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"job",
"(",
")",
",",
"CondorDAGManJob",
")",
":",
"# create an external subdag from this dag",
"fh",
".",
"write",
"(",
"' '",
".",
"join",
"(",
"[",
"'SUBDAG EXTE... | 37.882353 | 17.058824 |
def load(filename):
"""Load variable from Pickle file
Args:
path (str): path of the file to load
Returns:
variable read from path
"""
fileObj = open(filename, 'rb')
variable = pickle.load(fileObj)
fileObj.close()
return variable | [
"def",
"load",
"(",
"filename",
")",
":",
"fileObj",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"variable",
"=",
"pickle",
".",
"load",
"(",
"fileObj",
")",
"fileObj",
".",
"close",
"(",
")",
"return",
"variable"
] | 20.769231 | 17.076923 |
def writeSwarmDescription(self, csvPath, outPath,
predictedField=None, swarmParams=None):
"""
Writes swarm description file (JSON).
:param csvPath: path to CSV data
:param outPath: absolute or relative file path to write swarm JSON file
:param predictedField: (string)
:para... | [
"def",
"writeSwarmDescription",
"(",
"self",
",",
"csvPath",
",",
"outPath",
",",
"predictedField",
"=",
"None",
",",
"swarmParams",
"=",
"None",
")",
":",
"if",
"self",
".",
"_confluence",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Missing Confluence! C... | 42.25 | 11.85 |
def NoSuchEntityOk(f):
""" Decorator to remove NoSuchEntity exceptions, and raises all others. """
def ExceptionFilter(*args):
try:
return f(*args)
except boto.exception.BotoServerError as e:
if e.error_code == 'NoSuchEntity':
pass
else:
raise
except:
raise
... | [
"def",
"NoSuchEntityOk",
"(",
"f",
")",
":",
"def",
"ExceptionFilter",
"(",
"*",
"args",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
")",
"except",
"boto",
".",
"exception",
".",
"BotoServerError",
"as",
"e",
":",
"if",
"e",
".",
"error_co... | 24.571429 | 19.071429 |
def to_dict(self, save_data=True):
"""
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:param boolean save_data: if true, it adds the training data self.X and self.Y to the dictionary
:return dict: json ... | [
"def",
"to_dict",
"(",
"self",
",",
"save_data",
"=",
"True",
")",
":",
"input_dict",
"=",
"super",
"(",
"GP",
",",
"self",
")",
".",
"_save_to_input_dict",
"(",
")",
"input_dict",
"[",
"\"class\"",
"]",
"=",
"\"GPy.core.GP\"",
"if",
"not",
"save_data",
... | 45.424242 | 19.727273 |
def DbGetAttributeAlias(self, argin):
""" Get the attribute name for the given alias.
If alias not found in database, returns an empty string.
:param argin: The attribute alias name
:type: tango.DevString
:return: The attribute name (device/attribute)
:rtype: tango.DevSt... | [
"def",
"DbGetAttributeAlias",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbGetAttributeAlias()\"",
")",
"return",
"self",
".",
"db",
".",
"get_attribute_alias",
"(",
"argin",
")"
] | 42.1 | 11.7 |
def cutout(im, n_holes, length):
""" Cut out n_holes number of square holes of size length in image at random locations. Holes may overlap. """
r,c,*_ = im.shape
mask = np.ones((r, c), np.int32)
for n in range(n_holes):
y = np.random.randint(0, r)
x = np.random.randint(0, c)
y1 ... | [
"def",
"cutout",
"(",
"im",
",",
"n_holes",
",",
"length",
")",
":",
"r",
",",
"c",
",",
"",
"*",
"_",
"=",
"im",
".",
"shape",
"mask",
"=",
"np",
".",
"ones",
"(",
"(",
"r",
",",
"c",
")",
",",
"np",
".",
"int32",
")",
"for",
"n",
"in",
... | 34.235294 | 13.411765 |
def __handle_changed_state(self, state):
"""
we need to pack a struct with the following five numbers:
tv_sec, tv_usec, ev_type, code, value
then write it using __write_to_character_device
seconds, mircroseconds, ev_type, code, value
time we just use now
ev_type... | [
"def",
"__handle_changed_state",
"(",
"self",
",",
"state",
")",
":",
"timeval",
"=",
"self",
".",
"__get_timeval",
"(",
")",
"events",
"=",
"self",
".",
"__get_button_events",
"(",
"state",
",",
"timeval",
")",
"events",
".",
"extend",
"(",
"self",
".",
... | 36.052632 | 14.684211 |
def cover(self, pageid):
"""
Get a cover image given a page id.
:param str pageid: The pageid for the light novel you want a cover image for
:return str: the image url
"""
r = requests.get(self.api,
params={'action': 'query', 'prop': 'pageimages'... | [
"def",
"cover",
"(",
"self",
",",
"pageid",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"api",
",",
"params",
"=",
"{",
"'action'",
":",
"'query'",
",",
"'prop'",
":",
"'pageimages'",
",",
"'pageids'",
":",
"pageid",
",",
"'format'"... | 47.055556 | 22.5 |
def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5):
"""
Wait for the virtual OS to go into the indicated state.
Input:
Request Handle
userid whose state is to be monitored
Desired state, 'up' or 'down', case sensitive
Maximum attempts to wait for desired st... | [
"def",
"waitForOSState",
"(",
"rh",
",",
"userid",
",",
"desiredState",
",",
"maxQueries",
"=",
"90",
",",
"sleepSecs",
"=",
"5",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.waitForOSState, userid: \"",
"+",
"userid",
"+",
"\" state: \"",
"+",
"d... | 30.790323 | 20.854839 |
def get_configs(self):
"""
Return a list of all installed configs.
"""
self.check_configs_ready()
result = []
for bot in self.bots.values():
result.extend(list(bot.get_models()))
return result | [
"def",
"get_configs",
"(",
"self",
")",
":",
"self",
".",
"check_configs_ready",
"(",
")",
"result",
"=",
"[",
"]",
"for",
"bot",
"in",
"self",
".",
"bots",
".",
"values",
"(",
")",
":",
"result",
".",
"extend",
"(",
"list",
"(",
"bot",
".",
"get_m... | 25.2 | 12.2 |
def confd_state_smp_number_of_threads(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
smp = ET.SubElement(confd_state, "smp")
number_of_threads = ... | [
"def",
"confd_state_smp_number_of_threads",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"confd-state\"",
",",
"xmlns",
"=",
... | 45.909091 | 18.909091 |
def get_task_list(self):
"""
Queries the GenePattern server and returns a list of GPTask objects,
each representing one of the modules installed on the server. Useful
for determining which are available on the server.
"""
request = urllib.request.Request(self.url + '/rest... | [
"def",
"get_task_list",
"(",
"self",
")",
":",
"request",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"self",
".",
"url",
"+",
"'/rest/v1/tasks/all.json'",
")",
"if",
"self",
".",
"authorization_header",
"(",
")",
"is",
"not",
"None",
":",
"request... | 47.894737 | 17.473684 |
def fetch(self, collection, **kwargs):
'''
return one record from the collection whose parameters match kwargs
---
kwargs should be a dictionary whose keys match column names (in
traditional SQL / fields in NoSQL) and whose values are the values of
those fields.
e... | [
"def",
"fetch",
"(",
"self",
",",
"collection",
",",
"*",
"*",
"kwargs",
")",
":",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
")",
"data",
"=",
"yield",
"Op",
"(",
"self",
".",
"db",
"[",
"collection",
"]",
".",
"find_one",
",",
"kwa... | 41.916667 | 22.916667 |
def hide_intf_loopback_holder_interface_loopback_ip_ip_config_address_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_intf_loopback_holder = ET.SubElement(config, "hide-intf-loopback-holder", xmlns="urn:brocade.com:mgmt:brocade-intf-loopback")
... | [
"def",
"hide_intf_loopback_holder_interface_loopback_ip_ip_config_address_address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_intf_loopback_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
... | 52.823529 | 21.470588 |
def upload(ctx, product, git_ref, dirname, aws_id, aws_secret, ci_env,
on_travis_push, on_travis_pr, on_travis_api, on_travis_cron,
skip_upload):
"""Upload a new site build to LSST the Docs.
"""
logger = logging.getLogger(__name__)
if skip_upload:
click.echo('Skipping ltd ... | [
"def",
"upload",
"(",
"ctx",
",",
"product",
",",
"git_ref",
",",
"dirname",
",",
"aws_id",
",",
"aws_secret",
",",
"ci_env",
",",
"on_travis_push",
",",
"on_travis_pr",
",",
"on_travis_api",
",",
"on_travis_cron",
",",
"skip_upload",
")",
":",
"logger",
"="... | 32.672414 | 18.896552 |
def _create_sequences(self, func, iterable, chunksize, collector=None):
"""
Create the WorkUnit objects to process and pushes them on the
work queue. Each work unit is meant to process a slice of
iterable of size chunksize. If collector is specified, then
the ApplyResult objects ... | [
"def",
"_create_sequences",
"(",
"self",
",",
"func",
",",
"iterable",
",",
"chunksize",
",",
"collector",
"=",
"None",
")",
":",
"assert",
"not",
"self",
".",
"_closed",
"# No lock here. We assume it's atomic...",
"sequences",
"=",
"[",
"]",
"results",
"=",
"... | 36.588235 | 16.764706 |
def get_trips(self, authentication_info, start, end):
"""Get trips for this device between start and end."""
import requests
if (authentication_info is None or
not authentication_info.is_valid()):
return []
data_url = "https://api.ritassist.nl/api/trips/GetTrips... | [
"def",
"get_trips",
"(",
"self",
",",
"authentication_info",
",",
"start",
",",
"end",
")",
":",
"import",
"requests",
"if",
"(",
"authentication_info",
"is",
"None",
"or",
"not",
"authentication_info",
".",
"is_valid",
"(",
")",
")",
":",
"return",
"[",
"... | 36.105263 | 19.052632 |
def format_search_results(self, search_results):
"""Format search results.
Args:
search_results (list of `ResourceSearchResult`): Search to format.
Returns:
List of 2-tuple: Text and color to print in.
"""
formatted_lines = []
for search_result ... | [
"def",
"format_search_results",
"(",
"self",
",",
"search_results",
")",
":",
"formatted_lines",
"=",
"[",
"]",
"for",
"search_result",
"in",
"search_results",
":",
"lines",
"=",
"self",
".",
"_format_search_result",
"(",
"search_result",
")",
"formatted_lines",
"... | 28.6875 | 20.0625 |
def pause(self):
"""
Sends a "play" command to the player.
"""
msg = cr.Message()
msg.type = cr.PAUSE
self.send_message(msg) | [
"def",
"pause",
"(",
"self",
")",
":",
"msg",
"=",
"cr",
".",
"Message",
"(",
")",
"msg",
".",
"type",
"=",
"cr",
".",
"PAUSE",
"self",
".",
"send_message",
"(",
"msg",
")"
] | 23.714286 | 9.428571 |
def customers(self):
'''
List both any individuals signed up via the registration and payment system,
and any individuals signed up without payment.
'''
return Customer.objects.filter(
Q(privatelessoncustomer__lesson=self) |
Q(registration__eventregistrati... | [
"def",
"customers",
"(",
"self",
")",
":",
"return",
"Customer",
".",
"objects",
".",
"filter",
"(",
"Q",
"(",
"privatelessoncustomer__lesson",
"=",
"self",
")",
"|",
"Q",
"(",
"registration__eventregistration__event",
"=",
"self",
")",
")",
".",
"distinct",
... | 38.666667 | 20.666667 |
def from_string(cls, dataset_id, default_project=None):
"""Construct a dataset reference from dataset ID string.
Args:
dataset_id (str):
A dataset ID in standard SQL format. If ``default_project``
is not specified, this must included both the project ID and
... | [
"def",
"from_string",
"(",
"cls",
",",
"dataset_id",
",",
"default_project",
"=",
"None",
")",
":",
"output_dataset_id",
"=",
"dataset_id",
"output_project_id",
"=",
"default_project",
"parts",
"=",
"dataset_id",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"... | 39.022222 | 21.133333 |
def decode_spans(self, spans):
"""Decodes an encoded list of spans.
:param spans: encoded list of spans
:type spans: bytes
:return: list of spans
:rtype: list of Span
"""
decoded_spans = []
transport = TMemoryBuffer(spans)
if six.byte2int(spans) ... | [
"def",
"decode_spans",
"(",
"self",
",",
"spans",
")",
":",
"decoded_spans",
"=",
"[",
"]",
"transport",
"=",
"TMemoryBuffer",
"(",
"spans",
")",
"if",
"six",
".",
"byte2int",
"(",
"spans",
")",
"==",
"TType",
".",
"STRUCT",
":",
"_",
",",
"size",
"=... | 29.190476 | 14.47619 |
def _add_input_state(self, node, input_state):
"""
Add the input state to all successors of the given node.
:param node: The node whose successors' input states will be touched.
:param input_state: The state that will be added to successors of the node.
:return: ... | [
"def",
"_add_input_state",
"(",
"self",
",",
"node",
",",
"input_state",
")",
":",
"successors",
"=",
"self",
".",
"_graph_visitor",
".",
"successors",
"(",
"node",
")",
"for",
"succ",
"in",
"successors",
":",
"if",
"succ",
"in",
"self",
".",
"_state_map",... | 39.5625 | 23.3125 |
def has_unknown_attachment_error(self, page_id):
"""
Check has unknown attachment error on page
:param page_id:
:return:
"""
unknown_attachment_identifier = 'plugins/servlet/confluence/placeholder/unknown-attachment'
result = self.get_page_by_id(page_id, expand='b... | [
"def",
"has_unknown_attachment_error",
"(",
"self",
",",
"page_id",
")",
":",
"unknown_attachment_identifier",
"=",
"'plugins/servlet/confluence/placeholder/unknown-attachment'",
"result",
"=",
"self",
".",
"get_page_by_id",
"(",
"page_id",
",",
"expand",
"=",
"'body.view'"... | 43.428571 | 21.142857 |
def execute_concurrent_with_args(session, statement, parameters, *args, **kwargs):
"""
Like :meth:`~cassandra.concurrent.execute_concurrent()`, but takes a single
statement and a sequence of parameters. Each item in ``parameters``
should be a sequence or :const:`None`.
Example usage::
sta... | [
"def",
"execute_concurrent_with_args",
"(",
"session",
",",
"statement",
",",
"parameters",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"execute_concurrent",
"(",
"session",
",",
"zip",
"(",
"cycle",
"(",
"(",
"statement",
",",
")",
")",... | 47.076923 | 27.692308 |
def calc_max_bits(self, signed, values):
""" Calculates the maximim needed bits to represent a value """
b = 0
vmax = -10000000
for val in values:
if signed:
b = b | val if val >= 0 else b | ~val << 1
vmax = val if vmax < val else vmax... | [
"def",
"calc_max_bits",
"(",
"self",
",",
"signed",
",",
"values",
")",
":",
"b",
"=",
"0",
"vmax",
"=",
"-",
"10000000",
"for",
"val",
"in",
"values",
":",
"if",
"signed",
":",
"b",
"=",
"b",
"|",
"val",
"if",
"val",
">=",
"0",
"else",
"b",
"|... | 31.823529 | 16.941176 |
def ProcessFile(filename, vlevel, extra_check_functions=None):
"""Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An ... | [
"def",
"ProcessFile",
"(",
"filename",
",",
"vlevel",
",",
"extra_check_functions",
"=",
"None",
")",
":",
"_SetVerboseLevel",
"(",
"vlevel",
")",
"_BackupFilters",
"(",
")",
"if",
"not",
"ProcessConfigOverrides",
"(",
"filename",
")",
":",
"_RestoreFilters",
"(... | 39.505263 | 23.126316 |
def _get_err_msg(row, col, fld, val, prt_flds):
"""Return an informative message with details of xlsx write attempt."""
import traceback
traceback.print_exc()
err_msg = (
"ROW({R}) COL({C}) FIELD({F}) VAL({V})\n".format(R=row, C=col, F=fld, V=val),
"PRINT FIELDS({... | [
"def",
"_get_err_msg",
"(",
"row",
",",
"col",
",",
"fld",
",",
"val",
",",
"prt_flds",
")",
":",
"import",
"traceback",
"traceback",
".",
"print_exc",
"(",
")",
"err_msg",
"=",
"(",
"\"ROW({R}) COL({C}) FIELD({F}) VAL({V})\\n\"",
".",
"format",
"(",
"R",
"=... | 50.375 | 19.25 |
def restart(name, no_block=False, unmask=False, unmask_runtime=False):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is don... | [
"def",
"restart",
"(",
"name",
",",
"no_block",
"=",
"False",
",",
"unmask",
"=",
"False",
",",
"unmask_runtime",
"=",
"False",
")",
":",
"_check_for_unit_changes",
"(",
"name",
")",
"_check_unmask",
"(",
"name",
",",
"unmask",
",",
"unmask_runtime",
")",
... | 39.425926 | 27.425926 |
def relative_redirect_n_times(n):
"""Relatively 302 Redirects n times.
---
tags:
- Redirects
parameters:
- in: path
name: n
type: int
produces:
- text/html
responses:
302:
description: A redirection.
"""
assert n > 0
response = app.ma... | [
"def",
"relative_redirect_n_times",
"(",
"n",
")",
":",
"assert",
"n",
">",
"0",
"response",
"=",
"app",
".",
"make_response",
"(",
"\"\"",
")",
"response",
".",
"status_code",
"=",
"302",
"if",
"n",
"==",
"1",
":",
"response",
".",
"headers",
"[",
"\"... | 20.037037 | 23.037037 |
def read(self):
"""
Return a list of `KeyPress` instances. It won't return anything when
there was nothing to read. (This function doesn't block.)
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx
"""
max_count = 2048 # Max events to read a... | [
"def",
"read",
"(",
"self",
")",
":",
"max_count",
"=",
"2048",
"# Max events to read at the same time.",
"read",
"=",
"DWORD",
"(",
"0",
")",
"arrtype",
"=",
"INPUT_RECORD",
"*",
"max_count",
"input_records",
"=",
"arrtype",
"(",
")",
"# Get next batch of input e... | 37 | 19.571429 |
def update(self, _attributes=None, **attributes):
"""
Update the parent model on the relationship.
:param attributes: The update attributes
:type attributes: dict
:rtype: mixed
"""
if _attributes is not None:
attributes.update(_attributes)
i... | [
"def",
"update",
"(",
"self",
",",
"_attributes",
"=",
"None",
",",
"*",
"*",
"attributes",
")",
":",
"if",
"_attributes",
"is",
"not",
"None",
":",
"attributes",
".",
"update",
"(",
"_attributes",
")",
"instance",
"=",
"self",
".",
"get_results",
"(",
... | 25.533333 | 15.666667 |
def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | [
"def",
"gray2bgr",
"(",
"img",
")",
":",
"img",
"=",
"img",
"[",
"...",
",",
"None",
"]",
"if",
"img",
".",
"ndim",
"==",
"2",
"else",
"img",
"out_img",
"=",
"cv2",
".",
"cvtColor",
"(",
"img",
",",
"cv2",
".",
"COLOR_GRAY2BGR",
")",
"return",
"o... | 24.833333 | 17.583333 |
def fingerprint2keyid(fingerprint):
"""Returns keyid from fingerprint for private keys"""
if gnupg is None:
return
gpg = gnupg.GPG()
private_keys = gpg.list_keys(True)
keyid = None
for private_key in private_keys:
if private_key['fingerprint'] == config["gpg_key_fingerprint"]:... | [
"def",
"fingerprint2keyid",
"(",
"fingerprint",
")",
":",
"if",
"gnupg",
"is",
"None",
":",
"return",
"gpg",
"=",
"gnupg",
".",
"GPG",
"(",
")",
"private_keys",
"=",
"gpg",
".",
"list_keys",
"(",
"True",
")",
"keyid",
"=",
"None",
"for",
"private_key",
... | 23.875 | 21.0625 |
def format_field(self, value: Any, spec: str) -> str:
"""Method of string.Formatter that specifies the output of format()."""
from cirq import ops # HACK: avoids cyclic dependency.
if isinstance(value, (float, int)):
if isinstance(value, float):
value = round(value, ... | [
"def",
"format_field",
"(",
"self",
",",
"value",
":",
"Any",
",",
"spec",
":",
"str",
")",
"->",
"str",
":",
"from",
"cirq",
"import",
"ops",
"# HACK: avoids cyclic dependency.",
"if",
"isinstance",
"(",
"value",
",",
"(",
"float",
",",
"int",
")",
")",... | 47.6 | 10.066667 |
def celery_enable_all():
"""Enable johnny-cache in all celery tasks, clearing the local-store
after each task."""
from celery.signals import task_prerun, task_postrun, task_failure
task_prerun.connect(prerun_handler)
task_postrun.connect(postrun_handler)
# Also have to cleanup on failure.
ta... | [
"def",
"celery_enable_all",
"(",
")",
":",
"from",
"celery",
".",
"signals",
"import",
"task_prerun",
",",
"task_postrun",
",",
"task_failure",
"task_prerun",
".",
"connect",
"(",
"prerun_handler",
")",
"task_postrun",
".",
"connect",
"(",
"postrun_handler",
")",
... | 43.5 | 6.375 |
def pass_conditions(all_info, current_path, conditions, unknown_as_pass_condition = False):
"""
Pass all conditions?
:param all_info:
:param current_path:
:param conditions:
:param unknown_as_pass_condition: Consider an undetermined condition as passed
:return:
"""
result = False
... | [
"def",
"pass_conditions",
"(",
"all_info",
",",
"current_path",
",",
"conditions",
",",
"unknown_as_pass_condition",
"=",
"False",
")",
":",
"result",
"=",
"False",
"if",
"len",
"(",
"conditions",
")",
"==",
"0",
":",
"return",
"True",
"condition_operator",
"=... | 40.888889 | 22.933333 |
def tostring(self):
"""Return the string representation of the job description XML."""
root = self.as_element()
indent(root)
txt = ET.tostring(root, encoding="utf-8")
# Now remove the tokens used to order the attributes.
txt = re.sub(r'_[A-Z]_','',txt)
txt = '<?xm... | [
"def",
"tostring",
"(",
"self",
")",
":",
"root",
"=",
"self",
".",
"as_element",
"(",
")",
"indent",
"(",
"root",
")",
"txt",
"=",
"ET",
".",
"tostring",
"(",
"root",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"# Now remove the tokens used to order the attribu... | 41.555556 | 13.777778 |
def error(self, exc):
"""
log an error message:
:param exc: exception message
"""
msg = 'trying to execute a step in the environment: \n' \
' - Exception: %s' % exc
if self.logger is not None:
self.logger.error(msg)
self.by_cons... | [
"def",
"error",
"(",
"self",
",",
"exc",
")",
":",
"msg",
"=",
"'trying to execute a step in the environment: \\n'",
"' - Exception: %s'",
"%",
"exc",
"if",
"self",
".",
"logger",
"is",
"not",
"None",
":",
"self",
".",
"logger",
".",
"error",
"(",
"m... | 34 | 8.6 |
def list_storage_accounts_rg(access_token, subscription_id, rgname):
'''List the storage accounts in the specified resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
Re... | [
"def",
"list_storage_accounts_rg",
"(",
"access_token",
",",
"subscription_id",
",",
"rgname",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourcegroups/'",
",",
... | 41.235294 | 21.470588 |
def _get_versions(config=None):
"""Retrieve details on all programs available on the system.
"""
try:
from bcbio.pipeline import version
if hasattr(version, "__version__"):
bcbio_version = ("%s-%s" % (version.__version__, version.__git_revision__)
if ... | [
"def",
"_get_versions",
"(",
"config",
"=",
"None",
")",
":",
"try",
":",
"from",
"bcbio",
".",
"pipeline",
"import",
"version",
"if",
"hasattr",
"(",
"version",
",",
"\"__version__\"",
")",
":",
"bcbio_version",
"=",
"(",
"\"%s-%s\"",
"%",
"(",
"version",... | 43.933333 | 19.433333 |
def split_camel_case(text) -> list:
"""Splits words from CamelCase text."""
return list(reduce(
lambda a, b: (a + [b] if b.isupper() else a[:-1] + [a[-1] + b]),
text,
[]
)) | [
"def",
"split_camel_case",
"(",
"text",
")",
"->",
"list",
":",
"return",
"list",
"(",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"(",
"a",
"+",
"[",
"b",
"]",
"if",
"b",
".",
"isupper",
"(",
")",
"else",
"a",
"[",
":",
"-",
"1",
"]",
"+",
... | 28.857143 | 20.714286 |
def _find_key_cols(df):
"""Identify columns in a DataFrame that could be a unique key"""
keys = []
for col in df:
if len(df[col].unique()) == len(df[col]):
keys.append(col)
return keys | [
"def",
"_find_key_cols",
"(",
"df",
")",
":",
"keys",
"=",
"[",
"]",
"for",
"col",
"in",
"df",
":",
"if",
"len",
"(",
"df",
"[",
"col",
"]",
".",
"unique",
"(",
")",
")",
"==",
"len",
"(",
"df",
"[",
"col",
"]",
")",
":",
"keys",
".",
"appe... | 27.25 | 18.5 |
def schedule(self, time_or_delta, *args, **kwargs):
"""
A function to schedule running a RQ job at a given time
or after a given timespan::
@rq.job
def add(x, y):
return x + y
add.schedule(timedelta(hours=2), 1, 2, timeout=10)
add... | [
"def",
"schedule",
"(",
"self",
",",
"time_or_delta",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queue_name",
"=",
"kwargs",
".",
"pop",
"(",
"'queue'",
",",
"self",
".",
"queue_name",
")",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'time... | 34.691358 | 20.962963 |
def fetch(args: List[str], env: Dict[str, str] = None,
encoding: str = sys.getdefaultencoding()) -> str:
"""
Run a command and returns its stdout.
Args:
args: the command-line arguments
env: the operating system environment to use
encoding: the encoding to use for ``stdout... | [
"def",
"fetch",
"(",
"args",
":",
"List",
"[",
"str",
"]",
",",
"env",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"encoding",
":",
"str",
"=",
"sys",
".",
"getdefaultencoding",
"(",
")",
")",
"->",
"str",
":",
"stdout",
",",
"_... | 29 | 17.333333 |
def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
... | [
"def",
"login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_cl... | 30.608696 | 21.826087 |
def K_plug_valve_Crane(D1, D2, angle, fd=None, style=0):
r'''Returns the loss coefficient for a plug valve or cock valve as shown in
[1]_.
If β = 1:
.. math::
K = K_1 = K_2 = Nf_d
Otherwise:
.. math::
K_2 = \frac{K + 0.5\sqrt{\sin\frac{\theta}{2}}(1-\b... | [
"def",
"K_plug_valve_Crane",
"(",
"D1",
",",
"D2",
",",
"angle",
",",
"fd",
"=",
"None",
",",
"style",
"=",
"0",
")",
":",
"if",
"fd",
"is",
"None",
":",
"fd",
"=",
"ft_Crane",
"(",
"D2",
")",
"beta",
"=",
"D1",
"/",
"D2",
"try",
":",
"K",
"=... | 31.101449 | 27.884058 |
def int_to_base36(i):
"""
Django on py2 raises ValueError on large values.
"""
if six.PY2:
char_set = '0123456789abcdefghijklmnopqrstuvwxyz'
if i < 0:
raise ValueError("Negative base36 conversion input.")
if not isinstance(i, six.integer_types):
raise Type... | [
"def",
"int_to_base36",
"(",
"i",
")",
":",
"if",
"six",
".",
"PY2",
":",
"char_set",
"=",
"'0123456789abcdefghijklmnopqrstuvwxyz'",
"if",
"i",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Negative base36 conversion input.\"",
")",
"if",
"not",
"isinstance",
"(... | 30.6 | 16.1 |
def aggregate(table, metrics=None, by=None, having=None, **kwds):
"""
Aggregate a table with a given set of reductions, with grouping
expressions, and post-aggregation filters.
Parameters
----------
table : table expression
metrics : expression or expression list
by : optional, default ... | [
"def",
"aggregate",
"(",
"table",
",",
"metrics",
"=",
"None",
",",
"by",
"=",
"None",
",",
"having",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"metrics",
"is",
"None",
":",
"metrics",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"sorte... | 25.740741 | 18.333333 |
async def parseResults(self, api_data):
""" See CoverSource.parseResults. """
results = []
# parse HTML and get results
parser = lxml.etree.HTMLParser()
html = lxml.etree.XML(api_data.decode("latin-1"), parser)
for rank, result in enumerate(__class__.RESULTS_SELECTOR(html), 1):
# extract... | [
"async",
"def",
"parseResults",
"(",
"self",
",",
"api_data",
")",
":",
"results",
"=",
"[",
"]",
"# parse HTML and get results",
"parser",
"=",
"lxml",
".",
"etree",
".",
"HTMLParser",
"(",
")",
"html",
"=",
"lxml",
".",
"etree",
".",
"XML",
"(",
"api_d... | 37.632653 | 18.306122 |
def _iget_item_cache(self, item):
"""Return the cached item, item represents a positional indexer."""
ax = self._info_axis
if ax.is_unique:
lower = self._get_item_cache(ax[item])
else:
lower = self._take(item, axis=self._info_axis_number)
return lower | [
"def",
"_iget_item_cache",
"(",
"self",
",",
"item",
")",
":",
"ax",
"=",
"self",
".",
"_info_axis",
"if",
"ax",
".",
"is_unique",
":",
"lower",
"=",
"self",
".",
"_get_item_cache",
"(",
"ax",
"[",
"item",
"]",
")",
"else",
":",
"lower",
"=",
"self",... | 38.5 | 14.625 |
def replace(self, **kwargs):
"""
Return: a new :class:`Location` with specific ``kwargs`` replacing
their corresponding values.
Using BlockUsageLocator's replace function results in a mismatch of __init__ args and kwargs.
Replace tries to instantiate a Location object wi... | [
"def",
"replace",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# NOTE: Deprecation value is hard coded as True in __init__ and therefore does not need to be passed through.",
"return",
"Location",
"(",
"kwargs",
".",
"pop",
"(",
"'org'",
",",
"self",
".",
"course_key... | 47.166667 | 23.722222 |
def check_sweep(abf,sweep=None,dT=.1):
"""Plotting for an eyeball check of AP detection in the given sweep."""
if abf.APs is None:
APs=[]
else:
APs=cm.matrixToDicts(abf.APs)
if sweep is None or len(sweep)==0: #find the first sweep with >5APs in it
for sweepNum in range(abf.sweep... | [
"def",
"check_sweep",
"(",
"abf",
",",
"sweep",
"=",
"None",
",",
"dT",
"=",
".1",
")",
":",
"if",
"abf",
".",
"APs",
"is",
"None",
":",
"APs",
"=",
"[",
"]",
"else",
":",
"APs",
"=",
"cm",
".",
"matrixToDicts",
"(",
"abf",
".",
"APs",
")",
"... | 38.173077 | 17.076923 |
def make_grid(tensor, nrow=8, padding=2, pad_value=0):
"""Make a grid of images, via numpy.
Args:
tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
or a list of images all of the same size.
nrow (int, optional): Number of images displayed in each row of the grid... | [
"def",
"make_grid",
"(",
"tensor",
",",
"nrow",
"=",
"8",
",",
"padding",
"=",
"2",
",",
"pad_value",
"=",
"0",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"tensor",
",",
"np",
".",
"ndarray",
")",
"or",
"(",
"isinstance",
"(",
"tensor",
",",
... | 41.469388 | 24.795918 |
def gen_key(self, input):
"""Generate a GnuPG key through batch file key generation. See
:meth:`GPG.gen_key_input()` for creating the control input.
>>> import gnupg
>>> gpg = gnupg.GPG(homedir="doctests")
>>> key_input = gpg.gen_key_input()
>>> key = gpg.gen_key(key_inp... | [
"def",
"gen_key",
"(",
"self",
",",
"input",
")",
":",
"args",
"=",
"[",
"\"--gen-key --cert-digest-algo SHA512 --batch\"",
"]",
"key",
"=",
"self",
".",
"_result_map",
"[",
"'generate'",
"]",
"(",
"self",
")",
"f",
"=",
"_make_binary_stream",
"(",
"input",
... | 39.957447 | 18.191489 |
def init_db(self, db_path):
'''initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db
The custom path can be set with the environment variable SREGISTRY_DATABASE
when a user creates the client, we must initialize this db
the database s... | [
"def",
"init_db",
"(",
"self",
",",
"db_path",
")",
":",
"# Database Setup, use default if uri not provided",
"self",
".",
"database",
"=",
"'sqlite:///%s'",
"%",
"db_path",
"self",
".",
"storage",
"=",
"SREGISTRY_STORAGE",
"bot",
".",
"debug",
"(",
"\"Database loca... | 42.535714 | 24.392857 |
def downsample(vector, factor):
"""
downsample(vector, factor):
Downsample (by averaging) a vector by an integer factor.
"""
if (len(vector) % factor):
print "Length of 'vector' is not divisible by 'factor'=%d!" % factor
return 0
vector.shape = (len(vector) / factor, factor)
... | [
"def",
"downsample",
"(",
"vector",
",",
"factor",
")",
":",
"if",
"(",
"len",
"(",
"vector",
")",
"%",
"factor",
")",
":",
"print",
"\"Length of 'vector' is not divisible by 'factor'=%d!\"",
"%",
"factor",
"return",
"0",
"vector",
".",
"shape",
"=",
"(",
"l... | 34.8 | 12.4 |
def _choice_from(self, key: str) -> str:
"""Choice random element."""
data = self._data[key]
return self.random.choice(data) | [
"def",
"_choice_from",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"str",
":",
"data",
"=",
"self",
".",
"_data",
"[",
"key",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"data",
")"
] | 36.25 | 2.75 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'examples') and self.examples is not None:
_dict['examples'] = [x._to_dict() for x in self.examples]
if hasattr(self, 'pagination') and self.pagination is not None:
... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'examples'",
")",
"and",
"self",
".",
"examples",
"is",
"not",
"None",
":",
"_dict",
"[",
"'examples'",
"]",
"=",
"[",
"x",
".",
"_to_dict",
"(",
... | 48.375 | 21.25 |
def get_logs(self, id, **kwargs):
"""
Gets logs for specific Build Record
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callbac... | [
"def",
"get_logs",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_logs_with_http_info",
"(",
"id... | 38.6 | 15.8 |
def install(self, install_options, global_options=(), *args, **kwargs):
"""
Install everything in this set (after having downloaded and unpacked
the packages)
"""
to_install = self._to_install()
if to_install:
logger.info(
'Installing collecte... | [
"def",
"install",
"(",
"self",
",",
"install_options",
",",
"global_options",
"=",
"(",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"to_install",
"=",
"self",
".",
"_to_install",
"(",
")",
"if",
"to_install",
":",
"logger",
".",
"info",
... | 37.785714 | 15.97619 |
def installed(package, version):
"""
Check if the package meets the required version.
The version specifier consists of an optional comparator (one of =, ==, >,
<, >=, <=) and an arbitrarily long version number separated by dots. The
should be as you would expect, e.g. for an installed version '0.1... | [
"def",
"installed",
"(",
"package",
",",
"version",
")",
":",
"if",
"not",
"exists",
"(",
"package",
")",
":",
"return",
"False",
"number",
",",
"comparator",
"=",
"_split_version_specifier",
"(",
"version",
")",
"modversion",
"=",
"_query",
"(",
"package",
... | 25.886364 | 22.340909 |
def compute_offset_sad(dem1, dem2, pad=(9,9), plot=False):
"""Compute subpixel horizontal offset between input rasters using sum of absolute differences (SAD) method
"""
#This defines the search window size
#Use half-pixel stride?
#Note: stride is not properly implemented
#stride = 1
#ref =... | [
"def",
"compute_offset_sad",
"(",
"dem1",
",",
"dem2",
",",
"pad",
"=",
"(",
"9",
",",
"9",
")",
",",
"plot",
"=",
"False",
")",
":",
"#This defines the search window size",
"#Use half-pixel stride?",
"#Note: stride is not properly implemented ",
"#stride = 1",
"#ref ... | 35.45098 | 17.176471 |
def expand_actions(self, actions):
"""
Accepts an array of actions and returns an array of actions which match
"""
r = []
for action in actions:
r.append(action)
if action in self.aliased_actions:
r.extend(self.aliased_actions[action])
... | [
"def",
"expand_actions",
"(",
"self",
",",
"actions",
")",
":",
"r",
"=",
"[",
"]",
"for",
"action",
"in",
"actions",
":",
"r",
".",
"append",
"(",
"action",
")",
"if",
"action",
"in",
"self",
".",
"aliased_actions",
":",
"r",
".",
"extend",
"(",
"... | 32.3 | 13.7 |
def _main_thread_terminated(self):
"""Callback that attempts to send pending logs before termination."""
if not self.is_alive:
return
if not self._queue.empty():
print(
"Program shutting down, attempting to send %d queued log "
"entries to... | [
"def",
"_main_thread_terminated",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_alive",
":",
"return",
"if",
"not",
"self",
".",
"_queue",
".",
"empty",
"(",
")",
":",
"print",
"(",
"\"Program shutting down, attempting to send %d queued log \"",
"\"entries ... | 34.684211 | 20.631579 |
def get_referenced_object(self):
"""
:rtype: core.BunqModel
:raise: BunqException
"""
if self._MonetaryAccountBank is not None:
return self._MonetaryAccountBank
if self._MonetaryAccountJoint is not None:
return self._MonetaryAccountJoint
... | [
"def",
"get_referenced_object",
"(",
"self",
")",
":",
"if",
"self",
".",
"_MonetaryAccountBank",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_MonetaryAccountBank",
"if",
"self",
".",
"_MonetaryAccountJoint",
"is",
"not",
"None",
":",
"return",
"self",
"... | 29.315789 | 16.473684 |
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`CreateAccount` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].... | [
"def",
"from_xdr_object",
"(",
"cls",
",",
"op_xdr_object",
")",
":",
"if",
"not",
"op_xdr_object",
".",
"sourceAccount",
":",
"source",
"=",
"None",
"else",
":",
"source",
"=",
"encode_check",
"(",
"'account'",
",",
"op_xdr_object",
".",
"sourceAccount",
"[",... | 32.409091 | 18.272727 |
async def addNodes(self, nodedefs):
'''
Quickly add/modify a list of nodes from node definition tuples.
This API is the simplest/fastest way to add nodes, set node props,
and add tags to nodes remotely.
Args:
nodedefs (list): A list of node definition tuples. See be... | [
"async",
"def",
"addNodes",
"(",
"self",
",",
"nodedefs",
")",
":",
"async",
"with",
"await",
"self",
".",
"snap",
"(",
")",
"as",
"snap",
":",
"snap",
".",
"strict",
"=",
"False",
"async",
"for",
"node",
"in",
"snap",
".",
"addNodes",
"(",
"nodedefs... | 30 | 23.714286 |
def credits(self):
"""Returns either a tuple representing the credit range or a
single integer if the range is set to one value.
Use self.cred to always get the tuple.
"""
if self.cred[0] == self.cred[1]:
return self.cred[0]
return self.cred | [
"def",
"credits",
"(",
"self",
")",
":",
"if",
"self",
".",
"cred",
"[",
"0",
"]",
"==",
"self",
".",
"cred",
"[",
"1",
"]",
":",
"return",
"self",
".",
"cred",
"[",
"0",
"]",
"return",
"self",
".",
"cred"
] | 32.666667 | 12.111111 |
def token_getter(provider, token=None):
""" Generic token getter for all the providers """
session_key = provider + '_token'
if token is None:
token = session.get(session_key)
return token | [
"def",
"token_getter",
"(",
"provider",
",",
"token",
"=",
"None",
")",
":",
"session_key",
"=",
"provider",
"+",
"'_token'",
"if",
"token",
"is",
"None",
":",
"token",
"=",
"session",
".",
"get",
"(",
"session_key",
")",
"return",
"token"
] | 37.833333 | 6.833333 |
def render_svg(self, render_id, words, arcs):
"""Render SVG.
render_id (int): Unique ID, typically index of document.
words (list): Individual words and their tags.
arcs (list): Individual arcs and their start, end, direction and label.
RETURNS (unicode): Rendered SVG markup.
... | [
"def",
"render_svg",
"(",
"self",
",",
"render_id",
",",
"words",
",",
"arcs",
")",
":",
"self",
".",
"levels",
"=",
"self",
".",
"get_levels",
"(",
"arcs",
")",
"self",
".",
"highest_level",
"=",
"len",
"(",
"self",
".",
"levels",
")",
"self",
".",
... | 38.935484 | 17.096774 |
def get_orders(self, product_id=None, status=None, **kwargs):
""" List your current open orders.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Only open or un-settled orders are returned. As soon as an
order is no longer open ... | [
"def",
"get_orders",
"(",
"self",
",",
"product_id",
"=",
"None",
",",
"status",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"kwargs",
"if",
"product_id",
"is",
"not",
"None",
":",
"params",
"[",
"'product_id'",
"]",
"=",
"product_id... | 41.015625 | 19.28125 |
def set_column_gap(self, value):
"""Sets the gap value between columns
Args:
value (int or str): gap value (i.e. 10 or "10px")
"""
value = str(value) + 'px'
value = value.replace('pxpx', 'px')
self.style['grid-column-gap'] = value | [
"def",
"set_column_gap",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"+",
"'px'",
"value",
"=",
"value",
".",
"replace",
"(",
"'pxpx'",
",",
"'px'",
")",
"self",
".",
"style",
"[",
"'grid-column-gap'",
"]",
"=",
"valu... | 31.444444 | 12.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.