text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def destinations(stop):
"""Get destination information."""
from pyruter.api import Departures
async def get_destinations():
"""Get departure information."""
async with aiohttp.ClientSession() as session:
data = Departures(LOOP, stop, session=session)
result = await d... | [
"def",
"destinations",
"(",
"stop",
")",
":",
"from",
"pyruter",
".",
"api",
"import",
"Departures",
"async",
"def",
"get_destinations",
"(",
")",
":",
"\"\"\"Get departure information.\"\"\"",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"s... | 41.416667 | 12.583333 |
def list_comment(self, node, elem, minel):
"""Add list annotation to `elem`."""
lo = "0" if minel is None else minel.arg
maxel = node.search_one("max-elements")
hi = "" if maxel is None else maxel.arg
elem.insert(0, etree.Comment(
" # entries: %s..%s " % (lo, hi)))
... | [
"def",
"list_comment",
"(",
"self",
",",
"node",
",",
"elem",
",",
"minel",
")",
":",
"lo",
"=",
"\"0\"",
"if",
"minel",
"is",
"None",
"else",
"minel",
".",
"arg",
"maxel",
"=",
"node",
".",
"search_one",
"(",
"\"max-elements\"",
")",
"hi",
"=",
"\"\... | 45.5 | 6.9 |
def stats_set_tag(self, key, value=1):
"""Set the specified tag/value in the per-message measurements
.. versionadded:: 3.13.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate t... | [
"def",
"stats_set_tag",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"_measurement",
":",
"if",
"not",
"self",
".",
"IGNORE_OOB_STATS",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'stats_set_tag invoked outside... | 38.090909 | 18.5 |
def create_archive(self):
"""Create a new archive.
The method creates in the filesystem a brand new archive with
a random SHA1 as its name. The first byte of the hashcode will
be the name of the subdirectory; the remaining bytes, the
archive name.
:returns: a new `Archi... | [
"def",
"create_archive",
"(",
"self",
")",
":",
"hashcode",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"archive_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dirpath",
",",
"hashcode",
"[",
"0",
":",
"2",
"]",
")",
"archive_na... | 32.851852 | 20.37037 |
def rt_update(self, statement, linenum, mode, modulep, lineparser):
"""Uses the specified line parser to parse the given statement.
:arg statement: a string of lines that are part of a single statement.
:arg linenum: the line number of the first line in the statement relative to
the e... | [
"def",
"rt_update",
"(",
"self",
",",
"statement",
",",
"linenum",
",",
"mode",
",",
"modulep",
",",
"lineparser",
")",
":",
"#Most of the module is body, since that includes everything inside",
"#of the module ... end module keywords. Since docstrings are handled",
"#at a higher... | 60.578947 | 26.157895 |
def raster2pyramid(input_file, output_dir, options):
"""Create a tile pyramid out of an input raster dataset."""
pyramid_type = options["pyramid_type"]
scale_method = options["scale_method"]
output_format = options["output_format"]
resampling = options["resampling"]
zoom = options["zoom"]
bo... | [
"def",
"raster2pyramid",
"(",
"input_file",
",",
"output_dir",
",",
"options",
")",
":",
"pyramid_type",
"=",
"options",
"[",
"\"pyramid_type\"",
"]",
"scale_method",
"=",
"options",
"[",
"\"scale_method\"",
"]",
"output_format",
"=",
"options",
"[",
"\"output_for... | 37.776119 | 12.268657 |
def get_context():
"""Provide the context to use.
This function takes care of creating new contexts in case of forks.
"""
pid = os.getpid()
if pid not in context:
context[pid] = zmq.Context()
logger.debug('renewed context for PID %d', pid)
return context[pid] | [
"def",
"get_context",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"if",
"pid",
"not",
"in",
"context",
":",
"context",
"[",
"pid",
"]",
"=",
"zmq",
".",
"Context",
"(",
")",
"logger",
".",
"debug",
"(",
"'renewed context for PID %d'",
"... | 29.1 | 16.2 |
def get_route(ip):
'''
Return routing information for given destination ip
.. versionadded:: 2016.11.5
CLI Example::
salt '*' network.get_route 10.10.10.10
'''
cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip)
out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=Tru... | [
"def",
"get_route",
"(",
"ip",
")",
":",
"cmd",
"=",
"'Find-NetRoute -RemoteIPAddress {0}'",
".",
"format",
"(",
"ip",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"shell",
"=",
"'powershell'",
",",
"python_shell",
"=",
"True",
")",... | 27.222222 | 21.148148 |
def addi(self, begin, end, data=None):
"""
Shortcut for add(Interval(begin, end, data)).
Completes in O(log n) time.
"""
return self.add(Interval(begin, end, data)) | [
"def",
"addi",
"(",
"self",
",",
"begin",
",",
"end",
",",
"data",
"=",
"None",
")",
":",
"return",
"self",
".",
"add",
"(",
"Interval",
"(",
"begin",
",",
"end",
",",
"data",
")",
")"
] | 28.428571 | 10.142857 |
def encode_numpy(array):
'''Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape
'''
return {'data' : base64.... | [
"def",
"encode_numpy",
"(",
"array",
")",
":",
"return",
"{",
"'data'",
":",
"base64",
".",
"b64encode",
"(",
"array",
".",
"data",
")",
".",
"decode",
"(",
"'utf8'",
")",
",",
"'type'",
":",
"array",
".",
"dtype",
".",
"name",
",",
"'shape'",
":",
... | 34.916667 | 17.916667 |
def _compileSmsRegexes(self):
""" Compiles regular expression used for parsing SMS messages based on current mode """
if self._smsTextMode:
if self.CMGR_SM_DELIVER_REGEX_TEXT == None:
self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$... | [
"def",
"_compileSmsRegexes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_smsTextMode",
":",
"if",
"self",
".",
"CMGR_SM_DELIVER_REGEX_TEXT",
"==",
"None",
":",
"self",
".",
"CMGR_SM_DELIVER_REGEX_TEXT",
"=",
"re",
".",
"compile",
"(",
"r'^\\+CMGR: \"([^\"]+)\",\"(... | 73.875 | 32.5 |
def DOM_describeNode(self, **kwargs):
"""
Function path: DOM.describeNode
Domain: DOM
Method name: describeNode
Parameters:
Optional arguments:
'nodeId' (type: NodeId) -> Identifier of the node.
'backendNodeId' (type: BackendNodeId) -> Identifier of the backend node.
'objectId' (type:... | [
"def",
"DOM_describeNode",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'depth'",
"in",
"kwargs",
":",
"assert",
"isinstance",
"(",
"kwargs",
"[",
"'depth'",
"]",
",",
"(",
"int",
",",
")",
")",
",",
"\"Optional argument 'depth' must be of type '['... | 51.3125 | 31.375 |
def L(g,i):
"""recursively constructs L line for g; i = len(g)-1"""
g1 = g&(2**i)
if i:
n = Lwidth(i)
Ln = L(g,i-1)
if g1:
return Ln<<(2*n) | Ln<<n | Ln
else:
return int('1'*n,2)<<(2*n) | Ln<<n | Ln
else:
if g1:
return... | [
"def",
"L",
"(",
"g",
",",
"i",
")",
":",
"g1",
"=",
"g",
"&",
"(",
"2",
"**",
"i",
")",
"if",
"i",
":",
"n",
"=",
"Lwidth",
"(",
"i",
")",
"Ln",
"=",
"L",
"(",
"g",
",",
"i",
"-",
"1",
")",
"if",
"g1",
":",
"return",
"Ln",
"<<",
"(... | 24.333333 | 19.866667 |
def print_coords(rows, prefix=''):
"""Print coordinates within a sequence.
This is only used for debugging. Printed in a form that can be
pasted into Python for visualization."""
lat = [row['lat'] for row in rows]
lon = [row['lon'] for row in rows]
print('COORDS'+'-' * 5)
print("%slat, %sl... | [
"def",
"print_coords",
"(",
"rows",
",",
"prefix",
"=",
"''",
")",
":",
"lat",
"=",
"[",
"row",
"[",
"'lat'",
"]",
"for",
"row",
"in",
"rows",
"]",
"lon",
"=",
"[",
"row",
"[",
"'lon'",
"]",
"for",
"row",
"in",
"rows",
"]",
"print",
"(",
"'COOR... | 37 | 13.7 |
def get_container_create_kwargs(self, action, container_name, kwargs=None):
"""
Generates keyword arguments for the Docker client to create a container.
:param action: Action configuration.
:type action: ActionConfig
:param container_name: Container name.
:type container... | [
"def",
"get_container_create_kwargs",
"(",
"self",
",",
"action",
",",
"container_name",
",",
"kwargs",
"=",
"None",
")",
":",
"policy",
"=",
"self",
".",
"_policy",
"client_config",
"=",
"action",
".",
"client_config",
"container_map",
"=",
"action",
".",
"co... | 56.875 | 26.767857 |
def chars_in(bits, keyspace):
""" ..
log2(keyspace^x_chars) = bits
log(keyspace^x_chars) = log(2) * bits
exp(log(keyspace^x_chars)) = exp(log(2) * bits)
x_chars = log(exp(log(2) * bits)) / log(keyspace)
..
-> (#int) number of characters in @bits of entropy given the @... | [
"def",
"chars_in",
"(",
"bits",
",",
"keyspace",
")",
":",
"keyspace",
"=",
"len",
"(",
"keyspace",
")",
"if",
"keyspace",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Keyspace size must be >1\"",
")",
"bits_per_cycle",
"=",
"512",
"if",
"bits",
">",
"bit... | 35.64 | 13.68 |
def run_script_with_context(script_path, cwd, context):
"""Execute a script after rendering it with Jinja.
:param script_path: Absolute path to the script to run.
:param cwd: The directory to run the script from.
:param context: Cookiecutter project template context.
"""
_, extension = os.path.... | [
"def",
"run_script_with_context",
"(",
"script_path",
",",
"cwd",
",",
"context",
")",
":",
"_",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"script_path",
")",
"contents",
"=",
"io",
".",
"open",
"(",
"script_path",
",",
"'r'",
",",
... | 31.2 | 16.6 |
def set_settings(self, settings):
"""
Set every given settings as object attributes.
Args:
settings (dict): Dictionnary of settings.
"""
for k, v in settings.items():
setattr(self, k, v) | [
"def",
"set_settings",
"(",
"self",
",",
"settings",
")",
":",
"for",
"k",
",",
"v",
"in",
"settings",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")"
] | 24.3 | 15.3 |
def queuestats(self):
""" Compute ETAs for every known queue & subqueue """
start_time = time.time()
log.debug("Starting queue stats...")
# Fetch all known queues
queues = [Queue(q) for q in Queue.all_known()]
new_queues = {queue.id for queue in queues}
old_que... | [
"def",
"queuestats",
"(",
"self",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"log",
".",
"debug",
"(",
"\"Starting queue stats...\"",
")",
"# Fetch all known queues",
"queues",
"=",
"[",
"Queue",
"(",
"q",
")",
"for",
"q",
"in",
"Queue",
... | 34.909091 | 22.757576 |
def _make_value(self, field_name, field_spec, value_spec, field_params, value):
"""
Contructs an appropriate Asn1Value object for a field
:param field_name:
A unicode string of the field name
:param field_spec:
An Asn1Value class that is the field spec
... | [
"def",
"_make_value",
"(",
"self",
",",
"field_name",
",",
"field_spec",
",",
"value_spec",
",",
"field_params",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"and",
"'optional'",
"in",
"field_params",
":",
"return",
"VOID",
"specs_different",
"=",
"f... | 35.810526 | 18.231579 |
def delete_logtail_config(self, project_name, config_name):
""" delete logtail config in a project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type config_name: string
:param config_name: ... | [
"def",
"delete_logtail_config",
"(",
"self",
",",
"project_name",
",",
"config_name",
")",
":",
"headers",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"resource",
"=",
"\"/configs/\"",
"+",
"config_name",
"(",
"resp",
",",
"headers",
")",
"=",
"self",
".",
"... | 33.5 | 19.35 |
def authenticate_with_access_token(access_token):
"""Authenticate using an existing access token."""
credentials = Credentials(access_token=access_token)
client = YamcsClient('localhost:8090', credentials=credentials)
for link in client.list_data_links('simulator'):
print(link) | [
"def",
"authenticate_with_access_token",
"(",
"access_token",
")",
":",
"credentials",
"=",
"Credentials",
"(",
"access_token",
"=",
"access_token",
")",
"client",
"=",
"YamcsClient",
"(",
"'localhost:8090'",
",",
"credentials",
"=",
"credentials",
")",
"for",
"link... | 42.428571 | 17.857143 |
def write(
contents: str,
path: Union[str, pathlib.Path],
verbose: bool = False,
logger_func=None,
) -> bool:
"""
Writes ``contents`` to ``path``.
Checks if ``path`` already exists and only write out new contents if the
old contents do not match.
Creates any intermediate missing di... | [
"def",
"write",
"(",
"contents",
":",
"str",
",",
"path",
":",
"Union",
"[",
"str",
",",
"pathlib",
".",
"Path",
"]",
",",
"verbose",
":",
"bool",
"=",
"False",
",",
"logger_func",
"=",
"None",
",",
")",
"->",
"bool",
":",
"print_func",
"=",
"logge... | 30.292683 | 13.902439 |
def slugs_configuration_camera_send(self, target, idOrder, order, force_mavlink1=False):
'''
Control for camara.
target : The system setting the commands (uint8_t)
idOrder : ID 0: brightness 1: aperture 2: iris 3: ICR ... | [
"def",
"slugs_configuration_camera_send",
"(",
"self",
",",
"target",
",",
"idOrder",
",",
"order",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"slugs_configuration_camera_encode",
"(",
"target",
",",
"idOrder"... | 58.1 | 43.5 |
def make_into_gene(self):
'''Tries to make into a gene sequence. Tries all three reading frames and both strands. Returns a tuple (new sequence, strand, frame) if it was successful. Otherwise returns None.'''
for reverse in [True, False]:
for frame in range(3):
new_seq = copy... | [
"def",
"make_into_gene",
"(",
"self",
")",
":",
"for",
"reverse",
"in",
"[",
"True",
",",
"False",
"]",
":",
"for",
"frame",
"in",
"range",
"(",
"3",
")",
":",
"new_seq",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"if",
"reverse",
":",
"new_seq",
... | 50.529412 | 27.588235 |
def find_by_username(self, username):
"""Return user by username if find in database otherwise None"""
data = (db.select(self.table).select('username', 'email', 'real_name',
'password', 'bio', 'status', 'role', 'uid').
condition('username', us... | [
"def",
"find_by_username",
"(",
"self",
",",
"username",
")",
":",
"data",
"=",
"(",
"db",
".",
"select",
"(",
"self",
".",
"table",
")",
".",
"select",
"(",
"'username'",
",",
"'email'",
",",
"'real_name'",
",",
"'password'",
",",
"'bio'",
",",
"'stat... | 51.875 | 20.375 |
def truncated_normal_like(x, mu, tau, a=None, b=None):
R"""
Truncated normal log-likelihood.
.. math::
f(x \mid \mu, \tau, a, b) = \frac{\phi(\frac{x-\mu}{\sigma})} {\Phi(\frac{b-\mu}{\sigma}) - \Phi(\frac{a-\mu}{\sigma})},
where :math:`\sigma^2=1/\tau`, `\phi` is the standard normal PDF and `... | [
"def",
"truncated_normal_like",
"(",
"x",
",",
"mu",
",",
"tau",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
")",
":",
"x",
"=",
"np",
".",
"atleast_1d",
"(",
"x",
")",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"-",
"np",
".",
"inf",
"a",
"... | 31.545455 | 19.75 |
def main(ctx, verbose, quiet):
"""
Execute the main mappyfile command
"""
verbosity = verbose - quiet
configure_logging(verbosity)
ctx.obj = {}
ctx.obj['verbosity'] = verbosity | [
"def",
"main",
"(",
"ctx",
",",
"verbose",
",",
"quiet",
")",
":",
"verbosity",
"=",
"verbose",
"-",
"quiet",
"configure_logging",
"(",
"verbosity",
")",
"ctx",
".",
"obj",
"=",
"{",
"}",
"ctx",
".",
"obj",
"[",
"'verbosity'",
"]",
"=",
"verbosity"
] | 24.625 | 7.125 |
def import_dotted_path(path):
"""
Takes a dotted path to a member name in a module, and returns
the member after importing it.
"""
# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)
try:
module_path, member_name = path.rsplit(".", 1)
module = import_module(mod... | [
"def",
"import_dotted_path",
"(",
"path",
")",
":",
"# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)",
"try",
":",
"module_path",
",",
"member_name",
"=",
"path",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"module",
"=",
"import_module",
"(",
... | 41.666667 | 15.333333 |
def symbolic_axis_rotation_matrix(axis, symbolic_theta):
"""Returns a rotation matrix around the given axis"""
[x, y, z] = axis
c = sympy.cos(symbolic_theta)
s = sympy.sin(symbolic_theta)
return sympy.Matrix([
[x**2 + (1 - x**2) * c, x * y * (1 - c) - z * s, x * z * (1 - c) + y * s],
... | [
"def",
"symbolic_axis_rotation_matrix",
"(",
"axis",
",",
"symbolic_theta",
")",
":",
"[",
"x",
",",
"y",
",",
"z",
"]",
"=",
"axis",
"c",
"=",
"sympy",
".",
"cos",
"(",
"symbolic_theta",
")",
"s",
"=",
"sympy",
".",
"sin",
"(",
"symbolic_theta",
")",
... | 47.7 | 22.6 |
def FromResponse(cls, response):
"""Create a DeviceFlowInfo from a server response.
The response should be a dict containing entries as described here:
http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1
"""
# device_code, user_code, and verification_url are require... | [
"def",
"FromResponse",
"(",
"cls",
",",
"response",
")",
":",
"# device_code, user_code, and verification_url are required.",
"kwargs",
"=",
"{",
"'device_code'",
":",
"response",
"[",
"'device_code'",
"]",
",",
"'user_code'",
":",
"response",
"[",
"'user_code'",
"]",... | 41.533333 | 16.833333 |
def serialize(self, content):
""" Serialize to JSON.
:return string: serializaed JSON
"""
worker = JSONSerializer(
scheme=self.resource,
options=self.resource._meta.emit_options,
format=self.resource._meta.emit_format,
**self.resource._me... | [
"def",
"serialize",
"(",
"self",
",",
"content",
")",
":",
"worker",
"=",
"JSONSerializer",
"(",
"scheme",
"=",
"self",
".",
"resource",
",",
"options",
"=",
"self",
".",
"resource",
".",
"_meta",
".",
"emit_options",
",",
"format",
"=",
"self",
".",
"... | 28.692308 | 12.769231 |
def _prepare_grids(self):
"""
depending on the type of grid (rectangular or triangle), prepare grids
or triangle lists
TODO: We want some nice way of not needing to know in the future if we
loaded triangles or quadratic elements.
"""
if(self.header['element... | [
"def",
"_prepare_grids",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"header",
"[",
"'element_infos'",
"]",
"[",
"0",
",",
"2",
"]",
"==",
"3",
")",
":",
"print",
"(",
"'Triangular grid found'",
")",
"self",
".",
"grid_is_rectangular",
"=",
"False",
... | 37.75 | 13.113636 |
def movable_items(self):
"""Filter selection
Filter items of selection that cannot be moved (i.e. are not instances of `Item`) and return the rest.
"""
view = self.view
if self._move_name_v:
yield InMotion(self._item, view)
else:
selected_items =... | [
"def",
"movable_items",
"(",
"self",
")",
":",
"view",
"=",
"self",
".",
"view",
"if",
"self",
".",
"_move_name_v",
":",
"yield",
"InMotion",
"(",
"self",
".",
"_item",
",",
"view",
")",
"else",
":",
"selected_items",
"=",
"set",
"(",
"view",
".",
"s... | 32.666667 | 17.2 |
def optional_str(deco):
"""
string 1개만 deco 인자로 오거나 없거나.
:param deco:
:return:
"""
@wraps(deco)
def dispatcher(*args, **kwargs):
# when only function arg
if not kwargs and len(args) == 1 and not isinstance(args[0], str) \
and args[0] is not None:
... | [
"def",
"optional_str",
"(",
"deco",
")",
":",
"@",
"wraps",
"(",
"deco",
")",
"def",
"dispatcher",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# when only function arg",
"if",
"not",
"kwargs",
"and",
"len",
"(",
"args",
")",
"==",
"1",
"and... | 23.952381 | 16.714286 |
def Davis_David(m, x, D, rhol, rhog, Cpl, kl, mul):
r'''Calculates the two-phase non-boiling heat transfer coefficient of a
liquid and gas flowing inside a tube of any inclination, as in [1]_ and
reviewed in [2]_.
.. math::
\frac{h_{TP} D}{k_l} = 0.060\left(\frac{\rho_L}{\rho_G}\right)^{0.28}... | [
"def",
"Davis_David",
"(",
"m",
",",
"x",
",",
"D",
",",
"rhol",
",",
"rhog",
",",
"Cpl",
",",
"kl",
",",
"mul",
")",
":",
"G",
"=",
"m",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
")",
"Prl",
"=",
"Prandtl",
"(",
"Cp",
"=",
"Cpl",
... | 34.306452 | 24.758065 |
def where_ends_with(self, field_name, value):
"""
To get all the document that ends with the value in the giving field_name
@param str field_name:The field name in the index you want to query.
@param str value: The value will be the fields value you want to query
"""
if ... | [
"def",
"where_ends_with",
"(",
"self",
",",
"field_name",
",",
"value",
")",
":",
"if",
"field_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"None field_name is invalid\"",
")",
"field_name",
"=",
"Query",
".",
"escape_if_needed",
"(",
"field_name",
")... | 39.1 | 21.3 |
def add_source(self, source):
"""Adds sources."""
if self._specific_sources:
return
try:
self._add_child(self.sources, self.sources_set, source)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str... | [
"def",
"add_source",
"(",
"self",
",",
"source",
")",
":",
"if",
"self",
".",
"_specific_sources",
":",
"return",
"try",
":",
"self",
".",
"_add_child",
"(",
"self",
".",
"sources",
",",
"self",
".",
"sources_set",
",",
"source",
")",
"except",
"TypeErro... | 38.384615 | 20.153846 |
def put(value):
"""Store an object in the object store.
Args:
value: The Python object to be stored.
Returns:
The object ID assigned to this value.
"""
worker = global_worker
worker.check_connected()
with profiling.profile("ray.put"):
if worker.mode == LOCAL_MODE:
... | [
"def",
"put",
"(",
"value",
")",
":",
"worker",
"=",
"global_worker",
"worker",
".",
"check_connected",
"(",
")",
"with",
"profiling",
".",
"profile",
"(",
"\"ray.put\"",
")",
":",
"if",
"worker",
".",
"mode",
"==",
"LOCAL_MODE",
":",
"# In LOCAL_MODE, ray.p... | 28.863636 | 14.136364 |
def save(self, processes=1, manifests=False):
"""
save will persist any changes that have been made to the bag
metadata (self.info).
If you have modified the payload of the bag (added, modified,
removed files in the data directory) and want to regenerate manifests
set th... | [
"def",
"save",
"(",
"self",
",",
"processes",
"=",
"1",
",",
"manifests",
"=",
"False",
")",
":",
"# Error checking",
"if",
"not",
"self",
".",
"path",
":",
"raise",
"BagError",
"(",
"_",
"(",
"'Bag.save() called before setting the path!'",
")",
")",
"if",
... | 44.56 | 26.773333 |
def toseries(self):
"""
Converts blocks to series.
"""
from thunder.series.series import Series
if self.mode == 'spark':
values = self.values.values_to_keys(tuple(range(1, len(self.shape)))).unchunk()
if self.mode == 'local':
values = self.values... | [
"def",
"toseries",
"(",
"self",
")",
":",
"from",
"thunder",
".",
"series",
".",
"series",
"import",
"Series",
"if",
"self",
".",
"mode",
"==",
"'spark'",
":",
"values",
"=",
"self",
".",
"values",
".",
"values_to_keys",
"(",
"tuple",
"(",
"range",
"("... | 28.714286 | 17.714286 |
def publictypes(self):
""" get all public types """
for t in self.wsdl.schema.types.values():
if t in self.params: continue
if t in self.types: continue
item = (t, t)
self.types.append(item)
tc = lambda x,y: cmp(x[0].name, y[0].name)
self.t... | [
"def",
"publictypes",
"(",
"self",
")",
":",
"for",
"t",
"in",
"self",
".",
"wsdl",
".",
"schema",
".",
"types",
".",
"values",
"(",
")",
":",
"if",
"t",
"in",
"self",
".",
"params",
":",
"continue",
"if",
"t",
"in",
"self",
".",
"types",
":",
... | 36.555556 | 7.444444 |
def __set_unit_price(self, value):
'''
Sets the unit price
@param value:str
'''
try:
if value < 0:
raise ValueError()
self.__unit_price = Decimal(str(value))
except ValueError:
raise ValueError("Unit Price must be a pos... | [
"def",
"__set_unit_price",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"if",
"value",
"<",
"0",
":",
"raise",
"ValueError",
"(",
")",
"self",
".",
"__unit_price",
"=",
"Decimal",
"(",
"str",
"(",
"value",
")",
")",
"except",
"ValueError",
":",
"... | 26.916667 | 19.583333 |
def parse_bcftools_stats(self):
"""
Find bcftools stats logs and parse their data
Bcftools stats reports contain 'sets' of data, which can
have multiple vcf files each (but usually don't). Here,
we treat each 'set' as a MultiQC sample, taking the first
input filen... | [
"def",
"parse_bcftools_stats",
"(",
"self",
")",
":",
"collapse_complementary",
"=",
"getattr",
"(",
"config",
",",
"'bcftools'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'collapse_complementary_changes'",
",",
"False",
")",
"if",
"collapse_complementary",
":",
"ty... | 45.910448 | 18.845771 |
def GamePlayFinder(**kwargs):
""" Docstring will be filled in by __init__.py """
querystring = _kwargs_to_qs(**kwargs)
url = '{}?{}'.format(GPF_URL, querystring)
# if verbose, print url
if kwargs.get('verbose', False):
print(url)
html = utils.get_html(url)
doc = pq(html)
# pars... | [
"def",
"GamePlayFinder",
"(",
"*",
"*",
"kwargs",
")",
":",
"querystring",
"=",
"_kwargs_to_qs",
"(",
"*",
"*",
"kwargs",
")",
"url",
"=",
"'{}?{}'",
".",
"format",
"(",
"GPF_URL",
",",
"querystring",
")",
"# if verbose, print url",
"if",
"kwargs",
".",
"g... | 28.88 | 16.88 |
def scale(self, image, size, crop, options):
"""
Wrapper for ``engine_scale``, checks if the scaling factor is below one or that scale_up
option is set to True before calling ``engine_scale``.
:param image:
:param size:
:param crop:
:param options:
:retur... | [
"def",
"scale",
"(",
"self",
",",
"image",
",",
"size",
",",
"crop",
",",
"options",
")",
":",
"original_size",
"=",
"self",
".",
"get_image_size",
"(",
"image",
")",
"factor",
"=",
"self",
".",
"_calculate_scaling_factor",
"(",
"original_size",
",",
"size... | 34.25 | 21.15 |
def pfx_path(path):
""" Prefix a path with the OS path separator if it is not already """
if path[0] != os.path.sep: return os.path.sep + path
else: return path | [
"def",
"pfx_path",
"(",
"path",
")",
":",
"if",
"path",
"[",
"0",
"]",
"!=",
"os",
".",
"path",
".",
"sep",
":",
"return",
"os",
".",
"path",
".",
"sep",
"+",
"path",
"else",
":",
"return",
"path"
] | 47.5 | 9.75 |
def function_name(fn):
""" Return function name in pretty style
:param fn: source function
:return: str
"""
fn_name = fn.__name__
if hasattr(fn, '__qualname__'):
return fn.__qualname__
elif hasattr(fn, '__self__'):
owner = fn.__self__
if isclass(owner) is False:
owner = owner.__class__
re... | [
"def",
"function_name",
"(",
"fn",
")",
":",
"fn_name",
"=",
"fn",
".",
"__name__",
"if",
"hasattr",
"(",
"fn",
",",
"'__qualname__'",
")",
":",
"return",
"fn",
".",
"__qualname__",
"elif",
"hasattr",
"(",
"fn",
",",
"'__self__'",
")",
":",
"owner",
"=... | 24.2 | 14.266667 |
def parse(filename_or_url, parser=None, base_url=None, **kw):
"""
Parse a filename, URL, or file-like object into an HTML document
tree. Note: this returns a tree, not an element. Use
``parse(...).getroot()`` to get the document root.
You can override the base URL with the ``base_url`` keyword. ... | [
"def",
"parse",
"(",
"filename_or_url",
",",
"parser",
"=",
"None",
",",
"base_url",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"parser",
"is",
"None",
":",
"parser",
"=",
"html_parser",
"return",
"etree",
".",
"parse",
"(",
"filename_or_url",
"... | 41.916667 | 19.083333 |
def get_subsequencesinsertion(cls, subsequences, indent) -> str:
"""Return the insertion string required for the given group of
sequences.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> from hydpy import prepare_model
>>> model = prepare_model('hland_v1')
>>> print(XS... | [
"def",
"get_subsequencesinsertion",
"(",
"cls",
",",
"subsequences",
",",
"indent",
")",
"->",
"str",
":",
"blanks",
"=",
"' '",
"*",
"(",
"indent",
"*",
"4",
")",
"lines",
"=",
"[",
"f'{blanks}<element name=\"{subsequences.name}\"'",
",",
"f'{blanks} minO... | 38.948718 | 11.692308 |
def geom_rotate(g, ax, theta):
""" Rotation symmetry operation.
ax is rotation axis
g is assumed already translated to center of mass @ origin
Sense of rotation is the same as point_rotate
.. todo:: Complete geom_rotate docstring
"""
# Imports
import numpy as np
# Force g to n-... | [
"def",
"geom_rotate",
"(",
"g",
",",
"ax",
",",
"theta",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"# Force g to n-vector",
"g",
"=",
"make_nd_vec",
"(",
"g",
",",
"nd",
"=",
"None",
",",
"t",
"=",
"np",
".",
"float64",
",",
"norm",
"=",
... | 23.818182 | 21.681818 |
def start_child_span(operation_name, tracer=None, parent=None, tags=None):
"""
Start a new span as a child of parent_span. If parent_span is None,
start a new root span.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param parent: parent Sp... | [
"def",
"start_child_span",
"(",
"operation_name",
",",
"tracer",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"tracer",
"=",
"tracer",
"or",
"opentracing",
".",
"tracer",
"return",
"tracer",
".",
"start_span",
"(",
"operatio... | 33.117647 | 15.352941 |
def close(self):
"""Close the client. 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.
No further messages can be sent or received and the client
can... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"message_handler",
":",
"self",
".",
"message_handler",
".",
"destroy",
"(",
")",
"self",
".",
"message_handler",
"=",
"None",
"self",
".",
"_shutdown",
"=",
"True",
"if",
"self",
".",
"_keep_aliv... | 37.666667 | 13.151515 |
def libvlc_media_library_media_list(p_mlib):
'''Get media library subitems.
@param p_mlib: media library object.
@return: media list subitems.
'''
f = _Cfunctions.get('libvlc_media_library_media_list', None) or \
_Cfunction('libvlc_media_library_media_list', ((1,),), class_result(MediaList),... | [
"def",
"libvlc_media_library_media_list",
"(",
"p_mlib",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_library_media_list'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_library_media_list'",
",",
"(",
"(",
"1",
",",
")",
",",
"... | 42.666667 | 17.333333 |
def hazard_units(hazard):
"""Helper to get unit of a hazard.
:param hazard: Hazard type.
:type hazard: str
:returns: List of hazard units.
:rtype: list
"""
units = definition(hazard)['continuous_hazard_units']
return sorted(units, key=lambda k: k['key']) | [
"def",
"hazard_units",
"(",
"hazard",
")",
":",
"units",
"=",
"definition",
"(",
"hazard",
")",
"[",
"'continuous_hazard_units'",
"]",
"return",
"sorted",
"(",
"units",
",",
"key",
"=",
"lambda",
"k",
":",
"k",
"[",
"'key'",
"]",
")"
] | 25.272727 | 16.090909 |
def paragraph_starts(self):
"""The start positions of ``paragraphs`` layer elements."""
if not self.is_tagged(PARAGRAPHS):
self.tokenize_paragraphs()
return self.starts(PARAGRAPHS) | [
"def",
"paragraph_starts",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"PARAGRAPHS",
")",
":",
"self",
".",
"tokenize_paragraphs",
"(",
")",
"return",
"self",
".",
"starts",
"(",
"PARAGRAPHS",
")"
] | 42.4 | 3.8 |
def emit(self, span_datas):
"""
:type span_datas: list of :class:
`~opencensus.trace.span_data.SpanData`
:param list of opencensus.trace.span_data.SpanData span_datas:
SpanData tuples to emit
"""
with open(self.file_name, self.file_mode) as file:
... | [
"def",
"emit",
"(",
"self",
",",
"span_datas",
")",
":",
"with",
"open",
"(",
"self",
".",
"file_name",
",",
"self",
".",
"file_mode",
")",
"as",
"file",
":",
"# convert to the legacy trace json for easier refactoring",
"# TODO: refactor this to use the span data direct... | 46.076923 | 14.384615 |
def values(self):
"Property to access the Histogram values provided for backward compatibility"
if util.config.future_deprecations:
self.param.warning('Histogram.values is deprecated in favor of '
'common dimension_values method.')
return self.dimension... | [
"def",
"values",
"(",
"self",
")",
":",
"if",
"util",
".",
"config",
".",
"future_deprecations",
":",
"self",
".",
"param",
".",
"warning",
"(",
"'Histogram.values is deprecated in favor of '",
"'common dimension_values method.'",
")",
"return",
"self",
".",
"dimens... | 54.166667 | 22.166667 |
def find_root(filename, target='bids'):
"""Find base directory (root) for a filename.
Parameters
----------
filename : instance of Path
search the root for this file
target: str
'bids' (the directory containing 'participants.tsv'), 'subject' (the
directory starting with 'sub... | [
"def",
"find_root",
"(",
"filename",
",",
"target",
"=",
"'bids'",
")",
":",
"lg",
".",
"debug",
"(",
"f'Searching root in {filename}'",
")",
"if",
"target",
"==",
"'bids'",
"and",
"(",
"filename",
"/",
"'dataset_description.json'",
")",
".",
"exists",
"(",
... | 29.423077 | 19.423077 |
def write_byte_data(self, addr, cmd, val):
"""write_byte_data(addr, cmd, val)
Perform SMBus Write Byte Data transaction.
"""
self._set_addr(addr)
if SMBUS.i2c_smbus_write_byte_data(self._fd,
ffi.cast("__u8", cmd),
... | [
"def",
"write_byte_data",
"(",
"self",
",",
"addr",
",",
"cmd",
",",
"val",
")",
":",
"self",
".",
"_set_addr",
"(",
"addr",
")",
"if",
"SMBUS",
".",
"i2c_smbus_write_byte_data",
"(",
"self",
".",
"_fd",
",",
"ffi",
".",
"cast",
"(",
"\"__u8\"",
",",
... | 39.8 | 13.7 |
def feed_forward_gaussian(
config, action_space, observations, unused_length, state=None):
"""Independent feed forward networks for policy and value.
The policy network outputs the mean action and the standard deviation is
learned as independent parameter vector.
Args:
config: Configuration object.
... | [
"def",
"feed_forward_gaussian",
"(",
"config",
",",
"action_space",
",",
"observations",
",",
"unused_length",
",",
"state",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"action_space",
",",
"gym",
".",
"spaces",
".",
"Box",
")",
":",
"raise",
"V... | 41.254545 | 15.272727 |
def _Operations(self, rule, line):
"""Operators on the data record.
Operators come in two parts and are a '.' separated pair:
Operators that effect the input line or the current state (line_op).
'Next' Get next input line and restart parsing (default).
'Continue' Keep current input... | [
"def",
"_Operations",
"(",
"self",
",",
"rule",
",",
"line",
")",
":",
"# First process the Record operators.",
"if",
"rule",
".",
"record_op",
"==",
"'Record'",
":",
"self",
".",
"_AppendRecord",
"(",
")",
"elif",
"rule",
".",
"record_op",
"==",
"'Clear'",
... | 33.283019 | 22.169811 |
def numberOfXTilesAtZoom(self, zoom):
"Returns the number of tiles over x at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return maxCol - minCol + 1 | [
"def",
"numberOfXTilesAtZoom",
"(",
"self",
",",
"zoom",
")",
":",
"[",
"minRow",
",",
"minCol",
",",
"maxRow",
",",
"maxCol",
"]",
"=",
"self",
".",
"getExtentAddress",
"(",
"zoom",
")",
"return",
"maxCol",
"-",
"minCol",
"+",
"1"
] | 51.75 | 16.25 |
def as_frame(self):
""" :return: Multi-Index DataFrame """
data = {sid: pd.Series(data) for sid, data in self.response_map.iteritems()}
return pd.DataFrame.from_dict(data, orient='index') | [
"def",
"as_frame",
"(",
"self",
")",
":",
"data",
"=",
"{",
"sid",
":",
"pd",
".",
"Series",
"(",
"data",
")",
"for",
"sid",
",",
"data",
"in",
"self",
".",
"response_map",
".",
"iteritems",
"(",
")",
"}",
"return",
"pd",
".",
"DataFrame",
".",
"... | 52 | 21 |
def configure(self, options, conf):
"""Configure the plugin and system, based on selected options.
The base plugin class sets the plugin to enabled if the enable option
for the plugin (self.enable_opt) is true.
"""
self.conf = conf
if hasattr(options, self.enable_opt):
... | [
"def",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
":",
"self",
".",
"conf",
"=",
"conf",
"if",
"hasattr",
"(",
"options",
",",
"self",
".",
"enable_opt",
")",
":",
"self",
".",
"enabled",
"=",
"getattr",
"(",
"options",
",",
"self",
... | 41.222222 | 14.666667 |
def write(self, file):
"""Write the image to the open file object.
See `.save()` if you have a filename.
In general, you can only call this method once;
after it has been called the first time the PNG image is written,
the source data will have been streamed, and
cannot... | [
"def",
"write",
"(",
"self",
",",
"file",
")",
":",
"w",
"=",
"Writer",
"(",
"*",
"*",
"self",
".",
"info",
")",
"w",
".",
"write",
"(",
"file",
",",
"self",
".",
"rows",
")"
] | 31.153846 | 17.461538 |
def split_batches(self, data, minibatch_size= None):
"""Split data into minibatches with a specified size
Parameters
----------
data: iterable and indexable
List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames.
minibatch_size: int
Expected sizes of minibatc... | [
"def",
"split_batches",
"(",
"self",
",",
"data",
",",
"minibatch_size",
"=",
"None",
")",
":",
"if",
"minibatch_size",
"==",
"None",
":",
"minibatch_size",
"=",
"self",
".",
"minibatch_size",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
"or",
"isins... | 37.269231 | 25.461538 |
def negative_check_for_model_in_expected_future_models(target_state_m, model, msg, delete=True, with_logger=None):
""" Checks if the expected future models list/set includes still a specific model
Return False if the handed model is still in and also creates a warning message as feedback.
:param StateMode... | [
"def",
"negative_check_for_model_in_expected_future_models",
"(",
"target_state_m",
",",
"model",
",",
"msg",
",",
"delete",
"=",
"True",
",",
"with_logger",
"=",
"None",
")",
":",
"if",
"with_logger",
"is",
"None",
":",
"with_logger",
"=",
"logger",
"# check that... | 51.958333 | 27.791667 |
def get_public_members(obj):
"""
Retrieves a list of member-like objects (members or properties) that are
publically exposed.
:param obj: The object to probe.
:return: A list of strings.
"""
return {attr: getattr(obj, attr) for attr in dir(obj)
if not attr.startswith("_")
... | [
"def",
"get_public_members",
"(",
"obj",
")",
":",
"return",
"{",
"attr",
":",
"getattr",
"(",
"obj",
",",
"attr",
")",
"for",
"attr",
"in",
"dir",
"(",
"obj",
")",
"if",
"not",
"attr",
".",
"startswith",
"(",
"\"_\"",
")",
"and",
"not",
"hasattr",
... | 33.363636 | 13.909091 |
def shape(self, i=0):
"""Returns a shape object for a shape in the the geometry
record file."""
shp = self.__getFileObj(self.shp)
i = self.__restrictIndex(i)
offset = self.__shapeIndex(i)
if not offset:
# Shx index not available so use the full list.
... | [
"def",
"shape",
"(",
"self",
",",
"i",
"=",
"0",
")",
":",
"shp",
"=",
"self",
".",
"__getFileObj",
"(",
"self",
".",
"shp",
")",
"i",
"=",
"self",
".",
"__restrictIndex",
"(",
"i",
")",
"offset",
"=",
"self",
".",
"__shapeIndex",
"(",
"i",
")",
... | 35.75 | 8.75 |
def changelist_view(self, request, extra_context=None):
"""
Updates the changelist view to include settings from this admin.
"""
return super(TrackedLiveAdmin, self).changelist_view(
request, dict(extra_context or {},
url_name='admin:%s_%s_tracking_... | [
"def",
"changelist_view",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
")",
":",
"return",
"super",
"(",
"TrackedLiveAdmin",
",",
"self",
")",
".",
"changelist_view",
"(",
"request",
",",
"dict",
"(",
"extra_context",
"or",
"{",
"}",
","... | 47.636364 | 25.818182 |
def dichotomy(self, f, kmin=2, kmax=12, raise_no_convergence=True,):
"""
Compute the coefficients for a function f by dichotomy.
kmin, kmax: log2 of number of interpolation points to try
raise_no_convergence: whether to raise an exception if the dichotomy does not converge
"""
... | [
"def",
"dichotomy",
"(",
"self",
",",
"f",
",",
"kmin",
"=",
"2",
",",
"kmax",
"=",
"12",
",",
"raise_no_convergence",
"=",
"True",
",",
")",
":",
"for",
"k",
"in",
"range",
"(",
"kmin",
",",
"kmax",
")",
":",
"N",
"=",
"pow",
"(",
"2",
",",
... | 35.25 | 19.25 |
def enc(data, **kwargs):
'''
Alias to `{box_type}_encrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. ... | [
"def",
"enc",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'keyfile'",
"in",
"kwargs",
":",
"salt",
".",
"utils",
".",
"versions",
".",
"warn_until",
"(",
"'Neon'",
",",
"'The \\'keyfile\\' argument has been deprecated and will be removed in Salt '",
"'{... | 32.5 | 20.038462 |
def until_not(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value evaluates to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last ... | [
"def",
"until_not",
"(",
"self",
",",
"method",
",",
"message",
"=",
"''",
")",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"_timeout",
"while",
"True",
":",
"try",
":",
"value",
"=",
"method",
"(",
"self",
".",
"_driver"... | 40.818182 | 13.545455 |
def encode_multipart_formdata(fields, boundary=None):
"""
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary ... | [
"def",
"encode_multipart_formdata",
"(",
"fields",
",",
"boundary",
"=",
"None",
")",
":",
"body",
"=",
"BytesIO",
"(",
")",
"if",
"boundary",
"is",
"None",
":",
"boundary",
"=",
"choose_boundary",
"(",
")",
"for",
"field",
"in",
"iter_field_objects",
"(",
... | 28.444444 | 21.388889 |
def write_code(self, name, code):
"""
Writes code to a python file called 'name',
erasing the previous contents.
Files are created in a directory specified by gen_dir_name (see function gen_file_path)
File name is second argument of path
"""
file_path = self.gen_f... | [
"def",
"write_code",
"(",
"self",
",",
"name",
",",
"code",
")",
":",
"file_path",
"=",
"self",
".",
"gen_file_path",
"(",
"name",
")",
"with",
"open",
"(",
"file_path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"code",
")"
] | 39 | 10 |
def discover_handler_classes(handlers_package):
"""
Looks for handler classes within handler path module.
Currently it's not looking deep into nested module.
:param handlers_package: module path to handlers
:type handlers_package: string
:return: list of handler classes
"""
if handlers... | [
"def",
"discover_handler_classes",
"(",
"handlers_package",
")",
":",
"if",
"handlers_package",
"is",
"None",
":",
"return",
"# Add working directory into PYTHONPATH to import developer packages",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"getcwd",
... | 32.708333 | 20.708333 |
async def i2c_write_request(self, address, args):
"""
Write data to an i2c device.
:param address: i2c device address
:param args: A variable number of bytes to be sent to the device
passed in as a list
:returns: No return value.
"""
data =... | [
"async",
"def",
"i2c_write_request",
"(",
"self",
",",
"address",
",",
"args",
")",
":",
"data",
"=",
"[",
"address",
",",
"Constants",
".",
"I2C_WRITE",
"]",
"for",
"item",
"in",
"args",
":",
"item_lsb",
"=",
"item",
"&",
"0x7f",
"data",
".",
"append"... | 31.777778 | 13.333333 |
def get_all(jail=None):
'''
Return a list of all available services
.. versionchanged:: 2016.3.4
jail: optional jid or jail name
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = []
service = _cmd(jail)
for srv in __salt__['cmd.run']('{0} -l'.forma... | [
"def",
"get_all",
"(",
"jail",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"service",
"=",
"_cmd",
"(",
"jail",
")",
"for",
"srv",
"in",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} -l'",
".",
"format",
"(",
"service",
")",
")",
".",
"splitlines"... | 20.35 | 23.35 |
def list_accounts_add(self, id, account_ids):
"""
Add the account(s) given in `account_ids` to the list.
"""
id = self.__unpack_id(id)
if not isinstance(account_ids, list):
account_ids = [account_ids]
account_ids = list(map(lambda x: self.__unpack_id(... | [
"def",
"list_accounts_add",
"(",
"self",
",",
"id",
",",
"account_ids",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"if",
"not",
"isinstance",
"(",
"account_ids",
",",
"list",
")",
":",
"account_ids",
"=",
"[",
"account_ids",
"]",
... | 40.416667 | 17.25 |
def transform_specialfield(jsonify,f,v):
"helper for serialize_row"
raw = f.ser(v) if is_serdes(f) else v
return ujson.dumps(raw) if not isinstance(f,basestring) and jsonify else raw | [
"def",
"transform_specialfield",
"(",
"jsonify",
",",
"f",
",",
"v",
")",
":",
"raw",
"=",
"f",
".",
"ser",
"(",
"v",
")",
"if",
"is_serdes",
"(",
"f",
")",
"else",
"v",
"return",
"ujson",
".",
"dumps",
"(",
"raw",
")",
"if",
"not",
"isinstance",
... | 47 | 12.5 |
def get_config(workflow):
"""
Obtain configuration object
Does not fail
:return: ReactorConfig instance
"""
try:
workspace = workflow.plugin_workspace[ReactorConfigPlugin.key]
return workspace[WORKSPACE_CONF_KEY]
except KeyError:
# The plugin did not run or was not s... | [
"def",
"get_config",
"(",
"workflow",
")",
":",
"try",
":",
"workspace",
"=",
"workflow",
".",
"plugin_workspace",
"[",
"ReactorConfigPlugin",
".",
"key",
"]",
"return",
"workspace",
"[",
"WORKSPACE_CONF_KEY",
"]",
"except",
"KeyError",
":",
"# The plugin did not ... | 33.705882 | 18.176471 |
def pad_to(unpadded, target_len):
"""
Pad a string to the target length in characters, or return the original
string if it's longer than the target length.
"""
under = target_len - len(unpadded)
if under <= 0:
return unpadded
return unpadded + (' ' * under) | [
"def",
"pad_to",
"(",
"unpadded",
",",
"target_len",
")",
":",
"under",
"=",
"target_len",
"-",
"len",
"(",
"unpadded",
")",
"if",
"under",
"<=",
"0",
":",
"return",
"unpadded",
"return",
"unpadded",
"+",
"(",
"' '",
"*",
"under",
")"
] | 31.666667 | 10.777778 |
def spell_check(request):
"""
Implements the TinyMCE 4 spellchecker protocol
:param request: Django http request with JSON-RPC payload from TinyMCE 4
containing a language code and a text to check for errors.
:type request: django.http.request.HttpRequest
:return: Django http response conta... | [
"def",
"spell_check",
"(",
"request",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"output",
"=",
"{",
"'id'",
":",
"data",
"[",
"'id'",
"]",
"}",
"error",
"=",
"None",
"status",... | 38.342857 | 16.571429 |
def get_color_label(self):
"""Text for colorbar label
"""
if self.args.norm:
return 'Normalized to {}'.format(self.args.norm)
if len(self.units) == 1 and self.usetex:
return r'ASD $\left({0}\right)$'.format(
self.units[0].to_string('latex').strip('... | [
"def",
"get_color_label",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
".",
"norm",
":",
"return",
"'Normalized to {}'",
".",
"format",
"(",
"self",
".",
"args",
".",
"norm",
")",
"if",
"len",
"(",
"self",
".",
"units",
")",
"==",
"1",
"and",
... | 43.727273 | 13.090909 |
def spkapo(targ, et, ref, sobs, abcorr):
"""
Return the position of a target body relative to an observer,
optionally corrected for light time and stellar aberration.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkapo_c.html
:param targ: Target body.
:type targ: int
:param et: ... | [
"def",
"spkapo",
"(",
"targ",
",",
"et",
",",
"ref",
",",
"sobs",
",",
"abcorr",
")",
":",
"targ",
"=",
"ctypes",
".",
"c_int",
"(",
"targ",
")",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(... | 34.935484 | 15.709677 |
def _definition(self):
"""|FooterPart| object containing content of this footer."""
footerReference = self._sectPr.get_footerReference(self._hdrftr_index)
return self._document_part.footer_part(footerReference.rId) | [
"def",
"_definition",
"(",
"self",
")",
":",
"footerReference",
"=",
"self",
".",
"_sectPr",
".",
"get_footerReference",
"(",
"self",
".",
"_hdrftr_index",
")",
"return",
"self",
".",
"_document_part",
".",
"footer_part",
"(",
"footerReference",
".",
"rId",
")... | 58.75 | 20.75 |
def thumbnail(self):
"""Path to the thumbnail of the album."""
if self._thumbnail:
# stop if it is already set
return self._thumbnail
# Test the thumbnail from the Markdown file.
thumbnail = self.meta.get('thumbnail', [''])[0]
if thumbnail and isfile(jo... | [
"def",
"thumbnail",
"(",
"self",
")",
":",
"if",
"self",
".",
"_thumbnail",
":",
"# stop if it is already set",
"return",
"self",
".",
"_thumbnail",
"# Test the thumbnail from the Markdown file.",
"thumbnail",
"=",
"self",
".",
"meta",
".",
"get",
"(",
"'thumbnail'"... | 43.951613 | 19.258065 |
def arcsine_sqrt_transform(rel_abd):
"""
Takes the proportion data from relative_abundance() and applies the
variance stabilizing arcsine square root transformation:
X = sin^{-1} \sqrt p
"""
arcsint = lambda p: math.asin(math.sqrt(p))
return {col_id: {row_id: arcsint(rel_abd[col_id][row_id]... | [
"def",
"arcsine_sqrt_transform",
"(",
"rel_abd",
")",
":",
"arcsint",
"=",
"lambda",
"p",
":",
"math",
".",
"asin",
"(",
"math",
".",
"sqrt",
"(",
"p",
")",
")",
"return",
"{",
"col_id",
":",
"{",
"row_id",
":",
"arcsint",
"(",
"rel_abd",
"[",
"col_i... | 38.7 | 17.3 |
def wgs84togcj02(lng, lat):
"""
WGS84转GCJ02(火星坐标系)
:param lng:WGS84坐标系的经度
:param lat:WGS84坐标系的纬度
:return:
"""
if out_of_china(lng, lat): # 判断是否在国内
return lng, lat
dlat = transformlat(lng - 105.0, lat - 35.0)
dlng = transformlng(lng - 105.0, lat - 35.0)
radlat = lat / 180... | [
"def",
"wgs84togcj02",
"(",
"lng",
",",
"lat",
")",
":",
"if",
"out_of_china",
"(",
"lng",
",",
"lat",
")",
":",
"# 判断是否在国内",
"return",
"lng",
",",
"lat",
"dlat",
"=",
"transformlat",
"(",
"lng",
"-",
"105.0",
",",
"lat",
"-",
"35.0",
")",
"dlng",
... | 30.85 | 13.35 |
def flatten(l, types=(list, )):
"""
Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting,
flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]]
into [5, 6, 8, 3, 2, 2, 1, 3, 4]
This is safe to call on something not a list/tuple -... | [
"def",
"flatten",
"(",
"l",
",",
"types",
"=",
"(",
"list",
",",
")",
")",
":",
"# For backwards compatibility, this returned a list, not an iterable.",
"# Changing to return an iterable could break things.",
"if",
"not",
"isinstance",
"(",
"l",
",",
"types",
")",
":",
... | 44.923077 | 23.076923 |
def RunStateMethod(self,
method_name,
request=None,
responses=None,
event=None,
direct_response=None):
"""Completes the request by calling the state method.
Args:
method_name: The name of the state me... | [
"def",
"RunStateMethod",
"(",
"self",
",",
"method_name",
",",
"request",
"=",
"None",
",",
"responses",
"=",
"None",
",",
"event",
"=",
"None",
",",
"direct_response",
"=",
"None",
")",
":",
"client_id",
"=",
"None",
"try",
":",
"self",
".",
"context",
... | 35.217391 | 21.681159 |
def _start_server(self, *args):
"""Run the node local server"""
self.log("Starting server", args)
secure = self.certificate is not None
if secure:
self.log("Running SSL server with cert:", self.certificate)
else:
self.log("Running insecure server without ... | [
"def",
"_start_server",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"log",
"(",
"\"Starting server\"",
",",
"args",
")",
"secure",
"=",
"self",
".",
"certificate",
"is",
"not",
"None",
"if",
"secure",
":",
"self",
".",
"log",
"(",
"\"Running ... | 36.75 | 18.3 |
def authorized_get_account_balance(self, huid):
"""
FETCHES the account balance for the user defined with `huid`.
:rtype: ``bigint``
:returns: ``<amount_in_cents>``
:raises GeneralException:
:resource: ``fort/accounts/<huid>``
:access: authorized... | [
"def",
"authorized_get_account_balance",
"(",
"self",
",",
"huid",
")",
":",
"acc",
"=",
"self",
".",
"request",
"(",
"'get'",
",",
"safeformat",
"(",
"'fort/accounts/{:hex}'",
",",
"huid",
")",
")",
"return",
"int",
"(",
"acc",
"[",
"'balance'",
"]",
")"
... | 38.857143 | 16.142857 |
def mass_2d(self, r, rho0, Ra, Rs):
"""
mass enclosed projected 2d sphere of radius r
:param r:
:param rho0:
:param Ra:
:param Rs:
:return:
"""
Ra, Rs = self._sort_ra_rs(Ra, Rs)
sigma0 = self.rho2sigma(rho0, Ra, Rs)
m_2d = 2 * np.pi... | [
"def",
"mass_2d",
"(",
"self",
",",
"r",
",",
"rho0",
",",
"Ra",
",",
"Rs",
")",
":",
"Ra",
",",
"Rs",
"=",
"self",
".",
"_sort_ra_rs",
"(",
"Ra",
",",
"Rs",
")",
"sigma0",
"=",
"self",
".",
"rho2sigma",
"(",
"rho0",
",",
"Ra",
",",
"Rs",
")"... | 32.846154 | 18.384615 |
def _load_hooks(path):
"""Load hook module and register signals.
:param path: Absolute or relative path to module.
:return: module
"""
module = imp.load_source(os.path.splitext(os.path.basename(path))[0], path)
if not check_hook_mechanism_is_intact(module):
# no hooks - do nothing
... | [
"def",
"_load_hooks",
"(",
"path",
")",
":",
"module",
"=",
"imp",
".",
"load_source",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"0",
"]",
",",
"path",
")",
"if",
"not",
"check_h... | 37 | 19.266667 |
def childrenAtPath(self, path):
"""
Get a list of children at I{path} where I{path} is a (/) separated list
of element names expected to be children.
@param path: A (/) separated list of element names.
@type path: basestring
@return: The collection leaf nodes at the end ... | [
"def",
"childrenAtPath",
"(",
"self",
",",
"path",
")",
":",
"parts",
"=",
"[",
"p",
"for",
"p",
"in",
"path",
".",
"split",
"(",
"\"/\"",
")",
"if",
"p",
"]",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"return",
"self",
".",
"getChildren",
... | 35.133333 | 15 |
def load_extensions(self, group, name_filter=None, comp_filter=None, class_filter=None, product_name=None, unique=False):
"""Dynamically load and return extension objects of a given type.
This is the centralized way for all parts of CoreTools to allow plugin
behavior. Whenever a plugin is need... | [
"def",
"load_extensions",
"(",
"self",
",",
"group",
",",
"name_filter",
"=",
"None",
",",
"comp_filter",
"=",
"None",
",",
"class_filter",
"=",
"None",
",",
"product_name",
"=",
"None",
",",
"unique",
"=",
"False",
")",
":",
"found_extensions",
"=",
"[",
... | 51.651786 | 32.8125 |
def load_state_recursively(parent, state_path=None, dirty_states=[]):
"""Recursively loads the state
It calls this method on each sub-state of a container state.
:param parent: the root state of the last load call to which the loaded state will be added
:param state_path: the path on the filesystem w... | [
"def",
"load_state_recursively",
"(",
"parent",
",",
"state_path",
"=",
"None",
",",
"dirty_states",
"=",
"[",
"]",
")",
":",
"from",
"rafcon",
".",
"core",
".",
"states",
".",
"execution_state",
"import",
"ExecutionState",
"from",
"rafcon",
".",
"core",
"."... | 39.042553 | 23.414894 |
def delete_arrays(self, period = None):
"""
If ``period`` is ``None``, remove all known values of the variable.
If ``period`` is not ``None``, only remove all values for any period included in period (e.g. if period is "2017", values for "2017-01", "2017-07", etc. would be removed)
... | [
"def",
"delete_arrays",
"(",
"self",
",",
"period",
"=",
"None",
")",
":",
"self",
".",
"_memory_storage",
".",
"delete",
"(",
"period",
")",
"if",
"self",
".",
"_disk_storage",
":",
"self",
".",
"_disk_storage",
".",
"delete",
"(",
"period",
")"
] | 40 | 29.090909 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.