text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
"""Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an E... | [
"def",
"get_thread",
"(",
"self",
",",
"thread_id",
",",
"update_if_cached",
"=",
"True",
",",
"raise_404",
"=",
"False",
")",
":",
"# see if already cached",
"cached_thread",
"=",
"self",
".",
"_thread_cache",
".",
"get",
"(",
"thread_id",
")",
"if",
"cached_... | 30.588235 | 19.411765 |
def change_nick(self, nick):
"""Update this user's nick in all joined channels."""
old_nick = self.nick
self.nick = IRCstr(nick)
for c in self.channels:
c.users.remove(old_nick)
c.users.add(self.nick) | [
"def",
"change_nick",
"(",
"self",
",",
"nick",
")",
":",
"old_nick",
"=",
"self",
".",
"nick",
"self",
".",
"nick",
"=",
"IRCstr",
"(",
"nick",
")",
"for",
"c",
"in",
"self",
".",
"channels",
":",
"c",
".",
"users",
".",
"remove",
"(",
"old_nick",... | 29.555556 | 12.777778 |
def keyword(self, **kwargs):
"""
Search for keywords by name.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
Returns:
A dict respresentation of the JSON returned from the API.
"""
p... | [
"def",
"keyword",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"'keyword'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
"(",
"response",... | 28 | 17.375 |
def suppressionlist(self, page=1, page_size=1000, order_field="email", order_direction="asc"):
"""Gets this client's suppression list."""
params = {
"page": page,
"pagesize": page_size,
"orderfield": order_field,
"orderdirection": order_direction}
... | [
"def",
"suppressionlist",
"(",
"self",
",",
"page",
"=",
"1",
",",
"page_size",
"=",
"1000",
",",
"order_field",
"=",
"\"email\"",
",",
"order_direction",
"=",
"\"asc\"",
")",
":",
"params",
"=",
"{",
"\"page\"",
":",
"page",
",",
"\"pagesize\"",
":",
"p... | 46.222222 | 16.222222 |
def shorten_duplicate_content_url(url):
"""Remove anchor part and trailing index.html from URL."""
if '#' in url:
url = url.split('#', 1)[0]
if url.endswith('index.html'):
return url[:-10]
if url.endswith('index.htm'):
return url[:-9]
return url | [
"def",
"shorten_duplicate_content_url",
"(",
"url",
")",
":",
"if",
"'#'",
"in",
"url",
":",
"url",
"=",
"url",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"url",
".",
"endswith",
"(",
"'index.html'",
")",
":",
"return",
"url",
"[... | 31.222222 | 11.222222 |
def merkle(hashes, func=_merkle_hash256):
"""Convert an iterable of hashes or hashable objects into a binary tree,
construct the interior values using a passed-in constructor or compression
function, and return the root value of the tree. The default compressor is
the hash256 function, resulting in root... | [
"def",
"merkle",
"(",
"hashes",
",",
"func",
"=",
"_merkle_hash256",
")",
":",
"# We use append to duplicate the final item in the iterable of hashes, so",
"# we need hashes to be a list-like object, regardless of what we were",
"# passed.",
"hashes",
"=",
"list",
"(",
"iter",
"(... | 55.114286 | 24.885714 |
def splithost(url):
"""splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
global _hostprog
if _hostprog is None:
import re
_hostprog = re.compile('^//([^/?]*)(.*)$')
match = _hostprog.match(url)
if match:
host_port = match.group(1)
path = match.group(2)
... | [
"def",
"splithost",
"(",
"url",
")",
":",
"global",
"_hostprog",
"if",
"_hostprog",
"is",
"None",
":",
"import",
"re",
"_hostprog",
"=",
"re",
".",
"compile",
"(",
"'^//([^/?]*)(.*)$'",
")",
"match",
"=",
"_hostprog",
".",
"match",
"(",
"url",
")",
"if",... | 28.8 | 15.133333 |
async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
"""
Get decryption key for a given S3 object
:param key: Base64 decoded version of x-amz-key-v2
:param material_description: JSON decoded x-amz-matdesc
:return: Raw AES key bytes
... | [
"async",
"def",
"get_decryption_aes_key",
"(",
"self",
",",
"key",
":",
"bytes",
",",
"material_description",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"bytes",
":",
"raise",
"NotImplementedError",
"(",
")"
] | 39.777778 | 17.555556 |
def fetchFiles(self):
"""Returns a list of file items contained on the local repo."""
print("Fetching files from {}".format(self.baseDir))
files = glob(path.join(self.baseDir, '*'))
filesDef = []
for f in files:
print("Found SPARQL file {}".format(f))
rela... | [
"def",
"fetchFiles",
"(",
"self",
")",
":",
"print",
"(",
"\"Fetching files from {}\"",
".",
"format",
"(",
"self",
".",
"baseDir",
")",
")",
"files",
"=",
"glob",
"(",
"path",
".",
"join",
"(",
"self",
".",
"baseDir",
",",
"'*'",
")",
")",
"filesDef",... | 37.384615 | 13 |
def get_Name(name, short=False):
"""
Return the distinguished name of an X509 Certificate
:param name: Name object to return the DN from
:param short: Use short form (Default: False)
:type name: :class:`cryptography.x509.Name`
:type short: Boolean
:rtype: str
"... | [
"def",
"get_Name",
"(",
"name",
",",
"short",
"=",
"False",
")",
":",
"# For the shortform, we have a lookup table",
"# See RFC4514 for more details",
"sf",
"=",
"{",
"\"countryName\"",
":",
"\"C\"",
",",
"\"stateOrProvinceName\"",
":",
"\"ST\"",
",",
"\"localityName\""... | 31.64 | 19.64 |
def run_all():
""" Load the data that we're using to search for Li-rich giants.
Store it in dataset and model objects. """
DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels"
dates = os.listdir("/home/share/LAMOST/DR2/DR2_release")
dates = np.array(dates)
dates = np.delete(date... | [
"def",
"run_all",
"(",
")",
":",
"DATA_DIR",
"=",
"\"/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels\"",
"dates",
"=",
"os",
".",
"listdir",
"(",
"\"/home/share/LAMOST/DR2/DR2_release\"",
")",
"dates",
"=",
"np",
".",
"array",
"(",
"dates",
")",
"dates",
"=... | 41.3125 | 17.1875 |
def _setuplimits(self, constraints):
"""Setup the limits for every initialiser."""
self.constraints = tuple(constraints)
assert len(self.constraints) == self.fmodel.dim_x
self.goal = None | [
"def",
"_setuplimits",
"(",
"self",
",",
"constraints",
")",
":",
"self",
".",
"constraints",
"=",
"tuple",
"(",
"constraints",
")",
"assert",
"len",
"(",
"self",
".",
"constraints",
")",
"==",
"self",
".",
"fmodel",
".",
"dim_x",
"self",
".",
"goal",
... | 43 | 8.4 |
def nested_key_indices(nested_dict):
"""
Give an ordering to the outer and inner keys used in a dictionary that
maps to dictionaries.
"""
outer_keys, inner_keys = collect_nested_keys(nested_dict)
outer_key_indices = {k: i for (i, k) in enumerate(outer_keys)}
inner_key_indices = {k: i for (i,... | [
"def",
"nested_key_indices",
"(",
"nested_dict",
")",
":",
"outer_keys",
",",
"inner_keys",
"=",
"collect_nested_keys",
"(",
"nested_dict",
")",
"outer_key_indices",
"=",
"{",
"k",
":",
"i",
"for",
"(",
"i",
",",
"k",
")",
"in",
"enumerate",
"(",
"outer_keys... | 43.222222 | 14.777778 |
def cmd(send, msg, args):
"""Checks if a website is up.
Syntax: {command} <website>
"""
if not msg:
send("What are you trying to get to?")
return
nick = args['nick']
isup = get("http://isup.me/%s" % msg).text
if "looks down from here" in isup:
send("%s: %s is down" ... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"What are you trying to get to?\"",
")",
"return",
"nick",
"=",
"args",
"[",
"'nick'",
"]",
"isup",
"=",
"get",
"(",
"\"http://isup.me/%s\"",
"%",
"msg"... | 27.941176 | 14.411765 |
def check_for_debug(supernova_args, nova_args):
"""
If the user wanted to run the executable with debugging enabled, we need
to apply the correct arguments to the executable.
Heat is a corner case since it uses -d instead of --debug.
"""
# Heat requires special handling for debug arguments
... | [
"def",
"check_for_debug",
"(",
"supernova_args",
",",
"nova_args",
")",
":",
"# Heat requires special handling for debug arguments",
"if",
"supernova_args",
"[",
"'debug'",
"]",
"and",
"supernova_args",
"[",
"'executable'",
"]",
"==",
"'heat'",
":",
"nova_args",
".",
... | 36.285714 | 17.285714 |
def macronize_tags(self, text):
"""Return macronized form along with POS tags.
E.g. "Gallia est omnis divisa in partes tres," ->
[('gallia', 'n-s---fb-', 'galliā'), ('est', 'v3spia---', 'est'), ('omnis', 'a-s---mn-', 'omnis'),
('divisa', 't-prppnn-', 'dīvīsa'), ('in', 'r--------', 'in')... | [
"def",
"macronize_tags",
"(",
"self",
",",
"text",
")",
":",
"return",
"[",
"self",
".",
"_macronize_word",
"(",
"word",
")",
"for",
"word",
"in",
"self",
".",
"_retrieve_tag",
"(",
"text",
")",
"]"
] | 45.230769 | 25 |
def replicated_dataset(dataset, weights, n=None):
"Copy dataset, replicating each example in proportion to its weight."
n = n or len(dataset.examples)
result = copy.copy(dataset)
result.examples = weighted_replicate(dataset.examples, weights, n)
return result | [
"def",
"replicated_dataset",
"(",
"dataset",
",",
"weights",
",",
"n",
"=",
"None",
")",
":",
"n",
"=",
"n",
"or",
"len",
"(",
"dataset",
".",
"examples",
")",
"result",
"=",
"copy",
".",
"copy",
"(",
"dataset",
")",
"result",
".",
"examples",
"=",
... | 45.666667 | 18.333333 |
def get(
self):
"""*Calulate the angular separation between two locations on the sky*
Input precision should be respected.
**Key Arguments:**
**Return:**
- ``angularSeparation`` -- total angular separation between coordinates (arcsec)
- ``north`` --... | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get_angular_separation`` method'",
")",
"from",
"astrocalc",
".",
"coords",
"import",
"unit_conversion",
"# CONSTANTS",
"pi",
"=",
"(",
"4",
"*",
"math",
".",
"atan",
... | 31.878049 | 20.682927 |
def avail_approaches(pkg):
'''Create list of available modules.
Arguments
---------
pkg : module
module to inspect
Returns
---------
method : list
A list of available submodules
'''
methods = [modname for importer, modname, ispkg in
pkgutil.walk_packa... | [
"def",
"avail_approaches",
"(",
"pkg",
")",
":",
"methods",
"=",
"[",
"modname",
"for",
"importer",
",",
"modname",
",",
"ispkg",
"in",
"pkgutil",
".",
"walk_packages",
"(",
"path",
"=",
"pkg",
".",
"__path__",
")",
"if",
"modname",
"not",
"in",
"[",
"... | 24.5 | 21.277778 |
def wif_to_privkey(wif, compressed=True, net=BC):
"""Convert Wallet Import Format (WIF) to privkey bytes."""
key = b58decode(wif)
version, raw, check = key[0:1], key[1:-4], key[-4:]
assert version == net.wifprefix, "unexpected version byte"
check_compare = shasha(version + raw).digest()[:4]
as... | [
"def",
"wif_to_privkey",
"(",
"wif",
",",
"compressed",
"=",
"True",
",",
"net",
"=",
"BC",
")",
":",
"key",
"=",
"b58decode",
"(",
"wif",
")",
"version",
",",
"raw",
",",
"check",
"=",
"key",
"[",
"0",
":",
"1",
"]",
",",
"key",
"[",
"1",
":",... | 28.071429 | 22.071429 |
def paste(self):
"""Reimplemented slot to handle multiline paste action"""
text = to_text_string(QApplication.clipboard().text())
if len(text.splitlines()) > 1:
# Multiline paste
if self.new_input_line:
self.on_new_line()
self.remove_sel... | [
"def",
"paste",
"(",
"self",
")",
":",
"text",
"=",
"to_text_string",
"(",
"QApplication",
".",
"clipboard",
"(",
")",
".",
"text",
"(",
")",
")",
"if",
"len",
"(",
"text",
".",
"splitlines",
"(",
")",
")",
">",
"1",
":",
"# Multiline paste\r",
"if",... | 41.75 | 11.75 |
def get(self, name):
"""Get the parameter whose name is *name*.
The returned object is a :class:`.Parameter` instance. Raises
:exc:`ValueError` if no parameter has this name. Since multiple
parameters can have the same name, we'll return the last match, since
the last parameter ... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
".",
"strip",
"(",
")",
"for",
"param",
"in",
"reversed",
"(",
"self",
".",
"params",
")",
":",
"if",
"param",
".",
"name",
".",
"strip",
"(",
")",
"==",
... | 41.923077 | 17.230769 |
def source_file(self):
""" When using open, returns the filename used
"""
if self._filename is None:
self._filename = self._as_in_memory_geotiff()._filename
return self._filename | [
"def",
"source_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"_filename",
"is",
"None",
":",
"self",
".",
"_filename",
"=",
"self",
".",
"_as_in_memory_geotiff",
"(",
")",
".",
"_filename",
"return",
"self",
".",
"_filename"
] | 36.166667 | 10.333333 |
def match_one_string(pattern: str, s: str, *args):
"""
Make sure you know only none or one string will be matched! If you are not sure, use `match_one_pattern` instead.
:param pattern:
:param s:
:param args:
:return:
.. doctest::
>>> p = "\d+"
>>> s = "abc 123 def"
... | [
"def",
"match_one_string",
"(",
"pattern",
":",
"str",
",",
"s",
":",
"str",
",",
"*",
"args",
")",
":",
"try",
":",
"# `match` is either an empty list or a list of string.",
"match",
",",
"=",
"re",
".",
"findall",
"(",
"pattern",
",",
"s",
")",
"if",
"le... | 35.638889 | 25.361111 |
def listRuns(self, **kwargs):
"""
API to list all run dictionary, for example: [{'run_num': [160578, 160498, 160447, 160379]}].
At least one parameter is mandatory.
:param logical_file_name: List all runs in the file
:type logical_file_name: str
:param block_name: List ... | [
"def",
"listRuns",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"validParameters",
"=",
"[",
"'run_num'",
",",
"'logical_file_name'",
",",
"'block_name'",
",",
"'dataset'",
"]",
"requiredParameters",
"=",
"{",
"'multiple'",
":",
"validParameters",
"}",
"che... | 39.086957 | 22.73913 |
def set_precision(self, precision, persist=False):
"""
Set the precision of the sensor for the next readings.
If the ``persist`` argument is set to ``False`` this value
is "only" stored in the volatile SRAM, so it is reset when
the sensor gets power-cycled.
... | [
"def",
"set_precision",
"(",
"self",
",",
"precision",
",",
"persist",
"=",
"False",
")",
":",
"if",
"not",
"9",
"<=",
"precision",
"<=",
"12",
":",
"raise",
"ValueError",
"(",
"\"The given sensor precision '{0}' is out of range (9-12)\"",
".",
"format",
"(",
"p... | 37.8 | 24.44 |
def rightStatus(self, sheet):
'Compose right side of status bar.'
if sheet.currentThreads:
gerund = (' '+sheet.progresses[0].gerund) if sheet.progresses else ''
status = '%9d %2d%%%s' % (len(sheet), sheet.progressPct, gerund)
else:
status = '%9d %s' % (len(sh... | [
"def",
"rightStatus",
"(",
"self",
",",
"sheet",
")",
":",
"if",
"sheet",
".",
"currentThreads",
":",
"gerund",
"=",
"(",
"' '",
"+",
"sheet",
".",
"progresses",
"[",
"0",
"]",
".",
"gerund",
")",
"if",
"sheet",
".",
"progresses",
"else",
"''",
"stat... | 46.375 | 18.625 |
def track_statistic(self, name, description='', max_rows=None):
"""
Create a Statistic object in the Tracker.
"""
if name in self._tables:
raise TableConflictError(name)
if max_rows is None:
max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE
self.... | [
"def",
"track_statistic",
"(",
"self",
",",
"name",
",",
"description",
"=",
"''",
",",
"max_rows",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"_tables",
":",
"raise",
"TableConflictError",
"(",
"name",
")",
"if",
"max_rows",
"is",
"None",
... | 43.8 | 13.6 |
def pack(mtype, request, rid=None):
'''pack request to delimited data'''
envelope = wire.Envelope()
if rid is not None:
envelope.id = rid
envelope.type = mtype
envelope.message = request.SerializeToString()
data = envelope.SerializeToString()
data = encoder._VarintBytes(len(data)) +... | [
"def",
"pack",
"(",
"mtype",
",",
"request",
",",
"rid",
"=",
"None",
")",
":",
"envelope",
"=",
"wire",
".",
"Envelope",
"(",
")",
"if",
"rid",
"is",
"not",
"None",
":",
"envelope",
".",
"id",
"=",
"rid",
"envelope",
".",
"type",
"=",
"mtype",
"... | 33.2 | 10.6 |
def multinomial_like(x, n, p):
R"""
Multinomial log-likelihood.
Generalization of the binomial
distribution, but instead of each trial resulting in "success" or
"failure", each one results in exactly one of some fixed finite number k
of possible outcomes over n independent trials. 'x[i]' indica... | [
"def",
"multinomial_like",
"(",
"x",
",",
"n",
",",
"p",
")",
":",
"# flib expects 2d arguments. Do we still want to support multiple p",
"# values along realizations ?",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"p",
"=",
"np",
".",
"atleast_2d",
"(",
"p"... | 33.405405 | 22.189189 |
def _yarn_init(self, rm_address, requests_config, tags):
"""
Return a dictionary of {app_id: (app_name, tracking_url)} for running Spark applications.
"""
running_apps = self._yarn_get_running_spark_apps(rm_address, requests_config, tags)
# Report success after gathering all met... | [
"def",
"_yarn_init",
"(",
"self",
",",
"rm_address",
",",
"requests_config",
",",
"tags",
")",
":",
"running_apps",
"=",
"self",
".",
"_yarn_get_running_spark_apps",
"(",
"rm_address",
",",
"requests_config",
",",
"tags",
")",
"# Report success after gathering all met... | 39.466667 | 24.666667 |
def reset_parameter_group(self, name, reset_all_params=False,
parameters=None):
"""
Resets some or all of the parameters of a ParameterGroup to the
default value
:type key_name: string
:param key_name: The name of the ParameterGroup to reset
... | [
"def",
"reset_parameter_group",
"(",
"self",
",",
"name",
",",
"reset_all_params",
"=",
"False",
",",
"parameters",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'DBParameterGroupName'",
":",
"name",
"}",
"if",
"reset_all_params",
":",
"params",
"[",
"'ResetAllP... | 40.818182 | 16.909091 |
def events(self):
# type: () -> Generator[Event, None, None]
"""
Return a generator that provides any events that have been generated
by protocol activity.
:returns: generator of :class:`Event <wsproto.events.Event>` subclasses
"""
while self._events:
... | [
"def",
"events",
"(",
"self",
")",
":",
"# type: () -> Generator[Event, None, None]",
"while",
"self",
".",
"_events",
":",
"yield",
"self",
".",
"_events",
".",
"popleft",
"(",
")",
"try",
":",
"for",
"frame",
"in",
"self",
".",
"_proto",
".",
"received_fra... | 40.772727 | 19.227273 |
def config_get(self, parameter='*'):
"""Get the value of a configuration parameter(s).
If called without argument will return all parameters.
:raises TypeError: if parameter is not string
"""
if not isinstance(parameter, str):
raise TypeError("parameter must be str"... | [
"def",
"config_get",
"(",
"self",
",",
"parameter",
"=",
"'*'",
")",
":",
"if",
"not",
"isinstance",
"(",
"parameter",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"parameter must be str\"",
")",
"fut",
"=",
"self",
".",
"execute",
"(",
"b'CONFIG'",
... | 38.272727 | 15.727273 |
def update(self, hosted_number_order_sids=values.unset,
address_sid=values.unset, email=values.unset, cc_emails=values.unset,
status=values.unset, contact_title=values.unset,
contact_phone_number=values.unset):
"""
Update the AuthorizationDocumentInstance
... | [
"def",
"update",
"(",
"self",
",",
"hosted_number_order_sids",
"=",
"values",
".",
"unset",
",",
"address_sid",
"=",
"values",
".",
"unset",
",",
"email",
"=",
"values",
".",
"unset",
",",
"cc_emails",
"=",
"values",
".",
"unset",
",",
"status",
"=",
"va... | 44.628571 | 24.742857 |
def get_outside_collaborators(self, filter_=github.GithubObject.NotSet):
"""
:calls: `GET /orgs/:org/outside_collaborators <http://developer.github.com/v3/orgs/outside_collaborators>`_
:param filter_: string
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.... | [
"def",
"get_outside_collaborators",
"(",
"self",
",",
"filter_",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
")",
":",
"assert",
"(",
"filter_",
"is",
"github",
".",
"GithubObject",
".",
"NotSet",
"or",
"isinstance",
"(",
"filter_",
",",
"(",
"str",
... | 43.333333 | 20 |
def p_expr(self, p):
"""expr : assignment_expr
| expr COMMA assignment_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.Comma(left=p[1], right=p[3])
p[0].setpos(p, 2) | [
"def",
"p_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Comma",
"(",
"left",
"=",
"p... | 28.555556 | 13 |
def _get_log_commits(self):
"""
calls git log to complile a change list
"""
## check if update is necessary
cmd = "git log --pretty=oneline {}..".format(self.init_version)
cmdlist = shlex.split(cmd)
commits = subprocess.check_output(cmdlist)
## Sp... | [
"def",
"_get_log_commits",
"(",
"self",
")",
":",
"## check if update is necessary",
"cmd",
"=",
"\"git log --pretty=oneline {}..\"",
".",
"format",
"(",
"self",
".",
"init_version",
")",
"cmdlist",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"commits",
"=",
"s... | 39.636364 | 14.363636 |
def get_read_format(cls, source, args, kwargs):
"""Determine the read format for a given input source
"""
ctx = None
if isinstance(source, FILE_LIKE):
fileobj = source
filepath = source.name if hasattr(source, 'name') else None
else:
filepath = source
try:
... | [
"def",
"get_read_format",
"(",
"cls",
",",
"source",
",",
"args",
",",
"kwargs",
")",
":",
"ctx",
"=",
"None",
"if",
"isinstance",
"(",
"source",
",",
"FILE_LIKE",
")",
":",
"fileobj",
"=",
"source",
"filepath",
"=",
"source",
".",
"name",
"if",
"hasat... | 34 | 18.190476 |
def init_benchmarks(n_values=None):
"""Initialize the strings we'll run the regexes against.
The strings used in the benchmark are prefixed and suffixed by
strings that are repeated n times.
The sequence n_values contains the values for n.
If n_values is None the values of n from the original benc... | [
"def",
"init_benchmarks",
"(",
"n_values",
"=",
"None",
")",
":",
"if",
"n_values",
"is",
"None",
":",
"n_values",
"=",
"(",
"0",
",",
"5",
",",
"50",
",",
"250",
",",
"1000",
",",
"5000",
",",
"10000",
")",
"string_tables",
"=",
"{",
"n",
":",
"... | 28.7 | 19.4 |
def locateChild(self, ctx, segments):
"""
Return a Deferred which will fire with the customized version of the
resource being located.
"""
D = defer.maybeDeferred(
self.currentResource.locateChild, ctx, segments)
def finishLocating((nextRes, nextPath)):
... | [
"def",
"locateChild",
"(",
"self",
",",
"ctx",
",",
"segments",
")",
":",
"D",
"=",
"defer",
".",
"maybeDeferred",
"(",
"self",
".",
"currentResource",
".",
"locateChild",
",",
"ctx",
",",
"segments",
")",
"def",
"finishLocating",
"(",
"(",
"nextRes",
",... | 38.833333 | 14.833333 |
def _get_crmod_abmn(self):
"""return a Nx2 array with the measurement configurations formatted
CRTomo style
"""
ABMN = np.vstack((
self.configs[:, 0] * 1e4 + self.configs[:, 1],
self.configs[:, 2] * 1e4 + self.configs[:, 3],
)).T.astype(int)
return... | [
"def",
"_get_crmod_abmn",
"(",
"self",
")",
":",
"ABMN",
"=",
"np",
".",
"vstack",
"(",
"(",
"self",
".",
"configs",
"[",
":",
",",
"0",
"]",
"*",
"1e4",
"+",
"self",
".",
"configs",
"[",
":",
",",
"1",
"]",
",",
"self",
".",
"configs",
"[",
... | 35.222222 | 13.444444 |
def _tofile(self, fh, pam=False):
"""Write Netbm file."""
fh.seek(0)
fh.write(self._header(pam))
data = self.asarray(copy=False)
if self.maxval == 1:
data = numpy.packbits(data, axis=-1)
data.tofile(fh) | [
"def",
"_tofile",
"(",
"self",
",",
"fh",
",",
"pam",
"=",
"False",
")",
":",
"fh",
".",
"seek",
"(",
"0",
")",
"fh",
".",
"write",
"(",
"self",
".",
"_header",
"(",
"pam",
")",
")",
"data",
"=",
"self",
".",
"asarray",
"(",
"copy",
"=",
"Fal... | 31.875 | 9 |
def read_csv_arg_preprocess(abspath, memory_usage=100 * 1000 * 1000):
"""Automatically decide if we need to use iterator mode to read a csv file.
:param abspath: csv file absolute path.
:param memory_usage: max memory will be used for pandas.read_csv().
"""
if memory_usage < 1000 * 1000:
ra... | [
"def",
"read_csv_arg_preprocess",
"(",
"abspath",
",",
"memory_usage",
"=",
"100",
"*",
"1000",
"*",
"1000",
")",
":",
"if",
"memory_usage",
"<",
"1000",
"*",
"1000",
":",
"raise",
"ValueError",
"(",
"\"Please specify a valid memory usage for read_csv, \"",
"\"the v... | 38.565217 | 21.782609 |
def batch_watch(parameterized, run=True):
"""
Context manager to batch watcher events on a parameterized object.
The context manager will queue any events triggered by setting a
parameter on the supplied parameterized object and dispatch them
all at once when the context manager exits. If run=False ... | [
"def",
"batch_watch",
"(",
"parameterized",
",",
"run",
"=",
"True",
")",
":",
"BATCH_WATCH",
"=",
"parameterized",
".",
"param",
".",
"_BATCH_WATCH",
"parameterized",
".",
"param",
".",
"_BATCH_WATCH",
"=",
"True",
"try",
":",
"yield",
"finally",
":",
"para... | 41.5 | 17.125 |
def det(L):
"""
Determinant
Compute the determinant given a lower triangular matrix
Inputs:
L :
lower triangular matrix
Outputs:
det_L :
determinant of L
"""
size_L = L.shape
if np.size(L) == 1:
return np.array(L)
else:
... | [
"def",
"det",
"(",
"L",
")",
":",
"size_L",
"=",
"L",
".",
"shape",
"if",
"np",
".",
"size",
"(",
"L",
")",
"==",
"1",
":",
"return",
"np",
".",
"array",
"(",
"L",
")",
"else",
":",
"try",
":",
"assert",
"np",
".",
"all",
"(",
"np",
".",
... | 24.965517 | 16.689655 |
def creation_ordered(class_to_decorate):
"""
Class decorator that ensures that instances will be ordered after creation order when sorted.
:type class_to_decorate: class
:rtype: class
"""
next_index = functools.partial(next, itertools.count())
__init__orig = class_to_decorate.... | [
"def",
"creation_ordered",
"(",
"class_to_decorate",
")",
":",
"next_index",
"=",
"functools",
".",
"partial",
"(",
"next",
",",
"itertools",
".",
"count",
"(",
")",
")",
"__init__orig",
"=",
"class_to_decorate",
".",
"__init__",
"@",
"functools",
".",
"wraps"... | 29.785714 | 21.357143 |
def get_func(fullFuncName):
"""Retrieve a function object from a full dotted-package name."""
# Parse out the path, module, and function
lastDot = fullFuncName.rfind(u".")
funcName = fullFuncName[lastDot + 1:]
modPath = fullFuncName[:lastDot]
aMod = get_mod(modPath)
aFunc = getattr(aMod, f... | [
"def",
"get_func",
"(",
"fullFuncName",
")",
":",
"# Parse out the path, module, and function",
"lastDot",
"=",
"fullFuncName",
".",
"rfind",
"(",
"u\".\"",
")",
"funcName",
"=",
"fullFuncName",
"[",
"lastDot",
"+",
"1",
":",
"]",
"modPath",
"=",
"fullFuncName",
... | 31.941176 | 16.470588 |
def collect_data(bids_dir, participant_label, task=None, echo=None,
bids_validate=True):
"""
Uses pybids to retrieve the input data for a given participant
>>> bids_root, _ = collect_data(str(datadir / 'ds054'), '100185',
... bids_validate=False)
>>> bids... | [
"def",
"collect_data",
"(",
"bids_dir",
",",
"participant_label",
",",
"task",
"=",
"None",
",",
"echo",
"=",
"None",
",",
"bids_validate",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"bids_dir",
",",
"BIDSLayout",
")",
":",
"layout",
"=",
"bids_dir",
... | 45.966667 | 23.1 |
def create_hair_layer(aspect, ip):
'''Reads the HAIR.pgn file and creates
the hair layer.'''
layer = []
if 'HAIR' in aspect:
layer = pgnreader.parse_pagan_file(FILE_HAIR, ip, invert=False, sym=True)
return layer | [
"def",
"create_hair_layer",
"(",
"aspect",
",",
"ip",
")",
":",
"layer",
"=",
"[",
"]",
"if",
"'HAIR'",
"in",
"aspect",
":",
"layer",
"=",
"pgnreader",
".",
"parse_pagan_file",
"(",
"FILE_HAIR",
",",
"ip",
",",
"invert",
"=",
"False",
",",
"sym",
"=",
... | 33.285714 | 19 |
def dotted_name(self, idents):
"""dotted_name: NAME ('.' NAME)*"""
return idents[0].loc.join(idents[-1].loc), \
".".join(list(map(lambda x: x.value, idents))) | [
"def",
"dotted_name",
"(",
"self",
",",
"idents",
")",
":",
"return",
"idents",
"[",
"0",
"]",
".",
"loc",
".",
"join",
"(",
"idents",
"[",
"-",
"1",
"]",
".",
"loc",
")",
",",
"\".\"",
".",
"join",
"(",
"list",
"(",
"map",
"(",
"lambda",
"x",
... | 46.5 | 10.75 |
def parse(self, buf):
'''parse a FD FDM buffer'''
try:
t = struct.unpack(self.pack_string, buf)
except struct.error as msg:
raise fgFDMError('unable to parse - %s' % msg)
self.values = list(t) | [
"def",
"parse",
"(",
"self",
",",
"buf",
")",
":",
"try",
":",
"t",
"=",
"struct",
".",
"unpack",
"(",
"self",
".",
"pack_string",
",",
"buf",
")",
"except",
"struct",
".",
"error",
"as",
"msg",
":",
"raise",
"fgFDMError",
"(",
"'unable to parse - %s'"... | 34.571429 | 14 |
def getDomainRealm(self, inputURL, environ):
"""Resolve a relative url to the appropriate realm name."""
# we don't get the realm here, its already been resolved in
# request_resolver
if inputURL.startswith("/"):
inputURL = inputURL[1:]
parts = inputURL.split("/")
... | [
"def",
"getDomainRealm",
"(",
"self",
",",
"inputURL",
",",
"environ",
")",
":",
"# we don't get the realm here, its already been resolved in",
"# request_resolver",
"if",
"inputURL",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"inputURL",
"=",
"inputURL",
"[",
"1",
... | 41.75 | 9.5 |
def set_tags(self, tags):
"""Set multiple tags for the measurement.
:param dict tags: Tag key/value pairs to assign
This will overwrite the current value assigned to a tag
if one exists with the same name.
"""
for key, value in tags.items():
self.set_tag(ke... | [
"def",
"set_tags",
"(",
"self",
",",
"tags",
")",
":",
"for",
"key",
",",
"value",
"in",
"tags",
".",
"items",
"(",
")",
":",
"self",
".",
"set_tag",
"(",
"key",
",",
"value",
")"
] | 29 | 16.272727 |
def storeBatchServiceSpecialCase(st, pups):
"""
Adapt a L{Store} to L{IBatchService}.
If C{st} is a substore, return a simple wrapper that delegates to the site
store's L{IBatchService} powerup. Return C{None} if C{st} has no
L{BatchProcessingControllerService}.
"""
if st.parent is not Non... | [
"def",
"storeBatchServiceSpecialCase",
"(",
"st",
",",
"pups",
")",
":",
"if",
"st",
".",
"parent",
"is",
"not",
"None",
":",
"try",
":",
"return",
"_SubStoreBatchChannel",
"(",
"st",
")",
"except",
"TypeError",
":",
"return",
"None",
"storeService",
"=",
... | 32.111111 | 16.333333 |
async def get_all(
self,
direction: msg.StreamDirection = msg.StreamDirection.Forward,
from_position: Optional[Union[msg.Position, msg._PositionSentinel]] = None,
max_count: int = 100,
resolve_links: bool = True,
require_master: bool = False,
correlation_id: uuid.... | [
"async",
"def",
"get_all",
"(",
"self",
",",
"direction",
":",
"msg",
".",
"StreamDirection",
"=",
"msg",
".",
"StreamDirection",
".",
"Forward",
",",
"from_position",
":",
"Optional",
"[",
"Union",
"[",
"msg",
".",
"Position",
",",
"msg",
".",
"_PositionS... | 36.396226 | 21.415094 |
def download_url(url):
'''download a URL and return the content'''
if sys.version_info.major < 3:
from urllib2 import urlopen as url_open
from urllib2 import URLError as url_error
else:
from urllib.request import urlopen as url_open
from urllib.error import URLError as url_er... | [
"def",
"download_url",
"(",
"url",
")",
":",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
":",
"from",
"urllib2",
"import",
"urlopen",
"as",
"url_open",
"from",
"urllib2",
"import",
"URLError",
"as",
"url_error",
"else",
":",
"from",
"urllib",... | 32.733333 | 14.466667 |
def _create_graph(self, return_target_sources=None):
"""
Create a DiGraph out of the existing edge map.
:param return_target_sources: Used for making up those missing returns
:returns: A networkx.DiGraph() object
"""
if return_target_sources is None:
# We set ... | [
"def",
"_create_graph",
"(",
"self",
",",
"return_target_sources",
"=",
"None",
")",
":",
"if",
"return_target_sources",
"is",
"None",
":",
"# We set it to a defaultdict in order to be consistent with the",
"# actual parameter.",
"return_target_sources",
"=",
"defaultdict",
"... | 42.377778 | 17.488889 |
def GenesisBlock() -> Block:
"""
Create the GenesisBlock.
Returns:
BLock:
"""
prev_hash = UInt256(data=bytearray(32))
timestamp = int(datetime(2016, 7, 15, 15, 8, 21, tzinfo=pytz.utc).timestamp())
index = 0
consensus_data = 2083236893 # Pay t... | [
"def",
"GenesisBlock",
"(",
")",
"->",
"Block",
":",
"prev_hash",
"=",
"UInt256",
"(",
"data",
"=",
"bytearray",
"(",
"32",
")",
")",
"timestamp",
"=",
"int",
"(",
"datetime",
"(",
"2016",
",",
"7",
",",
"15",
",",
"15",
",",
"8",
",",
"21",
",",... | 38.333333 | 24.2 |
def update_last_view(self, app_id, attributes):
"""
Updates the last view for the active user
:param app_id: the app id
:param attributes: the body of the request in dictionary format
"""
if not isinstance(attributes, dict):
raise TypeError('Must be of type d... | [
"def",
"update_last_view",
"(",
"self",
",",
"app_id",
",",
"attributes",
")",
":",
"if",
"not",
"isinstance",
"(",
"attributes",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'Must be of type dict'",
")",
"attribute_data",
"=",
"json",
".",
"dumps",
"(... | 43 | 15.666667 |
def clone_source(self):
" Clone source and prepare templates "
print_header('Clone src: %s' % self.src, '-')
# Get source
source_dir = self._get_source()
# Append settings from source
self.read(op.join(source_dir, settings.CFGNAME))
self.templates += (self.arg... | [
"def",
"clone_source",
"(",
"self",
")",
":",
"print_header",
"(",
"'Clone src: %s'",
"%",
"self",
".",
"src",
",",
"'-'",
")",
"# Get source",
"source_dir",
"=",
"self",
".",
"_get_source",
"(",
")",
"# Append settings from source",
"self",
".",
"read",
"(",
... | 32.177778 | 23.244444 |
def __reorganize(self):
"""
Reorganize the keys into their proper section order for the NOAA output file
DO NOT parse data tables (paleoData or chronData). We will do those separately.
:param str key:
:param any value:
:return none:
"""
logger_lpd_noaa.inf... | [
"def",
"__reorganize",
"(",
"self",
")",
":",
"logger_lpd_noaa",
".",
"info",
"(",
"\"enter reorganize\"",
")",
"# NOAA files are organized in sections differently than NOAA. try to translate these sections.",
"for",
"key",
",",
"value",
"in",
"self",
".",
"lipd_data",
".",... | 55.266667 | 24.466667 |
def incrby(self, name, amount=1):
"""
increment the value for key by value: int
:param name: str the name of the redis key
:param amount: int
:return: Future()
"""
with self.pipe as pipe:
return pipe.incrby(self.redis_key(name), amount=amount) | [
"def",
"incrby",
"(",
"self",
",",
"name",
",",
"amount",
"=",
"1",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"incrby",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"amount",
"=",
"amount",
")"
] | 30.7 | 13.5 |
def bitterness(self, ibu_method, early_og, batch_size):
"Calculate bitterness based on chosen method"
if ibu_method == "tinseth":
bitterness = 1.65 * math.pow(0.000125, early_og - 1.0) * ((1 - math.pow(math.e, -0.04 * self.time)) / 4.15) * ((self.alpha / 100.0 * self.amount * 1000000) / bat... | [
"def",
"bitterness",
"(",
"self",
",",
"ibu_method",
",",
"early_og",
",",
"batch_size",
")",
":",
"if",
"ibu_method",
"==",
"\"tinseth\"",
":",
"bitterness",
"=",
"1.65",
"*",
"math",
".",
"pow",
"(",
"0.000125",
",",
"early_og",
"-",
"1.0",
")",
"*",
... | 50.6 | 38.866667 |
def create_content_spec(**kwargs):
"""Sugar. factory for a PhyloSchema object.
Repackages the kwargs to kwargs for PhyloSchema so that our
PhyloSchema.__init__ does not have to be soo rich
"""
format_str = kwargs.get('format', 'nexson')
nexson_version = kwargs.get('nexson_version', 'native')
... | [
"def",
"create_content_spec",
"(",
"*",
"*",
"kwargs",
")",
":",
"format_str",
"=",
"kwargs",
".",
"get",
"(",
"'format'",
",",
"'nexson'",
")",
"nexson_version",
"=",
"kwargs",
".",
"get",
"(",
"'nexson_version'",
",",
"'native'",
")",
"otu_label",
"=",
"... | 41.857143 | 13.785714 |
def get_all_child_edges(self):
"""Return tuples for all child GO IDs, containing current GO ID and child GO ID."""
all_child_edges = set()
for parent in self.children:
all_child_edges.add((parent.item_id, self.item_id))
all_child_edges |= parent.get_all_child_edges()
... | [
"def",
"get_all_child_edges",
"(",
"self",
")",
":",
"all_child_edges",
"=",
"set",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"children",
":",
"all_child_edges",
".",
"add",
"(",
"(",
"parent",
".",
"item_id",
",",
"self",
".",
"item_id",
")",
")",
... | 48.571429 | 10.714286 |
def saveTM(tm):
"""
Saves the temporal memory and the sequences generated for its training.
@param tm (TemporalMemory) temporal memory used during the experiment
"""
# Save the TM to a file for future use
proto1 = TemporalMemoryProto_capnp.TemporalMemoryProto.new_message()
tm.write(proto1)
# Write th... | [
"def",
"saveTM",
"(",
"tm",
")",
":",
"# Save the TM to a file for future use",
"proto1",
"=",
"TemporalMemoryProto_capnp",
".",
"TemporalMemoryProto",
".",
"new_message",
"(",
")",
"tm",
".",
"write",
"(",
"proto1",
")",
"# Write the proto to a file and read it back into... | 34.5 | 19.166667 |
def self_signed(self):
"""
:return:
A boolean - if the certificate is self-signed
"""
if self._self_signed is None:
self._self_signed = False
if self.asn1.self_signed in set(['yes', 'maybe']):
signature_algo = self.asn1['signature_alg... | [
"def",
"self_signed",
"(",
"self",
")",
":",
"if",
"self",
".",
"_self_signed",
"is",
"None",
":",
"self",
".",
"_self_signed",
"=",
"False",
"if",
"self",
".",
"asn1",
".",
"self_signed",
"in",
"set",
"(",
"[",
"'yes'",
",",
"'maybe'",
"]",
")",
":"... | 35.3 | 16.8 |
def _set_mac(self, v, load=False):
"""
Setter method for mac, mapped from YANG variable /mac (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... | [
"def",
"_set_mac",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"... | 75.136364 | 34.727273 |
def mapping_matrix(self):
"""The mapping matrix is a matrix representing the mapping between every unmasked pixel of a grid and \
the pixels of a pixelization. Non-zero entries signify a mapping, whereas zeros signify no mapping.
For example, if the regular grid has 5 pixels and the pixelizatio... | [
"def",
"mapping_matrix",
"(",
"self",
")",
":",
"return",
"mapper_util",
".",
"mapping_matrix_from_sub_to_pix",
"(",
"sub_to_pix",
"=",
"self",
".",
"sub_to_pix",
",",
"pixels",
"=",
"self",
".",
"pixels",
",",
"regular_pixels",
"=",
"self",
".",
"grid_stack",
... | 58.458333 | 34.875 |
def startup(self):
"""Perform startup actions.
This just chains down to the transport layer.
"""
log.info("Immediate delivery manager starting.")
log.debug("Initializing transport queue.")
self.transport.startup()
log.info("Imme... | [
"def",
"startup",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Immediate delivery manager starting.\"",
")",
"log",
".",
"debug",
"(",
"\"Initializing transport queue.\"",
")",
"self",
".",
"transport",
".",
"startup",
"(",
")",
"log",
".",
"info",
"(",
... | 28.5 | 17.666667 |
def disconnect(self):
"""! @brief Deinitialize the DAP I/O pins"""
# TODO Close the APs. When this is attempted, we get an undocumented 0x1d error. Doesn't
# seem to be necessary, anyway.
self._memory_interfaces = {}
self._link.enter_idle()
self._is_connecte... | [
"def",
"disconnect",
"(",
"self",
")",
":",
"# TODO Close the APs. When this is attempted, we get an undocumented 0x1d error. Doesn't",
"# seem to be necessary, anyway.",
"self",
".",
"_memory_interfaces",
"=",
"{",
"}",
"self",
".",
"_link",
".",
"enter_idle",
"(",
")",... | 40.25 | 16.25 |
def or_(cls, obj, **kwargs):
"""Query an object
:param obj:
object to test
:param kwargs: query specified in kwargssql
:return:
`True` if at leat one `kwargs` expression is `True`,
`False` otherwise.
:rtype: bool
"""
return cls.__e... | [
"def",
"or_",
"(",
"cls",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"__eval_seqexp",
"(",
"obj",
",",
"operator",
".",
"or_",
",",
"*",
"*",
"kwargs",
")"
] | 24.714286 | 19.928571 |
def _explode_raster(raster, band_names=[]):
# type: (_Raster, Iterable[str]) -> List[_Raster]
"""Splits a raster into multiband rasters.
"""
# Using band_names=[] does no harm because we are not mutating it in place
# and it makes MyPy happy
if not band_names:
band_names = raster.band_n... | [
"def",
"_explode_raster",
"(",
"raster",
",",
"band_names",
"=",
"[",
"]",
")",
":",
"# type: (_Raster, Iterable[str]) -> List[_Raster]",
"# Using band_names=[] does no harm because we are not mutating it in place",
"# and it makes MyPy happy",
"if",
"not",
"band_names",
":",
"ba... | 39.692308 | 23.615385 |
def import_blocks(*blocks: BaseBlock) -> Callable[[BaseChain], BaseChain]:
"""
Variadic argument version of :func:`~eth.tools.builder.chain.import_block`
"""
@functools.wraps(import_blocks)
def _import_blocks(chain: BaseChain) -> BaseChain:
for block in blocks:
chain.import_block... | [
"def",
"import_blocks",
"(",
"*",
"blocks",
":",
"BaseBlock",
")",
"->",
"Callable",
"[",
"[",
"BaseChain",
"]",
",",
"BaseChain",
"]",
":",
"@",
"functools",
".",
"wraps",
"(",
"import_blocks",
")",
"def",
"_import_blocks",
"(",
"chain",
":",
"BaseChain",... | 33.181818 | 16.454545 |
def get_children(self, tree_alias, item):
"""Returns item's children.
:param str|unicode tree_alias:
:param TreeItemBase|None item:
:rtype: list
"""
if not self.current_app_is_admin():
# We do not need i18n for a tree rendered in Admin dropdown.
t... | [
"def",
"get_children",
"(",
"self",
",",
"tree_alias",
",",
"item",
")",
":",
"if",
"not",
"self",
".",
"current_app_is_admin",
"(",
")",
":",
"# We do not need i18n for a tree rendered in Admin dropdown.",
"tree_alias",
"=",
"self",
".",
"resolve_tree_i18n_alias",
"(... | 35.583333 | 15.75 |
def v2_playbook_on_task_start(self, task, **kwargs):
"""Run when a task starts."""
self.last_task_name = task.get_name()
self.printed_last_task = False | [
"def",
"v2_playbook_on_task_start",
"(",
"self",
",",
"task",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"last_task_name",
"=",
"task",
".",
"get_name",
"(",
")",
"self",
".",
"printed_last_task",
"=",
"False"
] | 43 | 4.75 |
def readFace(self, line):
""" Each face consists of three or more sets of indices. Each set
consists of 1, 2 or 3 indices to vertices/normals/texcords.
"""
# Get parts (skip first)
indexSets = [num for num in line.split(' ') if num][1:]
final_face = []
for index... | [
"def",
"readFace",
"(",
"self",
",",
"line",
")",
":",
"# Get parts (skip first)",
"indexSets",
"=",
"[",
"num",
"for",
"num",
"in",
"line",
".",
"split",
"(",
"' '",
")",
"if",
"num",
"]",
"[",
"1",
":",
"]",
"final_face",
"=",
"[",
"]",
"for",
"i... | 41.288136 | 20.169492 |
def redraw_label(self):
"""
Re-calculates the position of the Label.
"""
# Convenience variables
sx,sy = self.size
x,y = self.pos
# Label position
self._label.anchor_x = "left"
self._label.x = x+sx/2.+sx
self._label.y = y+sy/2.+sy*... | [
"def",
"redraw_label",
"(",
"self",
")",
":",
"# Convenience variables",
"sx",
",",
"sy",
"=",
"self",
".",
"size",
"x",
",",
"y",
"=",
"self",
".",
"pos",
"# Label position",
"self",
".",
"_label",
".",
"anchor_x",
"=",
"\"left\"",
"self",
".",
"_label"... | 26.230769 | 10.538462 |
def acorr(blk, max_lag=None):
"""
Calculate the autocorrelation of a given 1-D block sequence.
Parameters
----------
blk :
An iterable with well-defined length. Don't use this function with Stream
objects!
max_lag :
The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``,
... | [
"def",
"acorr",
"(",
"blk",
",",
"max_lag",
"=",
"None",
")",
":",
"if",
"max_lag",
"is",
"None",
":",
"max_lag",
"=",
"len",
"(",
"blk",
")",
"-",
"1",
"return",
"[",
"sum",
"(",
"blk",
"[",
"n",
"]",
"*",
"blk",
"[",
"n",
"+",
"tau",
"]",
... | 28.916667 | 22.861111 |
def date(self,local=False):
""" Return the date object associated
:param local: if False [default] return UTC date. If True return localtz date
"""
return Date(self.get(local).date(),self.local_tz) | [
"def",
"date",
"(",
"self",
",",
"local",
"=",
"False",
")",
":",
"return",
"Date",
"(",
"self",
".",
"get",
"(",
"local",
")",
".",
"date",
"(",
")",
",",
"self",
".",
"local_tz",
")"
] | 45.8 | 15.8 |
def merge_base_attrs(attrs):
"""
:param dict attrs: If one of the attrs is named "base\_", assume that attribute is an instance of SimpleModel mapped on a Postgresql composite type, and that the base\_ instance is of a superclass of this class. Expand the attributes of the base\_ type and assign to clas... | [
"def",
"merge_base_attrs",
"(",
"attrs",
")",
":",
"base",
"=",
"attrs",
".",
"pop",
"(",
"'base_'",
",",
"None",
")",
"if",
"base",
":",
"d_out",
"(",
"\"SimpleModel.merge_base_attrs: base.table={0}\"",
".",
"format",
"(",
"base",
".",
"table",
")",
")",
... | 58.25 | 36.75 |
def get_dimension(self, dataset, dimension):
"""The method is getting information about dimension with items"""
path = '/api/1.0/meta/dataset/{}/dimension/{}'
return self._api_get(definition.Dimension, path.format(dataset, dimension)) | [
"def",
"get_dimension",
"(",
"self",
",",
"dataset",
",",
"dimension",
")",
":",
"path",
"=",
"'/api/1.0/meta/dataset/{}/dimension/{}'",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"Dimension",
",",
"path",
".",
"format",
"(",
"dataset",
",",
"d... | 51.8 | 20.4 |
def set_yticks(self, row, column, ticks):
"""Manually specify the y-axis tick values.
:param row,column: specify the subplot.
:param ticks: list of tick values.
"""
subplot = self.get_subplot_at(row, column)
subplot.set_yticks(ticks) | [
"def",
"set_yticks",
"(",
"self",
",",
"row",
",",
"column",
",",
"ticks",
")",
":",
"subplot",
"=",
"self",
".",
"get_subplot_at",
"(",
"row",
",",
"column",
")",
"subplot",
".",
"set_yticks",
"(",
"ticks",
")"
] | 30.555556 | 11.888889 |
def bishop88_mpp(photocurrent, saturation_current, resistance_series,
resistance_shunt, nNsVth, method='newton'):
"""
Find max power point.
Parameters
----------
photocurrent : numeric
photogenerated current (Iph or IL) in amperes [A]
saturation_current : numeric
... | [
"def",
"bishop88_mpp",
"(",
"photocurrent",
",",
"saturation_current",
",",
"resistance_series",
",",
"resistance_shunt",
",",
"nNsVth",
",",
"method",
"=",
"'newton'",
")",
":",
"# collect args",
"args",
"=",
"(",
"photocurrent",
",",
"saturation_current",
",",
"... | 37.690909 | 20.454545 |
def palettize(self, colormap):
"""Palettize the current image using `colormap`.
.. note::
Works only on "L" or "LA" images.
"""
if self.mode not in ("L", "LA"):
raise ValueError("Image should be grayscale to colorize")
l_data = self.data.sel(bands=['L... | [
"def",
"palettize",
"(",
"self",
",",
"colormap",
")",
":",
"if",
"self",
".",
"mode",
"not",
"in",
"(",
"\"L\"",
",",
"\"LA\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Image should be grayscale to colorize\"",
")",
"l_data",
"=",
"self",
".",
"data",
"."... | 27.862069 | 21.758621 |
def prompt(message, default=None, strip=True, suffix=' '):
""" Print a message and prompt user for input. Return user input. """
if default is not None:
prompt_text = "{0} [{1}]{2}".format(message, default, suffix)
else:
prompt_text = "{0}{1}".format(message, suffix)
input_value = get_i... | [
"def",
"prompt",
"(",
"message",
",",
"default",
"=",
"None",
",",
"strip",
"=",
"True",
",",
"suffix",
"=",
"' '",
")",
":",
"if",
"default",
"is",
"not",
"None",
":",
"prompt_text",
"=",
"\"{0} [{1}]{2}\"",
".",
"format",
"(",
"message",
",",
"defaul... | 29.625 | 20.1875 |
def load_xml(fp, object_pairs_hook=dict):
r"""
Parse the contents of the file-like object ``fp`` as an XML properties file
and return a `dict` of the key-value pairs.
Beyond basic XML well-formedness, `load_xml` only checks that the root
element is named "``properties``" and that all of its ``<entr... | [
"def",
"load_xml",
"(",
"fp",
",",
"object_pairs_hook",
"=",
"dict",
")",
":",
"tree",
"=",
"ET",
".",
"parse",
"(",
"fp",
")",
"return",
"object_pairs_hook",
"(",
"_fromXML",
"(",
"tree",
".",
"getroot",
"(",
")",
")",
")"
] | 50.342857 | 27.685714 |
def jvm_dependency_map(self):
"""A map of each JvmTarget in the context to the set of JvmTargets it depends on "directly".
"Directly" is in quotes here because it isn't quite the same as its normal use, which would be
filter(self._is_jvm_target, target.dependencies).
For this method, we define the set... | [
"def",
"jvm_dependency_map",
"(",
"self",
")",
":",
"jvm_deps",
"=",
"self",
".",
"_unfiltered_jvm_dependency_map",
"(",
")",
"return",
"{",
"target",
":",
"deps",
"for",
"target",
",",
"deps",
"in",
"jvm_deps",
".",
"items",
"(",
")",
"if",
"deps",
"and",... | 55.439024 | 38.780488 |
def get_screen_size(self, screen_no):
"""Returns the size of the given screen number"""
return GetScreenSize(display=self.display,
opcode=self.display.get_extension_major(extname),
window=self.id,
screen=screen_no,
... | [
"def",
"get_screen_size",
"(",
"self",
",",
"screen_no",
")",
":",
"return",
"GetScreenSize",
"(",
"display",
"=",
"self",
".",
"display",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_extension_major",
"(",
"extname",
")",
",",
"window",
"=",
"sel... | 45.428571 | 8.428571 |
def IsPayable(self):
"""
Flag indicating if the contract accepts payments.
Returns:
bool: True if supported. False otherwise.
"""
from neo.Core.State.ContractState import ContractPropertyState
return self.ContractProperties & ContractPropertyState.Payable > 0 | [
"def",
"IsPayable",
"(",
"self",
")",
":",
"from",
"neo",
".",
"Core",
".",
"State",
".",
"ContractState",
"import",
"ContractPropertyState",
"return",
"self",
".",
"ContractProperties",
"&",
"ContractPropertyState",
".",
"Payable",
">",
"0"
] | 34.666667 | 19.777778 |
def process_python(self, path):
"""Process a python file."""
(pylint_stdout, pylint_stderr) = epylint.py_run(
' '.join([str(path)] + self.pylint_opts), return_std=True)
emap = {}
print(pylint_stderr.read())
for line in pylint_stdout:
sys.stderr.write(line)... | [
"def",
"process_python",
"(",
"self",
",",
"path",
")",
":",
"(",
"pylint_stdout",
",",
"pylint_stderr",
")",
"=",
"epylint",
".",
"py_run",
"(",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"path",
")",
"]",
"+",
"self",
".",
"pylint_opts",
")",
",",
... | 36.294118 | 11.588235 |
def set_trig_end(self,time,pass_to_command_line=True):
"""
Set the trig end time of the analysis node by setting a --trig-end-time
option to the node when it is executed.
@param time: trig end time of job.
@bool pass_to_command_line: add trig-end-time as a variable option.
"""
if pass_to_com... | [
"def",
"set_trig_end",
"(",
"self",
",",
"time",
",",
"pass_to_command_line",
"=",
"True",
")",
":",
"if",
"pass_to_command_line",
":",
"self",
".",
"add_var_opt",
"(",
"'trig-end-time'",
",",
"time",
")",
"self",
".",
"__trig_end",
"=",
"time"
] | 39.3 | 11.5 |
def _render_dynamic(self, dynamic_exercise, min_rep,
desired_reps, desired_intensity, validate):
"""
Render a single dynamic exercise.
This is done for each exercise every week.
"""
# --------------------------------
# Generate possible repstring ... | [
"def",
"_render_dynamic",
"(",
"self",
",",
"dynamic_exercise",
",",
"min_rep",
",",
"desired_reps",
",",
"desired_intensity",
",",
"validate",
")",
":",
"# --------------------------------",
"# Generate possible repstring and calculate penalties",
"# ----------------------------... | 46.272727 | 20.515152 |
def get_protocols(self, device):
"""Returns a list of available protocols for the specified device."""
return self._reg.device_builder(device, self._rv).protocols | [
"def",
"get_protocols",
"(",
"self",
",",
"device",
")",
":",
"return",
"self",
".",
"_reg",
".",
"device_builder",
"(",
"device",
",",
"self",
".",
"_rv",
")",
".",
"protocols"
] | 58.666667 | 11.666667 |
def notificationNch():
"""NOTIFICATION/NCH Section 9.1.21b"""
a = L2PseudoLength(l2pLength=0x01)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x20) # 00100000
d = NtNRestOctets()
packet = a / b / c / d
return packet | [
"def",
"notificationNch",
"(",
")",
":",
"a",
"=",
"L2PseudoLength",
"(",
"l2pLength",
"=",
"0x01",
")",
"b",
"=",
"TpPd",
"(",
"pd",
"=",
"0x6",
")",
"c",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x20",
")",
"# 00100000",
"d",
"=",
"NtNRestOctets",
... | 29.125 | 12.375 |
def get_module_name(package):
"""
package must have these attributes:
e.g.:
package.DISTRIBUTION_NAME = "DragonPyEmulator"
package.DIST_GROUP = "console_scripts"
package.ENTRY_POINT = "DragonPy"
:return: a string like: "dragonpy.core.cli"
"""
distribution = get_distribut... | [
"def",
"get_module_name",
"(",
"package",
")",
":",
"distribution",
"=",
"get_distribution",
"(",
"package",
".",
"DISTRIBUTION_NAME",
")",
"entry_info",
"=",
"distribution",
".",
"get_entry_info",
"(",
"package",
".",
"DIST_GROUP",
",",
"package",
".",
"ENTRY_POI... | 36.842105 | 19.157895 |
def _import_yaml(config_file_path):
"""Return a configuration object
"""
try:
logger.info('Importing config %s...', config_file_path)
with open(config_file_path) as config_file:
return yaml.safe_load(config_file.read())
except IOError as ex:
raise RepexError('{0}: {1}... | [
"def",
"_import_yaml",
"(",
"config_file_path",
")",
":",
"try",
":",
"logger",
".",
"info",
"(",
"'Importing config %s...'",
",",
"config_file_path",
")",
"with",
"open",
"(",
"config_file_path",
")",
"as",
"config_file",
":",
"return",
"yaml",
".",
"safe_load"... | 44.666667 | 16.416667 |
def put_scancodes(self, scancodes):
"""Sends an array of scancodes to the keyboard.
in scancodes of type int
return codes_stored of type int
raises :class:`VBoxErrorIprtError`
Could not send all scan codes to virtual keyboard.
"""
if not isinstance... | [
"def",
"put_scancodes",
"(",
"self",
",",
"scancodes",
")",
":",
"if",
"not",
"isinstance",
"(",
"scancodes",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"scancodes can only be an instance of type list\"",
")",
"for",
"a",
"in",
"scancodes",
"[",
":",
... | 35.25 | 15.65 |
def _wrap_definition_section(source, width):
# type: (str, int) -> str
"""Wrap the given definition section string to the current terminal size.
Note:
Auto-adjusts the spacing between terms and definitions.
Args:
source: The section string to wrap.
Returns:
The wrapped sec... | [
"def",
"_wrap_definition_section",
"(",
"source",
",",
"width",
")",
":",
"# type: (str, int) -> str",
"index",
"=",
"source",
".",
"index",
"(",
"'\\n'",
")",
"+",
"1",
"definitions",
",",
"max_len",
"=",
"_get_definitions",
"(",
"source",
"[",
"index",
":",
... | 31.32 | 17.08 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.