text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _symbol_identifier_or_unquoted_symbol_handler(c, ctx, is_field_name=False):
"""Handles symbol tokens that begin with a dollar sign. These may end up being system symbols ($ion_*), symbol
identifiers ('$' DIGITS+), or regular unquoted symbols.
"""
assert c == _DOLLAR_SIGN
in_sexp = ctx.container.... | [
"def",
"_symbol_identifier_or_unquoted_symbol_handler",
"(",
"c",
",",
"ctx",
",",
"is_field_name",
"=",
"False",
")",
":",
"assert",
"c",
"==",
"_DOLLAR_SIGN",
"in_sexp",
"=",
"ctx",
".",
"container",
".",
"ion_type",
"is",
"IonType",
".",
"SEXP",
"ctx",
".",... | 40.54717 | 0.001817 |
def beacon(config):
'''
Emit a dict with a key "msgs" whose value is a list of messages
sent to the configured bot by one of the allowed usernames.
.. code-block:: yaml
beacons:
telegram_bot_msg:
- token: "<bot access token>"
- accept_from:
- "<v... | [
"def",
"beacon",
"(",
"config",
")",
":",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"log",
".",
"debug",
"(",
"'telegram_bot_msg beacon starting'",
")",
"ret",
"=",
"[",
"]",
"output",
"=",
... | 25.735849 | 0.000706 |
def directory(name,
user=None,
group=None,
recurse=None,
max_depth=None,
dir_mode=None,
file_mode=None,
makedirs=False,
clean=False,
require=None,
exclude_pat=None,
f... | [
"def",
"directory",
"(",
"name",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"recurse",
"=",
"None",
",",
"max_depth",
"=",
"None",
",",
"dir_mode",
"=",
"None",
",",
"file_mode",
"=",
"None",
",",
"makedirs",
"=",
"False",
",",
"clean"... | 37.596262 | 0.001017 |
def populate_tabs(self):
"""Populating tabs based on layer metadata."""
self.delete_tabs()
layer_purpose = self.metadata.get('layer_purpose')
if not layer_purpose:
message = tr(
'Key layer_purpose is not found in the layer {layer_name}'
).format(la... | [
"def",
"populate_tabs",
"(",
"self",
")",
":",
"self",
".",
"delete_tabs",
"(",
")",
"layer_purpose",
"=",
"self",
".",
"metadata",
".",
"get",
"(",
"'layer_purpose'",
")",
"if",
"not",
"layer_purpose",
":",
"message",
"=",
"tr",
"(",
"'Key layer_purpose is ... | 44.681818 | 0.001992 |
def filter(self, date=None, regroup=False, ignored=None, pushed=None, unmapped=None, current_workday=None):
"""
Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`}
items.
`date` can either be a single :class:`datetime.date` object to filter onl... | [
"def",
"filter",
"(",
"self",
",",
"date",
"=",
"None",
",",
"regroup",
"=",
"False",
",",
"ignored",
"=",
"None",
",",
"pushed",
"=",
"None",
",",
"unmapped",
"=",
"None",
",",
"current_workday",
"=",
"None",
")",
":",
"def",
"entry_filter",
"(",
"e... | 45.828283 | 0.002373 |
def _FormatHumanReadableSize(self, size):
"""Represents a number of bytes as a human readable string.
Args:
size (int): size in bytes.
Returns:
str: human readable string of the size.
"""
magnitude_1000 = 0
size_1000 = float(size)
while size_1000 >= 1000:
size_1000 /= 100... | [
"def",
"_FormatHumanReadableSize",
"(",
"self",
",",
"size",
")",
":",
"magnitude_1000",
"=",
"0",
"size_1000",
"=",
"float",
"(",
"size",
")",
"while",
"size_1000",
">=",
"1000",
":",
"size_1000",
"/=",
"1000",
"magnitude_1000",
"+=",
"1",
"magnitude_1024",
... | 26.583333 | 0.008065 |
def main(self, signature=''):
"""
A decorator that is used to register the main function with the given
`signature`::
@app.main()
def main(context):
# do something
pass
The main function is called, after any options and if no comm... | [
"def",
"main",
"(",
"self",
",",
"signature",
"=",
"''",
")",
":",
"signature",
"=",
"Signature",
".",
"from_string",
"(",
"signature",
",",
"option",
"=",
"False",
")",
"def",
"decorator",
"(",
"function",
")",
":",
"if",
"self",
".",
"main_func",
"is... | 31.241379 | 0.002141 |
def run_c_extension_with_fallback(
log_function,
extension,
c_function,
py_function,
args,
rconf
):
"""
Run a function calling a C extension, falling back
to a pure Python function if the former does not succeed.
:param function log_function: a logger fun... | [
"def",
"run_c_extension_with_fallback",
"(",
"log_function",
",",
"extension",
",",
"c_function",
",",
"py_function",
",",
"args",
",",
"rconf",
")",
":",
"computed",
"=",
"False",
"if",
"not",
"rconf",
"[",
"u\"c_extensions\"",
"]",
":",
"log_function",
"(",
... | 39.612245 | 0.002011 |
def search_regexp(self, pattern, audio_basename=None):
"""
First joins the words of the word_blocks of timestamps with space, per
audio_basename. Then matches `pattern` and calculates the index of the
word_block where the first and last word of the matched result appears
in. Then... | [
"def",
"search_regexp",
"(",
"self",
",",
"pattern",
",",
"audio_basename",
"=",
"None",
")",
":",
"def",
"indexes_in_transcript_to_start_end_second",
"(",
"index_tup",
",",
"audio_basename",
")",
":",
"\"\"\"\n Calculates the word block index by having the beginni... | 44.21978 | 0.000486 |
def convenience_calc_hessian(self, params):
"""
Calculates the hessian of the log-likelihood for this model / dataset.
Note that this function name is INCORRECT with regard to the actual
actions performed. The Nested Logit model uses the BHHH approximation
to the Fisher Informati... | [
"def",
"convenience_calc_hessian",
"(",
"self",
",",
"params",
")",
":",
"orig_nest_coefs",
",",
"betas",
"=",
"self",
".",
"convenience_split_params",
"(",
"params",
")",
"args",
"=",
"[",
"orig_nest_coefs",
",",
"betas",
",",
"self",
".",
"design",
",",
"s... | 38.5 | 0.00181 |
def _read_body_by_chunk(self, response, file, raw=False):
'''Read the connection using chunked transfer encoding.
Coroutine.
'''
reader = ChunkedTransferReader(self._connection)
file_is_async = hasattr(file, 'drain')
while True:
chunk_size, data = yield fro... | [
"def",
"_read_body_by_chunk",
"(",
"self",
",",
"response",
",",
"file",
",",
"raw",
"=",
"False",
")",
":",
"reader",
"=",
"ChunkedTransferReader",
"(",
"self",
".",
"_connection",
")",
"file_is_async",
"=",
"hasattr",
"(",
"file",
",",
"'drain'",
")",
"w... | 24.912281 | 0.001355 |
def get_modes(self, zone):
"""Returns the set of modes the device can be assigned."""
self._populate_full_data()
device = self._get_device(zone)
return device['thermostat']['allowedModes'] | [
"def",
"get_modes",
"(",
"self",
",",
"zone",
")",
":",
"self",
".",
"_populate_full_data",
"(",
")",
"device",
"=",
"self",
".",
"_get_device",
"(",
"zone",
")",
"return",
"device",
"[",
"'thermostat'",
"]",
"[",
"'allowedModes'",
"]"
] | 43.2 | 0.009091 |
def run_hybrid(wf, selector, workers):
"""
Returns the result of evaluating the workflow; runs through several
supplied workers in as many threads.
:param wf:
Workflow to compute
:type wf: :py:class:`Workflow` or :py:class:`PromisedObject`
:param selector:
A function selecting ... | [
"def",
"run_hybrid",
"(",
"wf",
",",
"selector",
",",
"workers",
")",
":",
"worker",
"=",
"hybrid_threaded_worker",
"(",
"selector",
",",
"workers",
")",
"return",
"Scheduler",
"(",
")",
".",
"run",
"(",
"worker",
",",
"get_workflow",
"(",
"wf",
")",
")"... | 29.894737 | 0.001706 |
def set_title(self, title):
"""
Set terminal title.
"""
if self.term not in ('linux', 'eterm-color'): # Not supported by the Linux console.
self.write_raw('\x1b]2;%s\x07' % title.replace('\x1b', '').replace('\x07', '')) | [
"def",
"set_title",
"(",
"self",
",",
"title",
")",
":",
"if",
"self",
".",
"term",
"not",
"in",
"(",
"'linux'",
",",
"'eterm-color'",
")",
":",
"# Not supported by the Linux console.",
"self",
".",
"write_raw",
"(",
"'\\x1b]2;%s\\x07'",
"%",
"title",
".",
"... | 43.166667 | 0.015152 |
def format_python_constraint(constraint):
"""
This helper will help in transforming
disjunctive constraint into proper constraint.
"""
if isinstance(constraint, Version):
if constraint.precision >= 3:
return "=={}".format(str(constraint))
# Transform 3.6 or 3
if ... | [
"def",
"format_python_constraint",
"(",
"constraint",
")",
":",
"if",
"isinstance",
"(",
"constraint",
",",
"Version",
")",
":",
"if",
"constraint",
".",
"precision",
">=",
"3",
":",
"return",
"\"=={}\"",
".",
"format",
"(",
"str",
"(",
"constraint",
")",
... | 28.342105 | 0.000898 |
def update_path(self, path):
"""
There are EXTENDED messages which don't include any routers at
all, and any of the EXTENDED messages may have some arbitrary
flags in them. So far, they're all upper-case and none start
with $ luckily. The routers in the path should all be
... | [
"def",
"update_path",
"(",
"self",
",",
"path",
")",
":",
"oldpath",
"=",
"self",
".",
"path",
"self",
".",
"path",
"=",
"[",
"]",
"for",
"p",
"in",
"path",
":",
"if",
"p",
"[",
"0",
"]",
"!=",
"'$'",
":",
"break",
"# this will create a Router if we ... | 38.677419 | 0.001627 |
def get_ph_bs_symm_line(bands_path, has_nac=False, labels_dict=None):
"""
Creates a pymatgen PhononBandStructure from a band.yaml file.
The labels will be extracted from the dictionary, if present.
If the 'eigenvector' key is found the eigendisplacements will be
calculated according to the formula:... | [
"def",
"get_ph_bs_symm_line",
"(",
"bands_path",
",",
"has_nac",
"=",
"False",
",",
"labels_dict",
"=",
"None",
")",
":",
"return",
"get_ph_bs_symm_line_from_dict",
"(",
"loadfn",
"(",
"bands_path",
")",
",",
"has_nac",
",",
"labels_dict",
")"
] | 44.882353 | 0.001284 |
def check_output_input(*popenargs, **kwargs):
"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
... | [
"def",
"check_output_input",
"(",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'stdout'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'stdout argument not allowed, it will be overridden.'",
")",
"if",
"'input'",
"in",
"kwargs",
":",
"if",
"'... | 36.421053 | 0.000938 |
def update(gandi, email, password, quota, fallback, alias_add, alias_del):
"""Update a mailbox."""
options = {}
if password:
password = click.prompt('password', hide_input=True,
confirmation_prompt=True)
options['password'] = password
if quota is not Non... | [
"def",
"update",
"(",
"gandi",
",",
"email",
",",
"password",
",",
"quota",
",",
"fallback",
",",
"alias_add",
",",
"alias_del",
")",
":",
"options",
"=",
"{",
"}",
"if",
"password",
":",
"password",
"=",
"click",
".",
"prompt",
"(",
"'password'",
",",... | 26.75 | 0.001805 |
def login(self, request, session, creds, segments):
"""
Called to check the credentials of a user.
Here we extend guard's implementation to preauthenticate users if they
have a valid persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP re... | [
"def",
"login",
"(",
"self",
",",
"request",
",",
"session",
",",
"creds",
",",
"segments",
")",
":",
"self",
".",
"_maybeCleanSessions",
"(",
")",
"if",
"isinstance",
"(",
"creds",
",",
"credentials",
".",
"Anonymous",
")",
":",
"preauth",
"=",
"self",
... | 36.326531 | 0.001094 |
def start_server():
"""Starts up the imolecule server, complete with argparse handling."""
parser = argparse.ArgumentParser(description="Opens a browser-based "
"client that interfaces with the "
"chemical format converter.")
parser.a... | [
"def",
"start_server",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Opens a browser-based \"",
"\"client that interfaces with the \"",
"\"chemical format converter.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--debug'",
"... | 47.756757 | 0.000555 |
def train(*tf_records: "Records to train on"):
"""Train on examples."""
tf.logging.set_verbosity(tf.logging.INFO)
estimator = dual_net.get_estimator()
effective_batch_size = FLAGS.train_batch_size
if FLAGS.use_tpu:
effective_batch_size *= FLAGS.num_tpu_cores
if FLAGS.use_tpu:
i... | [
"def",
"train",
"(",
"*",
"tf_records",
":",
"\"Records to train on\"",
")",
":",
"tf",
".",
"logging",
".",
"set_verbosity",
"(",
"tf",
".",
"logging",
".",
"INFO",
")",
"estimator",
"=",
"dual_net",
".",
"get_estimator",
"(",
")",
"effective_batch_size",
"... | 38.893939 | 0.00114 |
def flightmode_colours():
'''return mapping of flight mode to colours'''
from MAVProxy.modules.lib.grapher import flightmode_colours
mapping = {}
idx = 0
for (mode,t0,t1) in flightmodes:
if not mode in mapping:
mapping[mode] = flightmode_colours[idx]
idx += 1
... | [
"def",
"flightmode_colours",
"(",
")",
":",
"from",
"MAVProxy",
".",
"modules",
".",
"lib",
".",
"grapher",
"import",
"flightmode_colours",
"mapping",
"=",
"{",
"}",
"idx",
"=",
"0",
"for",
"(",
"mode",
",",
"t0",
",",
"t1",
")",
"in",
"flightmodes",
"... | 32.5 | 0.009975 |
def p_expr_list(self, p):
'''expr_list : expr_list COMMA expr
| expr'''
if len(p) == 4:
p[1].append(p[3])
p[0] = p[1]
elif len(p) == 2:
p[0] = [p[1]] | [
"def",
"p_expr_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"3",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"elif",
"len",
"(",
"p",
... | 27.875 | 0.008696 |
def get_angle(v1, v2, units="degrees"):
"""
Calculates the angle between two vectors.
Args:
v1: Vector 1
v2: Vector 2
units: "degrees" or "radians". Defaults to "degrees".
Returns:
Angle between them in degrees.
"""
d = np.dot(v1, v2) / np.linalg.norm(v1) / np.l... | [
"def",
"get_angle",
"(",
"v1",
",",
"v2",
",",
"units",
"=",
"\"degrees\"",
")",
":",
"d",
"=",
"np",
".",
"dot",
"(",
"v1",
",",
"v2",
")",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"v1",
")",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
... | 25.272727 | 0.001733 |
def dimension_ids(self):
""" Return the Dimensions on this shelf in the order in which
they were used."""
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Dimension)
]) | [
"def",
"dimension_ids",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sorted_ingredients",
"(",
"[",
"d",
".",
"id",
"for",
"d",
"in",
"self",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"d",
",",
"Dimension",
")",
"]",
")"
] | 39.5 | 0.008264 |
def crossvalidation_stats(errors1, errors2):
"""Paired difference test
of the CV errors of two models
Parameters:
-----------
errors1 : ndarray
The CV errors model 1
errors2 : ndarray
The CV errors model 2
Returns:
--------
pvalue : float
Two-sided P-value ... | [
"def",
"crossvalidation_stats",
"(",
"errors1",
",",
"errors2",
")",
":",
"# load modules",
"import",
"numpy",
"as",
"np",
"import",
"scipy",
".",
"stats",
"import",
"warnings",
"# Number of blocks",
"K",
"=",
"errors1",
".",
"shape",
"[",
"0",
"]",
"# display... | 21.065574 | 0.000743 |
def save_data(self, trigger_id, **data):
"""
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the sa... | [
"def",
"save_data",
"(",
"self",
",",
"trigger_id",
",",
"*",
"*",
"data",
")",
":",
"data",
"[",
"'output_format'",
"]",
"=",
"'md'",
"title",
",",
"content",
"=",
"super",
"(",
"ServiceTrello",
",",
"self",
")",
".",
"save_data",
"(",
"trigger_id",
"... | 40.138462 | 0.002245 |
def list(gandi, domain, zone_id, output, format, limit):
"""List DNS zone records for a domain."""
options = {
'items_per_page': limit,
}
output_keys = ['name', 'type', 'value', 'ttl']
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not... | [
"def",
"list",
"(",
"gandi",
",",
"domain",
",",
"zone_id",
",",
"output",
",",
"format",
",",
"limit",
")",
":",
"options",
"=",
"{",
"'items_per_page'",
":",
"limit",
",",
"}",
"output_keys",
"=",
"[",
"'name'",
",",
"'type'",
",",
"'value'",
",",
... | 37.340426 | 0.000555 |
def list_media_endpoint_keys(access_token, subscription_id, rgname, msname):
'''list the media endpoint keys in a media service
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
ms... | [
"def",
"list_media_endpoint_keys",
"(",
"access_token",
",",
"subscription_id",
",",
"rgname",
",",
"msname",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourceG... | 39.684211 | 0.001295 |
def search_responsify(serializer, mimetype):
"""Create a Records-REST search result response serializer.
:param serializer: Serializer instance.
:param mimetype: MIME type of response.
:returns: Function that generates a record HTTP response.
"""
def view(pid_fetcher, search_result, code=200, h... | [
"def",
"search_responsify",
"(",
"serializer",
",",
"mimetype",
")",
":",
"def",
"view",
"(",
"pid_fetcher",
",",
"search_result",
",",
"code",
"=",
"200",
",",
"headers",
"=",
"None",
",",
"links",
"=",
"None",
",",
"item_links_factory",
"=",
"None",
")",... | 36.25 | 0.00112 |
def recover_all(lbn, profile='default'):
'''
Set the all the workers in lbn to recover and activate them if they are not
CLI Examples:
.. code-block:: bash
salt '*' modjk.recover_all loadbalancer1
salt '*' modjk.recover_all loadbalancer1 other-profile
'''
ret = {}
config ... | [
"def",
"recover_all",
"(",
"lbn",
",",
"profile",
"=",
"'default'",
")",
":",
"ret",
"=",
"{",
"}",
"config",
"=",
"get_running",
"(",
"profile",
")",
"try",
":",
"workers_",
"=",
"config",
"[",
"'worker.{0}.balance_workers'",
".",
"format",
"(",
"lbn",
... | 28.25 | 0.001222 |
def _max_fitting_element(self, upper_limit):
"""Returns the largest element smaller than or equal to the limit"""
no_steps = (upper_limit - self._start) // abs(self._step)
return self._start + abs(self._step) * no_steps | [
"def",
"_max_fitting_element",
"(",
"self",
",",
"upper_limit",
")",
":",
"no_steps",
"=",
"(",
"upper_limit",
"-",
"self",
".",
"_start",
")",
"//",
"abs",
"(",
"self",
".",
"_step",
")",
"return",
"self",
".",
"_start",
"+",
"abs",
"(",
"self",
".",
... | 60 | 0.00823 |
def final_data_transform_factory(alg, sep, pre_sep):
"""
Create a function to transform a tuple.
Parameters
----------
alg : ns enum
Indicate how to format the *str*.
sep : str
Separator that was passed to *parse_string_factory*.
pre_sep : str
String separator to ins... | [
"def",
"final_data_transform_factory",
"(",
"alg",
",",
"sep",
",",
"pre_sep",
")",
":",
"if",
"alg",
"&",
"ns",
".",
"UNGROUPLETTERS",
"and",
"alg",
"&",
"ns",
".",
"LOCALEALPHA",
":",
"swap",
"=",
"alg",
"&",
"NS_DUMB",
"and",
"alg",
"&",
"ns",
".",
... | 30.895833 | 0.001307 |
def tags(self, value): # pylint: disable-msg=E0102
"""Set the tags in the configuraton (setter)"""
if not isinstance(value, list):
raise TypeError
self._config['tags'] = value | [
"def",
"tags",
"(",
"self",
",",
"value",
")",
":",
"# pylint: disable-msg=E0102",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"raise",
"TypeError",
"self",
".",
"_config",
"[",
"'tags'",
"]",
"=",
"value"
] | 41.4 | 0.014218 |
def process(name, path, data, module=True):
"""
Process data to create a screenshot which will be saved in
docs/screenshots/<name>.png
If module is True the screenshot will include the name and py3status.
"""
# create dir if not exists
try:
os.makedirs(path)
except OSError:
... | [
"def",
"process",
"(",
"name",
",",
"path",
",",
"data",
",",
"module",
"=",
"True",
")",
":",
"# create dir if not exists",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
":",
"pass",
"global",
"font",
",",
"glyph_data",
"if",... | 30.346154 | 0.001229 |
def get_upsampling_weight(in_channels, out_channels, kernel_size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (kernel_size + 1) // 2
if kernel_size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:kernel_size, :kernel_size]
filt = (1 ... | [
"def",
"get_upsampling_weight",
"(",
"in_channels",
",",
"out_channels",
",",
"kernel_size",
")",
":",
"factor",
"=",
"(",
"kernel_size",
"+",
"1",
")",
"//",
"2",
"if",
"kernel_size",
"%",
"2",
"==",
"1",
":",
"center",
"=",
"factor",
"-",
"1",
"else",
... | 43.857143 | 0.001595 |
def generate_image_from_url(url=None, timeout=30):
"""
Downloads and saves a image from url into a file.
"""
file_name = posixpath.basename(url)
img_tmp = NamedTemporaryFile(delete=True)
try:
response = requests.get(url, timeout=timeout)
response.raise_for_status()
except E... | [
"def",
"generate_image_from_url",
"(",
"url",
"=",
"None",
",",
"timeout",
"=",
"30",
")",
":",
"file_name",
"=",
"posixpath",
".",
"basename",
"(",
"url",
")",
"img_tmp",
"=",
"NamedTemporaryFile",
"(",
"delete",
"=",
"True",
")",
"try",
":",
"response",
... | 22.809524 | 0.002004 |
def outer_right_join(self, join_streamlet, window_config, join_function):
"""Return a new Streamlet by outer right join_streamlet with this streamlet
"""
from heronpy.streamlet.impl.joinbolt import JoinStreamlet, JoinBolt
join_streamlet_result = JoinStreamlet(JoinBolt.OUTER_RIGHT, window_config,
... | [
"def",
"outer_right_join",
"(",
"self",
",",
"join_streamlet",
",",
"window_config",
",",
"join_function",
")",
":",
"from",
"heronpy",
".",
"streamlet",
".",
"impl",
".",
"joinbolt",
"import",
"JoinStreamlet",
",",
"JoinBolt",
"join_streamlet_result",
"=",
"JoinS... | 56.888889 | 0.001923 |
def decode_bytes(f):
"""Decode a buffer length from a 2-byte unsigned int then read the
subsequent bytes.
Parameters
----------
f: file
File-like object with read method.
Raises
------
UnderflowDecodeError
When the end of stream is encountered before the end of the
... | [
"def",
"decode_bytes",
"(",
"f",
")",
":",
"buf",
"=",
"f",
".",
"read",
"(",
"FIELD_U16",
".",
"size",
")",
"if",
"len",
"(",
"buf",
")",
"<",
"FIELD_U16",
".",
"size",
":",
"raise",
"UnderflowDecodeError",
"(",
")",
"(",
"num_bytes",
",",
")",
"=... | 21.914286 | 0.001248 |
def linkcode_resolve(domain, info):
"""A simple function to find matching source code."""
module_name = info['module']
fullname = info['fullname']
attribute_name = fullname.split('.')[-1]
base_url = 'https://github.com/fmenabe/python-dokuwiki/blob/'
if release.endswith('-dev'):
base_url... | [
"def",
"linkcode_resolve",
"(",
"domain",
",",
"info",
")",
":",
"module_name",
"=",
"info",
"[",
"'module'",
"]",
"fullname",
"=",
"info",
"[",
"'fullname'",
"]",
"attribute_name",
"=",
"fullname",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"b... | 31.55102 | 0.000627 |
def fit_traptransit(ts,fs,p0):
"""
Fits trapezoid model to provided ts,fs
"""
pfit,success = leastsq(traptransit_resid,p0,args=(ts,fs))
if success not in [1,2,3,4]:
raise NoFitError
#logging.debug('success = {}'.format(success))
return pfit | [
"def",
"fit_traptransit",
"(",
"ts",
",",
"fs",
",",
"p0",
")",
":",
"pfit",
",",
"success",
"=",
"leastsq",
"(",
"traptransit_resid",
",",
"p0",
",",
"args",
"=",
"(",
"ts",
",",
"fs",
")",
")",
"if",
"success",
"not",
"in",
"[",
"1",
",",
"2",
... | 29.777778 | 0.039855 |
def tracer(frame, event, arg):
"""This is an internal function that is called every time a call is made
during a trace. It keeps track of relationships between calls.
"""
global func_count_max
global func_count
global trace_filter
global time_filter
global call_stack
global func_time... | [
"def",
"tracer",
"(",
"frame",
",",
"event",
",",
"arg",
")",
":",
"global",
"func_count_max",
"global",
"func_count",
"global",
"trace_filter",
"global",
"time_filter",
"global",
"call_stack",
"global",
"func_time",
"global",
"func_time_max",
"if",
"event",
"==",... | 31.530612 | 0.000941 |
def tickUpdate(self, tick_dict):
''' consume ticks '''
assert self.symbols
assert self.symbols[0] in tick_dict.keys()
symbol=self.symbols[0]
tick=tick_dict[symbol]
if self.increase_and_check_counter():
self.place_order(Order(account=self.account,
... | [
"def",
"tickUpdate",
"(",
"self",
",",
"tick_dict",
")",
":",
"assert",
"self",
".",
"symbols",
"assert",
"self",
".",
"symbols",
"[",
"0",
"]",
"in",
"tick_dict",
".",
"keys",
"(",
")",
"symbol",
"=",
"self",
".",
"symbols",
"[",
"0",
"]",
"tick",
... | 41.142857 | 0.01528 |
def _stringify_row(self, row_index):
'''
Stringifies an entire row, filling in blanks with prior titles as they are found.
'''
table_row = self.table[row_index]
prior_cell = None
for column_index in range(self.start[1], self.end[1]):
cell, changed = self._chec... | [
"def",
"_stringify_row",
"(",
"self",
",",
"row_index",
")",
":",
"table_row",
"=",
"self",
".",
"table",
"[",
"row_index",
"]",
"prior_cell",
"=",
"None",
"for",
"column_index",
"in",
"range",
"(",
"self",
".",
"start",
"[",
"1",
"]",
",",
"self",
"."... | 44.454545 | 0.008016 |
def _getClassifierRegion(self):
"""
Returns reference to the network's Classifier region
"""
if (self._netInfo.net is not None and
"Classifier" in self._netInfo.net.regions):
return self._netInfo.net.regions["Classifier"]
else:
return None | [
"def",
"_getClassifierRegion",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_netInfo",
".",
"net",
"is",
"not",
"None",
"and",
"\"Classifier\"",
"in",
"self",
".",
"_netInfo",
".",
"net",
".",
"regions",
")",
":",
"return",
"self",
".",
"_netInfo",
... | 30.111111 | 0.014337 |
def verification_resource(self, verification_id, audio=False):
"""
Get Verification Resource. Uses GET to /verifications/<verification_id> interface.
:Args:
* *verification_id*: (str) Verification ID
* *audio*: (boolean) If True, audio data associated with verification ... | [
"def",
"verification_resource",
"(",
"self",
",",
"verification_id",
",",
"audio",
"=",
"False",
")",
":",
"params",
"=",
"{",
"}",
"if",
"audio",
":",
"params",
"[",
"\"audio\"",
"]",
"=",
"True",
"response",
"=",
"self",
".",
"_get",
"(",
"url",
".",... | 45.75 | 0.008032 |
def normalize(text: str) -> str:
"""
Thai text normalize
:param str text: thai text
:return: thai text
**Example**::
>>> print(normalize("เเปลก")=="แปลก") # เ เ ป ล ก กับ แปลก
True
"""
for data in _NORMALIZE_RULE2:
text = re.sub(data[0].replace("t", "[่้๊๋]"), data[1], tex... | [
"def",
"normalize",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"for",
"data",
"in",
"_NORMALIZE_RULE2",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"data",
"[",
"0",
"]",
".",
"replace",
"(",
"\"t\"",
",",
"\"[่้๊๋]\"), data[",
"1",
"]",
" tex",
... | 30.8 | 0.002101 |
def build(cls, builder, *args, build_loop=None, **kwargs):
""" Build a hardware control API and initialize the adapter in one call
:param builder: the builder method to use (e.g.
:py:meth:`hardware_control.API.build_hardware_simulator`)
:param args: Args to forward to th... | [
"def",
"build",
"(",
"cls",
",",
"builder",
",",
"*",
"args",
",",
"build_loop",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"loop",
"=",
"asyncio",
".",
"new_event_loop",
"(",
")",
"kwargs",
"[",
"'loop'",
"]",
"=",
"loop",
"args",
"=",
"[",
... | 46.944444 | 0.00232 |
def read_rows(
self,
read_position,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Reads rows from the table in the format prescribed by the read
session. Each response contains one... | [
"def",
"read_rows",
"(",
"self",
",",
"read_position",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"met... | 44.470588 | 0.000776 |
def tables_with_counts(self):
"""Return the number of entries in all table."""
table_to_count = lambda t: self.count_rows(t)
return zip(self.tables, map(table_to_count, self.tables)) | [
"def",
"tables_with_counts",
"(",
"self",
")",
":",
"table_to_count",
"=",
"lambda",
"t",
":",
"self",
".",
"count_rows",
"(",
"t",
")",
"return",
"zip",
"(",
"self",
".",
"tables",
",",
"map",
"(",
"table_to_count",
",",
"self",
".",
"tables",
")",
")... | 50.75 | 0.014563 |
def get_mac_address_table_output_mac_address_table_mac_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Element("get_mac_address_table")
config = get_mac_address_table
output = ET.SubElement(get_mac_address_table, "... | [
"def",
"get_mac_address_table_output_mac_address_table_mac_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_mac_address_table",
"=",
"ET",
".",
"Element",
"(",
"\"get_mac_address_table\"",
")",
... | 48.647059 | 0.002372 |
def create(self, request):
"""Creates a new wiki page for the specified PullRequest instance. The page
gets initialized with basic information about the pull request, the tests
that will be run, etc. Returns the URL on the wiki.
:arg request: the PullRequest instance with testing inform... | [
"def",
"create",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"_site_login",
"(",
"request",
".",
"repo",
")",
"self",
".",
"prefix",
"=",
"\"{}_Pull_Request_{}\"",
".",
"format",
"(",
"request",
".",
"repo",
".",
"name",
",",
"request",
".",
"p... | 47.642857 | 0.013235 |
def site_is_of_motif_type(struct, n, approach="min_dist", delta=0.1, \
cutoff=10.0, thresh=None):
"""
Returns the motif type of the site with index n in structure struct;
currently featuring "tetrahedral", "octahedral", "bcc", and "cp"
(close-packed: fcc and hcp) as well as "sq... | [
"def",
"site_is_of_motif_type",
"(",
"struct",
",",
"n",
",",
"approach",
"=",
"\"min_dist\"",
",",
"delta",
"=",
"0.1",
",",
"cutoff",
"=",
"10.0",
",",
"thresh",
"=",
"None",
")",
":",
"if",
"thresh",
"is",
"None",
":",
"thresh",
"=",
"{",
"\"qtet\""... | 39.652174 | 0.000713 |
def count_rows_distinct(self, table, cols='*'):
"""Get the number distinct of rows in a particular table."""
return self.fetch('SELECT COUNT(DISTINCT {0}) FROM {1}'.format(join_cols(cols), wrap(table))) | [
"def",
"count_rows_distinct",
"(",
"self",
",",
"table",
",",
"cols",
"=",
"'*'",
")",
":",
"return",
"self",
".",
"fetch",
"(",
"'SELECT COUNT(DISTINCT {0}) FROM {1}'",
".",
"format",
"(",
"join_cols",
"(",
"cols",
")",
",",
"wrap",
"(",
"table",
")",
")"... | 72 | 0.013761 |
def force_string(val=None):
"""Force a string representation of an object
Args:
val: object to parse into a string
Returns:
str: String representation
"""
if val is None:
return ''
if isinstance(val, list):
newval = [str(x) for x in val]
return ';'.join... | [
"def",
"force_string",
"(",
"val",
"=",
"None",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"''",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"newval",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"val",
"]",
"return",
"... | 20.631579 | 0.002439 |
def route(**kwargs):
"""
Route a request to different views based on http verb.
Kwargs should be 'GET', 'POST', 'PUT', 'DELETE' or 'ELSE',
where the first four map to a view to route to for that type of
request method/verb, and 'ELSE' maps to a view to pass the request
to if the given request m... | [
"def",
"route",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"routed",
"(",
"request",
",",
"*",
"args2",
",",
"*",
"*",
"kwargs2",
")",
":",
"method",
"=",
"request",
".",
"method",
"if",
"method",
"in",
"kwargs",
":",
"req_method",
"=",
"kwargs",
"[... | 36.578947 | 0.001403 |
def _interpret_value(self, value):
"""Interprets a value passed in the constructor as
a :see:LocalizedValue.
If string:
Assumes it's the default language.
If dict:
Each key is a language and the value a string
in that language.
If list:
... | [
"def",
"_interpret_value",
"(",
"self",
",",
"value",
")",
":",
"for",
"lang_code",
",",
"_",
"in",
"settings",
".",
"LANGUAGES",
":",
"self",
".",
"set",
"(",
"lang_code",
",",
"self",
".",
"default_value",
")",
"if",
"isinstance",
"(",
"value",
",",
... | 28.69697 | 0.002043 |
def set_lines( lines, target_level, indent_string=" ", indent_empty_lines=False ):
""" Sets indentation for the given set of :lines:. """
first_non_empty_line_index = _get_first_non_empty_line_index( lines )
first_line_original_level = get_line_level( lines[first_non_empty_line_index], indent_strin... | [
"def",
"set_lines",
"(",
"lines",
",",
"target_level",
",",
"indent_string",
"=",
"\" \"",
",",
"indent_empty_lines",
"=",
"False",
")",
":",
"first_non_empty_line_index",
"=",
"_get_first_non_empty_line_index",
"(",
"lines",
")",
"first_line_original_level",
"=",
... | 47.826087 | 0.018717 |
def phon(self, cls='current', previousdelimiter="", strict=False,correctionhandling=CorrectionHandling.CURRENT):
"""Get the phonetic representation associated with this element (of the specified class)
The phonetic content will be constructed from child-elements whereever possible, as they are more spe... | [
"def",
"phon",
"(",
"self",
",",
"cls",
"=",
"'current'",
",",
"previousdelimiter",
"=",
"\"\"",
",",
"strict",
"=",
"False",
",",
"correctionhandling",
"=",
"CorrectionHandling",
".",
"CURRENT",
")",
":",
"if",
"strict",
":",
"return",
"self",
".",
"phonc... | 49.916667 | 0.00955 |
def view_component_planes(self, dimensions=None, figsize=None,
colormap=cm.Spectral_r, colorbar=False,
bestmatches=False, bestmatchcolors=None,
labels=None, zoom=None, filename=None):
"""Observe the component planes in the... | [
"def",
"view_component_planes",
"(",
"self",
",",
"dimensions",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"colormap",
"=",
"cm",
".",
"Spectral_r",
",",
"colorbar",
"=",
"False",
",",
"bestmatches",
"=",
"False",
",",
"bestmatchcolors",
"=",
"None",
"... | 53.906977 | 0.002119 |
def _on_process_error(self, error):
"""
Display child process error in the text edit.
"""
if self is None:
return
err = PROCESS_ERROR_STRING[error]
self._formatter.append_message(err + '\r\n', output_format=OutputFormat.ErrorMessageFormat) | [
"def",
"_on_process_error",
"(",
"self",
",",
"error",
")",
":",
"if",
"self",
"is",
"None",
":",
"return",
"err",
"=",
"PROCESS_ERROR_STRING",
"[",
"error",
"]",
"self",
".",
"_formatter",
".",
"append_message",
"(",
"err",
"+",
"'\\r\\n'",
",",
"output_f... | 36.5 | 0.010033 |
def _win32_rmtree(path, verbose=0):
"""
rmtree for win32 that treats junctions like directory symlinks.
The junction removal portion may not be safe on race conditions.
There is a known issue that prevents shutil.rmtree from
deleting directories with junctions.
https://bugs.python.org/issue3122... | [
"def",
"_win32_rmtree",
"(",
"path",
",",
"verbose",
"=",
"0",
")",
":",
"# --- old version using the shell ---",
"# def _rmjunctions(root):",
"# subdirs = []",
"# for type_or_size, name, pointed in _win32_dir(root):",
"# if type_or_size == '<DIR>':",
"# sub... | 34.92 | 0.000557 |
def connect_any_signal_changed(self, function):
"""
Connects the "anything changed" signal for all of the tree to the
specified function.
Parameters
----------
function
Function to connect to this signal.
"""
# loop over all t... | [
"def",
"connect_any_signal_changed",
"(",
"self",
",",
"function",
")",
":",
"# loop over all top level parameters",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_widget",
".",
"topLevelItemCount",
"(",
")",
")",
":",
"# make sure there is only one connection!",
"try... | 31 | 0.008535 |
def _get_xml_rpc():
'''
Uses the OpenNebula cloud provider configurations to connect to the
OpenNebula API.
Returns the server connection created as well as the user and password
values from the cloud provider config file used to make the connection.
'''
vm_ = get_configured_provider()
... | [
"def",
"_get_xml_rpc",
"(",
")",
":",
"vm_",
"=",
"get_configured_provider",
"(",
")",
"xml_rpc",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'xml_rpc'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"user",
"=",
"config",
"."... | 28.32 | 0.001366 |
def lookup_instance(name: str, instance_type: str = '', image_name: str = '',
states: tuple = ('running', 'stopped', 'initializing')):
"""Looks up AWS instance for given instance name, like
simple.worker. If no instance found in current AWS environment, returns None. """
ec2 = get_ec2_resour... | [
"def",
"lookup_instance",
"(",
"name",
":",
"str",
",",
"instance_type",
":",
"str",
"=",
"''",
",",
"image_name",
":",
"str",
"=",
"''",
",",
"states",
":",
"tuple",
"=",
"(",
"'running'",
",",
"'stopped'",
",",
"'initializing'",
")",
")",
":",
"ec2",... | 39.195122 | 0.013358 |
def string_to_uuid(value, strict=True):
"""
Return a Universally Unique Identifier (UUID) object represented by
the specified string.
@param value: a string representation of a UUID.
@param strict: indicate whether the specified string MUST be of a
valid UUID representation.
@return: a... | [
"def",
"string_to_uuid",
"(",
"value",
",",
"strict",
"=",
"True",
")",
":",
"try",
":",
"return",
"None",
"if",
"is_undefined",
"(",
"value",
")",
"else",
"uuid",
".",
"UUID",
"(",
"value",
")",
"except",
"ValueError",
",",
"error",
":",
"if",
"strict... | 29.5625 | 0.002049 |
def iterboxed(self, rows):
"""
Iterator that yields each scanline in boxed row flat pixel format.
`rows` should be an iterator that yields the bytes of
each row in turn.
"""
def asvalues(raw):
"""
Convert a row of raw bytes into a flat row.
... | [
"def",
"iterboxed",
"(",
"self",
",",
"rows",
")",
":",
"def",
"asvalues",
"(",
"raw",
")",
":",
"\"\"\"\n Convert a row of raw bytes into a flat row.\n\n Result may or may not share with argument\n \"\"\"",
"if",
"self",
".",
"bitdepth",
"==",
... | 35.064516 | 0.001791 |
def prt(show=False):
"""
通过 ``装饰器`` 打印函数 ``参数, 运行时间, 返回值`` 等信息
- 如果 ``prt(show==True)`` 打印函数信息,
- 否则, 不做任何处理
.. code:: python
@prt(True)
def say():
print 'say'
'''
hello, world
----------------------------------------------------------------
... | [
"def",
"prt",
"(",
"show",
"=",
"False",
")",
":",
"def",
"dec",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"None",
"ts",
"=",
"time",
".",
"time",
... | 24.9375 | 0.000603 |
def _create_kubelet_prometheus_instance(self, instance):
"""
Create a copy of the instance and set default values.
This is so the base class can create a scraper_config with the proper values.
"""
kubelet_instance = deepcopy(instance)
kubelet_instance.update(
... | [
"def",
"_create_kubelet_prometheus_instance",
"(",
"self",
",",
"instance",
")",
":",
"kubelet_instance",
"=",
"deepcopy",
"(",
"instance",
")",
"kubelet_instance",
".",
"update",
"(",
"{",
"'namespace'",
":",
"self",
".",
"NAMESPACE",
",",
"# We need to specify a p... | 65.4 | 0.00861 |
def implicit_dynamic(cls, for_type=None, for_types=None):
"""Automatically generate late dynamic dispatchers to type.
This is similar to 'implicit_static', except instead of binding the
instance methods, it generates a dispatcher that will call whatever
instance method of the same name ... | [
"def",
"implicit_dynamic",
"(",
"cls",
",",
"for_type",
"=",
"None",
",",
"for_types",
"=",
"None",
")",
":",
"for",
"type_",
"in",
"cls",
".",
"__get_type_args",
"(",
"for_type",
",",
"for_types",
")",
":",
"implementations",
"=",
"{",
"}",
"for",
"func... | 43.809524 | 0.002128 |
def diam_kolmogorov(EnergyDis, Temp, ConcAl, ConcClay, coag, material,
DIM_FRACTAL):
"""Return the size of the floc with separation distances equal to
the Kolmogorov length and the inner viscous length scale.
"""
return (material.Diameter
* ((eta_kolmogorov(EnergyDis, Tem... | [
"def",
"diam_kolmogorov",
"(",
"EnergyDis",
",",
"Temp",
",",
"ConcAl",
",",
"ConcClay",
",",
"coag",
",",
"material",
",",
"DIM_FRACTAL",
")",
":",
"return",
"(",
"material",
".",
"Diameter",
"*",
"(",
"(",
"eta_kolmogorov",
"(",
"EnergyDis",
",",
"Temp",... | 43.75 | 0.001866 |
def set_permission(self, path, **kwargs):
"""Set permission of a path.
:param permission: The permission of a file/directory. Any radix-8 integer (leading zeros
may be omitted.)
:type permission: octal
"""
response = self._put(path, 'SETPERMISSION', **kwargs)
... | [
"def",
"set_permission",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_put",
"(",
"path",
",",
"'SETPERMISSION'",
",",
"*",
"*",
"kwargs",
")",
"assert",
"not",
"response",
".",
"content"
] | 37.777778 | 0.008621 |
def fallible_to_exec_result_or_raise(fallible_result, request):
"""Converts a FallibleExecuteProcessResult to a ExecuteProcessResult or raises an error."""
if fallible_result.exit_code == 0:
return ExecuteProcessResult(
fallible_result.stdout,
fallible_result.stderr,
fallible_result.output_di... | [
"def",
"fallible_to_exec_result_or_raise",
"(",
"fallible_result",
",",
"request",
")",
":",
"if",
"fallible_result",
".",
"exit_code",
"==",
"0",
":",
"return",
"ExecuteProcessResult",
"(",
"fallible_result",
".",
"stdout",
",",
"fallible_result",
".",
"stderr",
",... | 30.8125 | 0.009843 |
def pop(self):
"""
remove self from binary search tree
"""
entry = self
parent = self.parent
root = parent.child()
dir_per_sector = self.storage.sector_size // 128
max_dirs_entries = self.storage.dir_sector_count * dir_per_sector
count = 0
... | [
"def",
"pop",
"(",
"self",
")",
":",
"entry",
"=",
"self",
"parent",
"=",
"self",
".",
"parent",
"root",
"=",
"parent",
".",
"child",
"(",
")",
"dir_per_sector",
"=",
"self",
".",
"storage",
".",
"sector_size",
"//",
"128",
"max_dirs_entries",
"=",
"se... | 30.142857 | 0.002295 |
def _build_logging_config(level, apps_list, verbose, filename=None):
""" Return a copy of the DEFAULT_LOGGING config with installed application
loggers at the given log level. The 'default' handler is kept as a
console/stream writer unless a filename is passed in, which swaps the stream
handler out for... | [
"def",
"_build_logging_config",
"(",
"level",
",",
"apps_list",
",",
"verbose",
",",
"filename",
"=",
"None",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"DEFAULT_LOGGING",
")",
"# Swap out default stream handler for a file handler, if",
"# a filename is give... | 36.416667 | 0.00223 |
def emoticons(string):
'''emot.emoticons is use to detect emoticons from text
>>> text = "I love python 👨 :-)"
>>> emot.emoticons(text)
>>> {'value': [':-)'], 'location': [[16, 19]], 'mean': ['Happy face smiley'], 'flag': True}
'''
__entities = []
flag = True
try:
p... | [
"def",
"emoticons",
"(",
"string",
")",
":",
"__entities",
"=",
"[",
"]",
"flag",
"=",
"True",
"try",
":",
"pattern",
"=",
"u'('",
"+",
"u'|'",
".",
"join",
"(",
"k",
"for",
"k",
"in",
"emo_unicode",
".",
"EMOTICONS",
")",
"+",
"u')'",
"__entities",
... | 29.189189 | 0.015233 |
def open(self):
"""
Obtains the lvm, vg_t and pv_t handle. Usually you would never need to use this
method unless you are doing operations using the ctypes function wrappers in
conversion.py
*Raises:*
* HandleError
"""
self.vg.open()
self._... | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"vg",
".",
"open",
"(",
")",
"self",
".",
"__pvh",
"=",
"lvm_pv_from_uuid",
"(",
"self",
".",
"vg",
".",
"handle",
",",
"self",
".",
"uuid",
")",
"if",
"not",
"bool",
"(",
"self",
".",
"__pvh",
... | 32.5 | 0.008547 |
def record_type(values):
"""
Creates a record type field.
These serve as the header field on records, identifying them.
Usually this field can be only an specific value, but sometimes a small
range of codes is allowed. This is specified by the 'values' parameter.
While it is possible to set t... | [
"def",
"record_type",
"(",
"values",
")",
":",
"field",
"=",
"basic",
".",
"lookup",
"(",
"values",
",",
"name",
"=",
"'Record Type (one of %s)'",
"%",
"values",
")",
"return",
"field",
".",
"setResultsName",
"(",
"'record_type'",
")"
] | 32.5 | 0.001661 |
def get_line(s, bold=False, underline=False, blinking=False, color=None,
bgcolor=None, update_line=False):
"""
Returns a string with the given formatting.
"""
parts = []
if update_line:
parts.append(_UPDATE_LINE)
for val in [color, bgcolor]:
if val:
pa... | [
"def",
"get_line",
"(",
"s",
",",
"bold",
"=",
"False",
",",
"underline",
"=",
"False",
",",
"blinking",
"=",
"False",
",",
"color",
"=",
"None",
",",
"bgcolor",
"=",
"None",
",",
"update_line",
"=",
"False",
")",
":",
"parts",
"=",
"[",
"]",
"if",... | 22.259259 | 0.001595 |
def choose_path():
"""
Invoke a folder selection dialog here
:return:
"""
dirs = webview.create_file_dialog(webview.FOLDER_DIALOG)
if dirs and len(dirs) > 0:
directory = dirs[0]
if isinstance(directory, bytes):
directory = directory.decode("utf-8")
response =... | [
"def",
"choose_path",
"(",
")",
":",
"dirs",
"=",
"webview",
".",
"create_file_dialog",
"(",
"webview",
".",
"FOLDER_DIALOG",
")",
"if",
"dirs",
"and",
"len",
"(",
"dirs",
")",
">",
"0",
":",
"directory",
"=",
"dirs",
"[",
"0",
"]",
"if",
"isinstance",... | 26.625 | 0.002268 |
def dump(self, script, file=None):
"Write a compressed representation of script to the Pickler's file object."
if file is None:
file = self._file
self._dump(script, file, self._protocol, self._version) | [
"def",
"dump",
"(",
"self",
",",
"script",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"self",
".",
"_file",
"self",
".",
"_dump",
"(",
"script",
",",
"file",
",",
"self",
".",
"_protocol",
",",
"self",
".",
... | 46.6 | 0.012658 |
def sha(self):
"""Return sha, lazily compute if not done yet."""
if self._sha is None:
self._sha = compute_auth_key(self.userid, self.password)
return self._sha | [
"def",
"sha",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sha",
"is",
"None",
":",
"self",
".",
"_sha",
"=",
"compute_auth_key",
"(",
"self",
".",
"userid",
",",
"self",
".",
"password",
")",
"return",
"self",
".",
"_sha"
] | 38.4 | 0.010204 |
def build_byte_align_buff(bits):
"""Pad the left side of a bitarray with 0s to align its length with byte boundaries.
Args:
bits: A bitarray to be padded and aligned.
Returns:
A newly aligned bitarray.
"""
bitmod = len(bits)%8
if bitmod == 0:
rdiff = bitarray()
else... | [
"def",
"build_byte_align_buff",
"(",
"bits",
")",
":",
"bitmod",
"=",
"len",
"(",
"bits",
")",
"%",
"8",
"if",
"bitmod",
"==",
"0",
":",
"rdiff",
"=",
"bitarray",
"(",
")",
"else",
":",
"#KEEP bitarray",
"rdiff",
"=",
"bitarray",
"(",
"8",
"-",
"bitm... | 24.294118 | 0.009324 |
def json(**kwargs):
"""
Adds the specified data to the the output display window with the
specified key. This allows the user to make available arbitrary
JSON-compatible data to the display for runtime use.
:param kwargs:
Each keyword argument is added to the CD.data object with the
... | [
"def",
"json",
"(",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"r",
".",
"append_body",
"(",
"render",
".",
"json",
"(",
"*",
"*",
"kwargs",
")",
")",
"r",
".",
"stdout_interceptor",
".",
"write_source",
"(",
"'{}\\n'",
".",
"... | 33.533333 | 0.001934 |
def parent_widget(self):
""" Reimplemented to only return GraphicsItems """
parent = self.parent()
if parent is not None and isinstance(parent, QtGraphicsItem):
return parent.widget | [
"def",
"parent_widget",
"(",
"self",
")",
":",
"parent",
"=",
"self",
".",
"parent",
"(",
")",
"if",
"parent",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"parent",
",",
"QtGraphicsItem",
")",
":",
"return",
"parent",
".",
"widget"
] | 42.6 | 0.009217 |
def query_names(self, pat):
"""pat a shell pattern. See fnmatch.fnmatchcase. Print the
results to stdout."""
for item in self.chnames.items():
if fnmatch.fnmatchcase(item[1], pat):
print item | [
"def",
"query_names",
"(",
"self",
",",
"pat",
")",
":",
"for",
"item",
"in",
"self",
".",
"chnames",
".",
"items",
"(",
")",
":",
"if",
"fnmatch",
".",
"fnmatchcase",
"(",
"item",
"[",
"1",
"]",
",",
"pat",
")",
":",
"print",
"item"
] | 34 | 0.008197 |
def set_iscsi_initiator_info(self, initiator_iqn):
"""Set iSCSI initiator information in iLO.
:param initiator_iqn: Initiator iqn for iLO.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedInBiosError, if the system is
in the BIOS boot mode.
... | [
"def",
"set_iscsi_initiator_info",
"(",
"self",
",",
"initiator_iqn",
")",
":",
"sushy_system",
"=",
"self",
".",
"_get_sushy_system",
"(",
"PROLIANT_SYSTEM_ID",
")",
"if",
"(",
"self",
".",
"_is_boot_mode_uefi",
"(",
")",
")",
":",
"iscsi_data",
"=",
"{",
"'i... | 47.130435 | 0.001808 |
def get_niggli_reduced_lattice(self, tol: float = 1e-5) -> "Lattice":
"""
Get the Niggli reduced lattice using the numerically stable algo
proposed by R. W. Grosse-Kunstleve, N. K. Sauter, & P. D. Adams,
Acta Crystallographica Section A Foundations of Crystallography, 2003,
60(1)... | [
"def",
"get_niggli_reduced_lattice",
"(",
"self",
",",
"tol",
":",
"float",
"=",
"1e-5",
")",
"->",
"\"Lattice\"",
":",
"# lll reduction is more stable for skewed cells",
"matrix",
"=",
"self",
".",
"lll_matrix",
"a",
"=",
"matrix",
"[",
"0",
"]",
"b",
"=",
"m... | 32.391892 | 0.001417 |
def _table_cell(args, cell_body):
"""Implements the BigQuery table magic subcommand used to operate on tables
The supported syntax is:
%%bq tables <command> <args>
Commands:
{list, create, delete, describe, view}
Args:
args: the optional arguments following '%%bq tables command'.
cell_body: o... | [
"def",
"_table_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"if",
"args",
"[",
"'command'",
"]",
"==",
"'list'",
":",
"filter_",
"=",
"args",
"[",
"'filter'",
"]",
"if",
"args",
"[",
"'filter'",
"]",
"else",
"'*'",
"if",
"args",
"[",
"'dataset'",
... | 35.013889 | 0.010031 |
def gfortran_search_path(library_dirs):
"""Get the library directory paths for ``gfortran``.
Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs``
and then parses the paths. If this fails for any reason, this method will
print an error and return ``library_dirs``.
Args:
... | [
"def",
"gfortran_search_path",
"(",
"library_dirs",
")",
":",
"cmd",
"=",
"(",
"\"gfortran\"",
",",
"\"-print-search-dirs\"",
")",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"return_code",
"=",
... | 35.733333 | 0.001211 |
def memory(self):
"""
The maximum number of bytes of memory the job will require to run.
"""
if self._memory is not None:
return self._memory
elif self._config is not None:
return self._config.defaultMemory
else:
raise AttributeError("D... | [
"def",
"memory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_memory",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_memory",
"elif",
"self",
".",
"_config",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_config",
".",
"defaultMemory",
"else",
... | 35.9 | 0.008152 |
def save(self, *args, **kwargs):
"""
Save the person model so it updates his/her number of board connections field.
Also updates name
"""
self.name = str(self.company.name) + " --- " + str(self.person)
super(Director, self).save(*args, **kwargs) # Call the "real" sa... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"name",
"=",
"str",
"(",
"self",
".",
"company",
".",
"name",
")",
"+",
"\" --- \"",
"+",
"str",
"(",
"self",
".",
"person",
")",
"super",
"(",
"D... | 42.727273 | 0.008333 |
def moving_average_smooth(t, y, dy, span=None, cv=True,
t_out=None, span_out=None, period=None):
"""Perform a moving-average smooth of the data
Parameters
----------
t, y, dy : array_like
time, value, and error in value of the input data
span : array_like
t... | [
"def",
"moving_average_smooth",
"(",
"t",
",",
"y",
",",
"dy",
",",
"span",
"=",
"None",
",",
"cv",
"=",
"True",
",",
"t_out",
"=",
"None",
",",
"span_out",
"=",
"None",
",",
"period",
"=",
"None",
")",
":",
"prep",
"=",
"_prep_smooth",
"(",
"t",
... | 35.054054 | 0.00075 |
def split(self, decl_string):
"""implementation details"""
assert self.has_pattern(decl_string)
return self.name(decl_string), self.args(decl_string) | [
"def",
"split",
"(",
"self",
",",
"decl_string",
")",
":",
"assert",
"self",
".",
"has_pattern",
"(",
"decl_string",
")",
"return",
"self",
".",
"name",
"(",
"decl_string",
")",
",",
"self",
".",
"args",
"(",
"decl_string",
")"
] | 42.5 | 0.011561 |
def connect(self, (host, port)):
'''
Connect using a host,port tuple
'''
super(GeventTransport, self).connect((host, port), klass=socket.socket) | [
"def",
"connect",
"(",
"self",
",",
"(",
"host",
",",
"port",
")",
")",
":",
"super",
"(",
"GeventTransport",
",",
"self",
")",
".",
"connect",
"(",
"(",
"host",
",",
"port",
")",
",",
"klass",
"=",
"socket",
".",
"socket",
")"
] | 34.4 | 0.011364 |
def spawn(self, process):
"""Spawn a process.
Spawning a process binds it to this context and assigns the process a
pid which is returned. The process' ``initialize`` method is called.
Note: A process cannot send messages until it is bound to a context.
:param process: The process to bind to thi... | [
"def",
"spawn",
"(",
"self",
",",
"process",
")",
":",
"self",
".",
"_assert_started",
"(",
")",
"process",
".",
"bind",
"(",
"self",
")",
"self",
".",
"http",
".",
"mount_process",
"(",
"process",
")",
"self",
".",
"_processes",
"[",
"process",
".",
... | 31.368421 | 0.001629 |
def FZStaeckel(u,v,pot,delta): #pragma: no cover because unused
"""
NAME:
FZStaeckel
PURPOSE:
return the vertical force
INPUT:
u - confocal u
v - confocal v
pot - potential
delta - focus
OUTPUT:
FZ(u,v)
HISTORY:
2012-11-30 - Written - Bovy ... | [
"def",
"FZStaeckel",
"(",
"u",
",",
"v",
",",
"pot",
",",
"delta",
")",
":",
"#pragma: no cover because unused",
"R",
",",
"z",
"=",
"bovy_coords",
".",
"uv_to_Rz",
"(",
"u",
",",
"v",
",",
"delta",
"=",
"delta",
")",
"return",
"_evaluatezforces",
"(",
... | 22.222222 | 0.028777 |
def add(self, timer):
"""Add a timer to the heap"""
with self.lock:
if self.heap:
top = self.heap[0]
else:
top = None
assert timer not in self.timers
self.timers[timer] = timer
heapq.heappush(self.heap, timer)
... | [
"def",
"add",
"(",
"self",
",",
"timer",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"heap",
":",
"top",
"=",
"self",
".",
"heap",
"[",
"0",
"]",
"else",
":",
"top",
"=",
"None",
"assert",
"timer",
"not",
"in",
"self",
".",
... | 37.4 | 0.001738 |
def reads(paths, filename='data.h5', options=None, **keywords):
""" Reads data from an HDF5 file (high level).
High level function to read one or more pieces of data from an HDF5
file located at the paths specified in `paths` into Python
types. Each path is specified as a POSIX style path where the dat... | [
"def",
"reads",
"(",
"paths",
",",
"filename",
"=",
"'data.h5'",
",",
"options",
"=",
"None",
",",
"*",
"*",
"keywords",
")",
":",
"# Pack the different options into an Options class if an Options was",
"# not given. By default, the matlab_compatible option is set to",
"# Fal... | 37.436364 | 0.000946 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.