text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _parse_json(doc, exactly_one=True):
"""
Parse a location name, latitude, and longitude from an JSON response.
"""
status_code = doc.get("statusCode", 200)
if status_code != 200:
err = doc.get("errorDetails", "")
if status_code == 401:
r... | [
"def",
"_parse_json",
"(",
"doc",
",",
"exactly_one",
"=",
"True",
")",
":",
"status_code",
"=",
"doc",
".",
"get",
"(",
"\"statusCode\"",
",",
"200",
")",
"if",
"status_code",
"!=",
"200",
":",
"err",
"=",
"doc",
".",
"get",
"(",
"\"errorDetails\"",
"... | 36.903846 | 17.326923 |
def _parse_main(path=MAIN_CF):
'''
Parse files in the style of main.cf. This is not just a "name = value" file;
there are other rules:
* Comments start with #
* Any whitespace at the beginning of a line denotes that that line is a
continuation from the previous line.
* The whitespace ru... | [
"def",
"_parse_main",
"(",
"path",
"=",
"MAIN_CF",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"'r'",
")",
"as",
"fh_",
":",
"full_conf",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",... | 35.065217 | 19.630435 |
def truediv(self, other, axis="columns", level=None, fill_value=None):
"""Divides this DataFrame against another DataFrame/Series/scalar.
Args:
other: The object to use to apply the divide against this.
axis: The axis to divide over.
level: The Multilevel index... | [
"def",
"truediv",
"(",
"self",
",",
"other",
",",
"axis",
"=",
"\"columns\"",
",",
"level",
"=",
"None",
",",
"fill_value",
"=",
"None",
")",
":",
"return",
"self",
".",
"_binary_op",
"(",
"\"truediv\"",
",",
"other",
",",
"axis",
"=",
"axis",
",",
"... | 39.733333 | 21.4 |
def import_image(self, image_id, region_name):
'''
a method to import an image from another AWS region
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html
REQUIRED: aws credentials must have valid access to both regions
:param image_id: string wit... | [
"def",
"import_image",
"(",
"self",
",",
"image_id",
",",
"region_name",
")",
":",
"title",
"=",
"'%s.import_image'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs",
"input_fields",
"=",
"{",
"'image_id'",
":",
"image_id",
"}",
"for",
"key... | 39.80597 | 21.164179 |
def update_credentials(self, password):
"""Update credentials of a redfish system
:param password: password to be updated
"""
data = {
'Password': password,
}
self._conn.patch(self.path, data=data) | [
"def",
"update_credentials",
"(",
"self",
",",
"password",
")",
":",
"data",
"=",
"{",
"'Password'",
":",
"password",
",",
"}",
"self",
".",
"_conn",
".",
"patch",
"(",
"self",
".",
"path",
",",
"data",
"=",
"data",
")"
] | 27.777778 | 12.888889 |
def delete_tables(self, **kwargs):
"""
removes all the tables from the db
this is, obviously, very bad if you didn't mean to call this, because of that, you
have to pass in disable_protection=True, if it doesn't get that passed in, it won't
run this method
"""
if... | [
"def",
"delete_tables",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"'disable_protection'",
",",
"False",
")",
":",
"raise",
"ValueError",
"(",
"'In order to delete all the tables, pass in disable_protection=True'",
")",
... | 42.428571 | 21.285714 |
def baselevels(self):
"""
Optional baselevels configuration.
baselevels:
min: <zoom>
max: <zoom>
lower: <resampling method>
higher: <resampling method>
"""
if "baselevels" not in self._raw:
return {}
baselevels ... | [
"def",
"baselevels",
"(",
"self",
")",
":",
"if",
"\"baselevels\"",
"not",
"in",
"self",
".",
"_raw",
":",
"return",
"{",
"}",
"baselevels",
"=",
"self",
".",
"_raw",
"[",
"\"baselevels\"",
"]",
"minmax",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"... | 34.219512 | 19.146341 |
def get_galaxy_connection(history_id=None, obj=True):
"""
Given access to the configuration dict that galaxy passed us, we try and connect to galaxy's API.
First we try connecting to galaxy directly, using an IP address given
us by docker (since the galaxy host is the default gateway for doc... | [
"def",
"get_galaxy_connection",
"(",
"history_id",
"=",
"None",
",",
"obj",
"=",
"True",
")",
":",
"history_id",
"=",
"history_id",
"or",
"os",
".",
"environ",
"[",
"'HISTORY_ID'",
"]",
"key",
"=",
"os",
".",
"environ",
"[",
"'API_KEY'",
"]",
"### Customis... | 44.92 | 23.88 |
def wait_for_element_visible(self, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" Waits for an element to appear in the HTML of a page.
The element must be visible (it cannot be hidden). """
if page_utils.is_xpath_selector(selector):
... | [
"def",
"wait_for_element_visible",
"(",
"self",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"if",
"page_utils",
".",
"is_xpath_selector",
"(",
"selector",
")",
":",
"by",
"=",
... | 53.545455 | 13.636364 |
def reverse_complement_sequences(records):
"""
Transform sequences into reverse complements.
"""
logging.info('Applying _reverse_complement_sequences generator: '
'transforming sequences into reverse complements.')
for record in records:
rev_record = SeqRecord(record.seq.rev... | [
"def",
"reverse_complement_sequences",
"(",
"records",
")",
":",
"logging",
".",
"info",
"(",
"'Applying _reverse_complement_sequences generator: '",
"'transforming sequences into reverse complements.'",
")",
"for",
"record",
"in",
"records",
":",
"rev_record",
"=",
"SeqRecor... | 40.142857 | 15.571429 |
def Grayscale(alpha=0, from_colorspace="RGB", name=None, deterministic=False, random_state=None):
"""
Augmenter to convert images to their grayscale versions.
NOTE: Number of output channels is still 3, i.e. this augmenter just "removes" color.
TODO check dtype support
dtype support::
* ... | [
"def",
"Grayscale",
"(",
"alpha",
"=",
"0",
",",
"from_colorspace",
"=",
"\"RGB\"",
",",
"name",
"=",
"None",
",",
"deterministic",
"=",
"False",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"\"Unnamed%s\"",
... | 37.666667 | 27.805556 |
def _get_module(target):
"""Import a named class, module, method or function.
Accepts these formats:
".../file/path|module_name:Class.method"
".../file/path|module_name:Class"
".../file/path|module_name:function"
"module_name:Class"
"module_name:function"
"module... | [
"def",
"_get_module",
"(",
"target",
")",
":",
"filepath",
",",
"sep",
",",
"namespace",
"=",
"target",
".",
"rpartition",
"(",
"'|'",
")",
"if",
"sep",
"and",
"not",
"filepath",
":",
"raise",
"BadDirectory",
"(",
"\"Path to file not supplied.\"",
")",
"modu... | 34.142857 | 17.183673 |
def create_config_files(directory):
"""
Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return:
"""
# Some constant strings
config_zip_url = "https://s3-us-west-1.amazonaws.com/heartbleed/linux/linux-files.zip"
if not os.path.exists(di... | [
"def",
"create_config_files",
"(",
"directory",
")",
":",
"# Some constant strings",
"config_zip_url",
"=",
"\"https://s3-us-west-1.amazonaws.com/heartbleed/linux/linux-files.zip\"",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"os",
".",
"... | 38.838235 | 18.367647 |
def _refresh_html_home(self):
"""
Function to refresh the self._parent.html['home'] object
which provides the status if zones are scheduled to
start automatically (program_toggle).
"""
req = self._parent.client.get(HOME_ENDPOINT)
if req.status_code == 403:
... | [
"def",
"_refresh_html_home",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"_parent",
".",
"client",
".",
"get",
"(",
"HOME_ENDPOINT",
")",
"if",
"req",
".",
"status_code",
"==",
"403",
":",
"self",
".",
"_parent",
".",
"login",
"(",
")",
"self",
"... | 36.642857 | 11.785714 |
def read(self, read_list, verbose=False, log=False):
"""Read the content, returning a list of ReadingData objects."""
ret = []
mem_tot = _get_mem_total()
if mem_tot is not None and mem_tot <= self.REACH_MEM + self.MEM_BUFFER:
logger.error(
"Too little memory t... | [
"def",
"read",
"(",
"self",
",",
"read_list",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"mem_tot",
"=",
"_get_mem_total",
"(",
")",
"if",
"mem_tot",
"is",
"not",
"None",
"and",
"mem_tot",
"<=",
"self",
... | 39.288889 | 15.688889 |
def get_SCAT_box(slope, x_mean, y_mean, beta_threshold = .1):
"""
takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box
"""
# if beta_threshold is -999, that means null
if beta_thr... | [
"def",
"get_SCAT_box",
"(",
"slope",
",",
"x_mean",
",",
"y_mean",
",",
"beta_threshold",
"=",
".1",
")",
":",
"# if beta_threshold is -999, that means null",
"if",
"beta_threshold",
"==",
"-",
"999",
":",
"beta_threshold",
"=",
".1",
"slope_err_threshold",
"=",
"... | 45.488372 | 16.511628 |
def balanced_repartition(data, partitions):
""" balanced_repartition(data, partitions)
Reparations an RDD making sure data is evenly distributed across partitions
for Spark version < 2.1 (see: https://issues.apache.org/jira/browse/SPARK-17817)
or < 2.3 when #partitions is power of 2 (see: https://is... | [
"def",
"balanced_repartition",
"(",
"data",
",",
"partitions",
")",
":",
"def",
"repartition",
"(",
"data_inner",
",",
"partitions_inner",
")",
":",
"# repartition by zipping an index to the data, repartition by % on it and removing it\r",
"data_inner",
"=",
"data_inner",
"."... | 48.190476 | 26.904762 |
def parse(version):
"""Parse version to major, minor, patch, pre-release, build parts.
:param version: version string
:return: dictionary with the keys 'build', 'major', 'minor', 'patch',
and 'prerelease'. The prerelease or build keys can be None
if not provided
:rtype: dict
... | [
"def",
"parse",
"(",
"version",
")",
":",
"match",
"=",
"_REGEX",
".",
"match",
"(",
"version",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'%s is not valid SemVer string'",
"%",
"version",
")",
"version_parts",
"=",
"match",
".",
"... | 26.727273 | 22.151515 |
def remove_end_optionals(ir_blocks):
"""Return a list of IR blocks as a copy of the original, with EndOptional blocks removed."""
new_ir_blocks = []
for block in ir_blocks:
if not isinstance(block, EndOptional):
new_ir_blocks.append(block)
return new_ir_blocks | [
"def",
"remove_end_optionals",
"(",
"ir_blocks",
")",
":",
"new_ir_blocks",
"=",
"[",
"]",
"for",
"block",
"in",
"ir_blocks",
":",
"if",
"not",
"isinstance",
"(",
"block",
",",
"EndOptional",
")",
":",
"new_ir_blocks",
".",
"append",
"(",
"block",
")",
"re... | 41.428571 | 8.285714 |
def prefilter_line(self, line, continue_prompt=False):
"""Prefilter a single input line as text.
This method prefilters a single line of text by calling the
transformers and then the checkers/handlers.
"""
# print "prefilter_line: ", line, continue_prompt
# All handlers... | [
"def",
"prefilter_line",
"(",
"self",
",",
"line",
",",
"continue_prompt",
"=",
"False",
")",
":",
"# print \"prefilter_line: \", line, continue_prompt",
"# All handlers *must* return a value, even if it's blank ('').",
"# save the line away in case we crash, so the post-mortem handler c... | 39.155556 | 23.777778 |
def modulepath(filename):
"""
Find the relative path to its module of a python file if existing.
filename
string, name of a python file
"""
filepath = os.path.abspath(filename)
prepath = filepath[:filepath.rindex('/')]
postpath = '/'
if prepath.count('/') == 0 or not os.path.exist... | [
"def",
"modulepath",
"(",
"filename",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"prepath",
"=",
"filepath",
"[",
":",
"filepath",
".",
"rindex",
"(",
"'/'",
")",
"]",
"postpath",
"=",
"'/'",
"if",
"prepath",
... | 36.571429 | 23.714286 |
def query_string(self, **params):
"""Specify query string to use with the collection.
Returns: :py:class:`SearchResult`
"""
return SearchResult(self, self._api.get(self._href, **params)) | [
"def",
"query_string",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"SearchResult",
"(",
"self",
",",
"self",
".",
"_api",
".",
"get",
"(",
"self",
".",
"_href",
",",
"*",
"*",
"params",
")",
")"
] | 35.666667 | 13 |
def register_model(cls, model):
"""
Register a model class according to its remote name
Args:
model: the model to register
"""
rest_name = model.rest_name
resource_name = model.resource_name
if rest_name not in cls._model_rest_name_regis... | [
"def",
"register_model",
"(",
"cls",
",",
"model",
")",
":",
"rest_name",
"=",
"model",
".",
"rest_name",
"resource_name",
"=",
"model",
".",
"resource_name",
"if",
"rest_name",
"not",
"in",
"cls",
".",
"_model_rest_name_registry",
":",
"cls",
".",
"_model_res... | 36.222222 | 21.333333 |
def use_http_form_post(message, destination, relay_state,
typ="SAMLRequest"):
"""
Return a form that will automagically execute and POST the message
to the recipient.
:param message:
:param destination:
:param relay_state:
:param typ: W... | [
"def",
"use_http_form_post",
"(",
"message",
",",
"destination",
",",
"relay_state",
",",
"typ",
"=",
"\"SAMLRequest\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"six",
".",
"string_types",
")",
":",
"message",
"=",
"\"%s\"",
"%",
"(",
"me... | 34.75 | 17.375 |
def scheduled():
'''
List scheduled jobs.
'''
for job in sorted(schedulables(), key=lambda s: s.name):
for task in PeriodicTask.objects(task=job.name):
label = job_label(task.task, task.args, task.kwargs)
echo(SCHEDULE_LINE.format(
name=white(task.name.enc... | [
"def",
"scheduled",
"(",
")",
":",
"for",
"job",
"in",
"sorted",
"(",
"schedulables",
"(",
")",
",",
"key",
"=",
"lambda",
"s",
":",
"s",
".",
"name",
")",
":",
"for",
"task",
"in",
"PeriodicTask",
".",
"objects",
"(",
"task",
"=",
"job",
".",
"n... | 35.666667 | 17.5 |
def get_logged_in_by(self, login, parent_zc, duration=0):
"""Use another client to get logged in via preauth mechanism by an
already logged in admin.
It required the domain of the admin user to have preAuthKey
The preauth key cannot be created by API, do it with zmprov :
zmp... | [
"def",
"get_logged_in_by",
"(",
"self",
",",
"login",
",",
"parent_zc",
",",
"duration",
"=",
"0",
")",
":",
"domain_name",
"=",
"zobjects",
".",
"Account",
"(",
"name",
"=",
"login",
")",
".",
"get_domain",
"(",
")",
"preauth_key",
"=",
"parent_zc",
"."... | 40.117647 | 21.470588 |
def connectDb(engine = dbeng,
user = dbuser,
password = dbpwd,
host = dbhost,
port = dbport,
database = dbname,
params = "?charset=utf8&use_unicode=1",
echoopt = False):
"""Connect to database utility ... | [
"def",
"connectDb",
"(",
"engine",
"=",
"dbeng",
",",
"user",
"=",
"dbuser",
",",
"password",
"=",
"dbpwd",
",",
"host",
"=",
"dbhost",
",",
"port",
"=",
"dbport",
",",
"database",
"=",
"dbname",
",",
"params",
"=",
"\"?charset=utf8&use_unicode=1\"",
",",
... | 35.133333 | 16.533333 |
def locked_get(self):
"""Retrieve stored credential from the Django ORM.
Returns:
oauth2client.Credentials retrieved from the Django ORM, associated
with the ``model``, ``key_value``->``key_name`` pair used to query
for the model, and ``property_name`` identifying ... | [
"def",
"locked_get",
"(",
"self",
")",
":",
"query",
"=",
"{",
"self",
".",
"key_name",
":",
"self",
".",
"key_value",
"}",
"entities",
"=",
"self",
".",
"model_class",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"query",
")",
"if",
"len",
"(",
"... | 41.25 | 20.7 |
def key(self, identifier):
"""
A context-manager method. Yields the first :py:obj:`PGPKey` object that matches the provided identifier.
:param identifier: The identifier to use to select a loaded key.
:type identifier: :py:exc:`PGPMessage`, :py:exc:`PGPSignature`, ``str``
:raise... | [
"def",
"key",
"(",
"self",
",",
"identifier",
")",
":",
"if",
"isinstance",
"(",
"identifier",
",",
"PGPMessage",
")",
":",
"for",
"issuer",
"in",
"identifier",
".",
"issuers",
":",
"if",
"issuer",
"in",
"self",
":",
"identifier",
"=",
"issuer",
"break",... | 40.055556 | 20.722222 |
def _prepPayload(self, record):
"""
record: generated from logger module
This preps the payload to be formatted in whatever content-type is
expected from the RESTful API.
returns: a tuple of the data and the http content-type
"""
payload = self._getPayload(record... | [
"def",
"_prepPayload",
"(",
"self",
",",
"record",
")",
":",
"payload",
"=",
"self",
".",
"_getPayload",
"(",
"record",
")",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"payload",
",",
"default",
"=",
"serialize",
")",
"return",
"{",
"'json'",
":",
"(... | 35.5 | 16.071429 |
def run(cmd, **kwargs):
"""Echo a command before running it. Defaults to repo as cwd"""
log.info('> ' + list2cmdline(cmd))
kwargs.setdefault('cwd', HERE)
kwargs.setdefault('shell', os.name == 'nt')
if not isinstance(cmd, (list, tuple)) and os.name != 'nt':
cmd = shlex.split(cmd)
cmd[0] ... | [
"def",
"run",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"info",
"(",
"'> '",
"+",
"list2cmdline",
"(",
"cmd",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'cwd'",
",",
"HERE",
")",
"kwargs",
".",
"setdefault",
"(",
"'shell'",
",",
... | 41.666667 | 9.444444 |
def connect(cls, transport, rsa_keys=None, timeout_ms=1000,
auth_timeout_ms=100):
"""Establish a new connection to a device, connected via transport.
Args:
transport: A transport to use for reads/writes from/to the device,
usually an instance of UsbHandle, but really it can be anyth... | [
"def",
"connect",
"(",
"cls",
",",
"transport",
",",
"rsa_keys",
"=",
"None",
",",
"timeout_ms",
"=",
"1000",
",",
"auth_timeout_ms",
"=",
"100",
")",
":",
"timeout",
"=",
"timeouts",
".",
"PolledTimeout",
".",
"from_millis",
"(",
"timeout_ms",
")",
"if",
... | 44.632184 | 23.137931 |
def ReadPreprocessingInformation(self, knowledge_base):
"""Reads preprocessing information.
The preprocessing information contains the system configuration which
contains information about various system specific configuration data,
for example the user accounts.
Args:
knowledge_base (Knowle... | [
"def",
"ReadPreprocessingInformation",
"(",
"self",
",",
"knowledge_base",
")",
":",
"if",
"not",
"self",
".",
"_storage_file",
":",
"raise",
"IOError",
"(",
"'Unable to read from closed storage writer.'",
")",
"self",
".",
"_storage_file",
".",
"ReadPreprocessingInform... | 34.526316 | 23.052632 |
def insert_result(self, result):
"""
Insert a new result in the database.
This function also verifies that the result dictionaries saved in the
database have the following structure (with {'a': 1} representing a
dictionary, 'a' a key and 1 its value)::
{
... | [
"def",
"insert_result",
"(",
"self",
",",
"result",
")",
":",
"# This dictionary serves as a model for how the keys in the newly",
"# inserted result should be structured.",
"example_result",
"=",
"{",
"'params'",
":",
"{",
"k",
":",
"[",
"'...'",
"]",
"for",
"k",
"in",... | 37.75 | 20.204545 |
def _mergemap(map1, map2):
"""
Positions in map2 have an integer indicating the relative shift to
the equivalent position in map1. E.g., the i'th position in map2
corresponds to the i + map2[i] position in map1.
"""
merged = array('i', [0] * len(map2))
for i, shift in enumerate(map2):
... | [
"def",
"_mergemap",
"(",
"map1",
",",
"map2",
")",
":",
"merged",
"=",
"array",
"(",
"'i'",
",",
"[",
"0",
"]",
"*",
"len",
"(",
"map2",
")",
")",
"for",
"i",
",",
"shift",
"in",
"enumerate",
"(",
"map2",
")",
":",
"merged",
"[",
"i",
"]",
"=... | 36.6 | 11.4 |
def get_draws(fit, variables=None, ignore=None):
"""Extract draws from PyStan fit."""
if ignore is None:
ignore = []
if fit.mode == 1:
msg = "Model in mode 'test_grad'. Sampling is not conducted."
raise AttributeError(msg)
if fit.mode == 2 or fit.sim.get("samples") is No... | [
"def",
"get_draws",
"(",
"fit",
",",
"variables",
"=",
"None",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"ignore",
"is",
"None",
":",
"ignore",
"=",
"[",
"]",
"if",
"fit",
".",
"mode",
"==",
"1",
":",
"msg",
"=",
"\"Model in mode 'test_grad'. Samplin... | 37.7625 | 19.4 |
def get_field_identifiers(self):
"""
Builds a list of the field identifiers for all tables and joined tables by calling
``get_field_identifiers()`` on each table
:return: list of field identifiers
:rtype: list of str
"""
field_identifiers = []
for table i... | [
"def",
"get_field_identifiers",
"(",
"self",
")",
":",
"field_identifiers",
"=",
"[",
"]",
"for",
"table",
"in",
"self",
".",
"tables",
":",
"field_identifiers",
"+=",
"table",
".",
"get_field_identifiers",
"(",
")",
"for",
"join_item",
"in",
"self",
".",
"j... | 38.071429 | 15.071429 |
def debug(message, level=1):
"""
So we can tune how much debug output we get when we turn it on.
"""
if level <= debug_level:
logging.debug(' ' * (level - 1) * 2 + str(message)) | [
"def",
"debug",
"(",
"message",
",",
"level",
"=",
"1",
")",
":",
"if",
"level",
"<=",
"debug_level",
":",
"logging",
".",
"debug",
"(",
"' '",
"*",
"(",
"level",
"-",
"1",
")",
"*",
"2",
"+",
"str",
"(",
"message",
")",
")"
] | 32.666667 | 11.666667 |
def compute_ll_matrix(self, bounds, num_pts):
"""Compute the log likelihood over the (free) parameter space.
Parameters
----------
bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters
Bounds on the range to use for each of the param... | [
"def",
"compute_ll_matrix",
"(",
"self",
",",
"bounds",
",",
"num_pts",
")",
":",
"present_free_params",
"=",
"self",
".",
"free_params",
"[",
":",
"]",
"bounds",
"=",
"scipy",
".",
"atleast_2d",
"(",
"scipy",
".",
"asarray",
"(",
"bounds",
",",
"dtype",
... | 45.978723 | 23.276596 |
def run(self, args=None):
"""
Runs the set of tests within the given path.
"""
# Disable "Too many branches" and "Too many return statemets" warnings
# pylint: disable=R0912,R0911
retcodesummary = ExitCodes.EXIT_SUCCESS
self.args = args if args else self.args
... | [
"def",
"run",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"# Disable \"Too many branches\" and \"Too many return statemets\" warnings",
"# pylint: disable=R0912,R0911",
"retcodesummary",
"=",
"ExitCodes",
".",
"EXIT_SUCCESS",
"self",
".",
"args",
"=",
"args",
"if",
... | 38.338462 | 20.430769 |
def remove_empty_element(parent_to_parse, element_path, target_element=None):
"""
Searches for all empty sub-elements named after element_name in the parsed element,
and if it exists, removes them all and returns them as a list.
"""
element = get_element(parent_to_parse)
removed = []
if el... | [
"def",
"remove_empty_element",
"(",
"parent_to_parse",
",",
"element_path",
",",
"target_element",
"=",
"None",
")",
":",
"element",
"=",
"get_element",
"(",
"parent_to_parse",
")",
"removed",
"=",
"[",
"]",
"if",
"element",
"is",
"None",
"or",
"not",
"element... | 38.46 | 21.62 |
def _gen_identity(self, key, param=None):
"""generate identity according to key and param given"""
if self.identity_generator and param is not None:
if self.serializer:
param = self.serializer.serialize(param)
if self.compressor:
param = self.compr... | [
"def",
"_gen_identity",
"(",
"self",
",",
"key",
",",
"param",
"=",
"None",
")",
":",
"if",
"self",
".",
"identity_generator",
"and",
"param",
"is",
"not",
"None",
":",
"if",
"self",
".",
"serializer",
":",
"param",
"=",
"self",
".",
"serializer",
".",... | 42.181818 | 13.818182 |
def GetLocation(session=None):
"""Return specified location or if none the default location associated with the provided credentials and alias.
>>> clc.v2.Account.GetLocation()
u'WA1'
"""
if session is not None:
return session['location']
if not clc.LOCATION... | [
"def",
"GetLocation",
"(",
"session",
"=",
"None",
")",
":",
"if",
"session",
"is",
"not",
"None",
":",
"return",
"session",
"[",
"'location'",
"]",
"if",
"not",
"clc",
".",
"LOCATION",
":",
"clc",
".",
"v2",
".",
"API",
".",
"_Login",
"(",
")",
"r... | 32.818182 | 13.454545 |
def calc_uncertainty(quantity, sys_unc, mean=True):
"""Calculate the combined standard uncertainty of a quantity."""
n = len(quantity)
std = np.nanstd(quantity)
if mean:
std /= np.sqrt(n)
return np.sqrt(std**2 + sys_unc**2) | [
"def",
"calc_uncertainty",
"(",
"quantity",
",",
"sys_unc",
",",
"mean",
"=",
"True",
")",
":",
"n",
"=",
"len",
"(",
"quantity",
")",
"std",
"=",
"np",
".",
"nanstd",
"(",
"quantity",
")",
"if",
"mean",
":",
"std",
"/=",
"np",
".",
"sqrt",
"(",
... | 35.857143 | 11.714286 |
def diff_compute(self, text1, text2, checklines, deadline):
"""Find the differences between two texts. Assumes that the texts do not
have any common prefix or suffix.
Args:
text1: Old string to be diffed.
text2: New string to be diffed.
checklines: Speedup flag. If false, then don't r... | [
"def",
"diff_compute",
"(",
"self",
",",
"text1",
",",
"text2",
",",
"checklines",
",",
"deadline",
")",
":",
"if",
"not",
"text1",
":",
"# Just add some text (speedup).",
"return",
"[",
"(",
"self",
".",
"DIFF_INSERT",
",",
"text2",
")",
"]",
"if",
"not",... | 37.603448 | 18.87931 |
def _proxy_settings(self):
"""
Create/replace ~/.datacats/run/proxy-environment and return
entry for ro mount for containers
"""
if not ('https_proxy' in environ or 'HTTPS_PROXY' in environ
or 'http_proxy' in environ or 'HTTP_PROXY' in environ):
return... | [
"def",
"_proxy_settings",
"(",
"self",
")",
":",
"if",
"not",
"(",
"'https_proxy'",
"in",
"environ",
"or",
"'HTTPS_PROXY'",
"in",
"environ",
"or",
"'http_proxy'",
"in",
"environ",
"or",
"'HTTP_PROXY'",
"in",
"environ",
")",
":",
"return",
"{",
"}",
"https_pr... | 43.583333 | 18.25 |
def detail_poi(self, **kwargs):
"""Obtain detailed info of a given POI.
Args:
family (str): Family code of the POI (3 chars).
lang (str): Language code (*es* or *en*).
id (int): Optional, ID of the POI to query. Passing value -1 will
result in informa... | [
"def",
"detail_poi",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'language'",
":",
"util",
".",
"language_code",
"(",
"kwargs",
".",
"get",
"(",
"'lang'",
")",
")",
",",
"'family'",
":",
"kwargs",
".",
... | 32.612903 | 20.741935 |
def gene_counts(self):
"""
Returns number of elements overlapping each gene name. Expects the
derived class (VariantCollection or EffectCollection) to have
an implementation of groupby_gene_name.
"""
return {
gene_name: len(group)
for (gene_name, g... | [
"def",
"gene_counts",
"(",
"self",
")",
":",
"return",
"{",
"gene_name",
":",
"len",
"(",
"group",
")",
"for",
"(",
"gene_name",
",",
"group",
")",
"in",
"self",
".",
"groupby_gene_name",
"(",
")",
".",
"items",
"(",
")",
"}"
] | 33.909091 | 14.818182 |
def _build_app_dict(site, request, label=None):
"""
Builds the app dictionary. Takes an optional label parameters to filter
models of a specific app.
"""
app_dict = {}
if label:
models = {
m: m_a for m, m_a in site._registry.items()
if m._meta.app_label == label
... | [
"def",
"_build_app_dict",
"(",
"site",
",",
"request",
",",
"label",
"=",
"None",
")",
":",
"app_dict",
"=",
"{",
"}",
"if",
"label",
":",
"models",
"=",
"{",
"m",
":",
"m_a",
"for",
"m",
",",
"m_a",
"in",
"site",
".",
"_registry",
".",
"items",
... | 31.359375 | 19.234375 |
def integerize(self):
"""Convert co-ordinate values to integers."""
self.x = int(round(self.x))
self.y = int(round(self.y)) | [
"def",
"integerize",
"(",
"self",
")",
":",
"self",
".",
"x",
"=",
"int",
"(",
"round",
"(",
"self",
".",
"x",
")",
")",
"self",
".",
"y",
"=",
"int",
"(",
"round",
"(",
"self",
".",
"y",
")",
")"
] | 36 | 7.25 |
def maybe_upcast_for_op(obj):
"""
Cast non-pandas objects to pandas types to unify behavior of arithmetic
and comparison operations.
Parameters
----------
obj: object
Returns
-------
out : object
Notes
-----
Be careful to call this *after* determining the `name` attrib... | [
"def",
"maybe_upcast_for_op",
"(",
"obj",
")",
":",
"if",
"type",
"(",
"obj",
")",
"is",
"datetime",
".",
"timedelta",
":",
"# GH#22390 cast up to Timedelta to rely on Timedelta",
"# implementation; otherwise operation against numeric-dtype",
"# raises TypeError",
"return",
... | 37.055556 | 22.333333 |
def do_toggle_play(self, action):
"""
Widget Action to toggle play / pause.
"""
# TODO - move this into bot controller
# along with stuff in socketserver and shell
if self.pause_speed is None and not action.get_active():
self.pause_speed = self.bot._speed
... | [
"def",
"do_toggle_play",
"(",
"self",
",",
"action",
")",
":",
"# TODO - move this into bot controller",
"# along with stuff in socketserver and shell",
"if",
"self",
".",
"pause_speed",
"is",
"None",
"and",
"not",
"action",
".",
"get_active",
"(",
")",
":",
"self",
... | 36.083333 | 8.916667 |
def addSection(self, section):
"""
Adds a section to this menu. A section will create a label for the
menu to separate sections of the menu out.
:param section | <str>
"""
label = QLabel(section, self)
label.setMinimumHeight(self.titleHeight... | [
"def",
"addSection",
"(",
"self",
",",
"section",
")",
":",
"label",
"=",
"QLabel",
"(",
"section",
",",
"self",
")",
"label",
".",
"setMinimumHeight",
"(",
"self",
".",
"titleHeight",
"(",
")",
")",
"# setup font\r",
"font",
"=",
"label",
".",
"font",
... | 29.551724 | 14.931034 |
def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | [
"def",
"reset_cmd_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cmd_timeout",
":",
"self",
".",
"_cmd_timeout",
".",
"cancel",
"(",
")",
"self",
".",
"_cmd_timeout",
"=",
"self",
".",
"loop",
".",
"call_later",
"(",
"self",
".",
"client",
".",
... | 47.333333 | 14 |
def get_current_args(caller_level = 0, func = None, argNames = None):
"""Determines the args of current function call.
Use caller_level > 0 to get args of even earlier function calls in current stack.
"""
if argNames is None:
argNames = getargnames(getargspecs(func))
if func is None:
... | [
"def",
"get_current_args",
"(",
"caller_level",
"=",
"0",
",",
"func",
"=",
"None",
",",
"argNames",
"=",
"None",
")",
":",
"if",
"argNames",
"is",
"None",
":",
"argNames",
"=",
"getargnames",
"(",
"getargspecs",
"(",
"func",
")",
")",
"if",
"func",
"i... | 43.307692 | 13.538462 |
def find(root: Union[Path, str], dirs: bool = True) -> str:
"""A test helper simulating 'find'.
Iterates over directories and filenames, given as relative paths to the
root.
"""
if isinstance(root, str):
root = Path(root)
results: List[Path] = []
for dirpath, dirnames, filenames i... | [
"def",
"find",
"(",
"root",
":",
"Union",
"[",
"Path",
",",
"str",
"]",
",",
"dirs",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"root",
",",
"str",
")",
":",
"root",
"=",
"Path",
"(",
"root",
")",
"results",
":",
... | 29.473684 | 20.210526 |
def importcsv(self):
''' import data from csv '''
csv_path = os.path.join(os.path.dirname(__file__), self.stock_no_files)
with open(csv_path) as csv_file:
csv_data = csv.reader(csv_file)
result = {}
for i in csv_data:
try:
r... | [
"def",
"importcsv",
"(",
"self",
")",
":",
"csv_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"self",
".",
"stock_no_files",
")",
"with",
"open",
"(",
"csv_path",
")",
"as",
"csv_file",... | 37.8 | 14.2 |
def cs_axis_mapping(cls,
part_info, # type: Dict[str, Optional[Sequence]]
axes_to_move # type: Sequence[str]
):
# type: (...) -> Tuple[str, Dict[str, MotorInfo]]
"""Given the motor infos for the parts, filter those with scannable
... | [
"def",
"cs_axis_mapping",
"(",
"cls",
",",
"part_info",
",",
"# type: Dict[str, Optional[Sequence]]",
"axes_to_move",
"# type: Sequence[str]",
")",
":",
"# type: (...) -> Tuple[str, Dict[str, MotorInfo]]",
"cs_ports",
"=",
"set",
"(",
")",
"# type: Set[str]",
"axis_mapping",
... | 54.833333 | 16.933333 |
def find_dependencies(self, dependent_rev, recurse=None):
"""Find all dependencies of the given revision, recursively traversing
the dependency tree if requested.
"""
if recurse is None:
recurse = self.options.recurse
try:
dependent = self.get_commit(depe... | [
"def",
"find_dependencies",
"(",
"self",
",",
"dependent_rev",
",",
"recurse",
"=",
"None",
")",
":",
"if",
"recurse",
"is",
"None",
":",
"recurse",
"=",
"self",
".",
"options",
".",
"recurse",
"try",
":",
"dependent",
"=",
"self",
".",
"get_commit",
"("... | 38.877551 | 17.836735 |
def _make_event(self, tv_sec, tv_usec, ev_type, code, value):
"""Create a friendly Python object from an evdev style event."""
event_type = self.manager.get_event_type(ev_type)
eventinfo = {
"ev_type": event_type,
"state": value,
"timestamp": tv_sec + (tv_usec... | [
"def",
"_make_event",
"(",
"self",
",",
"tv_sec",
",",
"tv_usec",
",",
"ev_type",
",",
"code",
",",
"value",
")",
":",
"event_type",
"=",
"self",
".",
"manager",
".",
"get_event_type",
"(",
"ev_type",
")",
"eventinfo",
"=",
"{",
"\"ev_type\"",
":",
"even... | 40.363636 | 17.272727 |
def img2img_transformer_base():
"""Base params for local1d attention."""
hparams = image_transformer2d_base()
# learning related flags
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
# This version seems to benefit from a higher learning rate.
hparams.learning_rate = 0.2
... | [
"def",
"img2img_transformer_base",
"(",
")",
":",
"hparams",
"=",
"image_transformer2d_base",
"(",
")",
"# learning related flags",
"hparams",
".",
"layer_preprocess_sequence",
"=",
"\"n\"",
"hparams",
".",
"layer_postprocess_sequence",
"=",
"\"da\"",
"# This version seems ... | 36.388889 | 9.388889 |
def default_role(self):
"""Gets the @everyone role that all members have by default."""
return utils.find(lambda r: r.is_default(), self._roles.values()) | [
"def",
"default_role",
"(",
"self",
")",
":",
"return",
"utils",
".",
"find",
"(",
"lambda",
"r",
":",
"r",
".",
"is_default",
"(",
")",
",",
"self",
".",
"_roles",
".",
"values",
"(",
")",
")"
] | 55.666667 | 16.666667 |
def load(self, config):
"""load the configuration"""
self.config = config
if 'start' not in self.config:
raise ParseError('missing start entry')
if 'states' not in self.config:
raise ParseError('missing states entry')
if 'transitions' not in self.... | [
"def",
"load",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"config",
"=",
"config",
"if",
"'start'",
"not",
"in",
"self",
".",
"config",
":",
"raise",
"ParseError",
"(",
"'missing start entry'",
")",
"if",
"'states'",
"not",
"in",
"self",
".",
"... | 38.929825 | 14.649123 |
def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None):
"""
Live template for pycharm:
y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$desc$", link="$lnk$", params_string="$first_param$")
"""
init_description_w_tabs = description.strip().replace("\... | [
"def",
"clazz",
"(",
"clazz",
",",
"parent_clazz",
",",
"description",
",",
"link",
",",
"params_string",
",",
"init_super_args",
"=",
"None",
")",
":",
"init_description_w_tabs",
"=",
"description",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"\"\\n\"",
",... | 52.364486 | 28.439252 |
def find_bridges(prior_bridges=None):
""" Confirm or locate IP addresses of Philips Hue bridges.
`prior_bridges` -- optional list of bridge serial numbers
* omitted - all discovered bridges returned as dictionary
* single string - returns IP as string or None
* dictionary - validate provided ip's b... | [
"def",
"find_bridges",
"(",
"prior_bridges",
"=",
"None",
")",
":",
"found_bridges",
"=",
"{",
"}",
"# Validate caller's provided list",
"try",
":",
"prior_bridges_list",
"=",
"prior_bridges",
".",
"items",
"(",
")",
"except",
"AttributeError",
":",
"# if caller did... | 39.691489 | 19.297872 |
def entropy_H(self, data):
"""Calculate the entropy of a chunk of data."""
if len(data) == 0:
return 0.0
occurences = array.array('L', [0]*256)
for x in data:
occurences[ord(x)] += 1
entropy = 0
for x in occurenc... | [
"def",
"entropy_H",
"(",
"self",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"0.0",
"occurences",
"=",
"array",
".",
"array",
"(",
"'L'",
",",
"[",
"0",
"]",
"*",
"256",
")",
"for",
"x",
"in",
"data",
":",
... | 24.833333 | 17.666667 |
def xml(self, indent = ""):
"""Produce XML output for the profile"""
xml = "\n" + indent + "<profile>\n"
xml += indent + " <input>\n"
for inputtemplate in self.input:
xml += inputtemplate.xml(indent +" ") + "\n"
xml += indent + " </input>\n"
xml += indent +... | [
"def",
"xml",
"(",
"self",
",",
"indent",
"=",
"\"\"",
")",
":",
"xml",
"=",
"\"\\n\"",
"+",
"indent",
"+",
"\"<profile>\\n\"",
"xml",
"+=",
"indent",
"+",
"\" <input>\\n\"",
"for",
"inputtemplate",
"in",
"self",
".",
"input",
":",
"xml",
"+=",
"inputtem... | 43.230769 | 10.153846 |
def enable_data_link(self, instance, link):
"""
Enables a data link.
:param str instance: A Yamcs instance name.
:param str link: The name of the data link.
"""
req = rest_pb2.EditLinkRequest()
req.state = 'enabled'
url = '/links/{}/{}'.format(instance, l... | [
"def",
"enable_data_link",
"(",
"self",
",",
"instance",
",",
"link",
")",
":",
"req",
"=",
"rest_pb2",
".",
"EditLinkRequest",
"(",
")",
"req",
".",
"state",
"=",
"'enabled'",
"url",
"=",
"'/links/{}/{}'",
".",
"format",
"(",
"instance",
",",
"link",
")... | 34 | 10.727273 |
def mark_module_reloadable(self, module_name):
"""Reload the named module in the future (if it is imported)"""
try:
del self.skip_modules[module_name]
except KeyError:
pass
self.modules[module_name] = True | [
"def",
"mark_module_reloadable",
"(",
"self",
",",
"module_name",
")",
":",
"try",
":",
"del",
"self",
".",
"skip_modules",
"[",
"module_name",
"]",
"except",
"KeyError",
":",
"pass",
"self",
".",
"modules",
"[",
"module_name",
"]",
"=",
"True"
] | 36.428571 | 11.428571 |
def act(self):
"""
Carries out the action associated with the Save button
"""
g = get_root(self).globals
g.clog.info('\nSaving current application to disk')
# check instrument parameters
if not g.ipars.check():
g.clog.warn('Invalid instrument paramete... | [
"def",
"act",
"(",
"self",
")",
":",
"g",
"=",
"get_root",
"(",
"self",
")",
".",
"globals",
"g",
".",
"clog",
".",
"info",
"(",
"'\\nSaving current application to disk'",
")",
"# check instrument parameters",
"if",
"not",
"g",
".",
"ipars",
".",
"check",
... | 27.735294 | 16.794118 |
def parse_sitelist(sitelist):
"""Return list of Site instances from retrieved sitelist data"""
sites = []
for site in sitelist["Locations"]["Location"]:
try:
ident = site["id"]
name = site["name"]
except KeyError:
ident = site["@id"] # Difference between l... | [
"def",
"parse_sitelist",
"(",
"sitelist",
")",
":",
"sites",
"=",
"[",
"]",
"for",
"site",
"in",
"sitelist",
"[",
"\"Locations\"",
"]",
"[",
"\"Location\"",
"]",
":",
"try",
":",
"ident",
"=",
"site",
"[",
"\"id\"",
"]",
"name",
"=",
"site",
"[",
"\"... | 33.777778 | 14.333333 |
def from_jd(jd):
'''Calculate Bahai date from Julian day'''
jd = trunc(jd) + 0.5
g = gregorian.from_jd(jd)
gy = g[0]
bstarty = EPOCH_GREGORIAN_YEAR
if jd <= gregorian.to_jd(gy, 3, 20):
x = 1
else:
x = 0
# verify this next line...
bys = gy - (bstarty + (((gregorian.... | [
"def",
"from_jd",
"(",
"jd",
")",
":",
"jd",
"=",
"trunc",
"(",
"jd",
")",
"+",
"0.5",
"g",
"=",
"gregorian",
".",
"from_jd",
"(",
"jd",
")",
"gy",
"=",
"g",
"[",
"0",
"]",
"bstarty",
"=",
"EPOCH_GREGORIAN_YEAR",
"if",
"jd",
"<=",
"gregorian",
".... | 21.111111 | 22.074074 |
def visit_Assign(self, node, **kwargs):
"""Visit assignments in the correct order."""
self.visit(node.node, **kwargs)
self.visit(node.target, **kwargs) | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"node",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"visit",
"(",
"node",
".",
"target",
",",
"*",
"*",
"kwargs",
")"
] | 43 | 0.75 |
def ipaddress(not_valid=None):
"""
returns a string representing a random ip address
:param not_valid: if passed must be a list of integers representing valid class A netoworks that must be ignored
"""
not_valid_class_A = not_valid or []
class_a = [r for r in range(1, 256) if r not in not_... | [
"def",
"ipaddress",
"(",
"not_valid",
"=",
"None",
")",
":",
"not_valid_class_A",
"=",
"not_valid",
"or",
"[",
"]",
"class_a",
"=",
"[",
"r",
"for",
"r",
"in",
"range",
"(",
"1",
",",
"256",
")",
"if",
"r",
"not",
"in",
"not_valid_class_A",
"]",
"shu... | 35.428571 | 23.857143 |
def _on_notification(self, name, args):
"""Handle a msgpack-rpc notification."""
if IS_PYTHON3:
name = decode_if_bytes(name)
handler = self._notification_handlers.get(name, None)
if not handler:
msg = self._missing_handler_error(name, 'notification')
e... | [
"def",
"_on_notification",
"(",
"self",
",",
"name",
",",
"args",
")",
":",
"if",
"IS_PYTHON3",
":",
"name",
"=",
"decode_if_bytes",
"(",
"name",
")",
"handler",
"=",
"self",
".",
"_notification_handlers",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",... | 37.076923 | 17.076923 |
def get_filename(self, tag):
'''Extract and return a documentation filename from a tag.
Override as necessary, though this default implementation probably
covers all the cases of interest.
Args:
tag: A BeautifulSoup Tag that satisfies match_criterion.
Returns:
... | [
"def",
"get_filename",
"(",
"self",
",",
"tag",
")",
":",
"if",
"tag",
".",
"find",
"(",
"'filename'",
",",
"recursive",
"=",
"False",
")",
"is",
"not",
"None",
":",
"return",
"tag",
".",
"filename",
".",
"contents",
"[",
"0",
"]",
"elif",
"tag",
"... | 40.529412 | 25.470588 |
def deploy_and_set_registry(self) -> Address:
"""
Returns the address of a freshly deployed instance of the `vyper registry
<https://github.com/ethpm/py-ethpm/blob/master/ethpm/assets/vyper_registry/registry.vy>`__,
and sets the newly deployed registry as the active registry on ``web3.pm... | [
"def",
"deploy_and_set_registry",
"(",
"self",
")",
"->",
"Address",
":",
"self",
".",
"registry",
"=",
"VyperReferenceRegistry",
".",
"deploy_new_instance",
"(",
"self",
".",
"web3",
")",
"return",
"to_checksum_address",
"(",
"self",
".",
"registry",
".",
"addr... | 45.642857 | 28.357143 |
def import_list(
self,
listName,
pathToTaskpaperDoc
):
"""
*import tasks from a reminder.app list into a given taskpaper document*
**Key Arguments:**
- ``listName`` -- the name of the reminders list
- ``pathToTaskpaperDoc`` -- the path to the ... | [
"def",
"import_list",
"(",
"self",
",",
"listName",
",",
"pathToTaskpaperDoc",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``import_list`` method'",
")",
"newTasks",
"=",
"self",
".",
"_get_tasks_from_reminder_list",
"(",
"listName",
")",
"self"... | 34.486486 | 29.513514 |
def load_raw_arrays(self, fields, start_dt, end_dt, sids):
"""
Parameters
----------
fields : list of str
'open', 'high', 'low', 'close', or 'volume'
start_dt: Timestamp
Beginning of the window range.
end_dt: Timestamp
End of the window ra... | [
"def",
"load_raw_arrays",
"(",
"self",
",",
"fields",
",",
"start_dt",
",",
"end_dt",
",",
"sids",
")",
":",
"start_idx",
"=",
"self",
".",
"_find_position_of_minute",
"(",
"start_dt",
")",
"end_idx",
"=",
"self",
".",
"_find_position_of_minute",
"(",
"end_dt"... | 36.741935 | 18.870968 |
def runtime_spec(self, id):
"""
id is a string describing the runtime, e.g 'flashgames
Returns a configured DockerRuntime object
"""
try:
return self.runtimes[id]
except KeyError:
raise UnregisteredRuntime('No registered runtime with name: {}'.for... | [
"def",
"runtime_spec",
"(",
"self",
",",
"id",
")",
":",
"try",
":",
"return",
"self",
".",
"runtimes",
"[",
"id",
"]",
"except",
"KeyError",
":",
"raise",
"UnregisteredRuntime",
"(",
"'No registered runtime with name: {}'",
".",
"format",
"(",
"id",
")",
")... | 31.9 | 17.9 |
def _set_linkinfo_isllink_srcport_type(self, v, load=False):
"""
Setter method for linkinfo_isllink_srcport_type, mapped from YANG variable /brocade_fabric_service_rpc/show_linkinfo/output/show_link_info/linkinfo_isl/linkinfo_isllink_srcport_type (interfacetype-type)
If this variable is read-only (config: f... | [
"def",
"_set_linkinfo_isllink_srcport_type",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
... | 81.703704 | 41.074074 |
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will... | [
"def",
"_read",
"(",
"self",
",",
"stream",
",",
"text",
",",
"byte_order",
")",
":",
"dtype",
"=",
"self",
".",
"dtype",
"(",
"byte_order",
")",
"if",
"text",
":",
"self",
".",
"_read_txt",
"(",
"stream",
")",
"elif",
"_can_mmap",
"(",
"stream",
")"... | 38.407407 | 15.888889 |
def thread_function(self):
"""Thread function."""
self.__subscribed = True
url = SUBSCRIBE_ENDPOINT + "?token=" + self._session_token
data = self._session.query(url, method='GET', raw=True, stream=True)
if not data or not data.ok:
_LOGGER.debug("Did not receive a va... | [
"def",
"thread_function",
"(",
"self",
")",
":",
"self",
".",
"__subscribed",
"=",
"True",
"url",
"=",
"SUBSCRIBE_ENDPOINT",
"+",
"\"?token=\"",
"+",
"self",
".",
"_session_token",
"data",
"=",
"self",
".",
"_session",
".",
"query",
"(",
"url",
",",
"metho... | 37.833333 | 19.333333 |
def get_true_longitude_variables(nc):
'''
Returns a list of variables defining true longitude.
CF Chapter 4 refers to longitude as a coordinate variable that can also be
used in non-standard coordinate systems like rotated pole and other
projections. Chapter 5 refers to a concept of true longitude ... | [
"def",
"get_true_longitude_variables",
"(",
"nc",
")",
":",
"lons",
"=",
"get_longitude_variables",
"(",
"nc",
")",
"true_lons",
"=",
"[",
"]",
"for",
"lon",
"in",
"lons",
":",
"standard_name",
"=",
"getattr",
"(",
"nc",
".",
"variables",
"[",
"lon",
"]",
... | 41.416667 | 23.666667 |
def hex(self):
"""Return a hexadecimal representation of a BigFloat."""
sign = '-' if self._sign() else ''
e = self._exponent()
if isinstance(e, six.string_types):
return sign + e
m = self._significand()
_, digits, _ = _mpfr_get_str2(
16,
... | [
"def",
"hex",
"(",
"self",
")",
":",
"sign",
"=",
"'-'",
"if",
"self",
".",
"_sign",
"(",
")",
"else",
"''",
"e",
"=",
"self",
".",
"_exponent",
"(",
")",
"if",
"isinstance",
"(",
"e",
",",
"six",
".",
"string_types",
")",
":",
"return",
"sign",
... | 30.2 | 16.8 |
def createuser(self, email, name='', password=''):
"""
Return a bugzilla User for the given username
:arg email: The email address to use in bugzilla
:kwarg name: Real name to associate with the account
:kwarg password: Password to set for the bugzilla account
:raises XM... | [
"def",
"createuser",
"(",
"self",
",",
"email",
",",
"name",
"=",
"''",
",",
"password",
"=",
"''",
")",
":",
"self",
".",
"_proxy",
".",
"User",
".",
"create",
"(",
"email",
",",
"name",
",",
"password",
")",
"return",
"self",
".",
"getuser",
"(",... | 43.866667 | 13.866667 |
def get_options(argv):
"""Called to parse the given list as command-line arguments.
:returns:
an options object as returned by argparse.
"""
arg_parser = make_arg_parser()
options, unknown = arg_parser.parse_known_args(argv)
if unknown:
arg_parser.print_help()
raise exce... | [
"def",
"get_options",
"(",
"argv",
")",
":",
"arg_parser",
"=",
"make_arg_parser",
"(",
")",
"options",
",",
"unknown",
"=",
"arg_parser",
".",
"parse_known_args",
"(",
"argv",
")",
"if",
"unknown",
":",
"arg_parser",
".",
"print_help",
"(",
")",
"raise",
... | 32 | 13.642857 |
def match_request(self) -> None:
"""Match the request against the adapter.
Override this method to configure request matching, it should
set the request url_rule and view_args and optionally a
routing_exception.
"""
try:
self.request_websocket.url_rule, self.... | [
"def",
"match_request",
"(",
"self",
")",
"->",
"None",
":",
"try",
":",
"self",
".",
"request_websocket",
".",
"url_rule",
",",
"self",
".",
"request_websocket",
".",
"view_args",
"=",
"self",
".",
"url_adapter",
".",
"match",
"(",
")",
"# noqa",
"except"... | 45.909091 | 24.090909 |
def to_python(self, value):
"""
Validates that the input can be converted to a time. Returns a
Python datetime.time object.
"""
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value.time()
if... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"validators",
".",
"EMPTY_VALUES",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"time",
"(",
"... | 34.823529 | 16.470588 |
def present(name, owner=None, grants=None, **kwargs):
'''
Ensure that the named database is present with the specified options
name
The name of the database to manage
owner
Adds owner using AUTHORIZATION option
Grants
Can only be a list of strings
'''
ret = {'name': ... | [
"def",
"present",
"(",
"name",
",",
"owner",
"=",
"None",
",",
"grants",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",... | 36.21875 | 26.03125 |
def build(self, obj=None, queryset=None, push=True):
"""Trigger building of the indexes.
Support passing ``obj`` parameter to the indexes, so we can
trigger build only for one object.
"""
for index in self.indexes:
index.build(obj, queryset, push) | [
"def",
"build",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"queryset",
"=",
"None",
",",
"push",
"=",
"True",
")",
":",
"for",
"index",
"in",
"self",
".",
"indexes",
":",
"index",
".",
"build",
"(",
"obj",
",",
"queryset",
",",
"push",
")"
] | 36.625 | 11.375 |
def interpolate(self):
"""Do the interpolation and return resulting longitudes and latitudes.
"""
self.latitude = self._interp(self.lat_tiepoint)
self.longitude = self._interp(self.lon_tiepoint)
return self.latitude, self.longitude | [
"def",
"interpolate",
"(",
"self",
")",
":",
"self",
".",
"latitude",
"=",
"self",
".",
"_interp",
"(",
"self",
".",
"lat_tiepoint",
")",
"self",
".",
"longitude",
"=",
"self",
".",
"_interp",
"(",
"self",
".",
"lon_tiepoint",
")",
"return",
"self",
".... | 38 | 13.285714 |
def grab_bulbs(host, token=None):
"""Grab XML, then add all bulbs to a dict. Removes room functionality"""
xml = grab_xml(host, token)
bulbs = {}
for room in xml:
for device in room['device']:
bulbs[int(device['did'])] = device
return bulbs | [
"def",
"grab_bulbs",
"(",
"host",
",",
"token",
"=",
"None",
")",
":",
"xml",
"=",
"grab_xml",
"(",
"host",
",",
"token",
")",
"bulbs",
"=",
"{",
"}",
"for",
"room",
"in",
"xml",
":",
"for",
"device",
"in",
"room",
"[",
"'device'",
"]",
":",
"bul... | 34.125 | 11.875 |
def string_for_count(dictionary, count):
"""Create a random string of N=`count` words"""
string_to_print = ""
if count is not None:
if count == 0:
return ""
ranger = count
else:
ranger = 2
for index in range(ranger):
string_to_print += "{} ".format(get_ran... | [
"def",
"string_for_count",
"(",
"dictionary",
",",
"count",
")",
":",
"string_to_print",
"=",
"\"\"",
"if",
"count",
"is",
"not",
"None",
":",
"if",
"count",
"==",
"0",
":",
"return",
"\"\"",
"ranger",
"=",
"count",
"else",
":",
"ranger",
"=",
"2",
"fo... | 28.076923 | 17.076923 |
def DeregisterDefinition(self, artifact_definition):
"""Deregisters an artifact definition.
Artifact definitions are identified based on their lower case name.
Args:
artifact_definition (ArtifactDefinition): an artifact definition.
Raises:
KeyError: if an artifact definition is not set fo... | [
"def",
"DeregisterDefinition",
"(",
"self",
",",
"artifact_definition",
")",
":",
"artifact_definition_name",
"=",
"artifact_definition",
".",
"name",
".",
"lower",
"(",
")",
"if",
"artifact_definition_name",
"not",
"in",
"self",
".",
"_artifact_definitions",
":",
"... | 36.5 | 24.777778 |
def extract_keywords(self, sentence, span_info=False):
"""Searches in the string for all keywords present in corpus.
Keywords present are added to a list `keywords_extracted` and returned.
Args:
sentence (str): Line of text where we will search for keywords
Returns:
... | [
"def",
"extract_keywords",
"(",
"self",
",",
"sentence",
",",
"span_info",
"=",
"False",
")",
":",
"keywords_extracted",
"=",
"[",
"]",
"if",
"not",
"sentence",
":",
"# if sentence is empty or none just return empty list",
"return",
"keywords_extracted",
"if",
"not",
... | 46.348624 | 18.165138 |
def conditional_http_tween_factory(handler, registry):
"""
Tween that adds ETag headers and tells Pyramid to enable
conditional responses where appropriate.
"""
settings = registry.settings if hasattr(registry, 'settings') else {}
not_cacheble_list = []
if 'not.cachable.list' in settings:
... | [
"def",
"conditional_http_tween_factory",
"(",
"handler",
",",
"registry",
")",
":",
"settings",
"=",
"registry",
".",
"settings",
"if",
"hasattr",
"(",
"registry",
",",
"'settings'",
")",
"else",
"{",
"}",
"not_cacheble_list",
"=",
"[",
"]",
"if",
"'not.cachab... | 40.363636 | 19.878788 |
def start_auth(self, context, internal_req):
"""
See super class method satosa.backends.base.BackendModule#start_auth
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.Response
"""
target_entity_id = co... | [
"def",
"start_auth",
"(",
"self",
",",
"context",
",",
"internal_req",
")",
":",
"target_entity_id",
"=",
"context",
".",
"get_decoration",
"(",
"Context",
".",
"KEY_TARGET_ENTITYID",
")",
"if",
"target_entity_id",
":",
"entity_id",
"=",
"target_entity_id",
"retur... | 40.95 | 18.65 |
def interface_by_macaddr(self, macaddr):
'''
Given a MAC address, return the interface that 'owns' this address
'''
macaddr = EthAddr(macaddr)
for devname,iface in self._devinfo.items():
if iface.ethaddr == macaddr:
return iface
raise KeyError(... | [
"def",
"interface_by_macaddr",
"(",
"self",
",",
"macaddr",
")",
":",
"macaddr",
"=",
"EthAddr",
"(",
"macaddr",
")",
"for",
"devname",
",",
"iface",
"in",
"self",
".",
"_devinfo",
".",
"items",
"(",
")",
":",
"if",
"iface",
".",
"ethaddr",
"==",
"maca... | 39.888889 | 16.777778 |
def system_monitor_mail_fru_email_list_email(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor_mail = ET.SubElement(config, "system-monitor-mail", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
fru = ET.SubElement(system_monitor_mail, ... | [
"def",
"system_monitor_mail_fru_email_list_email",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"system_monitor_mail",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"system-monitor-mail\"",
",... | 46 | 17.916667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.