text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _levenshtein_distance(s1, s2):
"""
:param s1: A list or string
:param s2: Another list or string
:returns: The levenshtein distance between the two
"""
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for index2, num2 in enumerate(s2):
new_dis... | [
"def",
"_levenshtein_distance",
"(",
"s1",
",",
"s2",
")",
":",
"if",
"len",
"(",
"s1",
")",
">",
"len",
"(",
"s2",
")",
":",
"s1",
",",
"s2",
"=",
"s2",
",",
"s1",
"distances",
"=",
"range",
"(",
"len",
"(",
"s1",
")",
"+",
"1",
")",
"for",
... | 36.2 | 0.001346 |
def get(self, key):
"""
Retrieve object indexed by <key>
"""
try:
try:
obj = self.bucket.get(key)
except couchbase.exception.MemcachedError, inst:
if str(inst) == "Memcached error #1: Not found":
# for some reason the py cb client raises an error when
... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"try",
":",
"obj",
"=",
"self",
".",
"bucket",
".",
"get",
"(",
"key",
")",
"except",
"couchbase",
".",
"exception",
".",
"MemcachedError",
",",
"inst",
":",
"if",
"str",
"(",
"inst",
"... | 20.923077 | 0.02812 |
def tree_sph(polar, azimuthal, n, standardization, symbolic=False):
"""Evaluate all spherical harmonics of degree at most `n` at angles `polar`,
`azimuthal`.
"""
cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos
# Conventions from
# <https://en.wikipedia.org/wiki/Spherical_harmonics#O... | [
"def",
"tree_sph",
"(",
"polar",
",",
"azimuthal",
",",
"n",
",",
"standardization",
",",
"symbolic",
"=",
"False",
")",
":",
"cos",
"=",
"numpy",
".",
"vectorize",
"(",
"sympy",
".",
"cos",
")",
"if",
"symbolic",
"else",
"numpy",
".",
"cos",
"# Conven... | 31.4 | 0.002472 |
def _getEnumValues(self, data):
""" Returns a list of dictionary of valis value for this setting. """
enumstr = data.attrib.get('enumValues')
if not enumstr:
return None
if ':' in enumstr:
return {self._cast(k): v for k, v in [kv.split(':') for kv in enumstr.split... | [
"def",
"_getEnumValues",
"(",
"self",
",",
"data",
")",
":",
"enumstr",
"=",
"data",
".",
"attrib",
".",
"get",
"(",
"'enumValues'",
")",
"if",
"not",
"enumstr",
":",
"return",
"None",
"if",
"':'",
"in",
"enumstr",
":",
"return",
"{",
"self",
".",
"_... | 44.25 | 0.00831 |
def img2img_transformer2d_q3():
"""Current best hparams for local 2d."""
hparams = img2img_transformer2d_q1()
hparams.batch_size = 2
hparams.query_shape = (8, 16)
hparams.memory_flange = (8, 32)
return hparams | [
"def",
"img2img_transformer2d_q3",
"(",
")",
":",
"hparams",
"=",
"img2img_transformer2d_q1",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"query_shape",
"=",
"(",
"8",
",",
"16",
")",
"hparams",
".",
"memory_flange",
"=",
"(",
"8",
",... | 30.714286 | 0.031674 |
def add_mod(self, seq, mod):
"""Create a tree.{Complement, LookAhead, Neg, Until}"""
modstr = self.value(mod)
if modstr == '~':
seq.parser_tree = parsing.Complement(seq.parser_tree)
elif modstr == '!!':
seq.parser_tree = parsing.LookAhead(seq.parser_tree)
elif modstr == '!':
... | [
"def",
"add_mod",
"(",
"self",
",",
"seq",
",",
"mod",
")",
":",
"modstr",
"=",
"self",
".",
"value",
"(",
"mod",
")",
"if",
"modstr",
"==",
"'~'",
":",
"seq",
".",
"parser_tree",
"=",
"parsing",
".",
"Complement",
"(",
"seq",
".",
"parser_tree",
"... | 37.75 | 0.002155 |
def do_GET(self):
"""Implement the HTTP GET method.
The bulk of this code is wrapped in a big try block and anywhere
within the code may raise an IIIFError which then results in an
IIIF error response (section 5 of spec).
"""
self.compliance_uri = None
self.iiif ... | [
"def",
"do_GET",
"(",
"self",
")",
":",
"self",
".",
"compliance_uri",
"=",
"None",
"self",
".",
"iiif",
"=",
"IIIFRequest",
"(",
"baseurl",
"=",
"'/'",
")",
"try",
":",
"(",
"of",
",",
"mime_type",
")",
"=",
"self",
".",
"do_GET_body",
"(",
")",
"... | 41.027778 | 0.001984 |
def relpath(self):
"""Relative path."""
try:
return os.path.relpath(self.path)
except OSError:
# current working directory may not be defined!
return self.path | [
"def",
"relpath",
"(",
"self",
")",
":",
"try",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"self",
".",
"path",
")",
"except",
"OSError",
":",
"# current working directory may not be defined!",
"return",
"self",
".",
"path"
] | 30.428571 | 0.009132 |
def profile_update(request, template="accounts/account_profile_update.html",
extra_context=None):
"""
Profile update form.
"""
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None,
instance=request.user)
if r... | [
"def",
"profile_update",
"(",
"request",
",",
"template",
"=",
"\"accounts/account_profile_update.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"profile_form",
"=",
"get_profile_form",
"(",
")",
"form",
"=",
"profile_form",
"(",
"request",
".",
"POST",
"or... | 40.333333 | 0.001346 |
def rollback(using=None, sid=None):
"""
Possibility of calling transaction.rollback() in new Django versions (in atomic block).
Important: transaction savepoint (sid) is required for Django < 1.8
"""
if sid:
django.db.transaction.savepoint_rollback(sid)
else:
try:
dj... | [
"def",
"rollback",
"(",
"using",
"=",
"None",
",",
"sid",
"=",
"None",
")",
":",
"if",
"sid",
":",
"django",
".",
"db",
".",
"transaction",
".",
"savepoint_rollback",
"(",
"sid",
")",
"else",
":",
"try",
":",
"django",
".",
"db",
".",
"transaction",
... | 39.166667 | 0.012474 |
def sbar_(self, stack_index=None, label=None, style=None, opts=None,
options={}):
"""
Get a stacked bar chart
"""
self.opts(dict(stack_index=stack_index, color_index=stack_index))
try:
if stack_index is None:
self.err(self.sbar_, "Please provide a stack index parameter")
options["stack_index"] ... | [
"def",
"sbar_",
"(",
"self",
",",
"stack_index",
"=",
"None",
",",
"label",
"=",
"None",
",",
"style",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"options",
"=",
"{",
"}",
")",
":",
"self",
".",
"opts",
"(",
"dict",
"(",
"stack_index",
"=",
"sta... | 36 | 0.03675 |
def validate(self, document, schema=None, update=False, normalize=True):
""" Normalizes and validates a mapping against a validation-schema of
defined rules.
:param document: The document to normalize.
:type document: any :term:`mapping`
:param schema: The validation schema. Def... | [
"def",
"validate",
"(",
"self",
",",
"document",
",",
"schema",
"=",
"None",
",",
"update",
"=",
"False",
",",
"normalize",
"=",
"True",
")",
":",
"self",
".",
"update",
"=",
"update",
"self",
".",
"_unrequired_by_excludes",
"=",
"set",
"(",
")",
"self... | 39.756098 | 0.001796 |
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_insta... | [
"def",
"create",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"readonly",
":",
"return",
"HTTPMethodNotAllowed",
"(",
"headers",
"=",
"{",
"'Allow'",
":",
"'GET, HEAD'",
"}",
")",
"collection",
"=",
"loads",
"(",
"request",
".",
"body",
",",... | 41.482759 | 0.001625 |
def doi_exists(self, doi):
"""
This method retrieve a boolean according to the existence of a crossref
DOI number. It returns False if the API results a 404 status code.
args: Crossref DOI id (String)
return: Boolean
Example 1:
>>> from crossref.restful imp... | [
"def",
"doi_exists",
"(",
"self",
",",
"doi",
")",
":",
"request_url",
"=",
"build_url_endpoint",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"ENDPOINT",
",",
"doi",
"]",
")",
")",
"request_params",
"=",
"{",
"}",
"result",
"=",
"self",
".",
"do_... | 27.210526 | 0.001867 |
def parse_extends(self):
"""
For each part, create the inheritance parts from the ' extends '
"""
# To be able to manage multiple extends, you need to
# destroy the actual node and create many nodes that have
# mono extend. The first one gets all the css rules
for... | [
"def",
"parse_extends",
"(",
"self",
")",
":",
"# To be able to manage multiple extends, you need to",
"# destroy the actual node and create many nodes that have",
"# mono extend. The first one gets all the css rules",
"for",
"_selectors",
",",
"rules",
"in",
"self",
".",
"parts",
... | 45.345455 | 0.00157 |
def decode(col, charset):
"""
Computes the first argument into a string from a binary using the provided character set
(one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16').
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.decode(_to_java_column(... | [
"def",
"decode",
"(",
"col",
",",
"charset",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"decode",
"(",
"_to_java_column",
"(",
"col",
")",
",",
"charset",
")",
")"... | 47 | 0.008955 |
def deployment_export_template(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Exports the template used for the specified deployment.
:param name: The name of the deployment to query.
:param resource_group: The resource group name assigned to the
deployment.
CLI Exam... | [
"def",
"deployment_export_template",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"resconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'resource'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"deploy",
"=",
"resconn",... | 27.866667 | 0.002312 |
def is_declared(self):
"""
:return: True is the table is declared in the schema.
"""
return self.connection.query(
'SHOW TABLES in `{database}` LIKE "{table_name}"'.format(
database=self.database, table_name=self.table_name)).rowcount > 0 | [
"def",
"is_declared",
"(",
"self",
")",
":",
"return",
"self",
".",
"connection",
".",
"query",
"(",
"'SHOW TABLES in `{database}` LIKE \"{table_name}\"'",
".",
"format",
"(",
"database",
"=",
"self",
".",
"database",
",",
"table_name",
"=",
"self",
".",
"table_... | 41.714286 | 0.010067 |
def from_hostname(cls, hostname):
"""Retrieve virtual machine id associated to a hostname."""
result = cls.list({'hostname': str(hostname)})
if result:
return result[0]['id'] | [
"def",
"from_hostname",
"(",
"cls",
",",
"hostname",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
"{",
"'hostname'",
":",
"str",
"(",
"hostname",
")",
"}",
")",
"if",
"result",
":",
"return",
"result",
"[",
"0",
"]",
"[",
"'id'",
"]"
] | 41.2 | 0.009524 |
def parse_page(raw_page):
"""Create a dictionary with title, id, and list of revisions.
The dictionary contains:
"title": a string
"id": an integer
"revisions": a list of strings
Args:
raw_page: a string
Returns:
a dictionary, or None in the case of an error.
"""
ret = {"title": get_title(r... | [
"def",
"parse_page",
"(",
"raw_page",
")",
":",
"ret",
"=",
"{",
"\"title\"",
":",
"get_title",
"(",
"raw_page",
")",
",",
"\"id\"",
":",
"get_id",
"(",
"raw_page",
")",
"}",
"if",
"\":\"",
"in",
"ret",
"[",
"\"title\"",
"]",
":",
"return",
"None",
"... | 22.894737 | 0.013245 |
def convert(source_file, target_file, trim_unused_by_output="", verbose=False, compress_f16=False):
"""
Converts a TensorFlow model into a Barracuda model.
:param source_file: The TensorFlow Model
:param target_file: The name of the file the converted model will be saved to
:param trim_unused_by_out... | [
"def",
"convert",
"(",
"source_file",
",",
"target_file",
",",
"trim_unused_by_output",
"=",
"\"\"",
",",
"verbose",
"=",
"False",
",",
"compress_f16",
"=",
"False",
")",
":",
"if",
"(",
"type",
"(",
"verbose",
")",
"==",
"bool",
")",
":",
"args",
"=",
... | 39.850746 | 0.016627 |
def get_ht_op(_, data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n766.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict.
"""
protection = ('no', 'nonmember', 20, 'non-HT mixed')
sta_chan_width = (20, 'any')
answers = {
... | [
"def",
"get_ht_op",
"(",
"_",
",",
"data",
")",
":",
"protection",
"=",
"(",
"'no'",
",",
"'nonmember'",
",",
"20",
",",
"'non-HT mixed'",
")",
"sta_chan_width",
"=",
"(",
"20",
",",
"'any'",
")",
"answers",
"=",
"{",
"'primary channel'",
":",
"data",
... | 35.37037 | 0.001019 |
def tempput(local_path=None, remote_path=None, use_sudo=False,
mirror_local_mode=False, mode=None):
"""Put a file to remote and remove it afterwards"""
import warnings
warnings.simplefilter('ignore', RuntimeWarning)
if remote_path is None:
remote_path = os.tempnam()
put(local_pat... | [
"def",
"tempput",
"(",
"local_path",
"=",
"None",
",",
"remote_path",
"=",
"None",
",",
"use_sudo",
"=",
"False",
",",
"mirror_local_mode",
"=",
"False",
",",
"mode",
"=",
"None",
")",
":",
"import",
"warnings",
"warnings",
".",
"simplefilter",
"(",
"'igno... | 42.2 | 0.00232 |
def _add_warc_action_log(self, path, url):
'''Add the action log to the WARC file.'''
_logger.debug('Adding action log record.')
actions = []
with open(path, 'r', encoding='utf-8', errors='replace') as file:
for line in file:
actions.append(json.loads(line))
... | [
"def",
"_add_warc_action_log",
"(",
"self",
",",
"path",
",",
"url",
")",
":",
"_logger",
".",
"debug",
"(",
"'Adding action log record.'",
")",
"actions",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
",",
"err... | 38.181818 | 0.002323 |
def underscore_to_camelcase(value, first_upper=True):
"""Transform string from underscore_string to camelCase.
:param value: string with underscores
:param first_upper: the result will have its first character in upper case
:type value: str
:return: string in CamelCase or camelCase according to the... | [
"def",
"underscore_to_camelcase",
"(",
"value",
",",
"first_upper",
"=",
"True",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"camelized",
"=",
"\"\"",
".",
"join",
"(",
"x",
".",
"title",
"(",
")",
"if",
"x",
"else",
"'_'",
"for",
"x",
"in",
... | 34.95 | 0.001393 |
def lineAndColumnAt(s, pos):
r"""Return line and column of `pos` (0-based!) in `s`. Lines start with
1, columns with 0.
Examples:
>>> lineAndColumnAt("0123\n56", 5)
(2, 0)
>>> lineAndColumnAt("0123\n56", 6)
(2, 1)
>>> lineAndColumnAt("0123\n56", 0)
(1, 0)
"""
if pos >= len(... | [
"def",
"lineAndColumnAt",
"(",
"s",
",",
"pos",
")",
":",
"if",
"pos",
">=",
"len",
"(",
"s",
")",
":",
"raise",
"IndexError",
"(",
"\"`pos` %d not in string\"",
"%",
"pos",
")",
"# *don't* count last '\\n', if it is at pos!",
"line",
"=",
"s",
".",
"count",
... | 25.666667 | 0.008945 |
def table(
self, kudu_name, name=None, database=None, persist=False, external=True
):
"""
Convenience to expose an existing Kudu table (using CREATE TABLE) as an
Impala table. To create a new table both in the Hive Metastore with
storage in Kudu, use create_table.
No... | [
"def",
"table",
"(",
"self",
",",
"kudu_name",
",",
"name",
"=",
"None",
",",
"database",
"=",
"None",
",",
"persist",
"=",
"False",
",",
"external",
"=",
"True",
")",
":",
"# Law of demeter, but OK for now because internal class coupling",
"name",
",",
"databas... | 41.682927 | 0.001715 |
def pop_option(function, name):
"""
Used to remove an option applied by the @click.option decorator.
This is useful for when you want to subclass a decorated resource command
and *don't* want all of the options provided by the parent class'
implementation.
"""
for option in getattr(function... | [
"def",
"pop_option",
"(",
"function",
",",
"name",
")",
":",
"for",
"option",
"in",
"getattr",
"(",
"function",
",",
"'__click_params__'",
",",
"tuple",
"(",
")",
")",
":",
"if",
"option",
".",
"name",
"==",
"name",
":",
"function",
".",
"__click_params_... | 38.727273 | 0.002294 |
def xmoe_2d():
"""Two-dimensional hierarchical mixture of 16 experts."""
hparams = xmoe_top_2()
hparams.decoder_layers = ["att", "hmoe"] * 4
hparams.mesh_shape = "b0:2;b1:4"
hparams.outer_batch_size = 4
hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0"
hparams.moe_num_experts = [4, ... | [
"def",
"xmoe_2d",
"(",
")",
":",
"hparams",
"=",
"xmoe_top_2",
"(",
")",
"hparams",
".",
"decoder_layers",
"=",
"[",
"\"att\"",
",",
"\"hmoe\"",
"]",
"*",
"4",
"hparams",
".",
"mesh_shape",
"=",
"\"b0:2;b1:4\"",
"hparams",
".",
"outer_batch_size",
"=",
"4"... | 36.777778 | 0.026549 |
def estimate(coll, filter={}, sample=1):
"""
Estimate the number of documents in the collection
matching the filter.
Sample may be a fixed number of documents to sample
or a percentage of the total collection size.
>>> coll = getfixture('bulky_collection')
>>> estimate(coll)
100
>>... | [
"def",
"estimate",
"(",
"coll",
",",
"filter",
"=",
"{",
"}",
",",
"sample",
"=",
"1",
")",
":",
"total",
"=",
"coll",
".",
"estimated_document_count",
"(",
")",
"if",
"not",
"filter",
"and",
"sample",
"==",
"1",
":",
"return",
"total",
"if",
"sample... | 28 | 0.000986 |
def start_resolver(finder=None, wheel_cache=None):
"""Context manager to produce a resolver.
:param finder: A package finder to use for searching the index
:type finder: :class:`~pip._internal.index.PackageFinder`
:return: A 3-tuple of finder, preparer, resolver
:rtype: (:class:`~pip._internal.oper... | [
"def",
"start_resolver",
"(",
"finder",
"=",
"None",
",",
"wheel_cache",
"=",
"None",
")",
":",
"pip_command",
"=",
"get_pip_command",
"(",
")",
"pip_options",
"=",
"get_pip_options",
"(",
"pip_command",
"=",
"pip_command",
")",
"if",
"not",
"finder",
":",
"... | 34.875 | 0.001494 |
def native_container(self):
"""Native container object."""
if self.__native is None:
self.__native = self._get_container()
return self.__native | [
"def",
"native_container",
"(",
"self",
")",
":",
"if",
"self",
".",
"__native",
"is",
"None",
":",
"self",
".",
"__native",
"=",
"self",
".",
"_get_container",
"(",
")",
"return",
"self",
".",
"__native"
] | 29.166667 | 0.011111 |
def delete(args):
"""
Delete a template by name
"""
m = TemplateManager(args.hosts)
m.delete(args.name) | [
"def",
"delete",
"(",
"args",
")",
":",
"m",
"=",
"TemplateManager",
"(",
"args",
".",
"hosts",
")",
"m",
".",
"delete",
"(",
"args",
".",
"name",
")"
] | 19.666667 | 0.00813 |
def immerkaer(input, mode="reflect", cval=0.0):
r"""
Estimate the global noise.
The input image is assumed to have additive zero mean Gaussian noise. Using a
convolution with a Laplacian operator and a subsequent averaging the standard
deviation sigma of this noise is estimated. This estimation... | [
"def",
"immerkaer",
"(",
"input",
",",
"mode",
"=",
"\"reflect\"",
",",
"cval",
"=",
"0.0",
")",
":",
"# build nd-kernel to acquire square root of sum of squared elements",
"kernel",
"=",
"[",
"1",
",",
"-",
"2",
",",
"1",
"]",
"for",
"_",
"in",
"range",
"("... | 36.067568 | 0.010941 |
def remove_event(self, ref):
"""
Removes an event for a ref (reference),
"""
# is this reference one which has been setup?
if ref in self._refs:
self._refs[ref].remove_callback(ref) | [
"def",
"remove_event",
"(",
"self",
",",
"ref",
")",
":",
"# is this reference one which has been setup?",
"if",
"ref",
"in",
"self",
".",
"_refs",
":",
"self",
".",
"_refs",
"[",
"ref",
"]",
".",
"remove_callback",
"(",
"ref",
")"
] | 32.428571 | 0.008584 |
def _match_excluded(self, filename, patterns):
"""Call match real directly to skip unnecessary `exists` check."""
return _wcparse._match_real(
filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks
) | [
"def",
"_match_excluded",
"(",
"self",
",",
"filename",
",",
"patterns",
")",
":",
"return",
"_wcparse",
".",
"_match_real",
"(",
"filename",
",",
"patterns",
".",
"_include",
",",
"patterns",
".",
"_exclude",
",",
"patterns",
".",
"_follow",
",",
"self",
... | 42.666667 | 0.011494 |
def fig_kernel_lfp(savefolders, params, transient=200, T=[800., 1000.], X='L5E',
lags=[20, 20], channels=[0,3,7,11,13]):
'''
This function calculates the STA of LFP, extracts kernels and recontructs the LFP from kernels.
Arguments
::
transient : the time in milliseconds, ... | [
"def",
"fig_kernel_lfp",
"(",
"savefolders",
",",
"params",
",",
"transient",
"=",
"200",
",",
"T",
"=",
"[",
"800.",
",",
"1000.",
"]",
",",
"X",
"=",
"'L5E'",
",",
"lags",
"=",
"[",
"20",
",",
"20",
"]",
",",
"channels",
"=",
"[",
"0",
",",
"... | 40.066667 | 0.009079 |
def set_log_file(local_file=None):
"""
设置日志记录,按照每天一个文件,记录包括 info 以及以上级别的内容;
日志格式采取日志文件名直接加上日期,比如 fish_test.log.2018-05-27
:param:
* local_fie: (string) 日志文件名
:return: 无
举例如下::
from fishbase.fish_logger import *
from fishbase.fish_file import *
log_abs_filenam... | [
"def",
"set_log_file",
"(",
"local_file",
"=",
"None",
")",
":",
"default_log_file",
"=",
"'default.log'",
"_formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s %(levelname)s %(filename)s[ln:%(lineno)d] %(message)s'",
")",
"if",
"local_file",
"is",
"not",
"... | 23.931818 | 0.001825 |
def addSourceLocation(self, sourceLocationUri, weight):
"""
add a list of relevant sources by identifying them by their geographic location
@param sourceLocationUri: uri of the location where the sources should be geographically located
@param weight: importance of the provided list of s... | [
"def",
"addSourceLocation",
"(",
"self",
",",
"sourceLocationUri",
",",
"weight",
")",
":",
"assert",
"isinstance",
"(",
"weight",
",",
"(",
"float",
",",
"int",
")",
")",
",",
"\"weight value has to be a positive or negative integer\"",
"self",
".",
"topicPage",
... | 69.5 | 0.012433 |
def label(self):
""""Return first child of the column that is marked as a label. Returns self if the column is a label"""
if self.valuetype_class.is_label():
return self
for c in self.table.columns:
if c.parent == self.name and c.valuetype_class.is_label():
... | [
"def",
"label",
"(",
"self",
")",
":",
"if",
"self",
".",
"valuetype_class",
".",
"is_label",
"(",
")",
":",
"return",
"self",
"for",
"c",
"in",
"self",
".",
"table",
".",
"columns",
":",
"if",
"c",
".",
"parent",
"==",
"self",
".",
"name",
"and",
... | 31.272727 | 0.011299 |
def get_accounts(self, **params):
"""https://developers.coinbase.com/api/v2#list-accounts"""
response = self._get('v2', 'accounts', params=params)
return self._make_api_object(response, Account) | [
"def",
"get_accounts",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"'v2'",
",",
"'accounts'",
",",
"params",
"=",
"params",
")",
"return",
"self",
".",
"_make_api_object",
"(",
"response",
",",
"Account",
... | 53.75 | 0.009174 |
def extract_edges_from_callable(fn):
"""
This takes args and kwargs provided, and returns the names of the strings
assigned. If a string is not provided for a value, an exception is raised.
This is how we extract the edges provided in the brap call lambdas.
"""
def extractor(*args, **kwargs):
... | [
"def",
"extract_edges_from_callable",
"(",
"fn",
")",
":",
"def",
"extractor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Because I don't think this technique is common in python...\n\n Service constructors were defined as:\n lambda c: c... | 30.090909 | 0.000976 |
def bake(self, element, last_step=None):
"""Apply recipes to HTML tree. Will build recipes if needed."""
if last_step is not None:
try:
self.state['steps'] = [s for s in self.state['steps']
if int(s) < int(last_step)]
except... | [
"def",
"bake",
"(",
"self",
",",
"element",
",",
"last_step",
"=",
"None",
")",
":",
"if",
"last_step",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"state",
"[",
"'steps'",
"]",
"=",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"state",
"[",
... | 43.741573 | 0.000502 |
def add_edges_from(self, ebunch, attr_dict=None, **attr):
"""Version of add_edges_from that only writes to the database once"""
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
rais... | [
"def",
"add_edges_from",
"(",
"self",
",",
"ebunch",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"if",
"attr_dict",
"is",
"None",
":",
"attr_dict",
"=",
"attr",
"else",
":",
"try",
":",
"attr_dict",
".",
"update",
"(",
"attr",
")"... | 34.212121 | 0.001723 |
def memoized(maxsize=1024):
"""
Momoization decorator for immutable classes and pure functions.
"""
cache = SimpleCache(maxsize=maxsize)
def decorator(obj):
@wraps(obj)
def new_callable(*a, **kw):
def create_new():
return obj(*a, **kw)
key = ... | [
"def",
"memoized",
"(",
"maxsize",
"=",
"1024",
")",
":",
"cache",
"=",
"SimpleCache",
"(",
"maxsize",
"=",
"maxsize",
")",
"def",
"decorator",
"(",
"obj",
")",
":",
"@",
"wraps",
"(",
"obj",
")",
"def",
"new_callable",
"(",
"*",
"a",
",",
"*",
"*"... | 26.375 | 0.002288 |
def dump(obj, attributes = True, _refset = None):
"Show full value of a data object"
if _refset is None:
_refset = set()
if obj is None:
return None
elif isinstance(obj, DataObject):
if id(obj) in _refset:
attributes = False
else:
_refset.a... | [
"def",
"dump",
"(",
"obj",
",",
"attributes",
"=",
"True",
",",
"_refset",
"=",
"None",
")",
":",
"if",
"_refset",
"is",
"None",
":",
"_refset",
"=",
"set",
"(",
")",
"if",
"obj",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"obj... | 39 | 0.010007 |
def CheckFile(self, filename):
"""Validates the artifacts definition in a specific file.
Args:
filename (str): name of the artifacts definition file.
Returns:
bool: True if the file contains valid artifacts definitions.
"""
result = True
artifact_reader = reader.YamlArtifactsReader... | [
"def",
"CheckFile",
"(",
"self",
",",
"filename",
")",
":",
"result",
"=",
"True",
"artifact_reader",
"=",
"reader",
".",
"YamlArtifactsReader",
"(",
")",
"try",
":",
"for",
"artifact_definition",
"in",
"artifact_reader",
".",
"ReadFile",
"(",
"filename",
")",... | 37.38961 | 0.00846 |
def interpret_bit_flags(bit_flags, flip_bits=None):
"""
Converts input bit flags to a single integer value (bitmask) or `None`.
When input is a list of flags (either a Python list of integer flags or a
sting of comma- or '+'-separated list of flags), the returned bitmask
is obtained by summing inpu... | [
"def",
"interpret_bit_flags",
"(",
"bit_flags",
",",
"flip_bits",
"=",
"None",
")",
":",
"has_flip_bits",
"=",
"flip_bits",
"is",
"not",
"None",
"flip_bits",
"=",
"bool",
"(",
"flip_bits",
")",
"allow_non_flags",
"=",
"False",
"if",
"_is_int",
"(",
"bit_flags"... | 36.090909 | 0.00035 |
def POR(cpu, dest, src):
"""
Performs a bitwise logical OR operation on the source operand (second operand) and the destination operand
(first operand) and stores the result in the destination operand. The source operand can be an MMX technology
register or a 64-bit memory location or it... | [
"def",
"POR",
"(",
"cpu",
",",
"dest",
",",
"src",
")",
":",
"res",
"=",
"dest",
".",
"write",
"(",
"dest",
".",
"read",
"(",
")",
"|",
"src",
".",
"read",
"(",
")",
")"
] | 74.222222 | 0.010355 |
def handle_events(
function_maps, event_queue, event_matches_function_map,
terminate_signal):
"""Waits for events on the event queue and calls the registered functions.
:param function_maps: A list of classes that have inheritted from
:class:`FunctionMap`\ s describing what to do with e... | [
"def",
"handle_events",
"(",
"function_maps",
",",
"event_queue",
",",
"event_matches_function_map",
",",
"terminate_signal",
")",
":",
"while",
"True",
":",
"# print(\"HANDLE: Waiting for events!\")",
"event",
"=",
"event_queue",
".",
"get",
"(",
")",
"# print(\"HANDLE... | 42.393939 | 0.001398 |
async def get_type(media, path=None):
"""
Parameters
----------
media : file object
A file object of the image
path : str, optional
The path to the file
Returns
-------
str
The mimetype of the media
str
The category of the media on Twitter
"""
... | [
"async",
"def",
"get_type",
"(",
"media",
",",
"path",
"=",
"None",
")",
":",
"if",
"magic",
":",
"if",
"not",
"media",
":",
"raise",
"TypeError",
"(",
"\"Media data is empty\"",
")",
"_logger",
".",
"debug",
"(",
"\"guessing mimetype using magic\"",
")",
"m... | 26.485714 | 0.001041 |
def rows(self, cell_mode=CellMode.cooked):
"""Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the
cell_mode argument.
"""
for row_index in range(self.nrows):
yield self.parse_row(self.get_row(row_index), row_index, cell_mode) | [
"def",
"rows",
"(",
"self",
",",
"cell_mode",
"=",
"CellMode",
".",
"cooked",
")",
":",
"for",
"row_index",
"in",
"range",
"(",
"self",
".",
"nrows",
")",
":",
"yield",
"self",
".",
"parse_row",
"(",
"self",
".",
"get_row",
"(",
"row_index",
")",
","... | 47.333333 | 0.010381 |
def iter_valid_fields(meta):
"""walk through the available valid fields.."""
# fetch field configuration and always add the id_field as exclude
meta_fields = getattr(meta, 'fields', ())
meta_exclude = getattr(meta, 'exclude', ())
meta_exclude += (meta.document._meta.get('id_field'),)
# walk th... | [
"def",
"iter_valid_fields",
"(",
"meta",
")",
":",
"# fetch field configuration and always add the id_field as exclude",
"meta_fields",
"=",
"getattr",
"(",
"meta",
",",
"'fields'",
",",
"(",
")",
")",
"meta_exclude",
"=",
"getattr",
"(",
"meta",
",",
"'exclude'",
"... | 38.8 | 0.001258 |
def convert_selu(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert selu layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with k... | [
"def",
"convert_selu",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting selu ...'",
")",
"if",
"names",
"==",
"'short'",
":",
"tf_name",
"=",
"'SELU'",
"+",
... | 30 | 0.001346 |
def _insert_paragraph_before(self):
"""
Return a newly created paragraph, inserted directly before this
paragraph.
"""
p = self._p.add_p_before()
return Paragraph(p, self._parent) | [
"def",
"_insert_paragraph_before",
"(",
"self",
")",
":",
"p",
"=",
"self",
".",
"_p",
".",
"add_p_before",
"(",
")",
"return",
"Paragraph",
"(",
"p",
",",
"self",
".",
"_parent",
")"
] | 31.571429 | 0.008811 |
def on_same_strand(self):
'''Returns true iff the direction of the alignment is the same in the reference and the query'''
return (self.ref_start < self.ref_end) == (self.qry_start < self.qry_end) | [
"def",
"on_same_strand",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"ref_start",
"<",
"self",
".",
"ref_end",
")",
"==",
"(",
"self",
".",
"qry_start",
"<",
"self",
".",
"qry_end",
")"
] | 70 | 0.018868 |
def set_password(self, service, username, password):
"""Set password for the username of the service
"""
service = self._safe_string(service)
username = self._safe_string(username)
password = self._safe_string(password)
attrs = GnomeKeyring.Attribute.list_new()
Gn... | [
"def",
"set_password",
"(",
"self",
",",
"service",
",",
"username",
",",
"password",
")",
":",
"service",
"=",
"self",
".",
"_safe_string",
"(",
"service",
")",
"username",
"=",
"self",
".",
"_safe_string",
"(",
"username",
")",
"password",
"=",
"self",
... | 52.85 | 0.001859 |
def children(self):
"""获取此话题的子话题
:return: 此话题的子话题, 返回生成器
:rtype: Topic.Iterable
"""
self._make_soup()
child_topic_tag = self.soup.find('div', class_='child-topic')
if child_topic_tag is None:
return []
elif '共有' not in child_topic_tag.contents... | [
"def",
"children",
"(",
"self",
")",
":",
"self",
".",
"_make_soup",
"(",
")",
"child_topic_tag",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'div'",
",",
"class_",
"=",
"'child-topic'",
")",
"if",
"child_topic_tag",
"is",
"None",
":",
"return",
"[",
... | 38.694444 | 0.001401 |
def _processor(self):
"""Application processor to setup session for every request"""
self.store.cleanup(self._config.timeout)
self._load() | [
"def",
"_processor",
"(",
"self",
")",
":",
"self",
".",
"store",
".",
"cleanup",
"(",
"self",
".",
"_config",
".",
"timeout",
")",
"self",
".",
"_load",
"(",
")"
] | 39.75 | 0.012346 |
def remove_invalid_xml_chars(raw_xml):
"""Remove control and invalid characters from an xml stream.
Looks for invalid characters and subtitutes them with whitespaces.
This solution is based on these two posts: Olemis Lang's reponse
on StackOverflow (http://stackoverflow.com/questions/1707890) and
l... | [
"def",
"remove_invalid_xml_chars",
"(",
"raw_xml",
")",
":",
"illegal_unichrs",
"=",
"[",
"(",
"0x00",
",",
"0x08",
")",
",",
"(",
"0x0B",
",",
"0x1F",
")",
",",
"(",
"0x7F",
",",
"0x84",
")",
",",
"(",
"0x86",
",",
"0x9F",
")",
"]",
"illegal_ranges"... | 32 | 0.001011 |
def _build_proxy_contract_creation_constructor(self,
master_copy: str,
initializer: bytes,
funder: str,
payment_toke... | [
"def",
"_build_proxy_contract_creation_constructor",
"(",
"self",
",",
"master_copy",
":",
"str",
",",
"initializer",
":",
"bytes",
",",
"funder",
":",
"str",
",",
"payment_token",
":",
"str",
",",
"payment",
":",
"int",
")",
"->",
"ContractConstructor",
":",
... | 45.583333 | 0.008057 |
def generateStats(filename, statsInfo, maxSamples = None, filters=[], cache=True):
"""Generate requested statistics for a dataset and cache to a file.
If filename is None, then don't cache to a file"""
# Sanity checking
if not isinstance(statsInfo, dict):
raise RuntimeError("statsInfo must be a dict -- "
... | [
"def",
"generateStats",
"(",
"filename",
",",
"statsInfo",
",",
"maxSamples",
"=",
"None",
",",
"filters",
"=",
"[",
"]",
",",
"cache",
"=",
"True",
")",
":",
"# Sanity checking",
"if",
"not",
"isinstance",
"(",
"statsInfo",
",",
"dict",
")",
":",
"raise... | 32.325 | 0.017261 |
def delete(self, rid, raise_on_error=True):
"""Write cache data to the data store.
Args:
rid (str): The record identifier.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response.
"... | [
"def",
"delete",
"(",
"self",
",",
"rid",
",",
"raise_on_error",
"=",
"True",
")",
":",
"return",
"self",
".",
"ds",
".",
"delete",
"(",
"rid",
",",
"raise_on_error",
")"
] | 33 | 0.008043 |
def delete_user_contact_list(self, id, contact_list_id, **data):
"""
DELETE /users/:id/contact_lists/:contact_list_id/
Deletes the contact list. Returns ``{"deleted": true}``.
"""
return self.delete("/users/{0}/contact_lists/{0}/".format(id,contact_list_id), data=data) | [
"def",
"delete_user_contact_list",
"(",
"self",
",",
"id",
",",
"contact_list_id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"delete",
"(",
"\"/users/{0}/contact_lists/{0}/\"",
".",
"format",
"(",
"id",
",",
"contact_list_id",
")",
",",
"data",
... | 44.571429 | 0.015723 |
def multiplySeries(requestContext, *seriesLists):
"""
Takes two or more series and multiplies their points. A constant may not be
used. To multiply by a constant, use the scale() function.
Example::
&target=multiplySeries(Series.dividends,Series.divisors)
"""
if not seriesLists or no... | [
"def",
"multiplySeries",
"(",
"requestContext",
",",
"*",
"seriesLists",
")",
":",
"if",
"not",
"seriesLists",
"or",
"not",
"any",
"(",
"seriesLists",
")",
":",
"return",
"[",
"]",
"seriesList",
",",
"start",
",",
"end",
",",
"step",
"=",
"normalize",
"(... | 31.217391 | 0.001351 |
def carry_over_color(lines):
"""
Given a sequence of lines, for each line that contains a ANSI color escape
sequence without a reset, add a reset to the end of that line and copy all
colors in effect at the end of it to the beginning of the next line.
"""
lines2 = []
in_effect = ''
for s... | [
"def",
"carry_over_color",
"(",
"lines",
")",
":",
"lines2",
"=",
"[",
"]",
"in_effect",
"=",
"''",
"for",
"s",
"in",
"lines",
":",
"s",
"=",
"in_effect",
"+",
"s",
"in_effect",
"=",
"''",
"m",
"=",
"re",
".",
"search",
"(",
"COLOR_BEGIN_RGX",
"+",
... | 35.176471 | 0.001629 |
def guess_external_url(local_host, port):
"""Return a URL that is most likely to route to `local_host` from outside.
The point is that we may be running on a remote host from the user's
point of view, so they can't access `local_host` from a Web browser just
by typing ``http://localhost:12345/``.
"... | [
"def",
"guess_external_url",
"(",
"local_host",
",",
"port",
")",
":",
"if",
"local_host",
"in",
"[",
"'0.0.0.0'",
",",
"'::'",
"]",
":",
"# The server is listening on all interfaces, but we have to pick one.",
"# The system's FQDN should give us a hint.",
"local_host",
"=",
... | 45.258065 | 0.000698 |
def tf_summary_to_dict(tf_summary_str_or_pb, namespace=""):
"""Convert a Tensorboard Summary to a dictionary
Accepts either a tensorflow.summary.Summary
or one encoded as a string.
"""
values = {}
if isinstance(tf_summary_str_or_pb, Summary):
summary_pb = tf_summary_str_or_pb
elif i... | [
"def",
"tf_summary_to_dict",
"(",
"tf_summary_str_or_pb",
",",
"namespace",
"=",
"\"\"",
")",
":",
"values",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"tf_summary_str_or_pb",
",",
"Summary",
")",
":",
"summary_pb",
"=",
"tf_summary_str_or_pb",
"elif",
"isinstance",
... | 43.847826 | 0.00097 |
def set_pin_retries(ctx, pw_attempts, admin_pin, force):
"""
Manage pin-retries.
Sets the number of attempts available before locking for each PIN.
PW_ATTEMPTS should be three integer values corresponding to the number of
attempts for the PIN, Reset Code, and Admin PIN, respectively.
"""
c... | [
"def",
"set_pin_retries",
"(",
"ctx",
",",
"pw_attempts",
",",
"admin_pin",
",",
"force",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"resets_pins",
"=",
"controller",
".",
"version",
"<",
"(",
"4",
",",
"0",
",",
"0",
")"... | 40.428571 | 0.002301 |
def parse_command_line_parameters():
""" Parses command line arguments """
usage = 'usage: %prog [options] fasta_filepath'
version = 'Version: %prog 0.1'
parser = OptionParser(usage=usage, version=version)
# A binary 'verbose' flag
parser.add_option('-p', '--is_protein', action='store_true',
... | [
"def",
"parse_command_line_parameters",
"(",
")",
":",
"usage",
"=",
"'usage: %prog [options] fasta_filepath'",
"version",
"=",
"'Version: %prog 0.1'",
"parser",
"=",
"OptionParser",
"(",
"usage",
"=",
"usage",
",",
"version",
"=",
"version",
")",
"# A binary 'verbose' ... | 40.608696 | 0.001046 |
def getInterpretation(self):
"""
Get the value of the previously POSTed Tropo action.
"""
actions = self._actions
if (type (actions) is list):
dict = actions[0]
else:
dict = actions
return dict['interpretation'] | [
"def",
"getInterpretation",
"(",
"self",
")",
":",
"actions",
"=",
"self",
".",
"_actions",
"if",
"(",
"type",
"(",
"actions",
")",
"is",
"list",
")",
":",
"dict",
"=",
"actions",
"[",
"0",
"]",
"else",
":",
"dict",
"=",
"actions",
"return",
"dict",
... | 25.636364 | 0.010274 |
def _set_leftMargin(self, value):
"""
value will be an int or float.
Subclasses may override this method.
"""
diff = value - self.leftMargin
self.moveBy((diff, 0))
self.width += diff | [
"def",
"_set_leftMargin",
"(",
"self",
",",
"value",
")",
":",
"diff",
"=",
"value",
"-",
"self",
".",
"leftMargin",
"self",
".",
"moveBy",
"(",
"(",
"diff",
",",
"0",
")",
")",
"self",
".",
"width",
"+=",
"diff"
] | 25.666667 | 0.008368 |
def mix(self, cls):
"""
Returns a subclass of `cls` mixed with `self.mixins`.
:param cls: The base class to mix into
:type cls: `class`
"""
if hasattr(cls, 'unmixed_class'):
base_class = cls.unmixed_class
old_mixins = cls.__bases__[1:] # Skip th... | [
"def",
"mix",
"(",
"self",
",",
"cls",
")",
":",
"if",
"hasattr",
"(",
"cls",
",",
"'unmixed_class'",
")",
":",
"base_class",
"=",
"cls",
".",
"unmixed_class",
"old_mixins",
"=",
"cls",
".",
"__bases__",
"[",
"1",
":",
"]",
"# Skip the original unmixed cla... | 34.914286 | 0.002389 |
def compute_similarity(F, bound_idxs, dirichlet=False, xmeans=False, k=5,
offset=4):
"""Main function to compute the segment similarity of file file_struct.
Parameters
----------
F: np.ndarray
Matrix containing one feature vector per row.
bound_idxs: np.ndarray
... | [
"def",
"compute_similarity",
"(",
"F",
",",
"bound_idxs",
",",
"dirichlet",
"=",
"False",
",",
"xmeans",
"=",
"False",
",",
"k",
"=",
"5",
",",
"offset",
"=",
"4",
")",
":",
"# Get the feature segments",
"feat_segments",
"=",
"get_feat_segments",
"(",
"F",
... | 36.37037 | 0.000992 |
def get_dataframe():
""" get a generic (default) control section dataframe
Returns
-------
pandas.DataFrame : pandas.DataFrame
"""
names = []
[names.extend(line.split()) for line in CONTROL_VARIABLE_LINES]
defaults = []
[defaults.extend(... | [
"def",
"get_dataframe",
"(",
")",
":",
"names",
"=",
"[",
"]",
"[",
"names",
".",
"extend",
"(",
"line",
".",
"split",
"(",
")",
")",
"for",
"line",
"in",
"CONTROL_VARIABLE_LINES",
"]",
"defaults",
"=",
"[",
"]",
"[",
"defaults",
".",
"extend",
"(",
... | 34.555556 | 0.021898 |
def InitLog(file_name=None, log_level=logging.DEBUG,
screen_level=logging.CRITICAL, pdb=False):
'''
A little routine to initialize the logging functionality.
:param str file_name: The name of the file to log to. \
Default :py:obj:`None` (set internally by :py:mod:`everest`)
:para... | [
"def",
"InitLog",
"(",
"file_name",
"=",
"None",
",",
"log_level",
"=",
"logging",
".",
"DEBUG",
",",
"screen_level",
"=",
"logging",
".",
"CRITICAL",
",",
"pdb",
"=",
"False",
")",
":",
"# Initialize the logging",
"root",
"=",
"logging",
".",
"getLogger",
... | 32.166667 | 0.001257 |
def _build_discrete_cmap(cmap, levels, extend, filled):
"""
Build a discrete colormap and normalization of the data.
"""
import matplotlib as mpl
if not filled:
# non-filled contour plots
extend = 'max'
if extend == 'both':
ext_n = 2
elif extend in ['min', 'max']:
... | [
"def",
"_build_discrete_cmap",
"(",
"cmap",
",",
"levels",
",",
"extend",
",",
"filled",
")",
":",
"import",
"matplotlib",
"as",
"mpl",
"if",
"not",
"filled",
":",
"# non-filled contour plots",
"extend",
"=",
"'max'",
"if",
"extend",
"==",
"'both'",
":",
"ex... | 24.576923 | 0.001506 |
def get_next_action(self, request, application, label, roles):
""" Process the get_next_action request at the current step. """
# if user is logged and and not applicant, steal the
# application
if 'is_applicant' in roles:
# if we got this far, then we either we are logged i... | [
"def",
"get_next_action",
"(",
"self",
",",
"request",
",",
"application",
",",
"label",
",",
"roles",
")",
":",
"# if user is logged and and not applicant, steal the",
"# application",
"if",
"'is_applicant'",
"in",
"roles",
":",
"# if we got this far, then we either we are... | 46.222222 | 0.000523 |
def _excel_cell(cls, cell, quote_everything=False, quote_numbers=True,
_is_header=False):
"""
This will return a text that excel interprets correctly when
importing csv
:param cell: obj to store in the cell
:param quote_everything: bool to quote ev... | [
"def",
"_excel_cell",
"(",
"cls",
",",
"cell",
",",
"quote_everything",
"=",
"False",
",",
"quote_numbers",
"=",
"True",
",",
"_is_header",
"=",
"False",
")",
":",
"if",
"cell",
"is",
"None",
":",
"return",
"u''",
"if",
"cell",
"is",
"True",
":",
"retu... | 36.421053 | 0.002111 |
def is_number(dtype):
"""Return True is datatype dtype is a number kind"""
return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \
or ('short' in dtype.name) | [
"def",
"is_number",
"(",
"dtype",
")",
":",
"return",
"is_float",
"(",
"dtype",
")",
"or",
"(",
"'int'",
"in",
"dtype",
".",
"name",
")",
"or",
"(",
"'long'",
"in",
"dtype",
".",
"name",
")",
"or",
"(",
"'short'",
"in",
"dtype",
".",
"name",
")"
] | 49 | 0.01005 |
def user_avatar_url(username, size=64, default="retro"):
"""Get the avatar URL of the provided Fedora username.
The URL is returned from the Libravatar service.
Args:
username (str): The username to get the avatar of.
size (int): Size of the avatar in pixels (it's a square).
defaul... | [
"def",
"user_avatar_url",
"(",
"username",
",",
"size",
"=",
"64",
",",
"default",
"=",
"\"retro\"",
")",
":",
"openid",
"=",
"\"http://{}.id.fedoraproject.org/\"",
".",
"format",
"(",
"username",
")",
"return",
"libravatar_url",
"(",
"openid",
"=",
"openid",
... | 39.285714 | 0.001776 |
def _get_site_coeffs(self, sites, imt):
"""
Extracts correct coefficients for each site from Table 5 on p. 208
for each site.
:raises UserWarning:
If vs30 is below limit for site class D, since "E- and F-type
sites [...] are susceptible for liquefaction and failu... | [
"def",
"_get_site_coeffs",
"(",
"self",
",",
"sites",
",",
"imt",
")",
":",
"site_classes",
"=",
"self",
".",
"get_nehrp_classes",
"(",
"sites",
")",
"is_bedrock",
"=",
"self",
".",
"is_bedrock",
"(",
"sites",
")",
"if",
"'E'",
"in",
"site_classes",
":",
... | 35.8125 | 0.001699 |
def get_dataset():
"""Create a dataset for machine learning of segmentations.
Returns
-------
tuple :
(X, y) where X is a list of tuples. Each tuple is a feature. y
is a list of labels (0 for 'not in one symbol' and 1 for 'in symbol')
"""
seg_data = "segmentation-X.npy"
seg_... | [
"def",
"get_dataset",
"(",
")",
":",
"seg_data",
"=",
"\"segmentation-X.npy\"",
"seg_labels",
"=",
"\"segmentation-y.npy\"",
"# seg_ids = \"segmentation-ids.npy\"",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"seg_data",
")",
"and",
"os",
".",
"path",
".",
"isfil... | 40.693878 | 0.00049 |
def happy(args):
"""
%prog happy happy.txt
Make bi-directed graph from HAPPY mapping data. JCVI encodes uncertainties
in the order of the contigs / scaffolds.
: separates scaffolds
+ means telomere (though the telomere repeats may not show because the
telomere-adjacent sequence is missing)... | [
"def",
"happy",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"happy",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--prefix\"",
",",
"help",
"=",
"\"Add prefix to the name [default: %default]\"",
")",
"opts",
",",
"args",
"=",
"p",
".",
"p... | 33.119048 | 0.002095 |
def check_partition_status(method, uri, partition, valid_statuses=None,
invalid_statuses=None):
"""
Check that the partition is in one of the valid statuses (if specified)
and not in one of the invalid statuses (if specified), as indicated by its
'status' property.
If the... | [
"def",
"check_partition_status",
"(",
"method",
",",
"uri",
",",
"partition",
",",
"valid_statuses",
"=",
"None",
",",
"invalid_statuses",
"=",
"None",
")",
":",
"status",
"=",
"partition",
".",
"properties",
".",
"get",
"(",
"'status'",
",",
"None",
")",
... | 51.486486 | 0.000515 |
def _calc_position_for_pin(self, x, y, relative_position):
"""Determine position at fraction of x, y path.
:param x,y: two equal length lists of values describing a path.
:param relative_position: value between 0 and 1
:returns: the x, y position of the fraction (relative_position)
... | [
"def",
"_calc_position_for_pin",
"(",
"self",
",",
"x",
",",
"y",
",",
"relative_position",
")",
":",
"try",
":",
"max_idx_x",
"=",
"len",
"(",
"x",
")",
"-",
"1",
"max_idx_y",
"=",
"len",
"(",
"y",
")",
"-",
"1",
"except",
"TypeError",
":",
"return"... | 37.285714 | 0.001245 |
def __intermediate_bridge(self, interface, i):
"""
converts NetJSON bridge to
UCI intermediate data structure
"""
# ensure type "bridge" is only given to one logical interface
if interface['type'] == 'bridge' and i < 2:
bridge_members = ' '.join(interface.pop(... | [
"def",
"__intermediate_bridge",
"(",
"self",
",",
"interface",
",",
"i",
")",
":",
"# ensure type \"bridge\" is only given to one logical interface",
"if",
"interface",
"[",
"'type'",
"]",
"==",
"'bridge'",
"and",
"i",
"<",
"2",
":",
"bridge_members",
"=",
"' '",
... | 45.633333 | 0.002146 |
def service_confirmation(self, conn, bslpdu):
"""Receive packets forwarded by the proxy and redirect them to the proxy network adapter."""
if _debug: ProxyServerService._debug("service_confirmation %r %r", conn, bslpdu)
# make sure there is an adapter for it - or something went wrong
if... | [
"def",
"service_confirmation",
"(",
"self",
",",
"conn",
",",
"bslpdu",
")",
":",
"if",
"_debug",
":",
"ProxyServerService",
".",
"_debug",
"(",
"\"service_confirmation %r %r\"",
",",
"conn",
",",
"bslpdu",
")",
"# make sure there is an adapter for it - or something wen... | 51.8 | 0.011385 |
def breakpoint_info(self, handle=0, index=-1):
"""Returns the information about a set breakpoint.
Note:
Either ``handle`` or ``index`` can be specified. If the ``index``
is not provided, the ``handle`` must be set, and vice-versa. If
both ``index`` and ``handle`` are pro... | [
"def",
"breakpoint_info",
"(",
"self",
",",
"handle",
"=",
"0",
",",
"index",
"=",
"-",
"1",
")",
":",
"if",
"index",
"<",
"0",
"and",
"handle",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Handle must be provided if index is not set.'",
")",
"bp",
"=",
... | 36.1875 | 0.001682 |
def stream_url(self):
'''stream for this song - not re-encoded'''
path = '/Audio/{}/universal'.format(self.id)
return self.connector.get_url(path,
userId=self.connector.userid,
MaxStreamingBitrate=140000000,
Container='opus',
TranscodingContainer='opus... | [
"def",
"stream_url",
"(",
"self",
")",
":",
"path",
"=",
"'/Audio/{}/universal'",
".",
"format",
"(",
"self",
".",
"id",
")",
"return",
"self",
".",
"connector",
".",
"get_url",
"(",
"path",
",",
"userId",
"=",
"self",
".",
"connector",
".",
"userid",
... | 37.166667 | 0.02407 |
def targetSurfacemassLOS(self,d,l,log=False,deg=True):
"""
NAME:
targetSurfacemassLOS
PURPOSE:
evaluate the target surface mass along the LOS given l and d
INPUT:
d - distance along the line of sight (can be Quantity)
l - Galactic lon... | [
"def",
"targetSurfacemassLOS",
"(",
"self",
",",
"d",
",",
"l",
",",
"log",
"=",
"False",
",",
"deg",
"=",
"True",
")",
":",
"#Calculate R and phi",
"if",
"_APY_LOADED",
"and",
"isinstance",
"(",
"l",
",",
"units",
".",
"Quantity",
")",
":",
"lrad",
"=... | 24.755556 | 0.017271 |
def catch_post_mortem(host='', port=5555, patch_stdstreams=False):
"""
A context manager for tracking potentially error-prone code
If an unhandled exception is raised inside context manager's code block,
the post-mortem debugger is started automatically.
Example::
with web_pdb.catch_post_... | [
"def",
"catch_post_mortem",
"(",
"host",
"=",
"''",
",",
"port",
"=",
"5555",
",",
"patch_stdstreams",
"=",
"False",
")",
":",
"try",
":",
"yield",
"except",
"Exception",
":",
"post_mortem",
"(",
"None",
",",
"host",
",",
"port",
",",
"patch_stdstreams",
... | 30.961538 | 0.001205 |
def poisson_log_likelihood(x, data):
"""Poisson log-likelihood of ``data`` given noise parametrized by ``x``.
Parameters
----------
x : ``op.domain`` element
Value to condition the log-likelihood on.
data : ``op.range`` element
Data whose log-likelihood given ``x`` shall be calculat... | [
"def",
"poisson_log_likelihood",
"(",
"x",
",",
"data",
")",
":",
"if",
"np",
".",
"any",
"(",
"np",
".",
"less",
"(",
"x",
",",
"0",
")",
")",
":",
"raise",
"ValueError",
"(",
"'`x` must be non-negative'",
")",
"return",
"np",
".",
"sum",
"(",
"data... | 32.071429 | 0.002165 |
def keys(self, section, prefix=None):
"""
Returns all keys of a *section* in a list. When *prefix* is set, only keys starting with
that prefix are returned
"""
return [key for key, _ in self.items(section) if (not prefix or key.startswith(prefix))] | [
"def",
"keys",
"(",
"self",
",",
"section",
",",
"prefix",
"=",
"None",
")",
":",
"return",
"[",
"key",
"for",
"key",
",",
"_",
"in",
"self",
".",
"items",
"(",
"section",
")",
"if",
"(",
"not",
"prefix",
"or",
"key",
".",
"startswith",
"(",
"pre... | 47.166667 | 0.013889 |
def transpose_func(classes, table):
"""
Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict
"""
transposed_table = table
for i, item1 in enumerate(classes):
for j, item2 in enumerat... | [
"def",
"transpose_func",
"(",
"classes",
",",
"table",
")",
":",
"transposed_table",
"=",
"table",
"for",
"i",
",",
"item1",
"in",
"enumerate",
"(",
"classes",
")",
":",
"for",
"j",
",",
"item2",
"in",
"enumerate",
"(",
"classes",
")",
":",
"if",
"i",
... | 30.666667 | 0.001757 |
def fetch(self, start=None, stop=None):
"""
Fetch log records and return them as a list.
|Args|
* ``start`` (**int**): non-negative index of the first log
record to return.
* ``stop`` (**int**): non-negative index of the last log
record to return.
... | [
"def",
"fetch",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"# Set defaults if no explicit indices were provided.",
"if",
"not",
"start",
":",
"start",
"=",
"0",
"if",
"not",
"stop",
":",
"stop",
"=",
"len",
"(",
"self",
"... | 25.538462 | 0.001934 |
def Scroll_up(self, n, dl = 0):
"""鼠标滚轮向上n次
"""
self.Delay(dl)
self.mouse.scroll(vertical = n) | [
"def",
"Scroll_up",
"(",
"self",
",",
"n",
",",
"dl",
"=",
"0",
")",
":",
"self",
".",
"Delay",
"(",
"dl",
")",
"self",
".",
"mouse",
".",
"scroll",
"(",
"vertical",
"=",
"n",
")"
] | 24.4 | 0.047619 |
def generate_single_return_period(args):
"""
This function calculates a single return period for a single reach
"""
qout_file, return_period_file, rivid_index_list, step, num_years, \
method, mp_lock = args
skewvals = [-3.0, -2.8, -2.6, -2.4, -2.2, -2.0, -1.8, -1.6, -1.4, -1.2,
... | [
"def",
"generate_single_return_period",
"(",
"args",
")",
":",
"qout_file",
",",
"return_period_file",
",",
"rivid_index_list",
",",
"step",
",",
"num_years",
",",
"method",
",",
"mp_lock",
"=",
"args",
"skewvals",
"=",
"[",
"-",
"3.0",
",",
"-",
"2.8",
",",... | 51.171642 | 0.000143 |
def check_auth(args):
"""
Checks courseraoauth2client's connectivity to the coursera.org API servers
for a specific application
"""
oauth2_instance = oauth2.build_oauth2(args.app, args)
auth = oauth2_instance.build_authorizer()
my_profile_url = (
'https://api.coursera.org/api/externa... | [
"def",
"check_auth",
"(",
"args",
")",
":",
"oauth2_instance",
"=",
"oauth2",
".",
"build_oauth2",
"(",
"args",
".",
"app",
",",
"args",
")",
"auth",
"=",
"oauth2_instance",
".",
"build_authorizer",
"(",
")",
"my_profile_url",
"=",
"(",
"'https://api.coursera.... | 30.461538 | 0.002447 |
def get_resources_vms(call=None, resFilter=None, includeConfig=True):
'''
Retrieve all VMs available on this environment
CLI Example:
.. code-block:: bash
salt-cloud -f get_resources_vms my-proxmox-config
'''
timeoutTime = time.time() + 60
while True:
log.debug('Getting r... | [
"def",
"get_resources_vms",
"(",
"call",
"=",
"None",
",",
"resFilter",
"=",
"None",
",",
"includeConfig",
"=",
"True",
")",
":",
"timeoutTime",
"=",
"time",
".",
"time",
"(",
")",
"+",
"60",
"while",
"True",
":",
"log",
".",
"debug",
"(",
"'Getting re... | 32.462963 | 0.000554 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.