text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def translate(self, addr):
"""
Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
will point to the private IP address within the same datacenter.
"""
# get family of this address so we translate to the same
family = sock... | [
"def",
"translate",
"(",
"self",
",",
"addr",
")",
":",
"# get family of this address so we translate to the same",
"family",
"=",
"socket",
".",
"getaddrinfo",
"(",
"addr",
",",
"0",
",",
"socket",
".",
"AF_UNSPEC",
",",
"socket",
".",
"SOCK_STREAM",
")",
"[",
... | 43.071429 | 22.214286 |
def my_shared_endpoint_list(endpoint_id):
"""
Executor for `globus endpoint my-shared-endpoint-list`
"""
client = get_client()
ep_iterator = client.my_shared_endpoint_list(endpoint_id)
formatted_print(ep_iterator, fields=ENDPOINT_LIST_FIELDS) | [
"def",
"my_shared_endpoint_list",
"(",
"endpoint_id",
")",
":",
"client",
"=",
"get_client",
"(",
")",
"ep_iterator",
"=",
"client",
".",
"my_shared_endpoint_list",
"(",
"endpoint_id",
")",
"formatted_print",
"(",
"ep_iterator",
",",
"fields",
"=",
"ENDPOINT_LIST_FI... | 32.5 | 14.5 |
def group(merge_func, tokens):
"""
Group together those of the tokens for which the merge function returns
true. The merge function should accept two arguments/tokens and should
return a boolean indicating whether the strings should be merged or not.
Helper for tokenise(string, ..).
"""
output = []
if tokens:... | [
"def",
"group",
"(",
"merge_func",
",",
"tokens",
")",
":",
"output",
"=",
"[",
"]",
"if",
"tokens",
":",
"output",
".",
"append",
"(",
"tokens",
"[",
"0",
"]",
")",
"for",
"token",
"in",
"tokens",
"[",
"1",
":",
"]",
":",
"prev_token",
"=",
"out... | 22.409091 | 23.045455 |
def all(self):
""" Returns list with all indexed datasets. """
datasets = []
query = text("""
SELECT vid
FROM dataset_index;""")
for result in self.execute(query):
res = DatasetSearchResult()
res.vid = result[0]
res.b_score = ... | [
"def",
"all",
"(",
"self",
")",
":",
"datasets",
"=",
"[",
"]",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT vid\n FROM dataset_index;\"\"\"",
")",
"for",
"result",
"in",
"self",
".",
"execute",
"(",
"query",
")",
":",
"res",
"=",
"Dataset... | 26.071429 | 13.785714 |
def looks_like_index(series, index_names=('Unnamed: 0', 'pk', 'index', '')):
""" Tries to infer if the Series (usually leftmost column) should be the index_col
>>> looks_like_index(pd.Series(np.arange(100)))
True
"""
if series.name in index_names:
return True
if (series == series.index.... | [
"def",
"looks_like_index",
"(",
"series",
",",
"index_names",
"=",
"(",
"'Unnamed: 0'",
",",
"'pk'",
",",
"'index'",
",",
"''",
")",
")",
":",
"if",
"series",
".",
"name",
"in",
"index_names",
":",
"return",
"True",
"if",
"(",
"series",
"==",
"series",
... | 31.842105 | 17.789474 |
def _load_schema(name, path=__file__):
"""Load a schema from disk"""
path = os.path.join(os.path.dirname(path), name + '.yaml')
with open(path) as handle:
schema = yaml.safe_load(handle)
fast_schema = rapidjson.Validator(rapidjson.dumps(schema))
return path, (schema, fast_schema) | [
"def",
"_load_schema",
"(",
"name",
",",
"path",
"=",
"__file__",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"name",
"+",
"'.yaml'",
")",
"with",
"open",
"(",
"path",
")",... | 43.142857 | 8.428571 |
def serialize(self, include_class=True, save_dynamic=False, **kwargs):
"""Serializes a **HasProperties** instance to dictionary
This uses the Property serializers to serialize all Property values
to a JSON-compatible dictionary. Properties that are undefined are
not included. If the **H... | [
"def",
"serialize",
"(",
"self",
",",
"include_class",
"=",
"True",
",",
"save_dynamic",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_getting_serialized'",
",",
"False",
")",
":",
"raise",
"utils",
".",
"SelfRefe... | 42.902439 | 20.829268 |
def filter_slaves(selfie, slaves):
"""
Remove slaves that are in an ODOWN or SDOWN state
also remove slaves that do not have 'ok' master-link-status
"""
return [(s['ip'], s['port']) for s in slaves
if not s['is_odown'] and
not s['is_sdown'] and
... | [
"def",
"filter_slaves",
"(",
"selfie",
",",
"slaves",
")",
":",
"return",
"[",
"(",
"s",
"[",
"'ip'",
"]",
",",
"s",
"[",
"'port'",
"]",
")",
"for",
"s",
"in",
"slaves",
"if",
"not",
"s",
"[",
"'is_odown'",
"]",
"and",
"not",
"s",
"[",
"'is_sdown... | 39.666667 | 8.111111 |
def get_server_public(self, password_verifier, server_private):
"""B = (k*v + g^b) % N
:param int password_verifier:
:param int server_private:
:rtype: int
"""
return ((self._mult * password_verifier) + pow(self._gen, server_private, self._prime)) % self._prime | [
"def",
"get_server_public",
"(",
"self",
",",
"password_verifier",
",",
"server_private",
")",
":",
"return",
"(",
"(",
"self",
".",
"_mult",
"*",
"password_verifier",
")",
"+",
"pow",
"(",
"self",
".",
"_gen",
",",
"server_private",
",",
"self",
".",
"_pr... | 37.875 | 20.25 |
def filter_catalog(catalog, **kwargs):
""" Create a new catalog selected from input based on photometry.
Parameters
----------
bright_limit : float
Fraction of catalog based on brightness that should be retained.
Value of 1.00 means full catalog.
max_bright : int
Maximum nu... | [
"def",
"filter_catalog",
"(",
"catalog",
",",
"*",
"*",
"kwargs",
")",
":",
"# interpret input pars",
"bright_limit",
"=",
"kwargs",
".",
"get",
"(",
"'bright_limit'",
",",
"1.00",
")",
"max_bright",
"=",
"kwargs",
".",
"get",
"(",
"'max_bright'",
",",
"None... | 31.25 | 20.204545 |
def _version_from_git_describe():
"""
Read the version from ``git describe``. It returns the latest tag with an
optional suffix if the current directory is not exactly on the tag.
Example::
$ git describe --always
v2.3.2-346-g164a52c075c8
The tag prefix (``v``) and the git commit ... | [
"def",
"_version_from_git_describe",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"_SCAPY_PKG_DIR",
")",
",",
"'.git'",
")",
")",
":",
"# noqa: E501",
"... | 34.073171 | 23.634146 |
def save_loop(self):
"""
Saves the state if it has changed.
"""
last_hash = hash(repr(self.hosts))
while self.running:
eventlet.sleep(self.save_interval)
next_hash = hash(repr(self.hosts))
if next_hash != last_hash:
self.save()
... | [
"def",
"save_loop",
"(",
"self",
")",
":",
"last_hash",
"=",
"hash",
"(",
"repr",
"(",
"self",
".",
"hosts",
")",
")",
"while",
"self",
".",
"running",
":",
"eventlet",
".",
"sleep",
"(",
"self",
".",
"save_interval",
")",
"next_hash",
"=",
"hash",
"... | 31.545455 | 6.090909 |
def zscore(data2d, axis=0):
"""Standardize the mean and variance of the data axis Parameters.
:param data2d: DataFrame to normalize.
:param axis: int, Which axis to normalize across. If 0, normalize across rows,
if 1, normalize across columns. If None, don't change data
... | [
"def",
"zscore",
"(",
"data2d",
",",
"axis",
"=",
"0",
")",
":",
"if",
"axis",
"is",
"None",
":",
"# normalized to mean and std using entire matrix",
"# z_scored = (data2d - data2d.values.mean()) / data2d.values.std(ddof=1)",
"return",
"data2d",
"assert",
"axis",
"in",
"[... | 34.266667 | 22.333333 |
def pdf(self):
"""
Returns the probability density function(pdf).
Returns
-------
function: The probability density function of the distribution.
Examples
--------
>>> from pgmpy.factors.distributions import GaussianDistribution
>>> dist = GD(var... | [
"def",
"pdf",
"(",
"self",
")",
":",
"return",
"lambda",
"*",
"args",
":",
"multivariate_normal",
".",
"pdf",
"(",
"args",
",",
"self",
".",
"mean",
".",
"reshape",
"(",
"1",
",",
"len",
"(",
"self",
".",
"variables",
")",
")",
"[",
"0",
"]",
","... | 35.782609 | 20.043478 |
def distribute(build):
""" distribute the uranium package """
build.packages.install("wheel")
build.packages.install("twine")
build.executables.run([
"python", "setup.py",
"sdist", "bdist_wheel", "--universal", "upload",
])
build.executables.run([
"twine", "upload", "dist... | [
"def",
"distribute",
"(",
"build",
")",
":",
"build",
".",
"packages",
".",
"install",
"(",
"\"wheel\"",
")",
"build",
".",
"packages",
".",
"install",
"(",
"\"twine\"",
")",
"build",
".",
"executables",
".",
"run",
"(",
"[",
"\"python\"",
",",
"\"setup.... | 29.090909 | 14 |
def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
"""
# One iteration changes the opinion of N agent pairs using the following procedure:
# - first one agent is selected
... | [
"def",
"iteration",
"(",
"self",
",",
"node_status",
"=",
"True",
")",
":",
"# One iteration changes the opinion of N agent pairs using the following procedure:",
"# - first one agent is selected",
"# - then a second agent is selected based on a probability that decreases with the distance t... | 48.123077 | 26.584615 |
def shape(self, shape=None):
"""We need to shift buffers in order to change shape"""
if shape is None:
return self._shape
data, color = self.renderer.manager.set_shape(self.model.id, shape)
self.model.data = data
self.color = color
self._shape = shape | [
"def",
"shape",
"(",
"self",
",",
"shape",
"=",
"None",
")",
":",
"if",
"shape",
"is",
"None",
":",
"return",
"self",
".",
"_shape",
"data",
",",
"color",
"=",
"self",
".",
"renderer",
".",
"manager",
".",
"set_shape",
"(",
"self",
".",
"model",
".... | 38 | 13.625 |
def validate(self, value):
"""Validate field value."""
if value is not None and not isinstance(value, bool):
raise ValidationError("field must be a boolean")
super().validate(value) | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"ValidationError",
"(",
"\"field must be a boolean\"",
")",
"super",
"(",
")",
".",
"val... | 35.5 | 17.333333 |
def create_deposit_address(self, currency):
"""Create deposit address of currency for deposit. You can just create one deposit address.
https://docs.kucoin.com/#create-deposit-address
:param currency: Name of currency
:type currency: string
.. code:: python
addres... | [
"def",
"create_deposit_address",
"(",
"self",
",",
"currency",
")",
":",
"data",
"=",
"{",
"'currency'",
":",
"currency",
"}",
"return",
"self",
".",
"_post",
"(",
"'deposit-addresses'",
",",
"True",
",",
"data",
"=",
"data",
")"
] | 24.733333 | 24.4 |
def run(self):
"""Redirects messages until a shutdown message is received."""
while True:
if not self.task_socket.poll(-1):
continue
msg = self.task_socket.recv_multipart()
msg_type = msg[1]
if self.debug:
self.stats.appen... | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"not",
"self",
".",
"task_socket",
".",
"poll",
"(",
"-",
"1",
")",
":",
"continue",
"msg",
"=",
"self",
".",
"task_socket",
".",
"recv_multipart",
"(",
")",
"msg_type",
"=",
"msg",
"... | 38.374101 | 17.381295 |
def extend_relations(self, data, kind):
"""Extend metadata for tables or views
:param data: list of (rel_name, ) tuples
:param kind: either 'tables' or 'views'
:return:
"""
# 'data' is a generator object. It can throw an exception while being
# consumed. This coul... | [
"def",
"extend_relations",
"(",
"self",
",",
"data",
",",
"kind",
")",
":",
"# 'data' is a generator object. It can throw an exception while being",
"# consumed. This could happen if the user has launched the app without",
"# specifying a database name. This exception must be handled to prev... | 41.8 | 18.4 |
def run_code(node: Code, parent_node: Node = None, node_globals: InheritedDict = None, **args): #pylint: disable=unused-argument
'''Executes node content as python module and adds its definitions to globals'''
if not node.xml_node.text:
return
code = node.xml_node.text
try:
globs = node_... | [
"def",
"run_code",
"(",
"node",
":",
"Code",
",",
"parent_node",
":",
"Node",
"=",
"None",
",",
"node_globals",
":",
"InheritedDict",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"#pylint: disable=unused-argument",
"if",
"not",
"node",
".",
"xml_node",
".... | 47.666667 | 24.238095 |
def message_index(index_url):
"""get message index of components for urllib2.
Args:
url(string):
Returns:
list: messages
"""
idx = csv.reader(urllib2.urlopen(index_url), delimiter=':')
messages = []
for line in idx:
messages.append(line)
return messages | [
"def",
"message_index",
"(",
"index_url",
")",
":",
"idx",
"=",
"csv",
".",
"reader",
"(",
"urllib2",
".",
"urlopen",
"(",
"index_url",
")",
",",
"delimiter",
"=",
"':'",
")",
"messages",
"=",
"[",
"]",
"for",
"line",
"in",
"idx",
":",
"messages",
".... | 21.285714 | 20.428571 |
def inst_repr(instance, fmt='str', public_only=True):
"""
Generate class instance signature from its __dict__
From python 3.6 dict is ordered and order of attributes will be preserved automatically
Args:
instance: class instance
fmt: ['json', 'str']
public_only: if display publi... | [
"def",
"inst_repr",
"(",
"instance",
",",
"fmt",
"=",
"'str'",
",",
"public_only",
"=",
"True",
")",
":",
"if",
"not",
"hasattr",
"(",
"instance",
",",
"'__dict__'",
")",
":",
"return",
"''",
"if",
"public_only",
":",
"inst_dict",
"=",
"{",
"k",
":",
... | 30.146341 | 19.658537 |
def _simulate_matern(D1, D2, D3, N, num_inducing, plot_sim=False):
"""Simulate some data drawn from a matern covariance and a periodic exponential for use in MRD demos."""
Q_signal = 4
import GPy
import numpy as np
np.random.seed(3000)
k = GPy.kern.Matern32(Q_signal, 1., lengthscale=(np.random.... | [
"def",
"_simulate_matern",
"(",
"D1",
",",
"D2",
",",
"D3",
",",
"N",
",",
"num_inducing",
",",
"plot_sim",
"=",
"False",
")",
":",
"Q_signal",
"=",
"4",
"import",
"GPy",
"import",
"numpy",
"as",
"np",
"np",
".",
"random",
".",
"seed",
"(",
"3000",
... | 38.384615 | 22.487179 |
def create_api_method_response(restApiId, resourcePath, httpMethod, statusCode, responseParameters=None,
responseModels=None, region=None, key=None, keyid=None, profile=None):
'''
Create API method response for a method on a given resource in the given API
CLI Example:
.... | [
"def",
"create_api_method_response",
"(",
"restApiId",
",",
"resourcePath",
",",
"httpMethod",
",",
"statusCode",
",",
"responseParameters",
"=",
"None",
",",
"responseModels",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"="... | 56.75 | 43.178571 |
def from_hdf5(cls, filename, dataset_name=None, group_name=None):
r"""Attempts read in and convert a dataset in an hdf5 file into a
unyt_array.
Parameters
----------
filename: string
The filename to of the hdf5 file.
dataset_name: string
The name of ... | [
"def",
"from_hdf5",
"(",
"cls",
",",
"filename",
",",
"dataset_name",
"=",
"None",
",",
"group_name",
"=",
"None",
")",
":",
"from",
"unyt",
".",
"_on_demand_imports",
"import",
"_h5py",
"as",
"h5py",
"import",
"pickle",
"if",
"dataset_name",
"is",
"None",
... | 32.777778 | 20.222222 |
def analyze_one_classification_result(storage_client, file_path,
adv_batch, dataset_batches,
dataset_meta):
"""Reads and analyzes one classification result.
This method reads file with classification result and counts
how many images wer... | [
"def",
"analyze_one_classification_result",
"(",
"storage_client",
",",
"file_path",
",",
"adv_batch",
",",
"dataset_batches",
",",
"dataset_meta",
")",
":",
"class_result",
"=",
"read_classification_results",
"(",
"storage_client",
",",
"file_path",
")",
"if",
"class_r... | 38.282609 | 18.869565 |
def getcellslicenp(self, columnname, nparray, rownr, blc, trc, inc=[]):
"""Get a slice from a column cell into the given numpy array.
The columnname and (0-relative) rownr indicate the table cell.
The numpy array has to be C-contiguous with a shape matching the
shape of the slice. Data... | [
"def",
"getcellslicenp",
"(",
"self",
",",
"columnname",
",",
"nparray",
",",
"rownr",
",",
"blc",
",",
"trc",
",",
"inc",
"=",
"[",
"]",
")",
":",
"if",
"not",
"nparray",
".",
"flags",
".",
"c_contiguous",
"or",
"nparray",
".",
"size",
"==",
"0",
... | 51.35 | 27.35 |
def cgnr(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None,
callback=None, residuals=None):
"""Conjugate Gradient, Normal Residual algorithm.
Applies CG to the normal equations, A.H A x = b. Left preconditioning
is supported. Note that unless A is well-conditioned, the use of
CGNR is ... | [
"def",
"cgnr",
"(",
"A",
",",
"b",
",",
"x0",
"=",
"None",
",",
"tol",
"=",
"1e-5",
",",
"maxiter",
"=",
"None",
",",
"xtype",
"=",
"None",
",",
"M",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"residuals",
"=",
"None",
")",
":",
"# Store t... | 28.75 | 20.822917 |
def exprvar(name, index=None):
r"""Return a unique Expression variable.
A Boolean *variable* is an abstract numerical quantity that may assume any
value in the set :math:`B = \{0, 1\}`.
The ``exprvar`` function returns a unique Boolean variable instance
represented by a logic expression.
Variab... | [
"def",
"exprvar",
"(",
"name",
",",
"index",
"=",
"None",
")",
":",
"bvar",
"=",
"boolfunc",
".",
"var",
"(",
"name",
",",
"index",
")",
"try",
":",
"var",
"=",
"_LITS",
"[",
"bvar",
".",
"uniqid",
"]",
"except",
"KeyError",
":",
"var",
"=",
"_LI... | 34.688889 | 19.244444 |
def do_undisplay(self, arg):
"""
undisplay expression
Remove expression from the display list.
"""
try:
del self._get_display_list()[arg]
except KeyError:
print('** %s not in the display list **' % arg, file=self.stdout) | [
"def",
"do_undisplay",
"(",
"self",
",",
"arg",
")",
":",
"try",
":",
"del",
"self",
".",
"_get_display_list",
"(",
")",
"[",
"arg",
"]",
"except",
"KeyError",
":",
"print",
"(",
"'** %s not in the display list **'",
"%",
"arg",
",",
"file",
"=",
"self",
... | 28.4 | 15.8 |
def responseInColor(request, status, headers, prefix='Response', opts=None):
"Prints the response info in color"
code, message = status.split(None, 1)
message = '%s [%s] => Request %s %s %s on pid %d' % (
prefix,
code,
str(request.host),
request.method,
request.path,
... | [
"def",
"responseInColor",
"(",
"request",
",",
"status",
",",
"headers",
",",
"prefix",
"=",
"'Response'",
",",
"opts",
"=",
"None",
")",
":",
"code",
",",
"message",
"=",
"status",
".",
"split",
"(",
"None",
",",
"1",
")",
"message",
"=",
"'%s [%s] =>... | 29.222222 | 16.777778 |
def show(self):
""" More details about the selected issue or trace frame.
"""
self._verify_entrypoint_selected()
if self.current_issue_instance_id != -1:
self._show_current_issue_instance()
return
self._show_current_trace_frame() | [
"def",
"show",
"(",
"self",
")",
":",
"self",
".",
"_verify_entrypoint_selected",
"(",
")",
"if",
"self",
".",
"current_issue_instance_id",
"!=",
"-",
"1",
":",
"self",
".",
"_show_current_issue_instance",
"(",
")",
"return",
"self",
".",
"_show_current_trace_fr... | 28.6 | 14.4 |
def parse_tuple_type_str(old_from_type_str):
"""
Used by BaseCoder subclasses as a convenience for implementing the
``from_type_str`` method required by ``ABIRegistry``. Useful if normalizing
then parsing a tuple type string is required in that method.
"""
@functools.wraps(old_from_type_str)
... | [
"def",
"parse_tuple_type_str",
"(",
"old_from_type_str",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"old_from_type_str",
")",
"def",
"new_from_type_str",
"(",
"cls",
",",
"type_str",
",",
"registry",
")",
":",
"normalized_type_str",
"=",
"normalize",
"(",
"t... | 33.645161 | 16.870968 |
def get_string_counter(fc, feature_name):
'''Find and return a :class:`~dossier.fc.StringCounter` at
`feature_name` or at `DISPLAY_PREFIX` + `feature_name` in the
`fc`, or return None.
'''
if feature_name not in fc:
feature = fc.get(FC.DISPLAY_PREFIX + feature_name)
else:
featur... | [
"def",
"get_string_counter",
"(",
"fc",
",",
"feature_name",
")",
":",
"if",
"feature_name",
"not",
"in",
"fc",
":",
"feature",
"=",
"fc",
".",
"get",
"(",
"FC",
".",
"DISPLAY_PREFIX",
"+",
"feature_name",
")",
"else",
":",
"feature",
"=",
"fc",
".",
"... | 30.5 | 19.214286 |
def _serialize(self, target_obj, data_type=None, **kwargs):
"""Serialize data into a string according to type.
:param target_obj: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str, dict
:raises: SerializationError if serialization fails... | [
"def",
"_serialize",
"(",
"self",
",",
"target_obj",
",",
"data_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"key_transformer",
"=",
"kwargs",
".",
"get",
"(",
"\"key_transformer\"",
",",
"self",
".",
"key_transformer",
")",
"keep_readonly",
"=",
... | 47.733333 | 21.819048 |
def set_property_value(self, name, value, dry_run=False):
"""Set or remove property value.
See DAVResource.set_property_value()
"""
if value is None:
# We can never remove properties
raise DAVError(HTTP_FORBIDDEN)
if name == "{virtres:}tags":
... | [
"def",
"set_property_value",
"(",
"self",
",",
"name",
",",
"value",
",",
"dry_run",
"=",
"False",
")",
":",
"if",
"value",
"is",
"None",
":",
"# We can never remove properties",
"raise",
"DAVError",
"(",
"HTTP_FORBIDDEN",
")",
"if",
"name",
"==",
"\"{virtres:... | 36.5 | 12.708333 |
async def load_message(self, msg_type, msg=None):
"""
Loads message if the given type from the reader.
Supports reading directly to existing message.
:param msg_type:
:param msg:
:return:
"""
msg = msg_type() if msg is None else msg
fields = msg_t... | [
"async",
"def",
"load_message",
"(",
"self",
",",
"msg_type",
",",
"msg",
"=",
"None",
")",
":",
"msg",
"=",
"msg_type",
"(",
")",
"if",
"msg",
"is",
"None",
"else",
"msg",
"fields",
"=",
"msg_type",
".",
"f_specs",
"(",
")",
"if",
"msg_type",
"else"... | 30.533333 | 17.733333 |
def audit_customer_subscription(customer, unknown=True):
"""
Audits the provided customer's subscription against stripe and returns a pair
that contains a boolean and a result type.
Default result types can be found in zebra.conf.defaults and can be
overridden in your project's settings.
"""
... | [
"def",
"audit_customer_subscription",
"(",
"customer",
",",
"unknown",
"=",
"True",
")",
":",
"if",
"(",
"hasattr",
"(",
"customer",
",",
"'suspended'",
")",
"and",
"customer",
".",
"suspended",
")",
":",
"result",
"=",
"AUDIT_RESULTS",
"[",
"'suspended'",
"... | 41.238095 | 18.857143 |
def generate_pretty_output(self, stat, verbose, output_function, logs=True):
"""
Send the formated to the provided function
:param stat: if True print stat instead of full output
:param verbose: bool
:param output_function: function to send output to
"""
has_che... | [
"def",
"generate_pretty_output",
"(",
"self",
",",
"stat",
",",
"verbose",
",",
"output_function",
",",
"logs",
"=",
"True",
")",
":",
"has_check",
"=",
"False",
"for",
"r",
"in",
"self",
".",
"results",
":",
"has_check",
"=",
"True",
"if",
"stat",
":",
... | 40.153846 | 17.076923 |
def is_writable_dir(directory, **kwargs):
""" tests to see if the directory is writable. If the directory does
it can attempt to create it. If unable returns False
args:
directory: filepath to the directory
kwargs:
mkdir[bool]: create the directory if it does not exist
... | [
"def",
"is_writable_dir",
"(",
"directory",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"testfile",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
"dir",
"=",
"directory",
")",
"testfile",
".",
"close",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"i... | 30.551724 | 16.034483 |
async def _dhcp_handler(self):
"""
Mini DHCP server, respond DHCP packets from OpenFlow
"""
conn = self._connection
ofdef = self._connection.openflowdef
l3 = self._parent._gettableindex('l3input', self._connection.protocol.vhost)
dhcp_packet_matcher = OpenflowAsyn... | [
"async",
"def",
"_dhcp_handler",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"_connection",
"ofdef",
"=",
"self",
".",
"_connection",
".",
"openflowdef",
"l3",
"=",
"self",
".",
"_parent",
".",
"_gettableindex",
"(",
"'l3input'",
",",
"self",
".",
"... | 63.833333 | 28.042857 |
def init_requests_cache(refresh_cache=False):
"""
Initializes a cache which the ``requests`` library will consult for
responses, before making network requests.
:param refresh_cache: Whether the cache should be cleared out
"""
# Cache data from external sources; used in some checks
dirs = A... | [
"def",
"init_requests_cache",
"(",
"refresh_cache",
"=",
"False",
")",
":",
"# Cache data from external sources; used in some checks",
"dirs",
"=",
"AppDirs",
"(",
"\"stix2-validator\"",
",",
"\"OASIS\"",
")",
"# Create cache dir if doesn't exist",
"try",
":",
"os",
".",
... | 34 | 15.090909 |
def register(self, lookup: Lookup, encoder: Encoder, decoder: Decoder, label: str=None) -> None:
"""
Registers the given ``encoder`` and ``decoder`` under the given
``lookup``. A unique string label may be optionally provided that can
be used to refer to the registration by name.
... | [
"def",
"register",
"(",
"self",
",",
"lookup",
":",
"Lookup",
",",
"encoder",
":",
"Encoder",
",",
"decoder",
":",
"Decoder",
",",
"label",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"register_encoder",
"(",
"lookup",
",",
"encoder",... | 58.918919 | 30.486486 |
def preprocess_fallback_config():
"""Preprocesses the fallback include and library paths depending on the
platform."""
global LIBIGRAPH_FALLBACK_INCLUDE_DIRS
global LIBIGRAPH_FALLBACK_LIBRARY_DIRS
global LIBIGRAPH_FALLBACK_LIBRARIES
if os.name == 'nt' and distutils.ccompiler.get_default_com... | [
"def",
"preprocess_fallback_config",
"(",
")",
":",
"global",
"LIBIGRAPH_FALLBACK_INCLUDE_DIRS",
"global",
"LIBIGRAPH_FALLBACK_LIBRARY_DIRS",
"global",
"LIBIGRAPH_FALLBACK_LIBRARIES",
"if",
"os",
".",
"name",
"==",
"'nt'",
"and",
"distutils",
".",
"ccompiler",
".",
"get_d... | 52.352941 | 27.382353 |
def Input_dispatchMouseEvent(self, type, x, y, **kwargs):
"""
Function path: Input.dispatchMouseEvent
Domain: Input
Method name: dispatchMouseEvent
Parameters:
Required arguments:
'type' (type: string) -> Type of the mouse event.
'x' (type: number) -> X coordinate of the event relative to ... | [
"def",
"Input_dispatchMouseEvent",
"(",
"self",
",",
"type",
",",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"type",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'type' must be of type '['str']'. Received type: '%s'\"",
... | 51.135593 | 29.338983 |
def find_node_group_membership(self, node):
"""
Identifies the group for which a node belongs to.
"""
for group, nodelist in self.nodes.items():
if node in nodelist:
return group | [
"def",
"find_node_group_membership",
"(",
"self",
",",
"node",
")",
":",
"for",
"group",
",",
"nodelist",
"in",
"self",
".",
"nodes",
".",
"items",
"(",
")",
":",
"if",
"node",
"in",
"nodelist",
":",
"return",
"group"
] | 33.142857 | 7.142857 |
def AgregarReceptor(self, cuit, iibb, nro_socio, nro_fet, **kwargs):
"Agrego un receptor a la liq."
rcpt = dict(cuit=cuit, iibb=iibb, nroSocio=nro_socio, nroFET=nro_fet)
self.solicitud['receptor'] = rcpt
return True | [
"def",
"AgregarReceptor",
"(",
"self",
",",
"cuit",
",",
"iibb",
",",
"nro_socio",
",",
"nro_fet",
",",
"*",
"*",
"kwargs",
")",
":",
"rcpt",
"=",
"dict",
"(",
"cuit",
"=",
"cuit",
",",
"iibb",
"=",
"iibb",
",",
"nroSocio",
"=",
"nro_socio",
",",
"... | 48.6 | 17.8 |
def is_not(self, other):
"""
Ensures :attr:`subject` is not *other* (object identity check).
"""
self._run(unittest_case.assertIsNot, (self._subject, other))
return ChainInspector(self._subject) | [
"def",
"is_not",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_run",
"(",
"unittest_case",
".",
"assertIsNot",
",",
"(",
"self",
".",
"_subject",
",",
"other",
")",
")",
"return",
"ChainInspector",
"(",
"self",
".",
"_subject",
")"
] | 38.166667 | 13.166667 |
def get_timeseries_list(points, timestamp):
"""Convert a list of `GaugePoint`s into a list of `TimeSeries`.
Get a :class:`opencensus.metrics.export.time_series.TimeSeries` for each
measurement in `points`. Each series contains a single
:class:`opencensus.metrics.export.point.Point` that represents the ... | [
"def",
"get_timeseries_list",
"(",
"points",
",",
"timestamp",
")",
":",
"ts_list",
"=",
"[",
"]",
"for",
"lv",
",",
"gp",
"in",
"points",
".",
"items",
"(",
")",
":",
"point",
"=",
"point_module",
".",
"Point",
"(",
"gp",
".",
"to_point_value",
"(",
... | 42.136364 | 21.954545 |
def rename_abiext(self, inext, outext):
"""Rename the Abinit file with extension inext with the new extension outext"""
infile = self.has_abiext(inext)
if not infile:
raise RuntimeError('no file with extension %s in %s' % (inext, self))
for i in range(len(infile) - 1, -1, -1... | [
"def",
"rename_abiext",
"(",
"self",
",",
"inext",
",",
"outext",
")",
":",
"infile",
"=",
"self",
".",
"has_abiext",
"(",
"inext",
")",
"if",
"not",
"infile",
":",
"raise",
"RuntimeError",
"(",
"'no file with extension %s in %s'",
"%",
"(",
"inext",
",",
... | 38.266667 | 19.4 |
def get_step_name(self, index: int) -> str:
"""
Give the waterfall step a unique name
"""
step_name = self._steps[index].__qualname__
if not step_name or ">" in step_name :
step_name = f"Step{index + 1}of{len(self._steps)}"
return step_name | [
"def",
"get_step_name",
"(",
"self",
",",
"index",
":",
"int",
")",
"->",
"str",
":",
"step_name",
"=",
"self",
".",
"_steps",
"[",
"index",
"]",
".",
"__qualname__",
"if",
"not",
"step_name",
"or",
"\">\"",
"in",
"step_name",
":",
"step_name",
"=",
"f... | 29.3 | 14.3 |
def get_tables(self):
""" Returns a collection of this worksheet tables"""
url = self.build_url(self._endpoints.get('get_tables'))
response = self.session.get(url)
if not response:
return []
data = response.json()
return [self.table_constructor(parent=self... | [
"def",
"get_tables",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_tables'",
")",
")",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
"if",
"not",
"response"... | 30.307692 | 23.230769 |
def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None,
axis=None, **kwargs):
'''
Plot bar for each value in `values`, colored based on values mapped onto
the specified color map.
Args
----
values (pandas.Series) : Numeric values to plot one bar per va... | [
"def",
"plot_color_map_bars",
"(",
"values",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"color_map",
"=",
"None",
",",
"axis",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"axis",
"is",
"None",
":",
"fig",
",",
"axis",
"=",
... | 32.625 | 24.8125 |
def upsert(self, events):
"""Inserts/updates the given events into MySQL"""
existing = self.get_existing_keys(events)
inserts = [e for e in events if not e[self.key] in existing]
updates = [e for e in events if e[self.key] in existing]
self.insert(inserts)
self.update(upd... | [
"def",
"upsert",
"(",
"self",
",",
"events",
")",
":",
"existing",
"=",
"self",
".",
"get_existing_keys",
"(",
"events",
")",
"inserts",
"=",
"[",
"e",
"for",
"e",
"in",
"events",
"if",
"not",
"e",
"[",
"self",
".",
"key",
"]",
"in",
"existing",
"]... | 45.571429 | 14.285714 |
def mode(self, **kwargs):
"""Returns a new QueryCompiler with modes calculated for each label along given axis.
Returns:
A new QueryCompiler with modes calculated.
"""
axis = kwargs.get("axis", 0)
def mode_builder(df, **kwargs):
result = df.mode(**kwargs... | [
"def",
"mode",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"axis",
"=",
"kwargs",
".",
"get",
"(",
"\"axis\"",
",",
"0",
")",
"def",
"mode_builder",
"(",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"df",
".",
"mode",
"(",
"*",
... | 43.763158 | 18.5 |
def subcommand(self, *args):
"""Get subcommand acting on a service. Subcommand will run in service directory
and with the environment variables used to run the service itself.
Args:
*args: Arguments to run command (e.g. "redis-cli", "-n", "1")
Returns:
Subcom... | [
"def",
"subcommand",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"Subcommand",
"(",
"*",
"args",
",",
"directory",
"=",
"self",
".",
"directory",
",",
"env_vars",
"=",
"self",
".",
"env_vars",
")"
] | 37.909091 | 24.090909 |
def get_files_by_path(path):
'''Get a file or set of files from a file path
Return list of files with path
'''
if os.path.isfile(path):
return [path]
if os.path.isdir(path):
return get_morph_files(path)
raise IOError('Invalid data path %s' % path) | [
"def",
"get_files_by_path",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"[",
"path",
"]",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"get_morph_files",
"(",
"path",
")... | 25.363636 | 17.909091 |
def _find_spec_from_path(name, path=None):
"""Return the spec for the specified module.
First, sys.modules is checked to see if the module was already imported. If
so, then sys.modules[name].__spec__ is returned. If that happens to be
set to None, then ValueError is raised. If the module is not in
s... | [
"def",
"_find_spec_from_path",
"(",
"name",
",",
"path",
"=",
"None",
")",
":",
"if",
"name",
"not",
"in",
"sys",
".",
"modules",
":",
"return",
"_find_spec",
"(",
"name",
",",
"path",
")",
"else",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"nam... | 43.730769 | 20.615385 |
def _sheet_meta_from_regex(m, sheets, old_name, name, ct_paleo, ct_chron):
"""
Build metadata for a sheet. Receive valid regex match object and use that to create metadata.
:param obj m: Regex match object
:param list sheets: Running list of sheet metadata
:param str old_name: Original sheet name
... | [
"def",
"_sheet_meta_from_regex",
"(",
"m",
",",
"sheets",
",",
"old_name",
",",
"name",
",",
"ct_paleo",
",",
"ct_chron",
")",
":",
"try",
":",
"idx_model",
"=",
"None",
"idx_table",
"=",
"None",
"pc",
"=",
"m",
".",
"group",
"(",
"1",
")",
"# Get the ... | 39.333333 | 17.033333 |
def locate_unknown_arc_lines(self, slitlet2d,
times_sigma_threshold=15,
minimum_threshold=None,
delta_x_max=30,
delta_y_min=30,
min_dist_from_middle=15):
... | [
"def",
"locate_unknown_arc_lines",
"(",
"self",
",",
"slitlet2d",
",",
"times_sigma_threshold",
"=",
"15",
",",
"minimum_threshold",
"=",
"None",
",",
"delta_x_max",
"=",
"30",
",",
"delta_y_min",
"=",
"30",
",",
"min_dist_from_middle",
"=",
"15",
")",
":",
"#... | 49.303249 | 17.754513 |
def apply_patch(self, patch_name):
"""Applies the patch *patch_name* on to the current working directory in
case the patch exists. In case applying the patch was successful, the
patch is automatically removed from the stash. Returns ``True`` in case
applying the patch was successful, oth... | [
"def",
"apply_patch",
"(",
"self",
",",
"patch_name",
")",
":",
"if",
"patch_name",
"in",
"self",
".",
"get_patches",
"(",
")",
":",
"patch_path",
"=",
"self",
".",
"_get_patch_path",
"(",
"patch_name",
")",
"# Apply the patch, and determine the files that have been... | 46.806452 | 22.967742 |
def example_generator(all_files, urls_path, sum_token):
"""Generate examples."""
def fix_run_on_sents(line):
if u"@highlight" in line:
return line
if not line:
return line
if line[-1] in END_TOKENS:
return line
return line + u"."
filelist = example_splits(urls_path, all_files)
... | [
"def",
"example_generator",
"(",
"all_files",
",",
"urls_path",
",",
"sum_token",
")",
":",
"def",
"fix_run_on_sents",
"(",
"line",
")",
":",
"if",
"u\"@highlight\"",
"in",
"line",
":",
"return",
"line",
"if",
"not",
"line",
":",
"return",
"line",
"if",
"l... | 26.513514 | 18.945946 |
def get_conditional_instance(self, parameter_names):
""" get a new Schur instance that includes conditional update from
some parameters becoming known perfectly
Parameters
----------
parameter_names : list
parameters that are to be treated as notionally perfectly
... | [
"def",
"get_conditional_instance",
"(",
"self",
",",
"parameter_names",
")",
":",
"if",
"not",
"isinstance",
"(",
"parameter_names",
",",
"list",
")",
":",
"parameter_names",
"=",
"[",
"parameter_names",
"]",
"for",
"iname",
",",
"name",
"in",
"enumerate",
"("... | 39.204082 | 18.857143 |
def get_mac_address(
interface=None, ip=None, ip6=None,
hostname=None, network_request=True
):
# type: (Optional[str], Optional[str], Optional[str], Optional[str], bool) -> Optional[str]
"""Get a Unicast IEEE 802 MAC-48 address from a local interface or remote host.
You must only use one of... | [
"def",
"get_mac_address",
"(",
"interface",
"=",
"None",
",",
"ip",
"=",
"None",
",",
"ip6",
"=",
"None",
",",
"hostname",
"=",
"None",
",",
"network_request",
"=",
"True",
")",
":",
"# type: (Optional[str], Optional[str], Optional[str], Optional[str], bool) -> Option... | 39.927419 | 21.927419 |
def expects_none(options):
"""
Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected.
"""
if any(options.get(key) is no... | [
"def",
"expects_none",
"(",
"options",
")",
":",
"if",
"any",
"(",
"options",
".",
"get",
"(",
"key",
")",
"is",
"not",
"None",
"for",
"key",
"in",
"[",
"\"count\"",
",",
"\"maximum\"",
",",
"\"minimum\"",
",",
"\"between\"",
"]",
")",
":",
"return",
... | 29.333333 | 26.266667 |
def reload_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
reload = ET.Element("reload")
config = reload
input = ET.SubElement(reload, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwa... | [
"def",
"reload_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"reload",
"=",
"ET",
".",
"Element",
"(",
"\"reload\"",
")",
"config",
"=",
"reload",
"input",
"=",
"ET",
"."... | 35.083333 | 10.333333 |
def add_point(self, point, value, check=True):
"""Add a point to the TextTier
:param int point: Time of the point.
:param str value: Text of the point.
:param bool check: Flag to check for overlap.
:raises Exception: If overlap or wrong tiertype.
"""
if self.tier... | [
"def",
"add_point",
"(",
"self",
",",
"point",
",",
"value",
",",
"check",
"=",
"True",
")",
":",
"if",
"self",
".",
"tier_type",
"!=",
"'TextTier'",
":",
"raise",
"Exception",
"(",
"'Tiertype must be TextTier.'",
")",
"if",
"check",
"and",
"any",
"(",
"... | 43 | 11.538462 |
def _execShowCountCmd(self, showcmd):
"""Execute 'show' command and return result dictionary.
@param cmd: Command string.
@return: Result dictionary.
"""
result = None
lines = self._execCmd("show", showcmd + " count")
for line in line... | [
"def",
"_execShowCountCmd",
"(",
"self",
",",
"showcmd",
")",
":",
"result",
"=",
"None",
"lines",
"=",
"self",
".",
"_execCmd",
"(",
"\"show\"",
",",
"showcmd",
"+",
"\" count\"",
")",
"for",
"line",
"in",
"lines",
":",
"mobj",
"=",
"re",
".",
"match"... | 32 | 12 |
def get_first_of_week(self):
"""
Returns an integer representing the first day of the week.
0 represents Monday, 6 represents Sunday.
"""
if self.first_of_week is None:
raise ImproperlyConfigured("%s.first_of_week is required." % self.__class__.__name__)
if s... | [
"def",
"get_first_of_week",
"(",
"self",
")",
":",
"if",
"self",
".",
"first_of_week",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"%s.first_of_week is required.\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"if",
"self",
".",
"first_of... | 45.363636 | 21.727273 |
def delete_index(self, index_name):
"""
Removes an existing index in the locally cached DesignDocument
indexes dictionary.
:param str index_name: Name used to identify the index.
"""
index = self.get_index(index_name)
if index is None:
return
... | [
"def",
"delete_index",
"(",
"self",
",",
"index_name",
")",
":",
"index",
"=",
"self",
".",
"get_index",
"(",
"index_name",
")",
"if",
"index",
"is",
"None",
":",
"return",
"self",
".",
"indexes",
".",
"__delitem__",
"(",
"index_name",
")"
] | 28.833333 | 16.166667 |
def check_git_version():
"""Check the installed git version against a known-stable version.
If the git version is less then ``MIN_GIT_VERSION``, a warning is raised.
If git is not installed at all on this system, we also raise a warning for
that.
The original reason why this check was introduced ... | [
"def",
"check_git_version",
"(",
")",
":",
"try",
":",
"version",
"=",
"git_version",
"(",
")",
"except",
"exceptions",
".",
"SimplGitCommandError",
":",
"warnings",
".",
"warn",
"(",
"\"Git does not appear to be installed!\"",
",",
"exceptions",
".",
"GitWarning",
... | 39.560976 | 22.902439 |
def editpermissions_group_view(self, request, group_id, forum_id=None):
""" Allows to edit group permissions for the considered forum.
The view displays a form to define which permissions are granted for the given group for the
considered forum.
"""
group = get_object_or_404(Gr... | [
"def",
"editpermissions_group_view",
"(",
"self",
",",
"request",
",",
"group_id",
",",
"forum_id",
"=",
"None",
")",
":",
"group",
"=",
"get_object_or_404",
"(",
"Group",
",",
"pk",
"=",
"group_id",
")",
"forum",
"=",
"get_object_or_404",
"(",
"Forum",
",",... | 43.684211 | 27.421053 |
def _merge_metadata(samples):
"""Merge all metadata into CSV file"""
samples = list(utils.flatten(samples))
out_dir = dd.get_work_dir(samples[0])
logger.info("summarize metadata")
out_file = os.path.join(out_dir, "metadata.csv")
sample_metrics = collections.defaultdict(dict)
for s in samples... | [
"def",
"_merge_metadata",
"(",
"samples",
")",
":",
"samples",
"=",
"list",
"(",
"utils",
".",
"flatten",
"(",
"samples",
")",
")",
"out_dir",
"=",
"dd",
".",
"get_work_dir",
"(",
"samples",
"[",
"0",
"]",
")",
"logger",
".",
"info",
"(",
"\"summarize ... | 41.444444 | 12.666667 |
def _get_populate_values(self, instance) -> Tuple[str, str]:
"""Gets all values (for each language) from the
specified's instance's `populate_from` field.
Arguments:
instance:
The instance to get the values from.
Returns:
A list of (lang_code, va... | [
"def",
"_get_populate_values",
"(",
"self",
",",
"instance",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"return",
"[",
"(",
"lang_code",
",",
"self",
".",
"_get_populate_from_value",
"(",
"instance",
",",
"self",
".",
"populate_from",
",",
"lang... | 27.043478 | 18.347826 |
def is_ip_address(value, **kwargs):
"""Indicate whether ``value`` is a valid IP address (version 4 or version 6).
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains ... | [
"def",
"is_ip_address",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"ip_address",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Ex... | 29.45 | 22.15 |
def render(self, context):
"""Handle the actual rendering.
"""
user = self._get_value(self.user_key, context)
feature = self._get_value(self.feature, context)
if feature is None:
return ''
allowed = show_feature(user, feature)
return self.nodelist.re... | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"user",
"=",
"self",
".",
"_get_value",
"(",
"self",
".",
"user_key",
",",
"context",
")",
"feature",
"=",
"self",
".",
"_get_value",
"(",
"self",
".",
"feature",
",",
"context",
")",
"if",
"fea... | 31.090909 | 16.727273 |
def cmd_post(self, connection, sender, target, payload):
"""
Sends a message
"""
msg_target, topic, content = self.parse_payload(payload)
def callback(sender, payload):
logging.info("POST RES from %s: %s", sender, payload)
self.__herald.post(msg_target, topi... | [
"def",
"cmd_post",
"(",
"self",
",",
"connection",
",",
"sender",
",",
"target",
",",
"payload",
")",
":",
"msg_target",
",",
"topic",
",",
"content",
"=",
"self",
".",
"parse_payload",
"(",
"payload",
")",
"def",
"callback",
"(",
"sender",
",",
"payload... | 33.2 | 18.8 |
def namedb_get_historic_names_by_address( cur, address, offset=None, count=None ):
"""
Get the list of all names ever owned by this address (except the current one), ordered by creation date.
Return a list of {'name': ..., 'block_id': ..., 'vtxindex': ...}}
"""
query = "SELECT name_records.name,his... | [
"def",
"namedb_get_historic_names_by_address",
"(",
"cur",
",",
"address",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"query",
"=",
"\"SELECT name_records.name,history.block_id,history.vtxindex FROM name_records JOIN history ON name_records.name = history.hi... | 34.129032 | 28.903226 |
def centralManagerDidUpdateState_(self, manager):
"""Called when the BLE adapter is powered on and ready to scan/connect
to devices.
"""
logger.debug('centralManagerDidUpdateState called')
# Notify adapter about changed central state.
get_provider()._adapter._state_change... | [
"def",
"centralManagerDidUpdateState_",
"(",
"self",
",",
"manager",
")",
":",
"logger",
".",
"debug",
"(",
"'centralManagerDidUpdateState called'",
")",
"# Notify adapter about changed central state.",
"get_provider",
"(",
")",
".",
"_adapter",
".",
"_state_changed",
"("... | 47.428571 | 12.142857 |
def emit_toi_stats(toi_set, peripherals):
"""
Calculates new TOI stats and emits them via statsd.
"""
count_by_zoom = defaultdict(int)
total = 0
for coord_int in toi_set:
coord = coord_unmarshall_int(coord_int)
count_by_zoom[coord.zoom] += 1
total += 1
peripherals.s... | [
"def",
"emit_toi_stats",
"(",
"toi_set",
",",
"peripherals",
")",
":",
"count_by_zoom",
"=",
"defaultdict",
"(",
"int",
")",
"total",
"=",
"0",
"for",
"coord_int",
"in",
"toi_set",
":",
"coord",
"=",
"coord_unmarshall_int",
"(",
"coord_int",
")",
"count_by_zoo... | 28.666667 | 15.444444 |
def constant_propagation(block, silence_unexpected_net_warnings=False):
""" Removes excess constants in the block.
Note on resulting block:
The output of the block can have wirevectors that are driven but not
listened to. This is to be expected. These are to be removed by the
_remove_unlistened_net... | [
"def",
"constant_propagation",
"(",
"block",
",",
"silence_unexpected_net_warnings",
"=",
"False",
")",
":",
"net_count",
"=",
"_NetCount",
"(",
"block",
")",
"while",
"net_count",
".",
"shrinking",
"(",
")",
":",
"_constant_prop_pass",
"(",
"block",
",",
"silen... | 42 | 17.545455 |
def _prepare_memoization_key(args, kwargs):
"""
Make a tuple of arguments which can be used as a key
for a memoized function's lookup_table. If some object can't be hashed
then used its __repr__ instead.
"""
key_list = []
for arg in args:
try:
hash(arg)
key_li... | [
"def",
"_prepare_memoization_key",
"(",
"args",
",",
"kwargs",
")",
":",
"key_list",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"try",
":",
"hash",
"(",
"arg",
")",
"key_list",
".",
"append",
"(",
"arg",
")",
"except",
":",
"key_list",
".",
"app... | 27.761905 | 14.809524 |
def _dmi_cast(key, val, clean=True):
'''
Simple caster thingy for trying to fish out at least ints & lists from strings
'''
if clean and not _dmi_isclean(key, val):
return
elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE):
if ',' in val:
val = [el.... | [
"def",
"_dmi_cast",
"(",
"key",
",",
"val",
",",
"clean",
"=",
"True",
")",
":",
"if",
"clean",
"and",
"not",
"_dmi_isclean",
"(",
"key",
",",
"val",
")",
":",
"return",
"elif",
"not",
"re",
".",
"match",
"(",
"r'serial|part|asset|product'",
",",
"key"... | 29.1875 | 23.1875 |
def one_item(self, item, detach:bool=False, denorm:bool=False, cpu:bool=False):
"Get `item` into a batch. Optionally `detach` and `denorm`."
ds = self.single_ds
with ds.set_item(item):
return self.one_batch(ds_type=DatasetType.Single, detach=detach, denorm=denorm, cpu=cpu) | [
"def",
"one_item",
"(",
"self",
",",
"item",
",",
"detach",
":",
"bool",
"=",
"False",
",",
"denorm",
":",
"bool",
"=",
"False",
",",
"cpu",
":",
"bool",
"=",
"False",
")",
":",
"ds",
"=",
"self",
".",
"single_ds",
"with",
"ds",
".",
"set_item",
... | 61 | 29.8 |
def schedCoro(self, coro):
'''
Schedules a free-running coroutine to run on this base's event loop. Kills the coroutine if Base is fini'd.
It does not pend on coroutine completion.
Precondition:
This function is *not* threadsafe and must be run on the Base's event loop
... | [
"def",
"schedCoro",
"(",
"self",
",",
"coro",
")",
":",
"import",
"synapse",
".",
"lib",
".",
"provenance",
"as",
"s_provenance",
"# avoid import cycle",
"if",
"__debug__",
":",
"assert",
"s_coro",
".",
"iscoro",
"(",
"coro",
")",
"import",
"synapse",
".",
... | 33.078947 | 25.026316 |
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only devices of current node
"""
super(NodeDeviceList, self).initial(request, *args, **kwargs)
#... | [
"def",
"initial",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"NodeDeviceList",
",",
"self",
")",
".",
"initial",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# ensure node exist... | 40.043478 | 17.956522 |
async def send_cred_def(self, s_id: str, revo: bool = True, rr_size: int = None) -> str:
"""
Create a credential definition as Issuer, store it in its wallet, and send it to the ledger.
Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure
to send cred... | [
"async",
"def",
"send_cred_def",
"(",
"self",
",",
"s_id",
":",
"str",
",",
"revo",
":",
"bool",
"=",
"True",
",",
"rr_size",
":",
"int",
"=",
"None",
")",
"->",
"str",
":",
"LOGGER",
".",
"debug",
"(",
"'Issuer.send_cred_def >>> s_id: %s, revo: %s, rr_size:... | 49.759494 | 32.417722 |
def get_version(self, service_id, version_number):
"""Get the version for a particular service."""
content = self._fetch("/service/%s/version/%d" % (service_id, version_number))
return FastlyVersion(self, content) | [
"def",
"get_version",
"(",
"self",
",",
"service_id",
",",
"version_number",
")",
":",
"content",
"=",
"self",
".",
"_fetch",
"(",
"\"/service/%s/version/%d\"",
"%",
"(",
"service_id",
",",
"version_number",
")",
")",
"return",
"FastlyVersion",
"(",
"self",
",... | 54 | 13.25 |
def total_cost(self, p=None, p_cost=None, pcost_model=None):
""" Computes total cost for the generator at the given output level.
"""
p = self.p if p is None else p
p_cost = self.p_cost if p_cost is None else p_cost
pcost_model = self.pcost_model if pcost_model is None else pcost... | [
"def",
"total_cost",
"(",
"self",
",",
"p",
"=",
"None",
",",
"p_cost",
"=",
"None",
",",
"pcost_model",
"=",
"None",
")",
":",
"p",
"=",
"self",
".",
"p",
"if",
"p",
"is",
"None",
"else",
"p",
"p_cost",
"=",
"self",
".",
"p_cost",
"if",
"p_cost"... | 36.268293 | 15.707317 |
def SequenceOf(klass):
"""Function to return a class that can encode and decode a list of
some other type."""
if _debug: SequenceOf._debug("SequenceOf %r", klass)
global _sequence_of_map
global _sequence_of_classes, _array_of_classes
# if this has already been built, return the cached one
... | [
"def",
"SequenceOf",
"(",
"klass",
")",
":",
"if",
"_debug",
":",
"SequenceOf",
".",
"_debug",
"(",
"\"SequenceOf %r\"",
",",
"klass",
")",
"global",
"_sequence_of_map",
"global",
"_sequence_of_classes",
",",
"_array_of_classes",
"# if this has already been built, retur... | 37.820144 | 20.733813 |
def normalize(text: str) -> str:
"""
Thai text normalize
:param str text: thai text
:return: thai text
**Example**::
>>> print(normalize("เเปลก")=="แปลก") # เ เ ป ล ก กับ แปลก
True
"""
for data in _NORMALIZE_RULE2:
text = re.sub(data[0].replace("t", "[่้๊๋]"), data[1], tex... | [
"def",
"normalize",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"for",
"data",
"in",
"_NORMALIZE_RULE2",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"data",
"[",
"0",
"]",
".",
"replace",
"(",
"\"t\"",
",",
"\"[่้๊๋]\"), data[",
"1",
"]",
" tex",
... | 30.8 | 19.066667 |
def check_python(code):
"""Yield errors."""
try:
compile(code, '<string>', 'exec')
except SyntaxError as exception:
yield (int(exception.lineno), exception.msg) | [
"def",
"check_python",
"(",
"code",
")",
":",
"try",
":",
"compile",
"(",
"code",
",",
"'<string>'",
",",
"'exec'",
")",
"except",
"SyntaxError",
"as",
"exception",
":",
"yield",
"(",
"int",
"(",
"exception",
".",
"lineno",
")",
",",
"exception",
".",
... | 30.5 | 11 |
def paths(self):
"""Get an iter of VenvPaths within the directory."""
contents = os.listdir(self.path)
contents = (os.path.join(self.path, path) for path in contents)
contents = (VenvPath(path) for path in contents)
return contents | [
"def",
"paths",
"(",
"self",
")",
":",
"contents",
"=",
"os",
".",
"listdir",
"(",
"self",
".",
"path",
")",
"contents",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"path",
")",
"for",
"path",
"in",
"contents",
")",
... | 44.333333 | 14.666667 |
def union(self, other, ignore_conflicts=False):
"""Return a new definition from the union of the definitions."""
result = self.copy()
result.union_update(other, ignore_conflicts)
return result | [
"def",
"union",
"(",
"self",
",",
"other",
",",
"ignore_conflicts",
"=",
"False",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"union_update",
"(",
"other",
",",
"ignore_conflicts",
")",
"return",
"result"
] | 44 | 10 |
def popwhile(cond, queue, *, side):
"""
Pop elements off a queue while `cond(nextelem)` is True.
Parameters
----------
cond : predicate
queue : deque
side : {'left', 'right'}
Returns
-------
popped : deque
Examples
--------
>>> from collections import deque
>>>... | [
"def",
"popwhile",
"(",
"cond",
",",
"queue",
",",
"*",
",",
"side",
")",
":",
"if",
"side",
"not",
"in",
"(",
"'left'",
",",
"'right'",
")",
":",
"raise",
"ValueError",
"(",
"\"`side` must be one of 'left' or 'right'\"",
")",
"out",
"=",
"deque",
"(",
"... | 20.5 | 20.934783 |
def extend(self, trajectory):
"""
Concatenate another trajectory
Args:
trajectory (Trajectory): Trajectory to add
"""
if self.time_step != trajectory.time_step:
raise ValueError('Trajectory not extended: Time steps of trajectories is incompatible')
... | [
"def",
"extend",
"(",
"self",
",",
"trajectory",
")",
":",
"if",
"self",
".",
"time_step",
"!=",
"trajectory",
".",
"time_step",
":",
"raise",
"ValueError",
"(",
"'Trajectory not extended: Time steps of trajectories is incompatible'",
")",
"if",
"len",
"(",
"self",
... | 50.565217 | 35.695652 |
def ordinal(self, num):
"""
Return the ordinal of num.
num can be an integer or text
e.g. ordinal(1) returns '1st'
ordinal('one') returns 'first'
"""
if re.match(r"\d", str(num)):
try:
num % 2
n = num
exce... | [
"def",
"ordinal",
"(",
"self",
",",
"num",
")",
":",
"if",
"re",
".",
"match",
"(",
"r\"\\d\"",
",",
"str",
"(",
"num",
")",
")",
":",
"try",
":",
"num",
"%",
"2",
"n",
"=",
"num",
"except",
"TypeError",
":",
"if",
"\".\"",
"in",
"str",
"(",
... | 30.351351 | 14.621622 |
def find_show_by_id(self, show_id):
"""doc: http://open.youku.com/docs/doc?id=59
"""
url = 'https://openapi.youku.com/v2/shows/show.json'
params = {
'client_id': self.client_id,
'show_id': show_id
}
r = requests.get(url, params=params)
chec... | [
"def",
"find_show_by_id",
"(",
"self",
",",
"show_id",
")",
":",
"url",
"=",
"'https://openapi.youku.com/v2/shows/show.json'",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'show_id'",
":",
"show_id",
"}",
"r",
"=",
"requests",
".",
"... | 31.272727 | 11.545455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.