text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def close(self):
"""
Closes the stream.
"""
self.flush()
try:
if self.stream is not None:
self.stream.flush()
_name = self.stream.name
self.stream.close()
self.client.copy(_name, self.filename)
ex... | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"flush",
"(",
")",
"try",
":",
"if",
"self",
".",
"stream",
"is",
"not",
"None",
":",
"self",
".",
"stream",
".",
"flush",
"(",
")",
"_name",
"=",
"self",
".",
"stream",
".",
"name",
"self",
"... | 26.5 | 11.357143 |
def to_fmt(self) -> str:
"""
Provide a useful representation of the register.
"""
infos = fmt.end(";\n", [])
s = fmt.sep(', ', [])
for ids in sorted(self.states.keys()):
s.lsdata.append(str(ids))
infos.lsdata.append(fmt.block('(', ')', [s]))
in... | [
"def",
"to_fmt",
"(",
"self",
")",
"->",
"str",
":",
"infos",
"=",
"fmt",
".",
"end",
"(",
"\";\\n\"",
",",
"[",
"]",
")",
"s",
"=",
"fmt",
".",
"sep",
"(",
"', '",
",",
"[",
"]",
")",
"for",
"ids",
"in",
"sorted",
"(",
"self",
".",
"states",... | 37.4 | 14.466667 |
def inurl(needles, haystack, position='any'):
"""convenience function to make string.find return bool"""
count = 0
# lowercase everything to do case-insensitive search
haystack2 = haystack.lower()
for needle in needles:
needle2 = needle.lower()
if position == 'any':
if... | [
"def",
"inurl",
"(",
"needles",
",",
"haystack",
",",
"position",
"=",
"'any'",
")",
":",
"count",
"=",
"0",
"# lowercase everything to do case-insensitive search",
"haystack2",
"=",
"haystack",
".",
"lower",
"(",
")",
"for",
"needle",
"in",
"needles",
":",
"n... | 26.541667 | 17.125 |
def _get_path():
"""Guarantee that /usr/local/bin and /usr/bin are in PATH"""
if _path:
return _path[0]
environ_paths = set(os.environ['PATH'].split(':'))
environ_paths.add('/usr/local/bin')
environ_paths.add('/usr/bin')
_path.append(':'.join(environ_paths))
logger.debug('PATH = %s',... | [
"def",
"_get_path",
"(",
")",
":",
"if",
"_path",
":",
"return",
"_path",
"[",
"0",
"]",
"environ_paths",
"=",
"set",
"(",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"':'",
")",
")",
"environ_paths",
".",
"add",
"(",
"'/usr/local/bi... | 34.2 | 11.2 |
def get_api_user_key(self, api_dev_key, username=None, password=None):
'''
Get api user key to enable posts from user accounts if username
and password available.
Not getting an api_user_key means that the posts will be "guest" posts
'''
username = username or get_config(... | [
"def",
"get_api_user_key",
"(",
"self",
",",
"api_dev_key",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"username",
"=",
"username",
"or",
"get_config",
"(",
"'pastebin'",
",",
"'api_user_name'",
")",
"password",
"=",
"password",
"o... | 43.458333 | 18.625 |
def contingency_table(dataframe, rownames, colnames, margins=True):
"""Contingency Table (also called Cross Tabulation)
- Table in a matrix format that displays the (multivariate) frequency distribution of the variables
- http://en.wikipedia.org/wiki/Contingency_table
Args:
rownames:... | [
"def",
"contingency_table",
"(",
"dataframe",
",",
"rownames",
",",
"colnames",
",",
"margins",
"=",
"True",
")",
":",
"# Taking just the rownames + colnames of the dataframe",
"sub_set",
"=",
"[",
"rownames",
",",
"colnames",
"]",
"_sub_df",
"=",
"dataframe",
"[",
... | 60.083333 | 28.583333 |
def load_conf(self, instance_id, instance_name, conf):
"""Load configuration received from Arbiter and pushed by our Scheduler daemon
:param instance_name: scheduler instance name
:type instance_name: str
:param instance_id: scheduler instance id
:type instance_id: str
:... | [
"def",
"load_conf",
"(",
"self",
",",
"instance_id",
",",
"instance_name",
",",
"conf",
")",
":",
"self",
".",
"pushed_conf",
"=",
"conf",
"logger",
".",
"info",
"(",
"\"loading my configuration (%s / %s):\"",
",",
"instance_id",
",",
"self",
".",
"pushed_conf",... | 45 | 19.625 |
def local_ip():
"""Get the local network IP of this machine"""
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith('127.'):
# Check eth0, eth1, eth2, en0, ...
interfaces = [
i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
] # :(
for inte... | [
"def",
"local_ip",
"(",
")",
":",
"ip",
"=",
"socket",
".",
"gethostbyname",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"if",
"ip",
".",
"startswith",
"(",
"'127.'",
")",
":",
"# Check eth0, eth1, eth2, en0, ...",
"interfaces",
"=",
"[",
"i",
"+",
... | 31.533333 | 15.666667 |
def bestModelInSprint(self, sprintIdx):
"""Return the best model ID and it's errScore from the given sprint,
which may still be in progress. This returns the best score from all models
in the sprint which have matured so far.
Parameters:
-------------------------------------------------------------... | [
"def",
"bestModelInSprint",
"(",
"self",
",",
"sprintIdx",
")",
":",
"# Get all the swarms in this sprint",
"swarms",
"=",
"self",
".",
"getAllSwarms",
"(",
"sprintIdx",
")",
"# Get the best model and score from each swarm",
"bestModelId",
"=",
"None",
"bestErrScore",
"="... | 35.5 | 16.181818 |
def submit_ham(self, params):
"""For submitting a ham comment to Akismet."""
# Check required params for submit-ham
for required in ['blog', 'user_ip', 'user_agent']:
if required not in params:
raise MissingParams(required)
response = self._request(... | [
"def",
"submit_ham",
"(",
"self",
",",
"params",
")",
":",
"# Check required params for submit-ham",
"for",
"required",
"in",
"[",
"'blog'",
",",
"'user_ip'",
",",
"'user_agent'",
"]",
":",
"if",
"required",
"not",
"in",
"params",
":",
"raise",
"MissingParams",
... | 32.214286 | 15.642857 |
def step_note_that(context, remark):
"""
Used as generic step that provides an additional remark/hint
and enhance the readability/understanding without performing any check.
.. code-block:: gherkin
Given that today is "April 1st"
But note that "April 1st is Fools day (and beware)"
... | [
"def",
"step_note_that",
"(",
"context",
",",
"remark",
")",
":",
"log",
"=",
"getattr",
"(",
"context",
",",
"\"log\"",
",",
"None",
")",
"if",
"log",
":",
"log",
".",
"info",
"(",
"u\"NOTE: %s;\"",
"%",
"remark",
")"
] | 31.153846 | 16.076923 |
def evaluate(self, num_eval_batches=None):
"""Run one round of evaluation, return loss and accuracy."""
num_eval_batches = num_eval_batches or self.num_eval_batches
with tf.Graph().as_default() as graph:
self.tensors = self.model.build_eval_graph(self.eval_data_paths,
... | [
"def",
"evaluate",
"(",
"self",
",",
"num_eval_batches",
"=",
"None",
")",
":",
"num_eval_batches",
"=",
"num_eval_batches",
"or",
"self",
".",
"num_eval_batches",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
"as",
"graph",
":",
"self... | 40.756757 | 19.081081 |
def clear_matplotlib_ticks(ax=None, axis="both"):
"""
Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" or "horizontal", "y... | [
"def",
"clear_matplotlib_ticks",
"(",
"ax",
"=",
"None",
",",
"axis",
"=",
"\"both\"",
")",
":",
"if",
"not",
"ax",
":",
"return",
"if",
"axis",
".",
"lower",
"(",
")",
"in",
"[",
"\"both\"",
",",
"\"x\"",
",",
"\"horizontal\"",
"]",
":",
"ax",
".",
... | 29.388889 | 17.722222 |
def execute(self, **minimize_options):
"""
Execute the basin-hopping minimization.
:param minimize_options: options to be passed on to
:func:`scipy.optimize.basinhopping`.
:return: :class:`symfit.core.fit_results.FitResults`
"""
if 'minimizer_kwargs' not in m... | [
"def",
"execute",
"(",
"self",
",",
"*",
"*",
"minimize_options",
")",
":",
"if",
"'minimizer_kwargs'",
"not",
"in",
"minimize_options",
":",
"minimize_options",
"[",
"'minimizer_kwargs'",
"]",
"=",
"{",
"}",
"if",
"'method'",
"not",
"in",
"minimize_options",
... | 51.033333 | 28.1 |
def convert_timestamps(obj):
"""
Convert unix timestamps in the scraper output to python datetimes
so that they will be saved properly as Mongo datetimes.
"""
for key in ('date', 'when', 'end', 'start_date', 'end_date'):
value = obj.get(key)
if value:
try:
... | [
"def",
"convert_timestamps",
"(",
"obj",
")",
":",
"for",
"key",
"in",
"(",
"'date'",
",",
"'when'",
",",
"'end'",
",",
"'start_date'",
",",
"'end_date'",
")",
":",
"value",
"=",
"obj",
".",
"get",
"(",
"key",
")",
"if",
"value",
":",
"try",
":",
"... | 33.277778 | 18.388889 |
def order(self, did, service_definition_id, consumer_account, auto_consume=False):
"""
Sign service agreement.
Sign the service agreement defined in the service section identified
by `service_definition_id` in the ddo and send the signed agreement to the purchase endpoint
associ... | [
"def",
"order",
"(",
"self",
",",
"did",
",",
"service_definition_id",
",",
"consumer_account",
",",
"auto_consume",
"=",
"False",
")",
":",
"assert",
"consumer_account",
".",
"address",
"in",
"self",
".",
"_keeper",
".",
"accounts",
",",
"f'Unrecognized consume... | 43.848485 | 25.060606 |
def print_report(label, user, system, real):
"""
Prints the report of one step of a benchmark.
"""
print("{:<12s} {:12f} {:12f} ( {:12f} )".format(label,
user,
system,
... | [
"def",
"print_report",
"(",
"label",
",",
"user",
",",
"system",
",",
"real",
")",
":",
"print",
"(",
"\"{:<12s} {:12f} {:12f} ( {:12f} )\"",
".",
"format",
"(",
"label",
",",
"user",
",",
"system",
",",
"real",
")",
")"
] | 42.375 | 10.625 |
def stream(self):
"""The workhorse of cinje: transform input lines and emit output lines.
After constructing an instance with a set of input lines iterate this property to generate the template.
"""
if 'init' not in self.flag:
root = True
self.prepare()
else:
root = False
# Track which lin... | [
"def",
"stream",
"(",
"self",
")",
":",
"if",
"'init'",
"not",
"in",
"self",
".",
"flag",
":",
"root",
"=",
"True",
"self",
".",
"prepare",
"(",
")",
"else",
":",
"root",
"=",
"False",
"# Track which lines were generated in response to which lines of source code... | 38.972973 | 32.702703 |
def norm(self) -> bk.BKTensor:
"""Return the norm of this vector"""
return bk.absolute(bk.inner(self.tensor, self.tensor)) | [
"def",
"norm",
"(",
"self",
")",
"->",
"bk",
".",
"BKTensor",
":",
"return",
"bk",
".",
"absolute",
"(",
"bk",
".",
"inner",
"(",
"self",
".",
"tensor",
",",
"self",
".",
"tensor",
")",
")"
] | 45.333333 | 10.666667 |
def update(self, sums):
"""
Update self.et with the sums as returned by VersionsX.sums_get
@param sums: {'version': {'file1':'hash1'}}
"""
for version in sums:
hashes = sums[version]
for filename in hashes:
hsh = hashes[filename]
... | [
"def",
"update",
"(",
"self",
",",
"sums",
")",
":",
"for",
"version",
"in",
"sums",
":",
"hashes",
"=",
"sums",
"[",
"version",
"]",
"for",
"filename",
"in",
"hashes",
":",
"hsh",
"=",
"hashes",
"[",
"filename",
"]",
"file_xpath",
"=",
"'./files/*[@ur... | 41.181818 | 15.636364 |
def subelement(element, xpath, tag, text, **kwargs):
"""
Searches element matching the *xpath* in *parent* and replaces it's *tag*,
*text* and *kwargs* attributes.
If the element in *xpath* is not found a new child element is created
with *kwargs* attributes and added.
Returns the found/create... | [
"def",
"subelement",
"(",
"element",
",",
"xpath",
",",
"tag",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"subelm",
"=",
"element",
".",
"find",
"(",
"xpath",
")",
"if",
"subelm",
"is",
"None",
":",
"subelm",
"=",
"etree",
".",
"SubElement",
"... | 25.954545 | 19.227273 |
def split_docstring(self, block):
"""Split a code block into a docstring and a body."""
try:
first_line, rest_of_lines = block.split("\n", 1)
except ValueError:
pass
else:
raw_first_line = split_leading_trailing_indent(rem_comment(first_line))[1]
... | [
"def",
"split_docstring",
"(",
"self",
",",
"block",
")",
":",
"try",
":",
"first_line",
",",
"rest_of_lines",
"=",
"block",
".",
"split",
"(",
"\"\\n\"",
",",
"1",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"raw_first_line",
"=",
"split_leadin... | 40.090909 | 18.909091 |
def slug_sub(match):
"""Assigns id-less headers a slug that is derived from their
titles. Slugs are generated by lower-casing the titles, stripping
all punctuation, and converting spaces to hyphens (-).
"""
level = match.group(1)
title = match.group(2)
slug = title.lower()
slug = re.sub(... | [
"def",
"slug_sub",
"(",
"match",
")",
":",
"level",
"=",
"match",
".",
"group",
"(",
"1",
")",
"title",
"=",
"match",
".",
"group",
"(",
"2",
")",
"slug",
"=",
"title",
".",
"lower",
"(",
")",
"slug",
"=",
"re",
".",
"sub",
"(",
"r'<.+?>|[^\\w-]'... | 37.357143 | 14.285714 |
def help_center_article_translations_missing(self, article_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#list-missing-translations"
api_path = "/api/v2/help_center/articles/{article_id}/translations/missing.json"
api_path = api_path.format(article_id=articl... | [
"def",
"help_center_article_translations_missing",
"(",
"self",
",",
"article_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/articles/{article_id}/translations/missing.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"article_id",
... | 73.2 | 33.2 |
def get_version(self):
"""
This gets the version of OpenALPR
:return: Version information
"""
ptr = self._get_version_func(self.alpr_pointer)
version_number = ctypes.cast(ptr, ctypes.c_char_p).value
version_number = _convert_from_charp(version_number)
se... | [
"def",
"get_version",
"(",
"self",
")",
":",
"ptr",
"=",
"self",
".",
"_get_version_func",
"(",
"self",
".",
"alpr_pointer",
")",
"version_number",
"=",
"ctypes",
".",
"cast",
"(",
"ptr",
",",
"ctypes",
".",
"c_char_p",
")",
".",
"value",
"version_number",... | 31.916667 | 15.583333 |
def es_get_class_defs(cls_def, cls_name):
"""
Reads through the class defs and gets the related es class
defintions
Args:
-----
class_defs: RdfDataset of class definitions
"""
rtn_dict = {key: value for key, value in cls_def.items() \
if key.startswith("kds_es")}
... | [
"def",
"es_get_class_defs",
"(",
"cls_def",
",",
"cls_name",
")",
":",
"rtn_dict",
"=",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"cls_def",
".",
"items",
"(",
")",
"if",
"key",
".",
"startswith",
"(",
"\"kds_es\"",
")",
"}",
"for",
... | 26.642857 | 17.214286 |
def _draw_mark(mark_type, options={}, axes_options={}, **kwargs):
"""Draw the mark of specified mark type.
Parameters
----------
mark_type: type
The type of mark to be drawn
options: dict (default: {})
Options for the scales to be created. If a scale labeled 'x' is
required ... | [
"def",
"_draw_mark",
"(",
"mark_type",
",",
"options",
"=",
"{",
"}",
",",
"axes_options",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"fig",
"=",
"kwargs",
".",
"pop",
"(",
"'figure'",
",",
"current_figure",
"(",
")",
")",
"scales",
"=",
"kw... | 44.12 | 17.413333 |
def copy_data(self, project, logstore, from_time, to_time=None,
to_client=None, to_project=None, to_logstore=None,
shard_list=None,
batch_size=None, compress=None, new_topic=None, new_source=None):
"""
copy data from one logstore to another one ... | [
"def",
"copy_data",
"(",
"self",
",",
"project",
",",
"logstore",
",",
"from_time",
",",
"to_time",
"=",
"None",
",",
"to_client",
"=",
"None",
",",
"to_project",
"=",
"None",
",",
"to_logstore",
"=",
"None",
",",
"shard_list",
"=",
"None",
",",
"batch_s... | 53.3 | 40.22 |
def list_probes():
"""Return the list of built-in probes."""
curdir = op.realpath(op.dirname(__file__))
return [op.splitext(fn)[0] for fn in os.listdir(op.join(curdir, 'probes'))
if fn.endswith('.prb')] | [
"def",
"list_probes",
"(",
")",
":",
"curdir",
"=",
"op",
".",
"realpath",
"(",
"op",
".",
"dirname",
"(",
"__file__",
")",
")",
"return",
"[",
"op",
".",
"splitext",
"(",
"fn",
")",
"[",
"0",
"]",
"for",
"fn",
"in",
"os",
".",
"listdir",
"(",
... | 44.4 | 14.2 |
def _get(self, api_call, params=None, method='GET', auth=False,
file_=None):
"""Function to preapre API call.
Parameters:
api_call (str): API function to be called.
params (str): API function parameters.
method (str): (Defauld: GET) HTTP method (GET, POS... | [
"def",
"_get",
"(",
"self",
",",
"api_call",
",",
"params",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"auth",
"=",
"False",
",",
"file_",
"=",
"None",
")",
":",
"url",
"=",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"site_url",
",",
"api_... | 38.03125 | 21.0625 |
def getitem(self, obj, argument):
"""Get an item or attribute of an object but prefer the item."""
try:
return obj[argument]
except (TypeError, LookupError):
if isinstance(argument, string_types):
try:
attr = str(argument)
... | [
"def",
"getitem",
"(",
"self",
",",
"obj",
",",
"argument",
")",
":",
"try",
":",
"return",
"obj",
"[",
"argument",
"]",
"except",
"(",
"TypeError",
",",
"LookupError",
")",
":",
"if",
"isinstance",
"(",
"argument",
",",
"string_types",
")",
":",
"try"... | 36.0625 | 10.6875 |
def _log_exception(self, exception):
"""
Logs an exception.
:param Exception exception: The exception.
:rtype: None
"""
self._io.error(str(exception).strip().split(os.linesep)) | [
"def",
"_log_exception",
"(",
"self",
",",
"exception",
")",
":",
"self",
".",
"_io",
".",
"error",
"(",
"str",
"(",
"exception",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"os",
".",
"linesep",
")",
")"
] | 24.222222 | 16.888889 |
def fix_linkdate(self, entry):
"""
Give a date for the entry, depending on feed.sync_by_date
Save it as feed.linkdate
"""
if self.sync_by_date:
try:
entry.linkdate = list(entry.published_parsed)
self.linkdate = list(entry.published_pars... | [
"def",
"fix_linkdate",
"(",
"self",
",",
"entry",
")",
":",
"if",
"self",
".",
"sync_by_date",
":",
"try",
":",
"entry",
".",
"linkdate",
"=",
"list",
"(",
"entry",
".",
"published_parsed",
")",
"self",
".",
"linkdate",
"=",
"list",
"(",
"entry",
".",
... | 44.666667 | 16.952381 |
def includePoint(self, p):
"""Extend rectangle to include point p."""
if not len(p) == 2:
raise ValueError("bad sequ. length")
self.x0, self.y0, self.x1, self.y1 = TOOLS._include_point_in_rect(self, p)
return self | [
"def",
"includePoint",
"(",
"self",
",",
"p",
")",
":",
"if",
"not",
"len",
"(",
"p",
")",
"==",
"2",
":",
"raise",
"ValueError",
"(",
"\"bad sequ. length\"",
")",
"self",
".",
"x0",
",",
"self",
".",
"y0",
",",
"self",
".",
"x1",
",",
"self",
".... | 42 | 16.333333 |
def get_stack(self, f, t):
"""Build the stack from frame and traceback"""
stack = []
if t and t.tb_frame == f:
t = t.tb_next
while f is not None:
stack.append((f, f.f_lineno))
f = f.f_back
stack.reverse()
i = max(0, len(stack) - 1)
... | [
"def",
"get_stack",
"(",
"self",
",",
"f",
",",
"t",
")",
":",
"stack",
"=",
"[",
"]",
"if",
"t",
"and",
"t",
".",
"tb_frame",
"==",
"f",
":",
"t",
"=",
"t",
".",
"tb_next",
"while",
"f",
"is",
"not",
"None",
":",
"stack",
".",
"append",
"(",... | 30.75 | 11.625 |
async def close_async(self):
"""Close the client asynchronously. This includes closing the Session
and CBS authentication layer as well as the Connection.
If the client was opened using an external Connection,
this will be left intact.
"""
if self.message_handler:
... | [
"async",
"def",
"close_async",
"(",
"self",
")",
":",
"if",
"self",
".",
"message_handler",
":",
"await",
"self",
".",
"message_handler",
".",
"destroy_async",
"(",
")",
"self",
".",
"message_handler",
"=",
"None",
"self",
".",
"_shutdown",
"=",
"True",
"i... | 43.851852 | 14 |
def executeTask(self,
inputs,
outSR=None,
processSR=None,
returnZ=False,
returnM=False,
f="json",
method="POST"
):
"""
performs the execute task... | [
"def",
"executeTask",
"(",
"self",
",",
"inputs",
",",
"outSR",
"=",
"None",
",",
"processSR",
"=",
"None",
",",
"returnZ",
"=",
"False",
",",
"returnM",
"=",
"False",
",",
"f",
"=",
"\"json\"",
",",
"method",
"=",
"\"POST\"",
")",
":",
"params",
"="... | 35.846154 | 11.846154 |
def symmetric_error(self):
"""Return the symmertic error
Similar to above, but zero implies no error estimate,
and otherwise this will either be the symmetric error,
or the average of the low,high asymmetric errors.
"""
# ADW: Should this be `np.nan`?
if self.__e... | [
"def",
"symmetric_error",
"(",
"self",
")",
":",
"# ADW: Should this be `np.nan`?",
"if",
"self",
".",
"__errors__",
"is",
"None",
":",
"return",
"0.",
"if",
"np",
".",
"isscalar",
"(",
"self",
".",
"__errors__",
")",
":",
"return",
"self",
".",
"__errors__"... | 37.307692 | 12.846154 |
def load_keysym_group(group):
'''Load all the keysyms in group.
Given a group name such as 'latin1' or 'katakana' load the keysyms
defined in module 'Xlib.keysymdef.group-name' into this XK module.'''
if '.' in group:
raise ValueError('invalid keysym group name: %s' % group)
G = globals() ... | [
"def",
"load_keysym_group",
"(",
"group",
")",
":",
"if",
"'.'",
"in",
"group",
":",
"raise",
"ValueError",
"(",
"'invalid keysym group name: %s'",
"%",
"group",
")",
"G",
"=",
"globals",
"(",
")",
"#Get a reference to XK.__dict__ a.k.a. globals",
"#Import just the ke... | 34.608696 | 22.782609 |
def quoted(text):
"""
Args:
text (str | unicode | None): Text to optionally quote
Returns:
(str): Quoted if 'text' contains spaces
"""
if text and " " in text:
sep = "'" if '"' in text else '"'
return "%s%s%s" % (sep, text, sep)
return text | [
"def",
"quoted",
"(",
"text",
")",
":",
"if",
"text",
"and",
"\" \"",
"in",
"text",
":",
"sep",
"=",
"\"'\"",
"if",
"'\"'",
"in",
"text",
"else",
"'\"'",
"return",
"\"%s%s%s\"",
"%",
"(",
"sep",
",",
"text",
",",
"sep",
")",
"return",
"text"
] | 23.833333 | 15.833333 |
def metablock(self):
"""Process the data.
Relevant variables of self:
numberOfBlockTypes[kind]: number of block types
currentBlockTypes[kind]: current block types (=0)
literalContextModes: the context modes for the literal block types
currentBlockCounts[kind]: counters fo... | [
"def",
"metablock",
"(",
"self",
")",
":",
"print",
"(",
"'Meta block contents'",
".",
"center",
"(",
"60",
",",
"'='",
")",
")",
"self",
".",
"currentBlockTypes",
"=",
"{",
"L",
":",
"0",
",",
"I",
":",
"0",
",",
"D",
":",
"0",
",",
"pL",
":",
... | 43.626263 | 13.89899 |
def write_json(self, path, contents, message):
"""Write json to disk.
Args:
path (str): the path to write to
contents (dict): the contents of the json blob
message (str): the message to log
"""
log.debug(message.format(path=path))
makedirs(os... | [
"def",
"write_json",
"(",
"self",
",",
"path",
",",
"contents",
",",
"message",
")",
":",
"log",
".",
"debug",
"(",
"message",
".",
"format",
"(",
"path",
"=",
"path",
")",
")",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
... | 32.769231 | 13.153846 |
def _scobit_transform_deriv_v(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
output_array=None,
*args, **kwargs):
"""
Parameters
----------
sy... | [
"def",
"_scobit_transform_deriv_v",
"(",
"systematic_utilities",
",",
"alt_IDs",
",",
"rows_to_alts",
",",
"shape_params",
",",
"output_array",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Note the np.exp is needed because the raw curvature par... | 48.936709 | 22.202532 |
def integridad_data(self, data_integr=None, key=None):
"""
Comprueba que el index de cada dataframe de la base de datos sea de fechas, único (sin duplicados) y creciente
:param data_integr:
:param key:
"""
def _assert_integridad(df):
if df is not None and not ... | [
"def",
"integridad_data",
"(",
"self",
",",
"data_integr",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"def",
"_assert_integridad",
"(",
"df",
")",
":",
"if",
"df",
"is",
"not",
"None",
"and",
"not",
"df",
".",
"empty",
":",
"assert",
"(",
"df",
... | 38.05 | 18.05 |
def deep_update_dict(default, options):
"""
Updates the values in a nested dict, while unspecified values will remain
unchanged
"""
for key in options.keys():
default_setting = default.get(key)
new_setting = options.get(key)
if isinstance(default_setting, dict):
d... | [
"def",
"deep_update_dict",
"(",
"default",
",",
"options",
")",
":",
"for",
"key",
"in",
"options",
".",
"keys",
"(",
")",
":",
"default_setting",
"=",
"default",
".",
"get",
"(",
"key",
")",
"new_setting",
"=",
"options",
".",
"get",
"(",
"key",
")",
... | 33.916667 | 10.916667 |
def Enumerate():
"""See base class."""
# Init a HID manager
hid_mgr = iokit.IOHIDManagerCreate(None, None)
if not hid_mgr:
raise errors.OsHidError('Unable to obtain HID manager reference')
iokit.IOHIDManagerSetDeviceMatching(hid_mgr, None)
# Get devices from HID manager
device_set_ref... | [
"def",
"Enumerate",
"(",
")",
":",
"# Init a HID manager",
"hid_mgr",
"=",
"iokit",
".",
"IOHIDManagerCreate",
"(",
"None",
",",
"None",
")",
"if",
"not",
"hid_mgr",
":",
"raise",
"errors",
".",
"OsHidError",
"(",
"'Unable to obtain HID manager reference'",
")",
... | 38.864865 | 20.243243 |
def set_substitution(self, word, substitution):
"""
Add a word substitution
:param word: The word to replace
:type word: str
:param substitution: The word's substitution
:type substitution: str
"""
# Parse the word and its substitution
raw_word ... | [
"def",
"set_substitution",
"(",
"self",
",",
"word",
",",
"substitution",
")",
":",
"# Parse the word and its substitution",
"raw_word",
"=",
"re",
".",
"escape",
"(",
"word",
")",
"raw_substitution",
"=",
"substitution",
"case_word",
"=",
"re",
".",
"escape",
"... | 43.166667 | 23.766667 |
def do_EOF(self, args):
"""Exit on system end of file character"""
if _debug: ConsoleCmd._debug("do_EOF %r", args)
return self.do_exit(args) | [
"def",
"do_EOF",
"(",
"self",
",",
"args",
")",
":",
"if",
"_debug",
":",
"ConsoleCmd",
".",
"_debug",
"(",
"\"do_EOF %r\"",
",",
"args",
")",
"return",
"self",
".",
"do_exit",
"(",
"args",
")"
] | 40.25 | 9.75 |
def _make_non_blocking(file_obj):
"""make file object non-blocking
Windows doesn't have the fcntl module, but someone on
stack overflow supplied this code as an answer, and it works
http://stackoverflow.com/a/34504971/2893090"""
if USING_WINDOWS:
LPDWORD = POINTER(DWORD)
PIPE_NOWAIT... | [
"def",
"_make_non_blocking",
"(",
"file_obj",
")",
":",
"if",
"USING_WINDOWS",
":",
"LPDWORD",
"=",
"POINTER",
"(",
"DWORD",
")",
"PIPE_NOWAIT",
"=",
"wintypes",
".",
"DWORD",
"(",
"0x00000001",
")",
"SetNamedPipeHandleState",
"=",
"windll",
".",
"kernel32",
"... | 39.4 | 23.24 |
def _match_regex(regex, obj):
"""
Returns true if the regex matches the object, or a string in the object
if it is some sort of container.
:param regex: A regex.
:type regex: ``regex``
:param obj: An arbitrary object.
:type object: ``object``
:rtype: ``bool``
"""
if isinstance(... | [
"def",
"_match_regex",
"(",
"regex",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"return",
"len",
"(",
"regex",
".",
"findall",
"(",
"obj",
")",
")",
">",
"0",
"elif",
"isinstance",
"(",
"obj",
"... | 30.590909 | 14.045455 |
def placeholder_symbol_table(name, version, max_id):
"""Constructs a shared symbol table that consists symbols that all have no known text.
This is generally used for cases where a shared symbol table is not available by the
application.
Args:
name (unicode): The name of the shared symbol tabl... | [
"def",
"placeholder_symbol_table",
"(",
"name",
",",
"version",
",",
"max_id",
")",
":",
"if",
"version",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Version must be grater than or equal to 1: %s'",
"%",
"version",
")",
"if",
"max_id",
"<",
"0",
":",
"raise",
... | 34.115385 | 23.846154 |
def scalar_projection(v1, v2):
'''compute the scalar projection of v1 upon v2
Args:
v1, v2: iterable
indices 0, 1, 2 corresponding to cartesian coordinates
Returns:
3-vector of the projection of point p onto the direction of v
'''
return np.dot(v1, v2) / np.linalg.norm(v2) | [
"def",
"scalar_projection",
"(",
"v1",
",",
"v2",
")",
":",
"return",
"np",
".",
"dot",
"(",
"v1",
",",
"v2",
")",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"v2",
")"
] | 28.090909 | 24.090909 |
def ensure_has_same_campaigns(self):
"""Ensure that the 2 campaigns to merge have been generated
from the same campaign.yaml
"""
lhs_yaml = osp.join(self.lhs, 'campaign.yaml')
rhs_yaml = osp.join(self.rhs, 'campaign.yaml')
assert osp.isfile(lhs_yaml)
assert osp.is... | [
"def",
"ensure_has_same_campaigns",
"(",
"self",
")",
":",
"lhs_yaml",
"=",
"osp",
".",
"join",
"(",
"self",
".",
"lhs",
",",
"'campaign.yaml'",
")",
"rhs_yaml",
"=",
"osp",
".",
"join",
"(",
"self",
".",
"rhs",
",",
"'campaign.yaml'",
")",
"assert",
"os... | 41.444444 | 5.888889 |
def encoded_query(self):
"""Returns the encoded query string of the URL. This may be different from the rawquery element,
as that contains the query parsed by urllib but unmodified.
The return value takes the form of key=value&key=value, and it never contains a leading question mark.
"""... | [
"def",
"encoded_query",
"(",
"self",
")",
":",
"if",
"self",
".",
"query",
"is",
"not",
"None",
"and",
"self",
".",
"query",
"!=",
"''",
"and",
"self",
".",
"query",
"!=",
"{",
"}",
":",
"try",
":",
"return",
"urlencode",
"(",
"self",
".",
"query",... | 54.916667 | 28.166667 |
def read_html(io, match='.+', flavor=None, header=None, index_col=None,
skiprows=None, attrs=None, parse_dates=False,
tupleize_cols=None, thousands=',', encoding=None,
decimal='.', converters=None, na_values=None,
keep_default_na=True, displayed_only=True):
r"... | [
"def",
"read_html",
"(",
"io",
",",
"match",
"=",
"'.+'",
",",
"flavor",
"=",
"None",
",",
"header",
"=",
"None",
",",
"index_col",
"=",
"None",
",",
"skiprows",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"parse_dates",
"=",
"False",
",",
"tupleize... | 42.857143 | 26.910714 |
def securityHandler(self, value):
""" sets the security handler """
if isinstance(value, BaseSecurityHandler):
if isinstance(value, security.AGOLTokenSecurityHandler):
self._securityHandler = value
elif isinstance(value, security.OAuthSecurityHandler):
... | [
"def",
"securityHandler",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"BaseSecurityHandler",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"security",
".",
"AGOLTokenSecurityHandler",
")",
":",
"self",
".",
"_securityHandler"... | 42.777778 | 13.777778 |
def _remove_debug_only(self):
"""Iterate through each handler removing the invalid dictConfig key of
debug_only.
"""
LOGGER.debug('Removing debug only from handlers')
for handler in self.config[self.HANDLERS]:
if self.DEBUG_ONLY in self.config[self.HANDLERS][handler]... | [
"def",
"_remove_debug_only",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Removing debug only from handlers'",
")",
"for",
"handler",
"in",
"self",
".",
"config",
"[",
"self",
".",
"HANDLERS",
"]",
":",
"if",
"self",
".",
"DEBUG_ONLY",
"in",
"self",... | 42.888889 | 17.888889 |
def _OsmoticPressure(T, P, S):
"""Procedure to calculate the osmotic pressure of seawater
Parameters
----------
T : float
Tmperature, [K]
P : float
Pressure, [MPa]
S : float
Salinity, [kg/kg]
Returns
-------
Posm : float
Osmotic pressure, [MPa]
... | [
"def",
"_OsmoticPressure",
"(",
"T",
",",
"P",
",",
"S",
")",
":",
"pw",
"=",
"_Region1",
"(",
"T",
",",
"P",
")",
"gw",
"=",
"pw",
"[",
"\"h\"",
"]",
"-",
"T",
"*",
"pw",
"[",
"\"s\"",
"]",
"def",
"f",
"(",
"Posm",
")",
":",
"pw2",
"=",
... | 22.515152 | 21.818182 |
def _make_package(binder):
"""Makes an ``.epub.Package`` from a Binder'ish instance."""
package_id = binder.id
if package_id is None:
package_id = hash(binder)
package_name = "{}.opf".format(package_id)
extensions = get_model_extensions(binder)
template_env = jinja2.Environment(trim_... | [
"def",
"_make_package",
"(",
"binder",
")",
":",
"package_id",
"=",
"binder",
".",
"id",
"if",
"package_id",
"is",
"None",
":",
"package_id",
"=",
"hash",
"(",
"binder",
")",
"package_name",
"=",
"\"{}.opf\"",
".",
"format",
"(",
"package_id",
")",
"extens... | 40.871429 | 18.028571 |
def _write_json(filepath, data, kwargs):
"""See documentation of mpu.io.write."""
with io_stl.open(filepath, 'w', encoding='utf8') as outfile:
if 'indent' not in kwargs:
kwargs['indent'] = 4
if 'sort_keys' not in kwargs:
kwargs['sort_keys'] = True
if 'separators' ... | [
"def",
"_write_json",
"(",
"filepath",
",",
"data",
",",
"kwargs",
")",
":",
"with",
"io_stl",
".",
"open",
"(",
"filepath",
",",
"'w'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"outfile",
":",
"if",
"'indent'",
"not",
"in",
"kwargs",
":",
"kwargs",
... | 39.285714 | 5.714286 |
def get_config_parameter_loglevel(config: ConfigParser,
section: str,
param: str,
default: int) -> int:
"""
Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g.
mapping ``'debug'`` to ``logg... | [
"def",
"get_config_parameter_loglevel",
"(",
"config",
":",
"ConfigParser",
",",
"section",
":",
"str",
",",
"param",
":",
"str",
",",
"default",
":",
"int",
")",
"->",
"int",
":",
"try",
":",
"value",
"=",
"config",
".",
"get",
"(",
"section",
",",
"p... | 35.742857 | 13.857143 |
def markdown2html(markdown_text):
'''
Convert markdown text to HTML. with extensions.
:param markdown_text: The markdown text.
:return: The HTML text.
'''
html = markdown.markdown(
markdown_text,
extensions=[
WikiLinkExtension(base_url='/wiki/', end_url=''),
... | [
"def",
"markdown2html",
"(",
"markdown_text",
")",
":",
"html",
"=",
"markdown",
".",
"markdown",
"(",
"markdown_text",
",",
"extensions",
"=",
"[",
"WikiLinkExtension",
"(",
"base_url",
"=",
"'/wiki/'",
",",
"end_url",
"=",
"''",
")",
",",
"'markdown.extensio... | 33.65 | 14.25 |
def _speak_none(self, element):
"""
No speak any content of element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
# pylint: disable=no-self-use
element.set_attribute('role', 'presentation')
element... | [
"def",
"_speak_none",
"(",
"self",
",",
"element",
")",
":",
"# pylint: disable=no-self-use",
"element",
".",
"set_attribute",
"(",
"'role'",
",",
"'presentation'",
")",
"element",
".",
"set_attribute",
"(",
"'aria-hidden'",
",",
"'true'",
")",
"element",
".",
"... | 35.333333 | 16.166667 |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
opt = "db_url"
... | [
"def",
"fix_config",
"(",
"self",
",",
"options",
")",
":",
"opt",
"=",
"\"db_url\"",
"if",
"opt",
"not",
"in",
"options",
":",
"options",
"[",
"opt",
"]",
"=",
"\"jdbc:mysql://somehost:3306/somedatabase\"",
"if",
"opt",
"not",
"in",
"self",
".",
"help",
"... | 33.565217 | 19.391304 |
def do_get_dataset(data, key, create=False):
"""Get a dataset.
Parameters
----------
data : `None` or `dict` of `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`])
Data.
key : `str`
Dataset key.
create : `bool`, optional
C... | [
"def",
"do_get_dataset",
"(",
"data",
",",
"key",
",",
"create",
"=",
"False",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"try",
":",
"return",
"data",
"[",
"key",
"]",
"except",
"KeyError",
":",
"if",
"create",
":",
"dataset",
"=",... | 27.185185 | 19.703704 |
def handle_packet(self, packet):
"""Lets librtmp look at a packet and send a response
if needed."""
if not isinstance(packet, RTMPPacket):
raise ValueError("A RTMPPacket argument is required")
return librtmp.RTMP_ClientPacket(self.rtmp, packet.packet) | [
"def",
"handle_packet",
"(",
"self",
",",
"packet",
")",
":",
"if",
"not",
"isinstance",
"(",
"packet",
",",
"RTMPPacket",
")",
":",
"raise",
"ValueError",
"(",
"\"A RTMPPacket argument is required\"",
")",
"return",
"librtmp",
".",
"RTMP_ClientPacket",
"(",
"se... | 36.625 | 18.125 |
def check_block_spacing(
self,
first_block_type: LineType,
second_block_type: LineType,
error_message: str,
) -> typing.Generator[AAAError, None, None]:
"""
Checks there is a clear single line between ``first_block_type`` and
``second_block_type``.
No... | [
"def",
"check_block_spacing",
"(",
"self",
",",
"first_block_type",
":",
"LineType",
",",
"second_block_type",
":",
"LineType",
",",
"error_message",
":",
"str",
",",
")",
"->",
"typing",
".",
"Generator",
"[",
"AAAError",
",",
"None",
",",
"None",
"]",
":",... | 34.285714 | 21.22449 |
def _add_index_server(self):
"""Adds index-server to 'distutil's 'index-servers' param."""
index_servers = '\n\t'.join(self.servers.keys())
self.conf.set('distutils', 'index-servers', index_servers) | [
"def",
"_add_index_server",
"(",
"self",
")",
":",
"index_servers",
"=",
"'\\n\\t'",
".",
"join",
"(",
"self",
".",
"servers",
".",
"keys",
"(",
")",
")",
"self",
".",
"conf",
".",
"set",
"(",
"'distutils'",
",",
"'index-servers'",
",",
"index_servers",
... | 54.75 | 13.5 |
def cli(config, server, api_key, all, credentials, project):
"""Create the cli command line."""
# Check first for the pybossa.rc file to configure server and api-key
home = expanduser("~")
if os.path.isfile(os.path.join(home, '.pybossa.cfg')):
config.parser.read(os.path.join(home, '.pybossa.cfg'... | [
"def",
"cli",
"(",
"config",
",",
"server",
",",
"api_key",
",",
"all",
",",
"credentials",
",",
"project",
")",
":",
"# Check first for the pybossa.rc file to configure server and api-key",
"home",
"=",
"expanduser",
"(",
"\"~\"",
")",
"if",
"os",
".",
"path",
... | 40.622222 | 19.022222 |
def sequence(self):
"""
Returns the volume group sequence number. This number increases
everytime the volume group is modified.
"""
self.open()
seq = lvm_vg_get_seqno(self.handle)
self.close()
return seq | [
"def",
"sequence",
"(",
"self",
")",
":",
"self",
".",
"open",
"(",
")",
"seq",
"=",
"lvm_vg_get_seqno",
"(",
"self",
".",
"handle",
")",
"self",
".",
"close",
"(",
")",
"return",
"seq"
] | 28.777778 | 13.888889 |
def _raw_parse(self):
"""Parse the source to find the interesting facts about its lines.
A handful of member fields are updated.
"""
# Find lines which match an exclusion pattern.
if self.exclude:
self.excluded = self.lines_matching(self.exclude)
# Tokenize... | [
"def",
"_raw_parse",
"(",
"self",
")",
":",
"# Find lines which match an exclusion pattern.",
"if",
"self",
".",
"exclude",
":",
"self",
".",
"excluded",
"=",
"self",
".",
"lines_matching",
"(",
"self",
".",
"exclude",
")",
"# Tokenize, to find excluded suites, to fin... | 44.934211 | 18.631579 |
def fft_frequencies(sr=22050, n_fft=2048):
'''Alternative implementation of `np.fft.fftfreq`
Parameters
----------
sr : number > 0 [scalar]
Audio sampling rate
n_fft : int > 0 [scalar]
FFT window size
Returns
-------
freqs : np.ndarray [shape=(1 + n_fft/2,)]
F... | [
"def",
"fft_frequencies",
"(",
"sr",
"=",
"22050",
",",
"n_fft",
"=",
"2048",
")",
":",
"return",
"np",
".",
"linspace",
"(",
"0",
",",
"float",
"(",
"sr",
")",
"/",
"2",
",",
"int",
"(",
"1",
"+",
"n_fft",
"//",
"2",
")",
",",
"endpoint",
"=",... | 23.5 | 23.1 |
def getattr(self, name, context=None, class_context=True):
"""Get an attribute from this class, using Python's attribute semantic.
This method doesn't look in the :attr:`instance_attrs` dictionary
since it is done by an :class:`Instance` proxy at inference time.
It may return an :class:... | [
"def",
"getattr",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
",",
"class_context",
"=",
"True",
")",
":",
"values",
"=",
"self",
".",
"locals",
".",
"get",
"(",
"name",
",",
"[",
"]",
")",
"if",
"name",
"in",
"self",
".",
"special_attri... | 42.561404 | 22.315789 |
def leaves(value, prefix=None):
"""
LIKE items() BUT RECURSIVE, AND ONLY FOR THE LEAVES (non dict) VALUES
SEE wrap_leaves FOR THE INVERSE
:param value: THE Mapping TO TRAVERSE
:param prefix: OPTIONAL PREFIX GIVEN TO EACH KEY
:return: Data, WHICH EACH KEY BEING A PATH INTO value TREE
"""
... | [
"def",
"leaves",
"(",
"value",
",",
"prefix",
"=",
"None",
")",
":",
"prefix",
"=",
"coalesce",
"(",
"prefix",
",",
"\"\"",
")",
"output",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"value",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"_get"... | 36.2 | 17.5 |
async def handle_server_error(self, req, res, mw_generator, error, err_count=0):
"""
Entry point for handling an exception that occured during
execution of the middleware chain.
This loops through the middleware generator - which should
produce error-handling functions of signatu... | [
"async",
"def",
"handle_server_error",
"(",
"self",
",",
"req",
",",
"res",
",",
"mw_generator",
",",
"error",
",",
"err_count",
"=",
"0",
")",
":",
"if",
"err_count",
">=",
"self",
".",
"error_recursion_max_depth",
":",
"raise",
"Exception",
"(",
"\"Too man... | 39.767857 | 20.946429 |
def compile(self, limit=None, params=None):
"""
Compile expression to whatever execution target, to verify
Returns
-------
compiled : value or list
query representation or list thereof
"""
from ibis.client import compile
return compile(self, l... | [
"def",
"compile",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"from",
"ibis",
".",
"client",
"import",
"compile",
"return",
"compile",
"(",
"self",
",",
"limit",
"=",
"limit",
",",
"params",
"=",
"params",
")"
] | 27.916667 | 15.916667 |
def get_next_seed(key, seed):
"""This takes a seed and generates the next seed in the sequence.
it simply calculates the hmac of the seed with the key. It returns
the next seed
:param key: the key to use for the HMAC
:param seed: the seed to permutate
"""
return... | [
"def",
"get_next_seed",
"(",
"key",
",",
"seed",
")",
":",
"return",
"hmac",
".",
"new",
"(",
"key",
",",
"seed",
",",
"hashlib",
".",
"sha256",
")",
".",
"digest",
"(",
")"
] | 39.666667 | 14.777778 |
def cancel(context, jobs, analysis_id):
"""Cancel all jobs in a run."""
analysis_obj = context.obj['store'].analysis(analysis_id)
if analysis_obj is None:
click.echo('analysis not found')
context.abort()
elif analysis_obj.status != 'running':
click.echo(f"analysis not running: {a... | [
"def",
"cancel",
"(",
"context",
",",
"jobs",
",",
"analysis_id",
")",
":",
"analysis_obj",
"=",
"context",
".",
"obj",
"[",
"'store'",
"]",
".",
"analysis",
"(",
"analysis_id",
")",
"if",
"analysis_obj",
"is",
"None",
":",
"click",
".",
"echo",
"(",
"... | 33.171429 | 15.142857 |
def set_iprouting(self, value=None, default=False, disable=False):
"""Configures the state of global ip routing
EosVersion:
4.13.7M
Args:
value(bool): True if ip routing should be enabled or False if
ip routing should be disabled
default (boo... | [
"def",
"set_iprouting",
"(",
"self",
",",
"value",
"=",
"None",
",",
"default",
"=",
"False",
",",
"disable",
"=",
"False",
")",
":",
"if",
"value",
"is",
"False",
":",
"disable",
"=",
"True",
"cmd",
"=",
"self",
".",
"command_builder",
"(",
"'ip routi... | 36.75 | 22.3 |
def start_discovery(add_callback=None, remove_callback=None):
"""
Start discovering chromecasts on the network.
This method will start discovering chromecasts on a separate thread. When
a chromecast is discovered, the callback will be called with the
discovered chromecast's zeroconf name. This is t... | [
"def",
"start_discovery",
"(",
"add_callback",
"=",
"None",
",",
"remove_callback",
"=",
"None",
")",
":",
"listener",
"=",
"CastListener",
"(",
"add_callback",
",",
"remove_callback",
")",
"service_browser",
"=",
"False",
"try",
":",
"service_browser",
"=",
"ze... | 41.642857 | 22.142857 |
def get(self, rule, default=None):
"""Return the existing version of the given rule. If the rule is
not present in the classifier set, return the default. If no
default was given, use None. This is useful for eliminating
duplicate copies of rules.
Usage:
unique_rule ... | [
"def",
"get",
"(",
"self",
",",
"rule",
",",
"default",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"rule",
",",
"ClassifierRule",
")",
"if",
"(",
"rule",
".",
"condition",
"not",
"in",
"self",
".",
"_population",
"or",
"rule",
".",
"action",
... | 44.96 | 22.36 |
def __check_command_completion(self, testsemicolon=True):
"""Check for command(s) completion
This function should be called each time a new argument is
seen by the parser in order to check a command is complete. As
not only one command can be ended when receiving a new
argument ... | [
"def",
"__check_command_completion",
"(",
"self",
",",
"testsemicolon",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"__curcommand",
".",
"iscomplete",
"(",
")",
":",
"return",
"True",
"ctype",
"=",
"self",
".",
"__curcommand",
".",
"get_type",
"(",
")... | 40.609756 | 18.195122 |
def List(validator):
"""
Creates a validator that runs the given validator on every item in a list
or other collection. The validator can mutate the values.
Any raised errors will be collected into a single ``Invalid`` error. Their
paths will be replaced with the index of the item. Will raise an er... | [
"def",
"List",
"(",
"validator",
")",
":",
"@",
"wraps",
"(",
"List",
")",
"def",
"built",
"(",
"value",
")",
":",
"if",
"not",
"hasattr",
"(",
"value",
",",
"'__iter__'",
")",
":",
"raise",
"Error",
"(",
"\"Must be a list\"",
")",
"invalid",
"=",
"I... | 31.266667 | 16 |
def release(major=False, minor=False, patch=True, pypi_index=None):
"""Overall process flow for performing a release"""
relver = next_release(major, minor, patch)
start_rel_branch(relver)
prepare_release(relver)
finish_rel_branch(relver)
publish(pypi_index) | [
"def",
"release",
"(",
"major",
"=",
"False",
",",
"minor",
"=",
"False",
",",
"patch",
"=",
"True",
",",
"pypi_index",
"=",
"None",
")",
":",
"relver",
"=",
"next_release",
"(",
"major",
",",
"minor",
",",
"patch",
")",
"start_rel_branch",
"(",
"relve... | 39.285714 | 12.285714 |
def assert_is_substring(substring, subject, message=None, extra=None):
"""Raises an AssertionError if substring is not a substring of subject."""
assert (
(subject is not None)
and (substring is not None)
and (subject.find(substring) != -1)
), _assert_fail_message(message, substring,... | [
"def",
"assert_is_substring",
"(",
"substring",
",",
"subject",
",",
"message",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"assert",
"(",
"(",
"subject",
"is",
"not",
"None",
")",
"and",
"(",
"substring",
"is",
"not",
"None",
")",
"and",
"(",
... | 49 | 16.142857 |
def as_struct_array(*columns):
"""pack a sequence of columns into a recarray
Parameters
----------
columns : sequence of key objects
Returns
-------
data : recarray
recarray containing the input columns as struct fields
"""
columns = [np.asarray(c) for c in columns]
row... | [
"def",
"as_struct_array",
"(",
"*",
"columns",
")",
":",
"columns",
"=",
"[",
"np",
".",
"asarray",
"(",
"c",
")",
"for",
"c",
"in",
"columns",
"]",
"rows",
"=",
"len",
"(",
"columns",
"[",
"0",
"]",
")",
"names",
"=",
"[",
"'f'",
"+",
"str",
"... | 26.857143 | 19.428571 |
def make_display_lines(self):
"""
生成输出行
注意: 多线程终端同时输出会有bug, 导致起始位置偏移, 需要在每行加\r
"""
self.screen_height, self.screen_width = self.linesnum() # 屏幕显示行数
display_lines = ['\r']
display_lines.append(self._title + '\r')
top = self.topline
bottom = self... | [
"def",
"make_display_lines",
"(",
"self",
")",
":",
"self",
".",
"screen_height",
",",
"self",
".",
"screen_width",
"=",
"self",
".",
"linesnum",
"(",
")",
"# 屏幕显示行数",
"display_lines",
"=",
"[",
"'\\r'",
"]",
"display_lines",
".",
"append",
"(",
"self",
".... | 32.742857 | 17.314286 |
def new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs):
''' Create a sentence-level tag '''
tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs)
return self.add_tag(tag_obj) | [
"def",
"new_tag",
"(",
"self",
",",
"label",
",",
"cfrom",
"=",
"-",
"1",
",",
"cto",
"=",
"-",
"1",
",",
"tagtype",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"tag_obj",
"=",
"Tag",
"(",
"label",
",",
"cfrom",
",",
"cto",
",",
"tagtype",
... | 52.75 | 14.75 |
def _resolve_non_literal_route(self, method, path):
"""Resolve a request to a wildcard or regex route handler.
Arguments:
method (str): HTTP method name, e.g. GET, POST, etc.
path (str): Request path
Returns:
tuple or None: A tuple of three items:
1. ... | [
"def",
"_resolve_non_literal_route",
"(",
"self",
",",
"method",
",",
"path",
")",
":",
"for",
"route_dict",
"in",
"(",
"self",
".",
"_wildcard",
",",
"self",
".",
"_regex",
")",
":",
"if",
"method",
"in",
"route_dict",
":",
"for",
"route",
"in",
"revers... | 34.434783 | 15.347826 |
def get_icon_by_extension(fname, scale_factor):
"""Return the icon depending on the file extension"""
application_icons = {}
application_icons.update(BIN_FILES)
application_icons.update(DOCUMENT_FILES)
if osp.isdir(fname):
return icon('DirOpenIcon', scale_factor)
else:
basename =... | [
"def",
"get_icon_by_extension",
"(",
"fname",
",",
"scale_factor",
")",
":",
"application_icons",
"=",
"{",
"}",
"application_icons",
".",
"update",
"(",
"BIN_FILES",
")",
"application_icons",
".",
"update",
"(",
"DOCUMENT_FILES",
")",
"if",
"osp",
".",
"isdir",... | 46.509804 | 15.588235 |
def get_requires_for_build_sdist(config_settings):
"""Invoke the optional get_requires_for_build_wheel hook
Returns [] if the hook is not defined.
"""
backend = _build_backend()
try:
hook = backend.get_requires_for_build_sdist
except AttributeError:
return []
else:
r... | [
"def",
"get_requires_for_build_sdist",
"(",
"config_settings",
")",
":",
"backend",
"=",
"_build_backend",
"(",
")",
"try",
":",
"hook",
"=",
"backend",
".",
"get_requires_for_build_sdist",
"except",
"AttributeError",
":",
"return",
"[",
"]",
"else",
":",
"return"... | 28 | 14.75 |
def find_files_cmd(data_path, minutes, start_time, end_time):
"""Find the log files depending on their modification time.
:param data_path: the path to the Kafka data directory
:type data_path: str
:param minutes: check the files modified in the last N minutes
:type minutes: int
:param start_ti... | [
"def",
"find_files_cmd",
"(",
"data_path",
",",
"minutes",
",",
"start_time",
",",
"end_time",
")",
":",
"if",
"minutes",
":",
"return",
"FIND_MINUTES_COMMAND",
".",
"format",
"(",
"data_path",
"=",
"data_path",
",",
"minutes",
"=",
"minutes",
",",
")",
"if"... | 32.096774 | 15.516129 |
def assign(self, link_type, product, linked_product, data=None,
identifierType=None):
"""
Assign a product link
:param link_type: type of link, one of 'cross_sell', 'up_sell',
'related' or 'grouped'
:param product: ID or SKU of product
:param linke... | [
"def",
"assign",
"(",
"self",
",",
"link_type",
",",
"product",
",",
"linked_product",
",",
"data",
"=",
"None",
",",
"identifierType",
"=",
"None",
")",
":",
"return",
"bool",
"(",
"self",
".",
"call",
"(",
"'catalog_product_link.assign'",
",",
"[",
"link... | 43.333333 | 19.111111 |
def hex(x):
'''
x-->bytes | bytearray
Returns-->bytes: hex-encoded
'''
if isinstance(x, bytearray):
x = bytes(x)
return encode(x, 'hex') | [
"def",
"hex",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"bytearray",
")",
":",
"x",
"=",
"bytes",
"(",
"x",
")",
"return",
"encode",
"(",
"x",
",",
"'hex'",
")"
] | 20.125 | 19.875 |
def raw_messages(self):
'''A generator yielding a :class:`MacMailMessage` binary
object for each message in this folder, based on message index
information in :class:`MacIndex` and content in
:class:`MacMail`.'''
if self.data:
# offset for first message, at end of Mai... | [
"def",
"raw_messages",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
":",
"# offset for first message, at end of Mail data file header",
"last_offset",
"=",
"24",
"self",
".",
"skipped_chunks",
"=",
"0",
"for",
"msginfo",
"in",
"self",
".",
"index",
".",
"me... | 45.083333 | 21.75 |
def directional_poisson_ratio(self, n, m, tol=1e-8):
"""
Calculates the poisson ratio for a specific direction
relative to a second, orthogonal direction
Args:
n (3-d vector): principal direction
m (3-d vector): secondary direction orthogonal to n
tol... | [
"def",
"directional_poisson_ratio",
"(",
"self",
",",
"n",
",",
"m",
",",
"tol",
"=",
"1e-8",
")",
":",
"n",
",",
"m",
"=",
"get_uvec",
"(",
"n",
")",
",",
"get_uvec",
"(",
"m",
")",
"if",
"not",
"np",
".",
"abs",
"(",
"np",
".",
"dot",
"(",
... | 40.875 | 16 |
def modules_and_args(modules=True, states=False, names_only=False):
'''
Walk the Salt install tree and return a dictionary or a list
of the functions therein as well as their arguments.
:param modules: Walk the modules directory if True
:param states: Walk the states directory if True
:param na... | [
"def",
"modules_and_args",
"(",
"modules",
"=",
"True",
",",
"states",
"=",
"False",
",",
"names_only",
"=",
"False",
")",
":",
"dirs",
"=",
"[",
"]",
"module_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",... | 28.75 | 22.928571 |
def get_media_list(self, media_type, offset, count):
"""
获取素材列表。
:param media_type: 素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)
:param offset: 从全部素材的该偏移位置开始返回,0表示从第一个素材返回
:param count: 返回素材的数量,取值在1到20之间
:return: 返回的 JSON 数据包
"""
return self.post(
... | [
"def",
"get_media_list",
"(",
"self",
",",
"media_type",
",",
"offset",
",",
"count",
")",
":",
"return",
"self",
".",
"post",
"(",
"url",
"=",
"\"https://api.weixin.qq.com/cgi-bin/material/batchget_material\"",
",",
"data",
"=",
"{",
"\"type\"",
":",
"media_type"... | 30.647059 | 16.882353 |
def sum_over_energy(self):
""" Reduce a 3D counts cube to a 2D counts map
"""
# Note that the array is using the opposite convention from WCS
# so we sum over axis 0 in the array, but drop axis 2 in the WCS object
return Map(np.sum(self.counts, axis=0), self.wcs.dropaxis(2)) | [
"def",
"sum_over_energy",
"(",
"self",
")",
":",
"# Note that the array is using the opposite convention from WCS",
"# so we sum over axis 0 in the array, but drop axis 2 in the WCS object",
"return",
"Map",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"counts",
",",
"axis",
"=",... | 51.666667 | 18.833333 |
def load(self, commit=None):
"""Load a result from the database."""
git_info = self.record_git_info(commit)
LOGGER.info("Loading result from '%s'.", git_info.hexsha)
result = MemoteResult(
self.session.query(Result.memote_result).
filter_by(hexsha=git_info.hexsha)... | [
"def",
"load",
"(",
"self",
",",
"commit",
"=",
"None",
")",
":",
"git_info",
"=",
"self",
".",
"record_git_info",
"(",
"commit",
")",
"LOGGER",
".",
"info",
"(",
"\"Loading result from '%s'.\"",
",",
"git_info",
".",
"hexsha",
")",
"result",
"=",
"MemoteR... | 43.083333 | 12.583333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.