text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def text_fd_to_metric_families(fd):
"""Parse Prometheus text format from a file descriptor.
This is a laxer parser than the main Go parser,
so successful parsing does not imply that the parsed
text meets the specification.
Yields Metric's.
"""
name = None
allowed_names = []
eof = F... | [
"def",
"text_fd_to_metric_families",
"(",
"fd",
")",
":",
"name",
"=",
"None",
"allowed_names",
"=",
"[",
"]",
"eof",
"=",
"False",
"seen_metrics",
"=",
"set",
"(",
")",
"def",
"build_metric",
"(",
"name",
",",
"documentation",
",",
"typ",
",",
"unit",
"... | 44.45122 | 20.95122 |
def find_jobs(self, job_ids):
"""Finds the jobs in the completed job queue."""
matched_jobs = []
if self.skip:
return matched_jobs
json_data = self.download_queue(job_ids)
if not json_data:
return matched_jobs
jobs = json_data["jobs"]
for... | [
"def",
"find_jobs",
"(",
"self",
",",
"job_ids",
")",
":",
"matched_jobs",
"=",
"[",
"]",
"if",
"self",
".",
"skip",
":",
"return",
"matched_jobs",
"json_data",
"=",
"self",
".",
"download_queue",
"(",
"job_ids",
")",
"if",
"not",
"json_data",
":",
"retu... | 28.315789 | 17.473684 |
def visit_while(self, node, parent):
"""visit a While node by returning a fresh instance of it"""
newnode = nodes.While(node.lineno, node.col_offset, parent)
newnode.postinit(
self.visit(node.test, newnode),
[self.visit(child, newnode) for child in node.body],
... | [
"def",
"visit_while",
"(",
"self",
",",
"node",
",",
"parent",
")",
":",
"newnode",
"=",
"nodes",
".",
"While",
"(",
"node",
".",
"lineno",
",",
"node",
".",
"col_offset",
",",
"parent",
")",
"newnode",
".",
"postinit",
"(",
"self",
".",
"visit",
"("... | 44.444444 | 16.444444 |
def request(self, url, method='GET', params=None, data=None,
expected_response_code=200, headers=None):
"""Make a HTTP request to the InfluxDB API.
:param url: the path of the HTTP request, e.g. write, query, etc.
:type url: str
:param method: the HTTP method for the req... | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"expected_response_code",
"=",
"200",
",",
"headers",
"=",
"None",
")",
":",
"url",
"=",
"\"{0}/{1}\"",
".",
"format",
... | 39.318841 | 17.086957 |
def _check_pattern_list(patterns, key, default=None):
"""Validates file search patterns from user configuration.
Acceptable input is a string (which will be converted to a singleton list),
a list of strings, or anything falsy (such as None or an empty dictionary).
Empty or unset input will be converted... | [
"def",
"_check_pattern_list",
"(",
"patterns",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"patterns",
":",
"return",
"default",
"if",
"isinstance",
"(",
"patterns",
",",
"basestring",
")",
":",
"return",
"[",
"patterns",
"]",
"if",
"... | 32.515152 | 23.333333 |
def process_utterance_online(self, utterance, frame_size=400, hop_size=160, chunk_size=1,
buffer_size=5760000, corpus=None):
"""
Process the utterance in **online** mode, chunk by chunk.
The processed chunks are yielded one after another.
Args:
... | [
"def",
"process_utterance_online",
"(",
"self",
",",
"utterance",
",",
"frame_size",
"=",
"400",
",",
"hop_size",
"=",
"160",
",",
"chunk_size",
"=",
"1",
",",
"buffer_size",
"=",
"5760000",
",",
"corpus",
"=",
"None",
")",
":",
"return",
"self",
".",
"p... | 56.464286 | 27.892857 |
def deepcopy_strip(item): # type: (Any) -> Any
"""
Make a deep copy of list and dict objects.
Intentionally do not copy attributes. This is to discard CommentedMap and
CommentedSeq metadata which is very expensive with regular copy.deepcopy.
"""
if isinstance(item, MutableMapping):
r... | [
"def",
"deepcopy_strip",
"(",
"item",
")",
":",
"# type: (Any) -> Any",
"if",
"isinstance",
"(",
"item",
",",
"MutableMapping",
")",
":",
"return",
"{",
"k",
":",
"deepcopy_strip",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"item",
")",... | 36.230769 | 17.461538 |
def add_default_name(text):
"""
Go through each line of the text and ensure that
a name is defined. Use '@' if there is none.
"""
global SUPPORTED_RECORDS
lines = text.split("\n")
ret = []
for line in lines:
tokens = tokenize_line(line)
if len(tokens) == 0:
... | [
"def",
"add_default_name",
"(",
"text",
")",
":",
"global",
"SUPPORTED_RECORDS",
"lines",
"=",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
"ret",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"tokens",
"=",
"tokenize_line",
"(",
"line",
")",
"if",
"... | 24.857143 | 17.52381 |
def create_filters(predicate_params, predicate_factory):
"""Create filter functions from a list of string parameters.
:param predicate_params: A list of predicate_param arguments as in `create_filter`.
:param predicate_factory: As in `create_filter`.
"""
filters = []
for predicate_param in predicate_params... | [
"def",
"create_filters",
"(",
"predicate_params",
",",
"predicate_factory",
")",
":",
"filters",
"=",
"[",
"]",
"for",
"predicate_param",
"in",
"predicate_params",
":",
"filters",
".",
"append",
"(",
"create_filter",
"(",
"predicate_param",
",",
"predicate_factory",... | 39.9 | 19.2 |
def _nodedev_event_update_cb(conn, dev, opaque):
'''
Node device update events handler
'''
_salt_send_event(opaque, conn, {
'nodedev': {
'name': dev.name()
},
'event': opaque['event']
}) | [
"def",
"_nodedev_event_update_cb",
"(",
"conn",
",",
"dev",
",",
"opaque",
")",
":",
"_salt_send_event",
"(",
"opaque",
",",
"conn",
",",
"{",
"'nodedev'",
":",
"{",
"'name'",
":",
"dev",
".",
"name",
"(",
")",
"}",
",",
"'event'",
":",
"opaque",
"[",
... | 23.3 | 18.3 |
def deconv2d(self, filter_size, output_channels, stride=1, padding='SAME', activation_fn=tf.nn.relu, b_value=0.0,
s_value=1.0, bn=True, trainable=True):
"""
2D Deconvolutional Layer
:param filter_size: int. assumes square filter
:param output_channels: int
:param... | [
"def",
"deconv2d",
"(",
"self",
",",
"filter_size",
",",
"output_channels",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
",",
"activation_fn",
"=",
"tf",
".",
"nn",
".",
"relu",
",",
"b_value",
"=",
"0.0",
",",
"s_value",
"=",
"1.0",
",",
... | 50.130435 | 21.652174 |
def body_encode(s, maxlinelen=76, eol=NL):
r"""Encode a string with base64.
Each line will be wrapped at, at most, maxlinelen characters (defaults to
76 characters).
Each line of encoded text will end with eol, which defaults to "\n". Set
this to "\r\n" if you will be using the result of this fun... | [
"def",
"body_encode",
"(",
"s",
",",
"maxlinelen",
"=",
"76",
",",
"eol",
"=",
"NL",
")",
":",
"if",
"not",
"s",
":",
"return",
"s",
"encvec",
"=",
"[",
"]",
"max_unencoded",
"=",
"maxlinelen",
"*",
"3",
"//",
"4",
"for",
"i",
"in",
"range",
"(",... | 34.73913 | 19.73913 |
def has(self, url, xpath=None):
"""Check if a URL (and xpath) exists in the cache
If DB has not been initialized yet, returns ``False`` for any URL.
Args:
url (str): If given, clear specific item only. Otherwise remove the DB file.
xpath (str): xpath to search (may be `... | [
"def",
"has",
"(",
"self",
",",
"url",
",",
"xpath",
"=",
"None",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"self",
".",
"db_path",
")",
":",
"return",
"False",
"return",
"self",
".",
"_query",
"(",
"url",
",",
"xpath",
")",
".",
"count"... | 32.75 | 23 |
def find_one_and_replace(self, filter, replacement, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace
"""
self._arctic_lib.check_quota()
return self._collection.find_one_and_replace(filter, repl... | [
"def",
"find_one_and_replace",
"(",
"self",
",",
"filter",
",",
"replacement",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_arctic_lib",
".",
"check_quota",
"(",
")",
"return",
"self",
".",
"_collection",
".",
"find_one_and_replace",
"(",
"filter",
",",... | 55.5 | 25.833333 |
def do_not_disturb(self):
"""Get if do not disturb is enabled."""
return bool(strtobool(str(self._settings_json.get(
CONST.SETTINGS_DO_NOT_DISTURB)))) | [
"def",
"do_not_disturb",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"strtobool",
"(",
"str",
"(",
"self",
".",
"_settings_json",
".",
"get",
"(",
"CONST",
".",
"SETTINGS_DO_NOT_DISTURB",
")",
")",
")",
")"
] | 43.75 | 9.5 |
def isConnected(self):
"""
Returns whether or not this connection is currently
active.
:return <bool> connected
"""
for pool in self.__pool.values():
if not pool.empty():
return True
return False | [
"def",
"isConnected",
"(",
"self",
")",
":",
"for",
"pool",
"in",
"self",
".",
"__pool",
".",
"values",
"(",
")",
":",
"if",
"not",
"pool",
".",
"empty",
"(",
")",
":",
"return",
"True",
"return",
"False"
] | 24.909091 | 13.454545 |
def create_datastore_from_yaml_schema(self, yaml_path, delete_first=0,
path=None):
# type: (str, Optional[int], Optional[str]) -> None
"""For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a YAML file
containi... | [
"def",
"create_datastore_from_yaml_schema",
"(",
"self",
",",
"yaml_path",
",",
"delete_first",
"=",
"0",
",",
"path",
"=",
"None",
")",
":",
"# type: (str, Optional[int], Optional[str]) -> None",
"data",
"=",
"load_yaml",
"(",
"yaml_path",
")",
"self",
".",
"create... | 57.941176 | 33.882353 |
def separable_convolution(input, weights, output=None, mode="reflect", cval=0.0, origin=0):
r"""
Calculate a n-dimensional convolution of a separable kernel to a n-dimensional input.
Achieved by calling convolution1d along the first axis, obtaining an intermediate
image, on which the next convoluti... | [
"def",
"separable_convolution",
"(",
"input",
",",
"weights",
",",
"output",
"=",
"None",
",",
"mode",
"=",
"\"reflect\"",
",",
"cval",
"=",
"0.0",
",",
"origin",
"=",
"0",
")",
":",
"input",
"=",
"numpy",
".",
"asarray",
"(",
"input",
")",
"output",
... | 38.619048 | 22.452381 |
def _token_to_ids(self, token):
"""Convert a single token to a list of integer ids."""
# Check cache
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._token_to_ids_cache[cache_location]
if cache_key == token:
return cache_value
subwords = self._token_to_subwor... | [
"def",
"_token_to_ids",
"(",
"self",
",",
"token",
")",
":",
"# Check cache",
"cache_location",
"=",
"hash",
"(",
"token",
")",
"%",
"self",
".",
"_cache_size",
"cache_key",
",",
"cache_value",
"=",
"self",
".",
"_token_to_ids_cache",
"[",
"cache_location",
"]... | 29.96 | 18.36 |
def network_interface_get_effective_route_table(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get all route tables for a specific network interface.
:param name: The name of the network interface to query.
:param resource_group: The resource group name assigned to the
ne... | [
"def",
"network_interface_get_effective_route_table",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"nic",
"=",... | 29.727273 | 26.030303 |
def estimate_allele_frequency(ac, an, a=1, b=100):
"""
Make sample (or other) names.
Parameters:
-----------
ac : array-like
Array-like object with the observed allele counts for each variant. If
ac is a pandas Series, the output dataframe will have the same index as
ac.
... | [
"def",
"estimate_allele_frequency",
"(",
"ac",
",",
"an",
",",
"a",
"=",
"1",
",",
"b",
"=",
"100",
")",
":",
"# Credible interval is 95% highest posterior density",
"td",
"=",
"dict",
"(",
"zip",
"(",
"[",
"'ci_lower'",
",",
"'ci_upper'",
"]",
",",
"stats",... | 29.055556 | 23.333333 |
def getmetadata(self, key=None):
"""Get the metadata that applies to this element, automatically inherited from parent elements"""
if self.metadata:
d = self.doc.submetadata[self.metadata]
elif self.parent:
d = self.parent.getmetadata()
elif self.doc:
... | [
"def",
"getmetadata",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"self",
".",
"metadata",
":",
"d",
"=",
"self",
".",
"doc",
".",
"submetadata",
"[",
"self",
".",
"metadata",
"]",
"elif",
"self",
".",
"parent",
":",
"d",
"=",
"self",
"... | 31.857143 | 14.785714 |
def ge(self, other, axis="columns", level=None):
"""Checks element-wise that this is greater than or equal to other.
Args:
other: A DataFrame or Series or scalar to compare to.
axis: The axis to perform the gt over.
level: The Multilevel index level to apply gt... | [
"def",
"ge",
"(",
"self",
",",
"other",
",",
"axis",
"=",
"\"columns\"",
",",
"level",
"=",
"None",
")",
":",
"return",
"self",
".",
"_binary_op",
"(",
"\"ge\"",
",",
"other",
",",
"axis",
"=",
"axis",
",",
"level",
"=",
"level",
")"
] | 39 | 19.5 |
def args(**kwargs):
""" allows us to temporarily override all the special keyword parameters in
a with context """
kwargs_str = ",".join(["%s=%r" % (k,v) for k,v in kwargs.items()])
raise DeprecationWarning("""
sh.args() has been deprecated because it was never thread safe. use the
following instead... | [
"def",
"args",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs_str",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"%s=%r\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"]",
")",
"raise",
"DeprecationWarning",... | 21.904762 | 24.142857 |
def setup_hds(self):
""" setup modflow head save file observations for given kper (zero-based
stress period index) and k (zero-based layer index) pairs using the
kperk argument.
Note
----
this can setup a shit-ton of observations
this is useful for dataw... | [
"def",
"setup_hds",
"(",
"self",
")",
":",
"if",
"self",
".",
"hds_kperk",
"is",
"None",
"or",
"len",
"(",
"self",
".",
"hds_kperk",
")",
"==",
"0",
":",
"return",
"from",
".",
"gw_utils",
"import",
"setup_hds_obs",
"# if len(self.hds_kperk) == 2:",
"# t... | 39.68 | 20.38 |
def count(self):
"""Total count of the matching items.
It sums up the count of partial results, and returns the total count of
matching items in the table.
"""
count = 0
operation = self._get_operation()
kwargs = self.kwargs.copy()
kwargs['select'] = 'COU... | [
"def",
"count",
"(",
"self",
")",
":",
"count",
"=",
"0",
"operation",
"=",
"self",
".",
"_get_operation",
"(",
")",
"kwargs",
"=",
"self",
".",
"kwargs",
".",
"copy",
"(",
")",
"kwargs",
"[",
"'select'",
"]",
"=",
"'COUNT'",
"limit",
"=",
"kwargs",
... | 35.285714 | 16.714286 |
def get_assessment_notification_session_for_bank(self, assessment_receiver, bank_id):
"""Gets the ``OsidSession`` associated with the assessment notification service for the given bank.
arg: assessment_receiver
(osid.assessment.AssessmentReceiver): the assessment
rece... | [
"def",
"get_assessment_notification_session_for_bank",
"(",
"self",
",",
"assessment_receiver",
",",
"bank_id",
")",
":",
"if",
"not",
"self",
".",
"supports_assessment_notification",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also in... | 51.444444 | 22.777778 |
def load_probe_file(recording, probe_file, channel_map=None, channel_groups=None):
'''Loads channel information into recording extractor. If a .prb file is given,
then 'location' and 'group' information for each channel is stored. If a .csv
file is given, then it will only store 'location'
Parameters
... | [
"def",
"load_probe_file",
"(",
"recording",
",",
"probe_file",
",",
"channel_map",
"=",
"None",
",",
"channel_groups",
"=",
"None",
")",
":",
"probe_file",
"=",
"Path",
"(",
"probe_file",
")",
"if",
"probe_file",
".",
"suffix",
"==",
"'.prb'",
":",
"probe_di... | 59.598039 | 30.970588 |
def _parse_json(self, page, exactly_one=True):
'''Returns location, (latitude, longitude) from json feed.'''
places = page.get('results', [])
if not len(places):
self._check_status(page.get('status'))
return None
def parse_place(place):
'''Get the lo... | [
"def",
"_parse_json",
"(",
"self",
",",
"page",
",",
"exactly_one",
"=",
"True",
")",
":",
"places",
"=",
"page",
".",
"get",
"(",
"'results'",
",",
"[",
"]",
")",
"if",
"not",
"len",
"(",
"places",
")",
":",
"self",
".",
"_check_status",
"(",
"pag... | 38.473684 | 19.842105 |
def reindex(report):
"""Reindex report so that 'TOTAL' is the last row"""
index = list(report.index)
i = index.index('TOTAL')
return report.reindex(index[:i] + index[i+1:] + ['TOTAL']) | [
"def",
"reindex",
"(",
"report",
")",
":",
"index",
"=",
"list",
"(",
"report",
".",
"index",
")",
"i",
"=",
"index",
".",
"index",
"(",
"'TOTAL'",
")",
"return",
"report",
".",
"reindex",
"(",
"index",
"[",
":",
"i",
"]",
"+",
"index",
"[",
"i",... | 39.2 | 12.8 |
def print_settings_example():
"""
You can use settings to get additional information from the user via their
dependencies.io configuration file. Settings will be automatically injected as
env variables with the "SETTING_" prefix.
All settings will be passed as strings. More complex types will be js... | [
"def",
"print_settings_example",
"(",
")",
":",
"SETTING_EXAMPLE_LIST",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"getenv",
"(",
"'SETTING_EXAMPLE_LIST'",
",",
"'[]'",
")",
")",
"SETTING_EXAMPLE_STRING",
"=",
"os",
".",
"getenv",
"(",
"'SETTING_EXAMPLE_STRING'",
... | 47.857143 | 25.571429 |
def newton(power_sum, elementary_symmetric_polynomial, order):
r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shor... | [
"def",
"newton",
"(",
"power_sum",
",",
"elementary_symmetric_polynomial",
",",
"order",
")",
":",
"if",
"len",
"(",
"power_sum",
")",
">",
"len",
"(",
"elementary_symmetric_polynomial",
")",
":",
"_update_elementary_symmetric_polynomial",
"(",
"power_sum",
",",
"el... | 41.8 | 30.68 |
def _partition_spec(self, shape, partition_info):
"""Build magic (and sparsely documented) shapes_and_slices spec string."""
if partition_info is None:
return '' # Empty string indicates a non-partitioned tensor.
ssi = tf.Variable.SaveSliceInfo(
full_name=self._var_name,
full_shape=pa... | [
"def",
"_partition_spec",
"(",
"self",
",",
"shape",
",",
"partition_info",
")",
":",
"if",
"partition_info",
"is",
"None",
":",
"return",
"''",
"# Empty string indicates a non-partitioned tensor.",
"ssi",
"=",
"tf",
".",
"Variable",
".",
"SaveSliceInfo",
"(",
"fu... | 42.6 | 10.4 |
def do_container(self, element, decl, pseudo):
"""Implement setting tag for new wrapper element."""
value = serialize(decl.value).strip()
if '|' in value:
namespace, tag = value.split('|', 1)
try:
namespace = self.css_namespaces[namespace]
ex... | [
"def",
"do_container",
"(",
"self",
",",
"element",
",",
"decl",
",",
"pseudo",
")",
":",
"value",
"=",
"serialize",
"(",
"decl",
".",
"value",
")",
".",
"strip",
"(",
")",
"if",
"'|'",
"in",
"value",
":",
"namespace",
",",
"tag",
"=",
"value",
"."... | 34.631579 | 16.421053 |
def to_csv(self, fileobj=sys.stdout):
"""Write data on file fileobj using CSV format."""
openclose = is_string(fileobj)
if openclose:
fileobj = open(fileobj, "w")
for idx, section in enumerate(self.sections):
fileobj.write(section.to_csvline(with_header=(idx == ... | [
"def",
"to_csv",
"(",
"self",
",",
"fileobj",
"=",
"sys",
".",
"stdout",
")",
":",
"openclose",
"=",
"is_string",
"(",
"fileobj",
")",
"if",
"openclose",
":",
"fileobj",
"=",
"open",
"(",
"fileobj",
",",
"\"w\"",
")",
"for",
"idx",
",",
"section",
"i... | 29.769231 | 18.076923 |
def create_title(article, language, title, slug=None, description=None,
page_title=None, menu_title=None, meta_description=None,
creation_date=None, image=None):
"""
Create an article title.
"""
# validate article
assert isinstance(article, Article)
# validate ... | [
"def",
"create_title",
"(",
"article",
",",
"language",
",",
"title",
",",
"slug",
"=",
"None",
",",
"description",
"=",
"None",
",",
"page_title",
"=",
"None",
",",
"menu_title",
"=",
"None",
",",
"meta_description",
"=",
"None",
",",
"creation_date",
"="... | 27.304348 | 19.73913 |
def change_parameters(self,params):
"""
Utility function for changing the approximate distribution parameters
"""
no_of_params = 0
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
self.q[core_param].vi_chang... | [
"def",
"change_parameters",
"(",
"self",
",",
"params",
")",
":",
"no_of_params",
"=",
"0",
"for",
"core_param",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"for",
"approx_param",
"in",
"range",
"(",
"self",
".",
"q",
"[",
"core_... | 43.222222 | 15.888889 |
def command(state, args):
"""Register watching regexp for an anime."""
args = parser.parse_args(args[1:])
aid = state.results.parse_aid(args.aid, default_key='db')
if args.query:
# Use regexp provided by user.
regexp = '.*'.join(args.query)
else:
# Make default regexp.
... | [
"def",
"command",
"(",
"state",
",",
"args",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
"[",
"1",
":",
"]",
")",
"aid",
"=",
"state",
".",
"results",
".",
"parse_aid",
"(",
"args",
".",
"aid",
",",
"default_key",
"=",
"'db'",
... | 40 | 14.2 |
def _spintaylor_aligned_prec_swapper(**p):
"""
SpinTaylorF2 is only single spin, it also struggles with anti-aligned spin
waveforms. This construct chooses between the aligned-twospin TaylorF2 model
and the precessing singlespin SpinTaylorF2 models. If aligned spins are
given, use TaylorF2, if nonal... | [
"def",
"_spintaylor_aligned_prec_swapper",
"(",
"*",
"*",
"p",
")",
":",
"orig_approximant",
"=",
"p",
"[",
"'approximant'",
"]",
"if",
"p",
"[",
"'spin2x'",
"]",
"==",
"0",
"and",
"p",
"[",
"'spin2y'",
"]",
"==",
"0",
"and",
"p",
"[",
"'spin1x'",
"]",... | 46.277778 | 18.055556 |
def move_cursor_one_letter(self, letter=RIGHT):
"""Move the cursor of one letter to the right (1) or the the left."""
assert letter in (self.RIGHT, self.LEFT)
if letter == self.RIGHT:
self.cursor += 1
if self.cursor > len(self.text):
self.cursor -= 1
... | [
"def",
"move_cursor_one_letter",
"(",
"self",
",",
"letter",
"=",
"RIGHT",
")",
":",
"assert",
"letter",
"in",
"(",
"self",
".",
"RIGHT",
",",
"self",
".",
"LEFT",
")",
"if",
"letter",
"==",
"self",
".",
"RIGHT",
":",
"self",
".",
"cursor",
"+=",
"1"... | 34.333333 | 11.916667 |
def _patch_for_tf1_12(tf):
"""Monkey patch tf 1.12 so tfds can use it."""
tf.io.gfile = tf.gfile
tf.io.gfile.copy = tf.gfile.Copy
tf.io.gfile.exists = tf.gfile.Exists
tf.io.gfile.glob = tf.gfile.Glob
tf.io.gfile.isdir = tf.gfile.IsDirectory
tf.io.gfile.listdir = tf.gfile.ListDirectory
tf.io.gfile.makedi... | [
"def",
"_patch_for_tf1_12",
"(",
"tf",
")",
":",
"tf",
".",
"io",
".",
"gfile",
"=",
"tf",
".",
"gfile",
"tf",
".",
"io",
".",
"gfile",
".",
"copy",
"=",
"tf",
".",
"gfile",
".",
"Copy",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"=",
"tf",
... | 40.666667 | 7.818182 |
def present_active_subjunctive(self):
"""
Strong verbs
I
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"])
>>> verb.present_active_subjunctive()
['líta', 'lítir', 'líti', 'lítim', 'lítið', 'líti']
II
... | [
"def",
"present_active_subjunctive",
"(",
"self",
")",
":",
"if",
"self",
".",
"sng",
"==",
"\"vera\"",
":",
"forms",
"=",
"[",
"\"sé\",",
" ",
"sér\", ",
"\"",
"é\", \"",
"s",
"m\", \"s",
"é",
"\", \"sé\"",
"]",
"",
"",
"return",
"forms",
"elif",
"self"... | 37.513158 | 20.381579 |
def cmd(send, msg, args):
"""Evaluates mathmatical expressions.
Syntax: {command} <expression>
"""
if not msg:
send("Calculate what?")
return
if "!" in msg:
args['do_kick'](args['target'], args['nick'], "hacking")
return
msg += '\n'
proc = subprocess.Popen... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Calculate what?\"",
")",
"return",
"if",
"\"!\"",
"in",
"msg",
":",
"args",
"[",
"'do_kick'",
"]",
"(",
"args",
"[",
"'target'",
"]",
",",
"args"... | 30.241379 | 25.137931 |
def removeService(self, service):
"""
Removes a service from the gateway.
@param service: Either the name or t of the service to remove from the
gateway, or .
@type service: C{callable} or a class instance
@raise NameError: Service not found.
"""
... | [
"def",
"removeService",
"(",
"self",
",",
"service",
")",
":",
"for",
"name",
",",
"wrapper",
"in",
"self",
".",
"services",
".",
"iteritems",
"(",
")",
":",
"if",
"service",
"in",
"(",
"name",
",",
"wrapper",
".",
"service",
")",
":",
"del",
"self",... | 35.8 | 14.2 |
def hpsplit(self, data: ['SASdata', str] = None,
cls: [str, list] = None,
code: str = None,
grow: str = None,
id: str = None,
input: [str, list, dict] = None,
model: str = None,
out: [str, bool, 'SASdata'] = ... | [
"def",
"hpsplit",
"(",
"self",
",",
"data",
":",
"[",
"'SASdata'",
",",
"str",
"]",
"=",
"None",
",",
"cls",
":",
"[",
"str",
",",
"list",
"]",
"=",
"None",
",",
"code",
":",
"str",
"=",
"None",
",",
"grow",
":",
"str",
"=",
"None",
",",
"id"... | 58.538462 | 27.461538 |
def validate_or_raise(self, *a, **k):
"""Some people would condemn this whole module screaming:
"Don't return success codes, use exceptions!"
This method allows them to be happy, too.
"""
validate, err = self.validate(*a, **k)
if err:
raise V... | [
"def",
"validate_or_raise",
"(",
"self",
",",
"*",
"a",
",",
"*",
"*",
"k",
")",
":",
"validate",
",",
"err",
"=",
"self",
".",
"validate",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
"if",
"err",
":",
"raise",
"ValidationException",
"(",
"err",
")",... | 30.416667 | 14.25 |
def ensure_state(default_getter, exc_class, default_msg=None):
"""Create a decorator factory function."""
def decorator(getter=default_getter, msg=default_msg):
def ensure_decorator(f):
@wraps(f)
def inner(self, *args, **kwargs):
if not getter(self):
... | [
"def",
"ensure_state",
"(",
"default_getter",
",",
"exc_class",
",",
"default_msg",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"getter",
"=",
"default_getter",
",",
"msg",
"=",
"default_msg",
")",
":",
"def",
"ensure_decorator",
"(",
"f",
")",
":",
"@... | 40.5 | 12.666667 |
def get_mail_keys(message, complete=True):
"""
Given an email.message.Message, return a set with all email parts to get
Args:
message (email.message.Message): email message object
complete (bool): if True returns all email headers
Returns:
set with all email parts
"""
... | [
"def",
"get_mail_keys",
"(",
"message",
",",
"complete",
"=",
"True",
")",
":",
"if",
"complete",
":",
"log",
".",
"debug",
"(",
"\"Get all headers\"",
")",
"all_headers_keys",
"=",
"{",
"i",
".",
"lower",
"(",
")",
"for",
"i",
"in",
"message",
".",
"k... | 30.863636 | 21.681818 |
def convert_reshape(node, **kwargs):
"""Map MXNet's Reshape operator attributes to onnx's Reshape operator.
Converts output shape attribute to output shape tensor
and return multiple created nodes.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
output_shape_list = convert_string_to_lis... | [
"def",
"convert_reshape",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"output_shape_list",
"=",
"convert_string_to_list",
"(",
"attrs",
"[",
"\"shape\"",
"]",
... | 30.209302 | 20.604651 |
def delete(self, queue='', if_unused=False, if_empty=False):
"""Delete a Queue.
:param str queue: Queue name
:param bool if_unused: Delete only if unused
:param bool if_empty: Delete only if empty
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError:... | [
"def",
"delete",
"(",
"self",
",",
"queue",
"=",
"''",
",",
"if_unused",
"=",
"False",
",",
"if_empty",
"=",
"False",
")",
":",
"if",
"not",
"compatibility",
".",
"is_string",
"(",
"queue",
")",
":",
"raise",
"AMQPInvalidArgument",
"(",
"'queue should be a... | 43.083333 | 20.208333 |
def _get_node_estimations(self, node_attr, node_id):
"""
Returns the data nodes estimations and `wait_inputs` flag.
:param node_attr:
Dictionary of node attributes.
:type node_attr: dict
:param node_id:
Data node's id.
:type node_id: str
... | [
"def",
"_get_node_estimations",
"(",
"self",
",",
"node_attr",
",",
"node_id",
")",
":",
"# Get data node estimations.",
"estimations",
"=",
"self",
".",
"_wf_pred",
"[",
"node_id",
"]",
"wait_in",
"=",
"node_attr",
"[",
"'wait_inputs'",
"]",
"# Namespace shortcut."... | 33.27907 | 22.813953 |
def get_stored_content_length(headers):
"""Return the content length (in bytes) of the object as stored in GCS.
x-goog-stored-content-length should always be present except when called via
the local dev_appserver. Therefore if it is not present we default to the
standard content-length header.
Args:
hea... | [
"def",
"get_stored_content_length",
"(",
"headers",
")",
":",
"length",
"=",
"headers",
".",
"get",
"(",
"'x-goog-stored-content-length'",
")",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"headers",
".",
"get",
"(",
"'content-length'",
")",
"return",
"le... | 31.470588 | 20.529412 |
def get_tracks(self, catalog, cache=True):
"""Get the tracks for a song given a catalog.
Args:
catalog (str): a string representing the catalog whose track you want to retrieve.
Returns:
A list of Track dicts.
Example:
>>> s ... | [
"def",
"get_tracks",
"(",
"self",
",",
"catalog",
",",
"cache",
"=",
"True",
")",
":",
"if",
"not",
"(",
"cache",
"and",
"(",
"'tracks'",
"in",
"self",
".",
"cache",
")",
"and",
"(",
"catalog",
"in",
"[",
"td",
"[",
"'catalog'",
"]",
"for",
"td",
... | 46.176471 | 24.588235 |
def execute(self, string, max_tacts=None):
"""Execute algorithm (if max_times = None, there can be forever loop)."""
counter = 0
self.last_rule = None
while True:
string = self.execute_once(string)
if self.last_rule is None or self.last_rule[2]:
b... | [
"def",
"execute",
"(",
"self",
",",
"string",
",",
"max_tacts",
"=",
"None",
")",
":",
"counter",
"=",
"0",
"self",
".",
"last_rule",
"=",
"None",
"while",
"True",
":",
"string",
"=",
"self",
".",
"execute_once",
"(",
"string",
")",
"if",
"self",
"."... | 35 | 18.785714 |
async def rawmsg(self, command, *args, **kwargs):
""" Send raw message. """
message = str(self._create_message(command, *args, **kwargs))
await self._send(message) | [
"async",
"def",
"rawmsg",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"str",
"(",
"self",
".",
"_create_message",
"(",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"await",
... | 46 | 11.25 |
def iterate(self, shuffle=True):
'''Iterate over batches in the dataset.
This method generates ``iteration_size`` batches from the dataset and
then returns.
Parameters
----------
shuffle : bool, optional
Shuffle the batches in this dataset if the iteration r... | [
"def",
"iterate",
"(",
"self",
",",
"shuffle",
"=",
"True",
")",
":",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"iteration_size",
")",
":",
"if",
"self",
".",
"_callable",
"is",
"not",
"None",
":",
"yield",
"self",
".",
"_callable",
"(",
")",
"e... | 31.652174 | 20.782609 |
def rebuild_method(self, prepared_request, response):
"""When being redirected we may want to change the method of the request
based on certain specs or browser behavior.
"""
method = prepared_request.method
# http://tools.ietf.org/html/rfc7231#section-6.4.4
if response.... | [
"def",
"rebuild_method",
"(",
"self",
",",
"prepared_request",
",",
"response",
")",
":",
"method",
"=",
"prepared_request",
".",
"method",
"# http://tools.ietf.org/html/rfc7231#section-6.4.4",
"if",
"response",
".",
"status_code",
"==",
"codes",
".",
"see_other",
"an... | 40.285714 | 19.285714 |
def write(self, chars, output, format='png'):
"""Generate and write an image CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destination.
:param format: image file format
"""
im = self.generate_image(chars)
return im.save(out... | [
"def",
"write",
"(",
"self",
",",
"chars",
",",
"output",
",",
"format",
"=",
"'png'",
")",
":",
"im",
"=",
"self",
".",
"generate_image",
"(",
"chars",
")",
"return",
"im",
".",
"save",
"(",
"output",
",",
"format",
"=",
"format",
")"
] | 36.777778 | 6.222222 |
def dynamize_last_evaluated_key(self, last_evaluated_key):
"""
Convert a last_evaluated_key parameter into the data structure
required for Layer1.
"""
d = None
if last_evaluated_key:
hash_key = last_evaluated_key['HashKeyElement']
d = {'HashKeyElem... | [
"def",
"dynamize_last_evaluated_key",
"(",
"self",
",",
"last_evaluated_key",
")",
":",
"d",
"=",
"None",
"if",
"last_evaluated_key",
":",
"hash_key",
"=",
"last_evaluated_key",
"[",
"'HashKeyElement'",
"]",
"d",
"=",
"{",
"'HashKeyElement'",
":",
"self",
".",
"... | 42.538462 | 17.769231 |
def dir(self, filetype, **kwargs):
"""Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
dir : str
Directory containing the file.
"""
full = k... | [
"def",
"dir",
"(",
"self",
",",
"filetype",
",",
"*",
"*",
"kwargs",
")",
":",
"full",
"=",
"kwargs",
".",
"get",
"(",
"'full'",
",",
"None",
")",
"if",
"not",
"full",
":",
"full",
"=",
"self",
".",
"full",
"(",
"filetype",
",",
"*",
"*",
"kwar... | 22.789474 | 18.105263 |
async def stepper_config(self, steps_per_revolution, stepper_pins):
"""
Configure stepper motor prior to operation.
This is a FirmataPlus feature.
:param steps_per_revolution: number of steps per motor revolution
:param stepper_pins: a list of control pin numbers - either 4 or ... | [
"async",
"def",
"stepper_config",
"(",
"self",
",",
"steps_per_revolution",
",",
"stepper_pins",
")",
":",
"data",
"=",
"[",
"PrivateConstants",
".",
"STEPPER_CONFIGURE",
",",
"steps_per_revolution",
"&",
"0x7f",
",",
"(",
"steps_per_revolution",
">>",
"7",
")",
... | 40.1875 | 19.8125 |
def log_to_stream(stream=sys.stderr, level=logging.NOTSET,
fmt=logging.BASIC_FORMAT):
""" Add :class:`logging.StreamHandler` to logger which logs to a stream.
:param stream. Stream to log to, default STDERR.
:param level: Log level, default NOTSET.
:param fmt: String with log format, ... | [
"def",
"log_to_stream",
"(",
"stream",
"=",
"sys",
".",
"stderr",
",",
"level",
"=",
"logging",
".",
"NOTSET",
",",
"fmt",
"=",
"logging",
".",
"BASIC_FORMAT",
")",
":",
"fmt",
"=",
"Formatter",
"(",
"fmt",
")",
"handler",
"=",
"StreamHandler",
"(",
")... | 34.357143 | 14.714286 |
def _prm_read_pandas(self, pd_node, full_name):
"""Reads a DataFrame from dis.
:param pd_node:
hdf5 node storing the pandas DataFrame
:param full_name:
Full name of the parameter or result whose data is to be loaded
:return:
Data to load
... | [
"def",
"_prm_read_pandas",
"(",
"self",
",",
"pd_node",
",",
"full_name",
")",
":",
"try",
":",
"name",
"=",
"pd_node",
".",
"_v_name",
"pathname",
"=",
"pd_node",
".",
"_v_pathname",
"pandas_store",
"=",
"self",
".",
"_hdf5store",
"pandas_data",
"=",
"panda... | 25.84 | 22.6 |
def prod(x, axis=None, keepdims=False):
"""Reduction along axes with product operation.
Args:
x (Variable): An input variable.
axis (None, int or tuple of ints): Axis or axes along which product is
calculated. Passing the default value `None` will reduce all dimensions.
keep... | [
"def",
"prod",
"(",
"x",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"from",
".",
"function_bases",
"import",
"prod",
"as",
"prod_base",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"range",
"(",
"x",
".",
"ndim",
")",
"elif... | 32.818182 | 21.818182 |
def _hasViewChangeQuorum(self):
# This method should just be present for master instance.
"""
Checks whether n-f nodes completed view change and whether one
of them is the next primary
"""
num_of_ready_nodes = len(self._view_change_done)
diff = self.quorum - num_o... | [
"def",
"_hasViewChangeQuorum",
"(",
"self",
")",
":",
"# This method should just be present for master instance.",
"num_of_ready_nodes",
"=",
"len",
"(",
"self",
".",
"_view_change_done",
")",
"diff",
"=",
"self",
".",
"quorum",
"-",
"num_of_ready_nodes",
"if",
"diff",
... | 40 | 18.666667 |
def _parse_sections(self):
""" parse sections and TOC """
def _list_to_dict(_dict, path, sec):
tmp = _dict
for elm in path[:-1]:
tmp = tmp[elm]
tmp[sec] = OrderedDict()
self._sections = list()
section_regexp = r"\n==* .* ==*\n" # '==... | [
"def",
"_parse_sections",
"(",
"self",
")",
":",
"def",
"_list_to_dict",
"(",
"_dict",
",",
"path",
",",
"sec",
")",
":",
"tmp",
"=",
"_dict",
"for",
"elm",
"in",
"path",
"[",
":",
"-",
"1",
"]",
":",
"tmp",
"=",
"tmp",
"[",
"elm",
"]",
"tmp",
... | 32.065217 | 13.456522 |
def index_open(self, index):
'''
Opens the speicified index.
http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close.html
> ElasticSearch().index_open('my_index')
'''
request = self.session
url = 'http://%s:%s/%s/_open' % (self.host, self.port, ... | [
"def",
"index_open",
"(",
"self",
",",
"index",
")",
":",
"request",
"=",
"self",
".",
"session",
"url",
"=",
"'http://%s:%s/%s/_open'",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"index",
")",
"response",
"=",
"request",
".",
"post"... | 34.727273 | 20.545455 |
def get_data(self):
"""Gets the asset content data.
return: (osid.transport.DataInputStream) - the length of the
content data
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
if not bool... | [
"def",
"get_data",
"(",
"self",
")",
":",
"if",
"not",
"bool",
"(",
"self",
".",
"_my_map",
"[",
"'data'",
"]",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'no data'",
")",
"dbase",
"=",
"JSONClientValidated",
"(",
"'repository'",
",",
"runti... | 39.866667 | 17.2 |
def poll_until_valid(authzr, clock, client, timeout=300.0):
"""
Poll an authorization until it is in a state other than pending or
processing.
:param ~acme.messages.AuthorizationResource auth: The authorization to
complete.
:param clock: The ``IReactorTime`` implementation to use; usually t... | [
"def",
"poll_until_valid",
"(",
"authzr",
",",
"clock",
",",
"client",
",",
"timeout",
"=",
"300.0",
")",
":",
"def",
"repoll",
"(",
"result",
")",
":",
"authzr",
",",
"retry_after",
"=",
"result",
"if",
"authzr",
".",
"body",
".",
"status",
"in",
"{",... | 40.142857 | 20.761905 |
def fix_line_numbers(body):
r"""Recomputes all line numbers based on the number of \n characters."""
maxline = 0
for node in body.pre_order():
maxline += node.prefix.count('\n')
if isinstance(node, Leaf):
node.lineno = maxline
maxline += str(node.value).count('\n') | [
"def",
"fix_line_numbers",
"(",
"body",
")",
":",
"maxline",
"=",
"0",
"for",
"node",
"in",
"body",
".",
"pre_order",
"(",
")",
":",
"maxline",
"+=",
"node",
".",
"prefix",
".",
"count",
"(",
"'\\n'",
")",
"if",
"isinstance",
"(",
"node",
",",
"Leaf"... | 38.75 | 8.75 |
def remove_in_progress_check(self, check):
"""Remove check from check in progress
:param check: Check to remove
:type check: alignak.objects.check.Check
:return: None
"""
# The check is consumed, update the in_checking properties
if check in self.checks_in_progre... | [
"def",
"remove_in_progress_check",
"(",
"self",
",",
"check",
")",
":",
"# The check is consumed, update the in_checking properties",
"if",
"check",
"in",
"self",
".",
"checks_in_progress",
":",
"self",
".",
"checks_in_progress",
".",
"remove",
"(",
"check",
")",
"sel... | 36.090909 | 10.727273 |
def unique_str(self):
""" A string that (ideally) uniquely represents this GC object. This
helps with naming files for caching. 'Unique' is defined as 'If
GC1 != GC2, then GC1.unique_str() != GC2.unique_str()'; conversely,
'If GC1 == GC2, then GC1.unique_str() == GC2.unique_str()'.
... | [
"def",
"unique_str",
"(",
"self",
")",
":",
"unique_str",
"=",
"\"_\"",
".",
"join",
"(",
"[",
"\"%.3f\"",
"%",
"f",
"for",
"f",
"in",
"self",
".",
"geotransform",
"]",
"+",
"[",
"\"%d\"",
"%",
"d",
"for",
"d",
"in",
"self",
".",
"x_size",
",",
"... | 41.391304 | 22.565217 |
def include(d, e):
"""Generate a pair of (directory, file-list) for installation.
'd' -- A directory
'e' -- A glob pattern"""
return (d, [f for f in glob.glob('%s/%s' % (d, e)) if os.path.isfile(f)]) | [
"def",
"include",
"(",
"d",
",",
"e",
")",
":",
"return",
"(",
"d",
",",
"[",
"f",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"'%s/%s'",
"%",
"(",
"d",
",",
"e",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
"]",
")"
] | 30.142857 | 22.428571 |
def cleanup_a_alpha_and_derivatives(self):
r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by
`GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for
every component'''
del(self.a, self.kappa, self.kappa0, self.kappa1, self.kappa2, self.kappa3, self.Tc) | [
"def",
"cleanup_a_alpha_and_derivatives",
"(",
"self",
")",
":",
"del",
"(",
"self",
".",
"a",
",",
"self",
".",
"kappa",
",",
"self",
".",
"kappa0",
",",
"self",
".",
"kappa1",
",",
"self",
".",
"kappa2",
",",
"self",
".",
"kappa3",
",",
"self",
"."... | 62.8 | 28.4 |
async def _skip(self, ctx):
""" Skips the current track. """
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.is_playing:
return await ctx.send('Not playing.')
await player.skip()
await ctx.send('⏭ | Skipped.') | [
"async",
"def",
"_skip",
"(",
"self",
",",
"ctx",
")",
":",
"player",
"=",
"self",
".",
"bot",
".",
"lavalink",
".",
"players",
".",
"get",
"(",
"ctx",
".",
"guild",
".",
"id",
")",
"if",
"not",
"player",
".",
"is_playing",
":",
"return",
"await",
... | 31.333333 | 15.666667 |
def validate_specs_from_path(specs_path):
"""
Validates Dusty specs at the given path. The following checks are performed:
-That the given path exists
-That there are bundles in the given path
-That the fields in the specs match those allowed in our schemas
-That references to ap... | [
"def",
"validate_specs_from_path",
"(",
"specs_path",
")",
":",
"# Validation of fields with schemer is now down implicitly through get_specs_from_path",
"# We are dealing with Dusty_Specs class in this file",
"log_to_client",
"(",
"\"Validating specs at path {}\"",
".",
"format",
"(",
"... | 48.789474 | 15.947368 |
def _draw(self):
"""Draw all the things"""
self._compute()
self._compute_x_labels()
self._compute_x_labels_major()
self._compute_y_labels()
self._compute_y_labels_major()
self._compute_secondary()
self._post_compute()
self._compute_margin()
... | [
"def",
"_draw",
"(",
"self",
")",
":",
"self",
".",
"_compute",
"(",
")",
"self",
".",
"_compute_x_labels",
"(",
")",
"self",
".",
"_compute_x_labels_major",
"(",
")",
"self",
".",
"_compute_y_labels",
"(",
")",
"self",
".",
"_compute_y_labels_major",
"(",
... | 30.666667 | 11.666667 |
def _scalePoints(points, scale=1, convertToInteger=True):
"""
Scale points and optionally convert them to integers.
"""
if convertToInteger:
points = [
(int(round(x * scale)), int(round(y * scale)))
for (x, y) in points
]
else:
points = [(x * scale, y ... | [
"def",
"_scalePoints",
"(",
"points",
",",
"scale",
"=",
"1",
",",
"convertToInteger",
"=",
"True",
")",
":",
"if",
"convertToInteger",
":",
"points",
"=",
"[",
"(",
"int",
"(",
"round",
"(",
"x",
"*",
"scale",
")",
")",
",",
"int",
"(",
"round",
"... | 29.75 | 17.083333 |
def set_hvac_mode(self, index, hvac_mode):
''' possible hvac modes are auto, auxHeatOnly, cool, heat, off '''
body = {"selection": {"selectionType": "thermostats",
"selectionMatch": self.thermostats[index]['identifier']},
"thermostat": {
... | [
"def",
"set_hvac_mode",
"(",
"self",
",",
"index",
",",
"hvac_mode",
")",
":",
"body",
"=",
"{",
"\"selection\"",
":",
"{",
"\"selectionType\"",
":",
"\"thermostats\"",
",",
"\"selectionMatch\"",
":",
"self",
".",
"thermostats",
"[",
"index",
"]",
"[",
"'ide... | 52.363636 | 14.727273 |
def add_edge(self, x, y, label=None):
"""Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.In... | [
"def",
"add_edge",
"(",
"self",
",",
"x",
",",
"y",
",",
"label",
"=",
"None",
")",
":",
"self",
".",
"adjacency_list",
"[",
"x",
"]",
".",
"append",
"(",
"(",
"y",
",",
"label",
")",
")",
"# multiple edges are allowed, so be careful",
"if",
"x",
"not"... | 45.428571 | 14.285714 |
def create(self, name=None, **kwargs):
"""Create a new project.
:param name: The name of the project.
:returns: An instance of the newly create project.
:rtype: renku.models.projects.Project
"""
data = self._client.api.create_project({'name': name})
return self.M... | [
"def",
"create",
"(",
"self",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"_client",
".",
"api",
".",
"create_project",
"(",
"{",
"'name'",
":",
"name",
"}",
")",
"return",
"self",
".",
"Meta",
".",
"mod... | 40.555556 | 14 |
def _get_properties(self, rule, scope, block):
"""
Implements properties and variables extraction and assignment
"""
prop, raw_value = (_prop_split_re.split(block.prop, 1) + [None])[:2]
if raw_value is not None:
raw_value = raw_value.strip()
try:
... | [
"def",
"_get_properties",
"(",
"self",
",",
"rule",
",",
"scope",
",",
"block",
")",
":",
"prop",
",",
"raw_value",
"=",
"(",
"_prop_split_re",
".",
"split",
"(",
"block",
".",
"prop",
",",
"1",
")",
"+",
"[",
"None",
"]",
")",
"[",
":",
"2",
"]"... | 36.962025 | 17.898734 |
def _get_fields_for_class(schema_graph, graphql_types, field_type_overrides, hidden_classes,
cls_name):
"""Return a dict from field name to GraphQL field type, for the specified graph class."""
properties = schema_graph.get_element_by_class_name(cls_name).properties
# Add leaf Gra... | [
"def",
"_get_fields_for_class",
"(",
"schema_graph",
",",
"graphql_types",
",",
"field_type_overrides",
",",
"hidden_classes",
",",
"cls_name",
")",
":",
"properties",
"=",
"schema_graph",
".",
"get_element_by_class_name",
"(",
"cls_name",
")",
".",
"properties",
"# A... | 49.757576 | 27.227273 |
def get_minor_version(version, remove=None):
"""Return minor version of a provided version string. Minor version is the
second component in the dot-separated version string. For non-version-like
strings this function returns ``None``.
The ``remove`` parameter is deprecated since version 1.18 and will b... | [
"def",
"get_minor_version",
"(",
"version",
",",
"remove",
"=",
"None",
")",
":",
"if",
"remove",
":",
"warnings",
".",
"warn",
"(",
"\"remove argument is deprecated\"",
",",
"DeprecationWarning",
")",
"version_split",
"=",
"version",
".",
"split",
"(",
"\".\"",... | 33.1 | 18.35 |
def autofill(ctx, f):
"""
Fills your timesheet up to today, for the defined auto_fill_days.
"""
auto_fill_days = ctx.obj['settings']['auto_fill_days']
if not auto_fill_days:
ctx.obj['view'].view.err("The parameter `auto_fill_days` must be set "
"to use this ... | [
"def",
"autofill",
"(",
"ctx",
",",
"f",
")",
":",
"auto_fill_days",
"=",
"ctx",
".",
"obj",
"[",
"'settings'",
"]",
"[",
"'auto_fill_days'",
"]",
"if",
"not",
"auto_fill_days",
":",
"ctx",
".",
"obj",
"[",
"'view'",
"]",
".",
"view",
".",
"err",
"("... | 31.652174 | 22.173913 |
def render_placeholder(request, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None):
"""
Render a :class:`~fluent_contents.models.Placeholder` object.
Returns a :class:`~fluent_contents.models.ContentItemOutput` object
which contains th... | [
"def",
"render_placeholder",
"(",
"request",
",",
"placeholder",
",",
"parent_object",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"cachable",
"=",
"None",
",",
"limit_parent_language",
"=",
"True",
",",
"fallback_language",
"=",
"None",
")",
":",
"ou... | 52.230769 | 27.820513 |
def print_help(self, classes=False):
"""Print the help for each Configurable class in self.classes.
If classes=False (the default), only flags and aliases are printed.
"""
self.print_subcommands()
self.print_options()
if classes:
if self.classes:
... | [
"def",
"print_help",
"(",
"self",
",",
"classes",
"=",
"False",
")",
":",
"self",
".",
"print_subcommands",
"(",
")",
"self",
".",
"print_options",
"(",
")",
"if",
"classes",
":",
"if",
"self",
".",
"classes",
":",
"print",
"\"Class parameters\"",
"print",... | 31.173913 | 17.130435 |
def Authenticate(self, app_id, challenge_data,
print_callback=sys.stderr.write):
"""See base class."""
# If authenticator is not plugged in, prompt
try:
device = u2f.GetLocalU2FInterface(origin=self.origin)
except errors.NoDeviceFoundError:
print_callback('Please insert yo... | [
"def",
"Authenticate",
"(",
"self",
",",
"app_id",
",",
"challenge_data",
",",
"print_callback",
"=",
"sys",
".",
"stderr",
".",
"write",
")",
":",
"# If authenticator is not plugged in, prompt",
"try",
":",
"device",
"=",
"u2f",
".",
"GetLocalU2FInterface",
"(",
... | 33.621622 | 20.189189 |
def get_type_name(t):
""" Get a human-friendly name for the given type.
:type t: type|None
:rtype: unicode
"""
# Lookup in the mapping
try:
return __type_names[t]
except KeyError:
# Specific types
if issubclass(t, six.integer_types):
return _(u'Integer nu... | [
"def",
"get_type_name",
"(",
"t",
")",
":",
"# Lookup in the mapping",
"try",
":",
"return",
"__type_names",
"[",
"t",
"]",
"except",
"KeyError",
":",
"# Specific types",
"if",
"issubclass",
"(",
"t",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"_"... | 25.375 | 15.5 |
def postinit(self, lower=None, upper=None, step=None):
"""Do some setup after initialisation.
:param lower: The lower index in the slice.
:value lower: NodeNG or None
:param upper: The upper index in the slice.
:value upper: NodeNG or None
:param step: The step to take... | [
"def",
"postinit",
"(",
"self",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
",",
"step",
"=",
"None",
")",
":",
"self",
".",
"lower",
"=",
"lower",
"self",
".",
"upper",
"=",
"upper",
"self",
".",
"step",
"=",
"step"
] | 29.866667 | 15 |
def _fix_path():
"""Finds the google_appengine directory and fixes Python imports to use it."""
import os
import sys
all_paths = os.environ.get('PYTHONPATH').split(os.pathsep)
for path_dir in all_paths:
dev_appserver_path = os.path.join(path_dir, 'dev_appserver.py')
if os.path.exists(dev_appserver_pat... | [
"def",
"_fix_path",
"(",
")",
":",
"import",
"os",
"import",
"sys",
"all_paths",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PYTHONPATH'",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"for",
"path_dir",
"in",
"all_paths",
":",
"dev_appserver_path... | 45.1875 | 17.9375 |
def _public(self, command, **params):
"""Invoke the 'command' public API with optional params."""
params['command'] = command
response = self.session.get(self._public_url, params=params)
return response | [
"def",
"_public",
"(",
"self",
",",
"command",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'command'",
"]",
"=",
"command",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"_public_url",
",",
"params",
"=",
"params",
")"... | 46 | 10.6 |
def word_freqs() -> List[Tuple[str, int]]:
"""
Get word frequency from Thai National Corpus (TNC)
"""
lines = list(get_corpus(_FILENAME))
listword = []
for line in lines:
listindata = line.split("\t")
listword.append((listindata[0], int(listindata[1])))
return listword | [
"def",
"word_freqs",
"(",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"int",
"]",
"]",
":",
"lines",
"=",
"list",
"(",
"get_corpus",
"(",
"_FILENAME",
")",
")",
"listword",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"listindata",
"=",
... | 27.636364 | 12.909091 |
def _get_access_token(self):
"""
Get IAM access token using API key.
"""
err = 'Failed to contact IAM token service'
try:
resp = super(IAMSession, self).request(
'POST',
self._token_url,
auth=self._token_auth,
... | [
"def",
"_get_access_token",
"(",
"self",
")",
":",
"err",
"=",
"'Failed to contact IAM token service'",
"try",
":",
"resp",
"=",
"super",
"(",
"IAMSession",
",",
"self",
")",
".",
"request",
"(",
"'POST'",
",",
"self",
".",
"_token_url",
",",
"auth",
"=",
... | 33.925926 | 17.111111 |
def from_json(cls, data):
"""Create a header from a dictionary.
Args:
data: {
"data_type": {}, //Type of data (e.g. Temperature)
"unit": string,
"analysis_period": {} // A Ladybug AnalysisPeriod
"metadata": {}, // A dictionary ... | [
"def",
"from_json",
"(",
"cls",
",",
"data",
")",
":",
"# assign default values",
"assert",
"'data_type'",
"in",
"data",
",",
"'Required keyword \"data_type\" is missing!'",
"keys",
"=",
"(",
"'data_type'",
",",
"'unit'",
",",
"'analysis_period'",
",",
"'metadata'",
... | 38 | 20.190476 |
def flatten_zip_dataset(*args):
"""A list of examples to a dataset containing mixed examples.
Given a list of `n` dataset examples, flatten them by converting
each element into a dataset and concatenating them to convert into a
single dataset.
Args:
*args: A list containing one example each from `n` dif... | [
"def",
"flatten_zip_dataset",
"(",
"*",
"args",
")",
":",
"flattened",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_tensors",
"(",
"args",
"[",
"0",
"]",
")",
"for",
"ex",
"in",
"args",
"[",
"1",
":",
"]",
":",
"flattened",
"=",
"flattened",
... | 33.555556 | 24.222222 |
def pos_tag(args):
"""Tag words with their part of speech."""
tagger = POSTagger(lang=args.lang)
tag(tagger, args) | [
"def",
"pos_tag",
"(",
"args",
")",
":",
"tagger",
"=",
"POSTagger",
"(",
"lang",
"=",
"args",
".",
"lang",
")",
"tag",
"(",
"tagger",
",",
"args",
")"
] | 29.25 | 11.75 |
def create_platform(platform):
'''
.. versionadded:: 2019.2.0
Create a new device platform
platform
String of device platform, e.g., ``junos``
CLI Example:
.. code-block:: bash
salt myminion netbox.create_platform junos
'''
nb_platform = get_('dcim', 'platforms', slu... | [
"def",
"create_platform",
"(",
"platform",
")",
":",
"nb_platform",
"=",
"get_",
"(",
"'dcim'",
",",
"'platforms'",
",",
"slug",
"=",
"slugify",
"(",
"platform",
")",
")",
"if",
"nb_platform",
":",
"return",
"False",
"else",
":",
"payload",
"=",
"{",
"'n... | 23.56 | 23.64 |
def kill(config, container, *args, **kwargs):
'''
Kill a running container
:type container: string
:param container: The container id to kill
:rtype: dict
:returns: boolean
'''
err = "Unknown"
client = _get_client(config)
try:
dcontainer = _get_container_infos(config, c... | [
"def",
"kill",
"(",
"config",
",",
"container",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"err",
"=",
"\"Unknown\"",
"client",
"=",
"_get_client",
"(",
"config",
")",
"try",
":",
"dcontainer",
"=",
"_get_container_infos",
"(",
"config",
",",
... | 27.192308 | 17.961538 |
def _check_request_results(self, results):
"""
Check the result of each request that we made. If a failure occurred,
but some requests succeeded, log and count the failures. If all
requests failed, raise an error.
:return:
The list of responses, with a None value for... | [
"def",
"_check_request_results",
"(",
"self",
",",
"results",
")",
":",
"responses",
"=",
"[",
"]",
"failed_endpoints",
"=",
"[",
"]",
"for",
"index",
",",
"result_tuple",
"in",
"enumerate",
"(",
"results",
")",
":",
"success",
",",
"result",
"=",
"result_... | 38.342857 | 19.028571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.