text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def parse_extended_entities(extended_entities_dict):
"""Parse media file URL:s form tweet data
:extended_entities_dict:
:returns: list of media file urls
"""
urls = []
if "media" in extended_entities_dict.keys():
for item in extended_entities_dict["media"]:
# add static i... | [
"def",
"parse_extended_entities",
"(",
"extended_entities_dict",
")",
":",
"urls",
"=",
"[",
"]",
"if",
"\"media\"",
"in",
"extended_entities_dict",
".",
"keys",
"(",
")",
":",
"for",
"item",
"in",
"extended_entities_dict",
"[",
"\"media\"",
"]",
":",
"# add sta... | 35.242424 | 0.001674 |
def escape(s, quote=False):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences. If
the optional flag `quote` is `True`, the quotation mark character is
also translated.
There is a special handling for `None` which escapes to an empty string.
:param s: the string to escape.
... | [
"def",
"escape",
"(",
"s",
",",
"quote",
"=",
"False",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"''",
"if",
"hasattr",
"(",
"s",
",",
"'__html__'",
")",
":",
"return",
"s",
".",
"__html__",
"(",
")",
"if",
"not",
"isinstance",
"(",
"s",
... | 32.32 | 0.002404 |
def normalize(dt, tz=UTC):
"""
Convert date or datetime to datetime with timezone.
:param dt: date to normalize
:param tz: the normalized date's timezone
:return: date as datetime with timezone
"""
if type(dt) is date:
dt = dt + relativedelta(hour=0)
elif type(dt) is datetime:
... | [
"def",
"normalize",
"(",
"dt",
",",
"tz",
"=",
"UTC",
")",
":",
"if",
"type",
"(",
"dt",
")",
"is",
"date",
":",
"dt",
"=",
"dt",
"+",
"relativedelta",
"(",
"hour",
"=",
"0",
")",
"elif",
"type",
"(",
"dt",
")",
"is",
"datetime",
":",
"pass",
... | 23.142857 | 0.001976 |
def catsimPopulation(tag, mc_source_id_start=1, n=5000, n_chunk=100, config='simulate_population.yaml'):
"""
n = Number of satellites to simulation
n_chunk = Number of satellites in a file chunk
"""
assert mc_source_id_start >= 1, "Starting mc_source_id must be >= 1"
assert n % n_chunk == 0, "... | [
"def",
"catsimPopulation",
"(",
"tag",
",",
"mc_source_id_start",
"=",
"1",
",",
"n",
"=",
"5000",
",",
"n_chunk",
"=",
"100",
",",
"config",
"=",
"'simulate_population.yaml'",
")",
":",
"assert",
"mc_source_id_start",
">=",
"1",
",",
"\"Starting mc_source_id mu... | 56.260101 | 0.008556 |
def update(self, z, R=None, hx_args=()):
""" Update the CKF with the given measurements. On return,
self.x and self.P contain the new mean and covariance of the filter.
Parameters
----------
z : numpy.array of shape (dim_z)
measurement vector
R : numpy.arra... | [
"def",
"update",
"(",
"self",
",",
"z",
",",
"R",
"=",
"None",
",",
"hx_args",
"=",
"(",
")",
")",
":",
"if",
"z",
"is",
"None",
":",
"self",
".",
"z",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"None",
"]",
"*",
"self",
".",
"dim_z",
"]",
"... | 32.04918 | 0.000993 |
def addToLayout(self, analysis, position=None):
""" Adds the analysis passed in to the worksheet's layout
"""
# TODO Redux
layout = self.getLayout()
container_uid = self.get_container_for(analysis)
if IRequestAnalysis.providedBy(analysis) and \
not IDuplic... | [
"def",
"addToLayout",
"(",
"self",
",",
"analysis",
",",
"position",
"=",
"None",
")",
":",
"# TODO Redux",
"layout",
"=",
"self",
".",
"getLayout",
"(",
")",
"container_uid",
"=",
"self",
".",
"get_container_for",
"(",
"analysis",
")",
"if",
"IRequestAnalys... | 52 | 0.001642 |
def add_all(self, statements, parameters):
"""
Adds a sequence of :class:`.Statement` objects and a matching sequence
of parameters to the batch. Statement and parameter sequences must be of equal length or
one will be truncated. :const:`None` can be used in the parameters position where... | [
"def",
"add_all",
"(",
"self",
",",
"statements",
",",
"parameters",
")",
":",
"for",
"statement",
",",
"value",
"in",
"zip",
"(",
"statements",
",",
"parameters",
")",
":",
"self",
".",
"add",
"(",
"statement",
",",
"value",
")"
] | 54.625 | 0.009009 |
def upgrade():
"""Upgrade database."""
current_date = datetime.utcnow()
# Add 'created' and 'updated' columns to RemoteAccount
_add_created_updated_columns('oauthclient_remoteaccount', current_date)
# Add 'created' and 'updated' columns to RemoteToken
_add_created_updated_columns('oauthclient_... | [
"def",
"upgrade",
"(",
")",
":",
"current_date",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# Add 'created' and 'updated' columns to RemoteAccount",
"_add_created_updated_columns",
"(",
"'oauthclient_remoteaccount'",
",",
"current_date",
")",
"# Add 'created' and 'updated' colu... | 39.166667 | 0.002079 |
def has_mixture_channel(val: Any) -> bool:
"""Returns whether the value has a mixture channel representation.
In contrast to `has_mixture` this method falls back to checking whether
the value has a unitary representation via `has_channel`.
Returns:
If `val` has a `_has_mixture_` method and its... | [
"def",
"has_mixture_channel",
"(",
"val",
":",
"Any",
")",
"->",
"bool",
":",
"mixture_getter",
"=",
"getattr",
"(",
"val",
",",
"'_has_mixture_'",
",",
"None",
")",
"result",
"=",
"NotImplemented",
"if",
"mixture_getter",
"is",
"None",
"else",
"mixture_getter... | 42.84 | 0.001826 |
def pie(n_labels=5,mode=None):
"""
Returns a DataFrame with the required format for
a pie plot
Parameters:
-----------
n_labels : int
Number of labels
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for random stock names
"""
return pd.DataFrame({'values':np.random.ra... | [
"def",
"pie",
"(",
"n_labels",
"=",
"5",
",",
"mode",
"=",
"None",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"'values'",
":",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"100",
",",
"n_labels",
")",
",",
"'labels'",
":",
"getN... | 23.3125 | 0.06701 |
def com_google_fonts_check_usweightclass(font, ttFont, style):
"""Checking OS/2 usWeightClass."""
from fontbakery.profiles.shared_conditions import is_ttf
weight_name, expected_value = expected_os2_weight(style)
value = ttFont['OS/2'].usWeightClass
if value != expected_value:
if is_ttf(ttFont) and \
... | [
"def",
"com_google_fonts_check_usweightclass",
"(",
"font",
",",
"ttFont",
",",
"style",
")",
":",
"from",
"fontbakery",
".",
"profiles",
".",
"shared_conditions",
"import",
"is_ttf",
"weight_name",
",",
"expected_value",
"=",
"expected_os2_weight",
"(",
"style",
")... | 43.25 | 0.008483 |
def plotAllSweeps(abfFile):
"""simple example how to load an ABF file and plot every sweep."""
r = io.AxonIO(filename=abfFile)
bl = r.read_block(lazy=False, cascade=True)
print(abfFile+"\nplotting %d sweeps..."%len(bl.segments))
plt.figure(figsize=(12,10))
plt.title(abfFile)
for sweep i... | [
"def",
"plotAllSweeps",
"(",
"abfFile",
")",
":",
"r",
"=",
"io",
".",
"AxonIO",
"(",
"filename",
"=",
"abfFile",
")",
"bl",
"=",
"r",
".",
"read_block",
"(",
"lazy",
"=",
"False",
",",
"cascade",
"=",
"True",
")",
"print",
"(",
"abfFile",
"+",
"\"... | 39.5 | 0.012367 |
def start_blocking(self):
""" Start the advertiser in the background, but wait until it is ready """
self._cav_started.clear()
self.start()
self._cav_started.wait() | [
"def",
"start_blocking",
"(",
"self",
")",
":",
"self",
".",
"_cav_started",
".",
"clear",
"(",
")",
"self",
".",
"start",
"(",
")",
"self",
".",
"_cav_started",
".",
"wait",
"(",
")"
] | 32 | 0.015228 |
def _handle_job_set(function):
"""A decorator for handling `taskhandle.JobSet`\s
A decorator for handling `taskhandle.JobSet`\s for `do` and `undo`
methods of `Change`\s.
"""
def call(self, job_set=taskhandle.NullJobSet()):
job_set.started_job(str(self))
function(self)
job_s... | [
"def",
"_handle_job_set",
"(",
"function",
")",
":",
"def",
"call",
"(",
"self",
",",
"job_set",
"=",
"taskhandle",
".",
"NullJobSet",
"(",
")",
")",
":",
"job_set",
".",
"started_job",
"(",
"str",
"(",
"self",
")",
")",
"function",
"(",
"self",
")",
... | 31.181818 | 0.011331 |
def unfreeze(self, names=None):
"""
unfreeze module, if names is not None, unfreeze layers that match given names
:param names: an array of layer names
:return:
"""
callBigDlFunc(self.bigdl_type, "unFreeze", self.value, names)
return self | [
"def",
"unfreeze",
"(",
"self",
",",
"names",
"=",
"None",
")",
":",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"unFreeze\"",
",",
"self",
".",
"value",
",",
"names",
")",
"return",
"self"
] | 35.875 | 0.010204 |
def parse_psimitab(content, fmt='tab27'):
"""https://code.google.com/archive/p/psimi/wikis/PsimiTab27Format.wiki
"""
columns = [
'Unique identifier for interactor A',
'Unique identifier for interactor B',
'Alternative identifier for interactor A',
'Alternative identifier for ... | [
"def",
"parse_psimitab",
"(",
"content",
",",
"fmt",
"=",
"'tab27'",
")",
":",
"columns",
"=",
"[",
"'Unique identifier for interactor A'",
",",
"'Unique identifier for interactor B'",
",",
"'Alternative identifier for interactor A'",
",",
"'Alternative identifier for interacto... | 37.47541 | 0.000853 |
def wkt_to_rectangle(extent):
"""Compute the rectangle from a WKT string.
It returns None if the extent is not valid WKT rectangle.
:param extent: The extent.
:type extent: basestring
:return: The rectangle or None if it is not a valid WKT rectangle.
:rtype: QgsRectangle
"""
geometry ... | [
"def",
"wkt_to_rectangle",
"(",
"extent",
")",
":",
"geometry",
"=",
"QgsGeometry",
".",
"fromWkt",
"(",
"extent",
")",
"if",
"not",
"geometry",
".",
"isGeosValid",
"(",
")",
":",
"return",
"None",
"polygon",
"=",
"geometry",
".",
"asPolygon",
"(",
")",
... | 24.071429 | 0.001427 |
def purge_tokens(self, input_token_attrs=None):
""" Removes all specified token_attrs that exist in instance.token_attrs
:param token_attrs: list(str), list of string values of tokens to remove. If None, removes all
"""
if input_token_attrs is None:
remove_attrs = s... | [
"def",
"purge_tokens",
"(",
"self",
",",
"input_token_attrs",
"=",
"None",
")",
":",
"if",
"input_token_attrs",
"is",
"None",
":",
"remove_attrs",
"=",
"self",
".",
"token_attrs",
"else",
":",
"remove_attrs",
"=",
"[",
"token_attr",
"for",
"token_attr",
"in",
... | 51.363636 | 0.012174 |
def generate_diary(self):
"""
extracts event information from core tables into diary files
"""
print('Generate diary files from Event rows only')
for r in self.table:
print(str(type(r)) + ' = ', r) | [
"def",
"generate_diary",
"(",
"self",
")",
":",
"print",
"(",
"'Generate diary files from Event rows only'",
")",
"for",
"r",
"in",
"self",
".",
"table",
":",
"print",
"(",
"str",
"(",
"type",
"(",
"r",
")",
")",
"+",
"' = '",
",",
"r",
")"
] | 34.714286 | 0.008032 |
def _cos_to_angle(result, deriv, sign=1):
"""Convert a cosine and its derivatives to an angle and its derivatives"""
v = np.arccos(np.clip(result[0], -1, 1))
if deriv == 0:
return v*sign,
if abs(result[0]) >= 1:
factor1 = 0
else:
factor1 = -1.0/np.sqrt(1-result[0]**2)
d =... | [
"def",
"_cos_to_angle",
"(",
"result",
",",
"deriv",
",",
"sign",
"=",
"1",
")",
":",
"v",
"=",
"np",
".",
"arccos",
"(",
"np",
".",
"clip",
"(",
"result",
"[",
"0",
"]",
",",
"-",
"1",
",",
"1",
")",
")",
"if",
"deriv",
"==",
"0",
":",
"re... | 34.176471 | 0.001675 |
def add_projection(query_proto, *projection):
"""Add projection properties to the given datatstore.Query proto message."""
for p in projection:
proto = query_proto.projection.add()
proto.property.name = p | [
"def",
"add_projection",
"(",
"query_proto",
",",
"*",
"projection",
")",
":",
"for",
"p",
"in",
"projection",
":",
"proto",
"=",
"query_proto",
".",
"projection",
".",
"add",
"(",
")",
"proto",
".",
"property",
".",
"name",
"=",
"p"
] | 42.4 | 0.013889 |
def is_class(data):
"""
checks that the data (which is a string, buffer, or a stream
supporting the read method) has the magic numbers indicating it is
a Java class file. Returns False if the magic numbers do not
match, or for any errors.
"""
try:
with unpack(data) as up:
... | [
"def",
"is_class",
"(",
"data",
")",
":",
"try",
":",
"with",
"unpack",
"(",
"data",
")",
"as",
"up",
":",
"magic",
"=",
"up",
".",
"unpack_struct",
"(",
"_BBBB",
")",
"return",
"magic",
"==",
"JAVA_CLASS_MAGIC",
"except",
"UnpackException",
":",
"return... | 26.875 | 0.002247 |
def reset_generation(self):
"""Reset the generation and memberId because we have fallen out of the group."""
with self._lock:
self._generation = Generation.NO_GENERATION
self.rejoin_needed = True
self.state = MemberState.UNJOINED | [
"def",
"reset_generation",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_generation",
"=",
"Generation",
".",
"NO_GENERATION",
"self",
".",
"rejoin_needed",
"=",
"True",
"self",
".",
"state",
"=",
"MemberState",
".",
"UNJOINED"
] | 46 | 0.010676 |
def encode(self, word, max_length=4, zero_pad=True):
"""Return the Phonix code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
zero_pad : bool
Pad the ... | [
"def",
"encode",
"(",
"self",
",",
"word",
",",
"max_length",
"=",
"4",
",",
"zero_pad",
"=",
"True",
")",
":",
"def",
"_start_repl",
"(",
"word",
",",
"src",
",",
"tar",
",",
"post",
"=",
"None",
")",
":",
"\"\"\"Replace src with tar at the start of word.... | 27.225806 | 0.000762 |
def build_urls(self: NodeVisitor, node: inheritance_diagram) -> Mapping[str, str]:
"""
Builds a mapping of class paths to URLs.
"""
current_filename = self.builder.current_docname + self.builder.out_suffix
urls = {}
for child in node:
# Another document
if child.get("refuri") is ... | [
"def",
"build_urls",
"(",
"self",
":",
"NodeVisitor",
",",
"node",
":",
"inheritance_diagram",
")",
"->",
"Mapping",
"[",
"str",
",",
"str",
"]",
":",
"current_filename",
"=",
"self",
".",
"builder",
".",
"current_docname",
"+",
"self",
".",
"builder",
"."... | 36.333333 | 0.001986 |
def list_line(self, line):
"""
Write the given iterable of values (line) to the file as items on the
same line. Any argument that stringifies to a string legal as a TSV data
item can be written.
Does not copy the line or build a big string in memory.
"""
... | [
"def",
"list_line",
"(",
"self",
",",
"line",
")",
":",
"if",
"len",
"(",
"line",
")",
"==",
"0",
":",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"str",
"(",
"line",
"[",
"0",
"]",
")",
")",
"for",
"item",
"in",
"line",
"[",
"1",
":"... | 29.210526 | 0.015707 |
def evaluate(expr, **variables):
"""
>>> evaluate('2**6')
64
>>> evaluate('1 + 2*3**(2 + 2) / (6 + -7)')
-161.0
>>> evaluate('5 < 4')
False
>>> evaluate('5 < a < 10', a=6)
True
"""
module = ast.parse(expr) # Module(body=[Expr(value=...)])
if len(module.body) != 1:
... | [
"def",
"evaluate",
"(",
"expr",
",",
"*",
"*",
"variables",
")",
":",
"module",
"=",
"ast",
".",
"parse",
"(",
"expr",
")",
"# Module(body=[Expr(value=...)])",
"if",
"len",
"(",
"module",
".",
"body",
")",
"!=",
"1",
":",
"raise",
"BadExpression",
"(",
... | 26.875 | 0.001497 |
def sendAppliedToOwner(self, context={}):
"""
Sent to project owner when user applies to a project
"""
super(ApplyMail, self).__init__(self.apply.project.owner.email, self.async, self.apply.project.owner.locale)
return self.sendEmail('volunteerApplied-ToOwner', 'New volunteer', context) | [
"def",
"sendAppliedToOwner",
"(",
"self",
",",
"context",
"=",
"{",
"}",
")",
":",
"super",
"(",
"ApplyMail",
",",
"self",
")",
".",
"__init__",
"(",
"self",
".",
"apply",
".",
"project",
".",
"owner",
".",
"email",
",",
"self",
".",
"async",
",",
... | 50.333333 | 0.009772 |
def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d):
"""All angles in radians."""
zeta_a = satz_a
zeta_b = satz_b
phi_a = compute_phi(zeta_a)
phi_b = compute_phi(zeta_b)
theta_a = compute_theta(zeta_a, phi_a)
theta_b = compute_theta(zeta_b, phi_b)
phi = (phi_a + phi_b) / 2
... | [
"def",
"compute_expansion_alignment",
"(",
"satz_a",
",",
"satz_b",
",",
"satz_c",
",",
"satz_d",
")",
":",
"zeta_a",
"=",
"satz_a",
"zeta_b",
"=",
"satz_b",
"phi_a",
"=",
"compute_phi",
"(",
"zeta_a",
")",
"phi_b",
"=",
"compute_phi",
"(",
"zeta_b",
")",
... | 30.652174 | 0.001376 |
def get_feature(name):
"""Get an instance of a ``Features`` class by ``name`` (str)."""
if name == 'css':
return CSSFeatures()
elif name == 'kohlschuetter':
return KohlschuetterFeatures()
elif name == 'readability':
return ReadabilityFeatures()
elif name == 'weninger':
... | [
"def",
"get_feature",
"(",
"name",
")",
":",
"if",
"name",
"==",
"'css'",
":",
"return",
"CSSFeatures",
"(",
")",
"elif",
"name",
"==",
"'kohlschuetter'",
":",
"return",
"KohlschuetterFeatures",
"(",
")",
"elif",
"name",
"==",
"'readability'",
":",
"return",... | 35.285714 | 0.001972 |
def minicalendar(context):
"""
Displays a little ajax version of the calendar.
"""
today = dt.date.today()
request = context['request']
home = request.site.root_page
cal = CalendarPage.objects.live().descendant_of(home).first()
calUrl = cal.get_url(request) if cal else None
if cal:
... | [
"def",
"minicalendar",
"(",
"context",
")",
":",
"today",
"=",
"dt",
".",
"date",
".",
"today",
"(",
")",
"request",
"=",
"context",
"[",
"'request'",
"]",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"cal",
"=",
"CalendarPage",
".",
"objects... | 37.619048 | 0.001235 |
def find_hostname(use_chroot=True):
"""
Find the host name to include in log messages.
:param use_chroot: Use the name of the chroot when inside a chroot?
(boolean, defaults to :data:`True`)
:returns: A suitable host name (a string).
Looks for :data:`CHROOT_FILES` that have ... | [
"def",
"find_hostname",
"(",
"use_chroot",
"=",
"True",
")",
":",
"for",
"chroot_file",
"in",
"CHROOT_FILES",
":",
"try",
":",
"with",
"open",
"(",
"chroot_file",
")",
"as",
"handle",
":",
"first_line",
"=",
"next",
"(",
"handle",
")",
"name",
"=",
"firs... | 34.318182 | 0.001289 |
def command_as_list(
self,
mark_success=False,
ignore_all_deps=False,
ignore_task_deps=False,
ignore_depends_on_past=False,
ignore_ti_state=False,
local=False,
pickle_id=None,
raw=False,
job_id=None,
... | [
"def",
"command_as_list",
"(",
"self",
",",
"mark_success",
"=",
"False",
",",
"ignore_all_deps",
"=",
"False",
",",
"ignore_task_deps",
"=",
"False",
",",
"ignore_depends_on_past",
"=",
"False",
",",
"ignore_ti_state",
"=",
"False",
",",
"local",
"=",
"False",
... | 32.318182 | 0.001365 |
def get_total_paid(self) -> Decimal:
""" Returns the total amount paid, in currency, for the stocks owned """
query = (
self.get_splits_query()
)
splits = query.all()
total = Decimal(0)
for split in splits:
total += split.value
return tot... | [
"def",
"get_total_paid",
"(",
"self",
")",
"->",
"Decimal",
":",
"query",
"=",
"(",
"self",
".",
"get_splits_query",
"(",
")",
")",
"splits",
"=",
"query",
".",
"all",
"(",
")",
"total",
"=",
"Decimal",
"(",
"0",
")",
"for",
"split",
"in",
"splits",
... | 25.916667 | 0.009317 |
def createNetwork(self, data, headers=None, query_params=None, content_type="application/json"):
"""
Create a new network
It is method for POST /network
"""
uri = self.client.base_url + "/network"
return self.client.post(uri, data, headers, query_params, content_type) | [
"def",
"createNetwork",
"(",
"self",
",",
"data",
",",
"headers",
"=",
"None",
",",
"query_params",
"=",
"None",
",",
"content_type",
"=",
"\"application/json\"",
")",
":",
"uri",
"=",
"self",
".",
"client",
".",
"base_url",
"+",
"\"/network\"",
"return",
... | 44.285714 | 0.009494 |
def getContactCreationParameters(self):
"""
Yield a L{Parameter} for each L{IContactType} known.
Each yielded object can be used with a L{LiveForm} to create a new
instance of a particular L{IContactType}.
"""
for contactType in self.getContactTypes():
if con... | [
"def",
"getContactCreationParameters",
"(",
"self",
")",
":",
"for",
"contactType",
"in",
"self",
".",
"getContactTypes",
"(",
")",
":",
"if",
"contactType",
".",
"allowMultipleContactItems",
":",
"descriptiveIdentifier",
"=",
"_descriptiveIdentifier",
"(",
"contactTy... | 43.409091 | 0.002049 |
def _keyring_equivalent(keyring_one, keyring_two):
"""
Check two keyrings are identical
"""
def keyring_extract_key(file_path):
"""
Cephx keyring files may or may not have white space before some lines.
They may have some values in quotes, so a safe way to compare is to
e... | [
"def",
"_keyring_equivalent",
"(",
"keyring_one",
",",
"keyring_two",
")",
":",
"def",
"keyring_extract_key",
"(",
"file_path",
")",
":",
"\"\"\"\n Cephx keyring files may or may not have white space before some lines.\n They may have some values in quotes, so a safe way to... | 38.454545 | 0.001153 |
def _validate_install(self):
''' a method to validate heroku is installed '''
self.printer('Checking heroku installation ... ', flush=True)
# import dependencies
from os import devnull
from subprocess import call, check_output
# validate cli installation... | [
"def",
"_validate_install",
"(",
"self",
")",
":",
"self",
".",
"printer",
"(",
"'Checking heroku installation ... '",
",",
"flush",
"=",
"True",
")",
"# import dependencies\r",
"from",
"os",
"import",
"devnull",
"from",
"subprocess",
"import",
"call",
",",
"check... | 32.318182 | 0.009563 |
def createClientCertificate(self, name, noPass = True, keyLength = 2048, days = 375):
"""Create a client certificate
"""
if not name:
raise ValueError('Require name')
configPath, keyPath, csrPath, certPath = \
os.path.join(self.basePath, self.FILE_CONFIG), \
... | [
"def",
"createClientCertificate",
"(",
"self",
",",
"name",
",",
"noPass",
"=",
"True",
",",
"keyLength",
"=",
"2048",
",",
"days",
"=",
"375",
")",
":",
"if",
"not",
"name",
":",
"raise",
"ValueError",
"(",
"'Require name'",
")",
"configPath",
",",
"key... | 64.44 | 0.016514 |
def tokenize_math(text):
r"""Prevents math from being tokenized.
:param Buffer text: iterator over line, with current position
>>> b = Buffer(r'$\min_x$ \command')
>>> tokenize_math(b)
'$'
>>> b = Buffer(r'$$\min_x$$ \command')
>>> tokenize_math(b)
'$$'
"""
if text.startswith('... | [
"def",
"tokenize_math",
"(",
"text",
")",
":",
"if",
"text",
".",
"startswith",
"(",
"'$'",
")",
"and",
"(",
"text",
".",
"position",
"==",
"0",
"or",
"text",
".",
"peek",
"(",
"-",
"1",
")",
"!=",
"'\\\\'",
"or",
"text",
".",
"endswith",
"(",
"r... | 32.75 | 0.001855 |
def set_permissions(obj_name,
principal,
permissions,
access_mode='grant',
applies_to=None,
obj_type='file',
reset_perms=False,
protected=None):
'''
Set the permissions of ... | [
"def",
"set_permissions",
"(",
"obj_name",
",",
"principal",
",",
"permissions",
",",
"access_mode",
"=",
"'grant'",
",",
"applies_to",
"=",
"None",
",",
"obj_type",
"=",
"'file'",
",",
"reset_perms",
"=",
"False",
",",
"protected",
"=",
"None",
")",
":",
... | 33.807229 | 0.000693 |
def getGenericInterface(interfaceVersion):
"""
Returns the interface of the specified version. This method must be called after VR_Init. The
pointer returned is valid until VR_Shutdown is called.
"""
error = EVRInitError()
result = _openvr.VR_GetGenericInterface(interfaceVersion, byref(erro... | [
"def",
"getGenericInterface",
"(",
"interfaceVersion",
")",
":",
"error",
"=",
"EVRInitError",
"(",
")",
"result",
"=",
"_openvr",
".",
"VR_GetGenericInterface",
"(",
"interfaceVersion",
",",
"byref",
"(",
"error",
")",
")",
"_checkInitError",
"(",
"error",
".",... | 40.666667 | 0.008021 |
def mapping_fields(mapping, parent=[]):
"""
reads an elasticsearh mapping dictionary and returns a list of fields
cojoined with a dot notation
args:
obj: the dictionary to parse
parent: name for a parent key. used with a recursive call
"""
rtn_obj = {}
for key, val... | [
"def",
"mapping_fields",
"(",
"mapping",
",",
"parent",
"=",
"[",
"]",
")",
":",
"rtn_obj",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"new_key",
"=",
"parent",
"+",
"[",
"key",
"]",
"new_key",
"=",
"... | 37.714286 | 0.002463 |
async def smap(source, func, *more_sources):
"""Apply a given function to the elements of one or several
asynchronous sequences.
Each element is used as a positional argument, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted. The fu... | [
"async",
"def",
"smap",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
")",
":",
"if",
"more_sources",
":",
"source",
"=",
"zip",
"(",
"source",
",",
"*",
"more_sources",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",... | 42.6875 | 0.001433 |
def bias_field_correction(
fmr,
fimout = '',
outpath = '',
fcomment = '_N4bias',
executable = '',
exe_options = [],
sitk_image_mask = True,
verbose = False,):
''' Correct for bias field in MR image(s) given in <fmr> as a string
(single file) o... | [
"def",
"bias_field_correction",
"(",
"fmr",
",",
"fimout",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fcomment",
"=",
"'_N4bias'",
",",
"executable",
"=",
"''",
",",
"exe_options",
"=",
"[",
"]",
",",
"sitk_image_mask",
"=",
"True",
",",
"verbose",
"=",... | 34.380682 | 0.014456 |
def run(self):
"""Run the test batch
"""
self.info_log("The test batch is ready.")
self.executed_tests = []
for test in self.tests:
localhost_instance = LocalhostInstance(
runner=self,
browser_config=self.browser_config,
... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"info_log",
"(",
"\"The test batch is ready.\"",
")",
"self",
".",
"executed_tests",
"=",
"[",
"]",
"for",
"test",
"in",
"self",
".",
"tests",
":",
"localhost_instance",
"=",
"LocalhostInstance",
"(",
"runner... | 31.138889 | 0.00173 |
def write_error(self, status_code, **kwargs):
'''
:param status_code:
:param kwargs:
:return:
'''
if "exc_info" in kwargs:
exc_info = kwargs["exc_info"]
error = exc_info[1]
errormessage = "%s: %s" % (status_code, error)
self.render("error.html", errormessage=errormessage... | [
"def",
"write_error",
"(",
"self",
",",
"status_code",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"exc_info\"",
"in",
"kwargs",
":",
"exc_info",
"=",
"kwargs",
"[",
"\"exc_info\"",
"]",
"error",
"=",
"exc_info",
"[",
"1",
"]",
"errormessage",
"=",
"\"%s:... | 27.866667 | 0.016204 |
def _embedding_classical_mds(matrix, dimensions=3, additive_correct=False):
"""
Private method to calculate CMDS embedding
:param dimensions: (int)
:return: coordinate matrix (np.array)
"""
if additive_correct:
dbc = double_centre(_additive_correct(matrix))
else:
dbc = double... | [
"def",
"_embedding_classical_mds",
"(",
"matrix",
",",
"dimensions",
"=",
"3",
",",
"additive_correct",
"=",
"False",
")",
":",
"if",
"additive_correct",
":",
"dbc",
"=",
"double_centre",
"(",
"_additive_correct",
"(",
"matrix",
")",
")",
"else",
":",
"dbc",
... | 33.333333 | 0.001946 |
def duration_outside_nwh(
self,
starttime: datetime.time = datetime.time(NORMAL_DAY_START_H),
endtime: datetime.time = datetime.time(NORMAL_DAY_END_H),
weekdays_only: bool = False,
weekends_only: bool = False) -> datetime.timedelta:
"""
Returns... | [
"def",
"duration_outside_nwh",
"(",
"self",
",",
"starttime",
":",
"datetime",
".",
"time",
"=",
"datetime",
".",
"time",
"(",
"NORMAL_DAY_START_H",
")",
",",
"endtime",
":",
"datetime",
".",
"time",
"=",
"datetime",
".",
"time",
"(",
"NORMAL_DAY_END_H",
")"... | 43.725 | 0.001119 |
def GetAmi(ec2, ami_spec):
""" Get the boto ami object given a AmiSpecification object. """
images = ec2.get_all_images(owners=[ami_spec.owner_id] )
requested_image = None
for image in images:
if image.name == ami_spec.ami_name:
requested_image = image
break
return requested_i... | [
"def",
"GetAmi",
"(",
"ec2",
",",
"ami_spec",
")",
":",
"images",
"=",
"ec2",
".",
"get_all_images",
"(",
"owners",
"=",
"[",
"ami_spec",
".",
"owner_id",
"]",
")",
"requested_image",
"=",
"None",
"for",
"image",
"in",
"images",
":",
"if",
"image",
"."... | 35.111111 | 0.012346 |
def home_timeline(self, delegate, params={}, extra_args=None):
"""Get updates from friends.
Calls the delgate once for each status object received."""
return self.__get('/statuses/home_timeline.xml', delegate, params,
txml.Statuses, extra_args=extra_args) | [
"def",
"home_timeline",
"(",
"self",
",",
"delegate",
",",
"params",
"=",
"{",
"}",
",",
"extra_args",
"=",
"None",
")",
":",
"return",
"self",
".",
"__get",
"(",
"'/statuses/home_timeline.xml'",
",",
"delegate",
",",
"params",
",",
"txml",
".",
"Statuses"... | 47.833333 | 0.010274 |
def IsDefault(self):
"""Determines if the data stream is the default data stream.
Returns:
bool: True if the data stream is the default data stream, false if not.
"""
if not self._tsk_attribute or not self._file_system:
return True
if self._file_system.IsHFS():
attribute_type = g... | [
"def",
"IsDefault",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_tsk_attribute",
"or",
"not",
"self",
".",
"_file_system",
":",
"return",
"True",
"if",
"self",
".",
"_file_system",
".",
"IsHFS",
"(",
")",
":",
"attribute_type",
"=",
"getattr",
"(",... | 30.5 | 0.010601 |
def _on_error_page_write_error(self, status_code, **kwargs):
"""Replaces the default Tornado error page with a Django-styled one"""
if oz.settings.get('debug'):
exception_type, exception_value, tback = sys.exc_info()
is_breakpoint = isinstance(exception_value, oz.error_pages.Deb... | [
"def",
"_on_error_page_write_error",
"(",
"self",
",",
"status_code",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"oz",
".",
"settings",
".",
"get",
"(",
"'debug'",
")",
":",
"exception_type",
",",
"exception_value",
",",
"tback",
"=",
"sys",
".",
"exc_info",... | 41 | 0.012325 |
def run(self):
"""
Process all incoming packets, until `stop()` is called. Intended to run
in its own thread.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(self._addr)
sock.settimeout(self._timeout)
with closing(sock):
w... | [
"def",
"run",
"(",
"self",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"sock",
".",
"bind",
"(",
"self",
".",
"_addr",
")",
"sock",
".",
"settimeout",
"(",
"self",
".",
"_tim... | 41.083333 | 0.001982 |
async def process_feed(self, url, send_mentions=True):
""" process a feed """
self._feed_domains.add(utils.get_domain(url))
if url in self._processed_feeds:
LOGGER.debug("Skipping already processed feed %s", url)
return
self._processed_feeds.add(url)
LO... | [
"async",
"def",
"process_feed",
"(",
"self",
",",
"url",
",",
"send_mentions",
"=",
"True",
")",
":",
"self",
".",
"_feed_domains",
".",
"add",
"(",
"utils",
".",
"get_domain",
"(",
"url",
")",
")",
"if",
"url",
"in",
"self",
".",
"_processed_feeds",
"... | 38.40625 | 0.00238 |
def resolve_from_dictionary(dictionary, key_list, default_value=None):
"""Take value from a given key list from dictionary.
Example: given dictionary d, key_list = ['foo', 'bar'],
it will try to resolve d['foo']['bar']. If not possible,
return default_value.
:param dictionary: A dictionary to reso... | [
"def",
"resolve_from_dictionary",
"(",
"dictionary",
",",
"key_list",
",",
"default_value",
"=",
"None",
")",
":",
"try",
":",
"current_value",
"=",
"dictionary",
"key_list",
"=",
"key_list",
"if",
"isinstance",
"(",
"key_list",
",",
"list",
")",
"else",
"[",
... | 30.142857 | 0.001148 |
def value_interval(ol,value):
'''
ol = [0, 4, 6, 8, 10, 14]
value_interval(ol,-1)
value_interval(ol,1)
value_interval(ol,2)
value_interval(ol,3)
value_interval(ol,4)
value_interval(ol,9)
value_interval(ol,14)
value_interval(ol,17)
'''
s... | [
"def",
"value_interval",
"(",
"ol",
",",
"value",
")",
":",
"si",
",",
"ei",
"=",
"where",
"(",
"ol",
",",
"value",
")",
"if",
"(",
"si",
"==",
"None",
")",
":",
"sv",
"=",
"None",
"else",
":",
"sv",
"=",
"ol",
"[",
"si",
"]",
"if",
"(",
"e... | 21.681818 | 0.014056 |
def _get_flow_for_token(csrf_token, request):
""" Looks up the flow in session to recover information about requested
scopes.
Args:
csrf_token: The token passed in the callback request that should
match the one previously generated and stored in the request on the
initial au... | [
"def",
"_get_flow_for_token",
"(",
"csrf_token",
",",
"request",
")",
":",
"flow_pickle",
"=",
"request",
".",
"session",
".",
"get",
"(",
"_FLOW_KEY",
".",
"format",
"(",
"csrf_token",
")",
",",
"None",
")",
"return",
"None",
"if",
"flow_pickle",
"is",
"N... | 38.933333 | 0.001672 |
def serialize(self, compact=False):
"""Serializes the object into a JWE token.
:param compact(boolean): if True generates the compact
representation, otherwise generates a standard JSON format.
:raises InvalidJWEOperation: if the object cannot serialized
with the compact repr... | [
"def",
"serialize",
"(",
"self",
",",
"compact",
"=",
"False",
")",
":",
"if",
"'ciphertext'",
"not",
"in",
"self",
".",
"objects",
":",
"raise",
"InvalidJWEOperation",
"(",
"\"No available ciphertext\"",
")",
"if",
"compact",
":",
"for",
"invalid",
"in",
"'... | 47.404762 | 0.000492 |
def _reset_state(self):
"""Reset state about the previous query in preparation for running another query"""
self._uuid = None
self._columns = None
self._rownumber = 0
# Internal helper state
self._state = self._STATE_NONE
self._data = None
self._columns = ... | [
"def",
"_reset_state",
"(",
"self",
")",
":",
"self",
".",
"_uuid",
"=",
"None",
"self",
".",
"_columns",
"=",
"None",
"self",
".",
"_rownumber",
"=",
"0",
"# Internal helper state",
"self",
".",
"_state",
"=",
"self",
".",
"_STATE_NONE",
"self",
".",
"_... | 35.111111 | 0.009259 |
def _get_exchanged_states(self, old_states, exchange_proposed,
exchange_proposed_n, sampled_replica_states,
sampled_replica_results):
"""Get list of TensorArrays holding exchanged states, and zeros."""
with tf.compat.v1.name_scope('get_exchanged_states'):
... | [
"def",
"_get_exchanged_states",
"(",
"self",
",",
"old_states",
",",
"exchange_proposed",
",",
"exchange_proposed_n",
",",
"sampled_replica_states",
",",
"sampled_replica_results",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"'get_excha... | 45.15 | 0.008941 |
def floordiv(x, y, context=None):
"""
Return the floor of ``x`` divided by ``y``.
The result is a ``BigFloat`` instance, rounded to the
context if necessary. Special cases match those of the
``div`` function.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr_fl... | [
"def",
"floordiv",
"(",
"x",
",",
"y",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr_floordiv",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
"BigFloat",
".",
"_implic... | 24.444444 | 0.002188 |
def move_to(self, x, y, pre_dl=None, post_dl=None):
"""Move mouse to (x, y)
**中文文档**
移动鼠标到 (x, y) 的坐标处。
"""
self.delay(pre_dl)
self.m.move(x, y)
self.delay(post_dl) | [
"def",
"move_to",
"(",
"self",
",",
"x",
",",
"y",
",",
"pre_dl",
"=",
"None",
",",
"post_dl",
"=",
"None",
")",
":",
"self",
".",
"delay",
"(",
"pre_dl",
")",
"self",
".",
"m",
".",
"move",
"(",
"x",
",",
"y",
")",
"self",
".",
"delay",
"(",... | 21.3 | 0.009009 |
def _calculate_unpack_filter(cls, includes=None, excludes=None, spec=None):
"""Take regex patterns and return a filter function.
:param list includes: List of include patterns to pass to _file_filter.
:param list excludes: List of exclude patterns to pass to _file_filter.
"""
include_patterns = cls... | [
"def",
"_calculate_unpack_filter",
"(",
"cls",
",",
"includes",
"=",
"None",
",",
"excludes",
"=",
"None",
",",
"spec",
"=",
"None",
")",
":",
"include_patterns",
"=",
"cls",
".",
"compile_patterns",
"(",
"includes",
"or",
"[",
"]",
",",
"field_name",
"=",... | 56 | 0.001033 |
def delete(self, bucket, key, extra_args=None, subscribers=None):
"""Delete an S3 object.
:type bucket: str
:param bucket: The name of the bucket.
:type key: str
:param key: The name of the S3 object to delete.
:type extra_args: dict
:param extra_args: Extra ar... | [
"def",
"delete",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"extra_args",
"=",
"None",
",",
"subscribers",
"=",
"None",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"{",
"}",
"if",
"subscribers",
"is",
"None",
":",
"subscribers... | 35.0625 | 0.001735 |
def do_macro(parser, token):
""" the function taking the parsed tag and returning
a DefineMacroNode object.
"""
try:
bits = token.split_contents()
tag_name, macro_name, arguments = bits[0], bits[1], bits[2:]
except IndexError:
raise template.TemplateSyntaxError(
"... | [
"def",
"do_macro",
"(",
"parser",
",",
"token",
")",
":",
"try",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"tag_name",
",",
"macro_name",
",",
"arguments",
"=",
"bits",
"[",
"0",
"]",
",",
"bits",
"[",
"1",
"]",
",",
"bits",
"[",
... | 34.540984 | 0.000461 |
def _list_records_internal(self, rtype=None, name=None, content=None, identifier=None):
"""
Filter and list DNS entries of domain zone on Easyname.
Easyname shows each entry in a HTML table row and each attribute on a
table column.
Args:
[rtype] (str): Filter by DNS rt... | [
"def",
"_list_records_internal",
"(",
"self",
",",
"rtype",
"=",
"None",
",",
"name",
"=",
"None",
",",
"content",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
":",
"name",
"=",
"self",
".",
"_full_name",
"(",
"name",
")",
"if",
"name",
"is",
"n... | 43.440678 | 0.001526 |
def assert_is_valid_key(key):
"""
Raise KeyError if a given config key violates any requirements.
The requirements are the following and can be individually deactivated
in ``sacred.SETTINGS.CONFIG_KEYS``:
* ENFORCE_MONGO_COMPATIBLE (default: True):
make sure the keys don't contain a '.' o... | [
"def",
"assert_is_valid_key",
"(",
"key",
")",
":",
"if",
"SETTINGS",
".",
"CONFIG",
".",
"ENFORCE_KEYS_MONGO_COMPATIBLE",
"and",
"(",
"isinstance",
"(",
"key",
",",
"basestring",
")",
"and",
"(",
"'.'",
"in",
"key",
"or",
"key",
"[",
"0",
"]",
"==",
"'$... | 41.90566 | 0.00044 |
def validate_utf8(alleged_utf8, error = None) :
"alleged_utf8 must be null-terminated bytes."
error, my_error = _get_error(error)
result = dbus.dbus_validate_utf8(alleged_utf8, error._dbobj) != 0
my_error.raise_if_set()
return \
result | [
"def",
"validate_utf8",
"(",
"alleged_utf8",
",",
"error",
"=",
"None",
")",
":",
"error",
",",
"my_error",
"=",
"_get_error",
"(",
"error",
")",
"result",
"=",
"dbus",
".",
"dbus_validate_utf8",
"(",
"alleged_utf8",
",",
"error",
".",
"_dbobj",
")",
"!=",... | 36.714286 | 0.015209 |
def verify_image_checksum(image_location, expected_checksum):
"""Verifies checksum (md5) of image file against the expected one.
This method generates the checksum of the image file on the fly and
verifies it against the expected checksum provided as argument.
:param image_location: location of image ... | [
"def",
"verify_image_checksum",
"(",
"image_location",
",",
"expected_checksum",
")",
":",
"try",
":",
"with",
"open",
"(",
"image_location",
",",
"'rb'",
")",
"as",
"fd",
":",
"actual_checksum",
"=",
"hash_file",
"(",
"fd",
")",
"except",
"IOError",
"as",
"... | 48.115385 | 0.000784 |
def fit(self, X):
""" Apply KMeans Clustering
X: dataset with feature vectors
"""
self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \
_kmeans(X, self.n_clusters, self.max_iter, self.n_trials, self.tol) | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"centers_",
",",
"self",
".",
"labels_",
",",
"self",
".",
"sse_arr_",
",",
"self",
".",
"n_iter_",
"=",
"_kmeans",
"(",
"X",
",",
"self",
".",
"n_clusters",
",",
"self",
".",
"max_iter",
... | 42.833333 | 0.015267 |
def get_url(self, environ):
"""Return the base URL."""
if self.override_url:
url = self.override_url
else:
# PEP333: wsgi.url_scheme, HTTP_HOST, SERVER_NAME, and SERVER_PORT
# can be used to reconstruct a request's complete URL
# Much of the follo... | [
"def",
"get_url",
"(",
"self",
",",
"environ",
")",
":",
"if",
"self",
".",
"override_url",
":",
"url",
"=",
"self",
".",
"override_url",
"else",
":",
"# PEP333: wsgi.url_scheme, HTTP_HOST, SERVER_NAME, and SERVER_PORT",
"# can be used to reconstruct a request's complete UR... | 43.909091 | 0.002026 |
def get_state(self, **kwargs):
"Return the minimal state for export."
state = {'x_cls':self.x.__class__, 'x_proc':self.x.processor,
'y_cls':self.y.__class__, 'y_proc':self.y.processor,
'tfms':self.tfms, 'tfm_y':self.tfm_y, 'tfmargs':self.tfmargs}
if hasattr(self... | [
"def",
"get_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"state",
"=",
"{",
"'x_cls'",
":",
"self",
".",
"x",
".",
"__class__",
",",
"'x_proc'",
":",
"self",
".",
"x",
".",
"processor",
",",
"'y_cls'",
":",
"self",
".",
"y",
".",
"__cl... | 58.875 | 0.025105 |
def plot_eq(fignum, DIblock, s):
"""
plots directions on eqarea projection
Parameters
__________
fignum : matplotlib figure number
DIblock : nested list of dec/inc pairs
s : specimen name
"""
# make the stereonet
plt.figure(num=fignum)
if len(DIblock) < 1:
return
# pl... | [
"def",
"plot_eq",
"(",
"fignum",
",",
"DIblock",
",",
"s",
")",
":",
"# make the stereonet",
"plt",
".",
"figure",
"(",
"num",
"=",
"fignum",
")",
"if",
"len",
"(",
"DIblock",
")",
"<",
"1",
":",
"return",
"# plt.clf()",
"if",
"not",
"isServer",
":",
... | 22.166667 | 0.001802 |
def maxCtxFont(font):
"""Calculate the usMaxContext value for an entire font."""
maxCtx = 0
for tag in ('GSUB', 'GPOS'):
if tag not in font:
continue
table = font[tag].table
if table.LookupList is None:
continue
for lookup in table.LookupList.Lookup:
... | [
"def",
"maxCtxFont",
"(",
"font",
")",
":",
"maxCtx",
"=",
"0",
"for",
"tag",
"in",
"(",
"'GSUB'",
",",
"'GPOS'",
")",
":",
"if",
"tag",
"not",
"in",
"font",
":",
"continue",
"table",
"=",
"font",
"[",
"tag",
"]",
".",
"table",
"if",
"table",
"."... | 31.357143 | 0.002212 |
def addMonitor(self, monitor):
"""
Subscribe to SingleLayer2DExperiment events.
@param monitor (SingleLayer2DExperimentMonitor)
An object that implements a set of monitor methods
@return (object)
An opaque object that can be used to refer to this monitor.
"""
token = self.nextMonitorT... | [
"def",
"addMonitor",
"(",
"self",
",",
"monitor",
")",
":",
"token",
"=",
"self",
".",
"nextMonitorToken",
"self",
".",
"nextMonitorToken",
"+=",
"1",
"self",
".",
"monitors",
"[",
"token",
"]",
"=",
"monitor",
"return",
"token"
] | 23.117647 | 0.002445 |
def value_from_object(self, obj):
"""Return value dumped to string."""
val = super(JSONField, self).value_from_object(obj)
return self.get_prep_value(val) | [
"def",
"value_from_object",
"(",
"self",
",",
"obj",
")",
":",
"val",
"=",
"super",
"(",
"JSONField",
",",
"self",
")",
".",
"value_from_object",
"(",
"obj",
")",
"return",
"self",
".",
"get_prep_value",
"(",
"val",
")"
] | 43.75 | 0.011236 |
def static(self, root, path, media_type=None, charset='UTF-8'):
"""Send content of a static file as response.
The path to the document root directory should be specified as
the root argument. This is very important to prevent directory
traversal attack. This method guarantees that only ... | [
"def",
"static",
"(",
"self",
",",
"root",
",",
"path",
",",
"media_type",
"=",
"None",
",",
"charset",
"=",
"'UTF-8'",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"''",
")",
... | 41.895833 | 0.000972 |
def stop(self):
"""Stop the progress bar."""
if self._progressing:
self._progressing = False
self._thread.join() | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_progressing",
":",
"self",
".",
"_progressing",
"=",
"False",
"self",
".",
"_thread",
".",
"join",
"(",
")"
] | 29.6 | 0.013158 |
def execute(self, requests, resp_generator, *args, **kwargs):
'''
Calls the resp_generator for all the requests in sequential order.
'''
return [resp_generator(request) for request in requests] | [
"def",
"execute",
"(",
"self",
",",
"requests",
",",
"resp_generator",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"resp_generator",
"(",
"request",
")",
"for",
"request",
"in",
"requests",
"]"
] | 45 | 0.008734 |
def add_ops(op_classes):
"""Decorator to add default implementation of ops."""
def f(cls):
for op_attr_name, op_class in op_classes.items():
ops = getattr(cls, '{name}_ops'.format(name=op_attr_name))
ops_map = getattr(cls, '{name}_op_nodes_map'.format(
name=op_att... | [
"def",
"add_ops",
"(",
"op_classes",
")",
":",
"def",
"f",
"(",
"cls",
")",
":",
"for",
"op_attr_name",
",",
"op_class",
"in",
"op_classes",
".",
"items",
"(",
")",
":",
"ops",
"=",
"getattr",
"(",
"cls",
",",
"'{name}_ops'",
".",
"format",
"(",
"nam... | 41.785714 | 0.001672 |
def new_stats_exporter(options=None, interval=None):
"""Get a stats exporter and running transport thread.
Create a new `StackdriverStatsExporter` with the given options and start
periodically exporting stats to stackdriver in the background.
Fall back to default auth if `options` is null. This will r... | [
"def",
"new_stats_exporter",
"(",
"options",
"=",
"None",
",",
"interval",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"_",
",",
"project_id",
"=",
"google",
".",
"auth",
".",
"default",
"(",
")",
"options",
"=",
"Options",
"(",
"project... | 37.852941 | 0.000758 |
def unpack(self, key, value):
"""Unpack and return value only if it is fresh."""
value, freshness = value
if not self.is_fresh(freshness):
raise KeyError('{} (stale)'.format(key))
return value | [
"def",
"unpack",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"value",
",",
"freshness",
"=",
"value",
"if",
"not",
"self",
".",
"is_fresh",
"(",
"freshness",
")",
":",
"raise",
"KeyError",
"(",
"'{} (stale)'",
".",
"format",
"(",
"key",
")",
")"... | 38.5 | 0.008475 |
def _confidence(matches, ext=None):
""" Rough confidence based on string length and file extension"""
results = []
for match in matches:
con = (0.8 if len(match.extension) > 9 else
float("0.{0}".format(len(match.extension))))
if ext == match.extension:
con = 0.9
... | [
"def",
"_confidence",
"(",
"matches",
",",
"ext",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"for",
"match",
"in",
"matches",
":",
"con",
"=",
"(",
"0.8",
"if",
"len",
"(",
"match",
".",
"extension",
")",
">",
"9",
"else",
"float",
"(",
"\"... | 42.909091 | 0.002075 |
def _einsum_helper(input_shapes, output_shape, mesh_impl):
"""Returns slicewise function and reduced mesh dimensions.
Assumes the output shape contains no new dimensions.
Args:
input_shapes: a list of Shapes
output_shape: a Shape
mesh_impl: a MeshImpl
Returns:
einsum_slice_fn: a function from ... | [
"def",
"_einsum_helper",
"(",
"input_shapes",
",",
"output_shape",
",",
"mesh_impl",
")",
":",
"input_shape_union",
"=",
"_shape_union",
"(",
"input_shapes",
")",
"total_num_dims",
"=",
"input_shape_union",
".",
"ndims",
"# list of input shapes that contain all dimensions."... | 40.65 | 0.00961 |
def render_field(parser, token):
"""
Render a form field using given attribute-value pairs
Takes form field as first argument and list of attribute-value pairs for
all other arguments. Attribute-value pairs should be in the form of
attribute=value or attribute="a value" for assignment and attribut... | [
"def",
"render_field",
"(",
"parser",
",",
"token",
")",
":",
"error_msg",
"=",
"'%r tag requires a form field followed by a list of attributes and values in the form attr=\"value\"'",
"%",
"token",
".",
"split_contents",
"(",
")",
"[",
"0",
"]",
"try",
":",
"bits",
"="... | 36.257143 | 0.001535 |
def shell_command():
"""Runs an interactive Python shell in the context of a given
Flask application. The application will populate the default
namespace of this shell according to its configuration.
This is useful for executing small snippets of management code
without having to manually configur... | [
"def",
"shell_command",
"(",
")",
":",
"from",
"flask",
".",
"globals",
"import",
"_app_ctx_stack",
"from",
"ptpython",
".",
"repl",
"import",
"embed",
"app",
"=",
"_app_ctx_stack",
".",
"top",
".",
"app",
"ctx",
"=",
"{",
"}",
"# Support the regular Python in... | 33.083333 | 0.001224 |
def extractall(path, to=None):
"""Extract archive file.
Parameters
----------
path: str
Path of archive file to be extracted.
to: str, optional
Directory to which the archive file will be extracted.
If None, it will be set to the parent directory of the archive file.
"""... | [
"def",
"extractall",
"(",
"path",
",",
"to",
"=",
"None",
")",
":",
"if",
"to",
"is",
"None",
":",
"to",
"=",
"osp",
".",
"dirname",
"(",
"path",
")",
"if",
"path",
".",
"endswith",
"(",
"'.zip'",
")",
":",
"opener",
",",
"mode",
"=",
"zipfile",
... | 28.97619 | 0.000795 |
def backprop(self, **args):
"""
Computes error and wed for back propagation of error.
"""
retval = self.compute_error(**args)
if self.learning:
self.compute_wed()
return retval | [
"def",
"backprop",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"retval",
"=",
"self",
".",
"compute_error",
"(",
"*",
"*",
"args",
")",
"if",
"self",
".",
"learning",
":",
"self",
".",
"compute_wed",
"(",
")",
"return",
"retval"
] | 28.625 | 0.008475 |
def PyplotHistogram():
"""
=============================================================
Demo of the histogram (hist) function with multiple data sets
=============================================================
Plot histogram with multiple sample sets and demonstrate:
* Use of legend wit... | [
"def",
"PyplotHistogram",
"(",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"np",
".",
"random",
".",
"seed",
"(",
"0",
")",
"n_bins",
"=",
"10",
"x",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"100... | 31.875 | 0.000634 |
def get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the given install requirement from the dependency cache.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequ... | [
"def",
"get_dependencies_from_cache",
"(",
"ireq",
")",
":",
"if",
"ireq",
".",
"editable",
"or",
"not",
"is_pinned_requirement",
"(",
"ireq",
")",
":",
"return",
"if",
"ireq",
"not",
"in",
"DEPENDENCY_CACHE",
":",
"return",
"cached",
"=",
"set",
"(",
"DEPEN... | 35.8 | 0.001554 |
def alias_name():
"""
Returns list of alias name by query paramaters
---
tags:
- Query functions
parameters:
- name: alias_name
in: query
type: string
required: false
description: 'Other names used to refer to a gene'
default: 'peptidase nexin-... | [
"def",
"alias_name",
"(",
")",
":",
"allowed_str_args",
"=",
"[",
"'alias_name'",
",",
"'hgnc_symbol'",
",",
"'hgnc_identifier'",
"]",
"allowed_int_args",
"=",
"[",
"'limit'",
",",
"]",
"allowed_bool_args",
"=",
"[",
"'is_previous_name'",
",",
"]",
"args",
"=",
... | 21.220339 | 0.000763 |
def create_model(modelfunc, fname='', listw=[], outfname='',
limit=int(3e6), min_pwlen=6, topk=10000, sep=r'\s+'):
""":modelfunc: is a function that takes a word and returns its
splits. for ngram model this function returns all the ngrams of a
word, for PCFG it will return splits of the pa... | [
"def",
"create_model",
"(",
"modelfunc",
",",
"fname",
"=",
"''",
",",
"listw",
"=",
"[",
"]",
",",
"outfname",
"=",
"''",
",",
"limit",
"=",
"int",
"(",
"3e6",
")",
",",
"min_pwlen",
"=",
"6",
",",
"topk",
"=",
"10000",
",",
"sep",
"=",
"r'\\s+'... | 36.175439 | 0.001416 |
def dataReceived(self, data):
"""Data received, react to it and respond if needed.
"""
# print "receiver dataReceived: <%s>" % data
msg = stomper.unpack_frame(data)
returned = self.sm.react(msg)
# print "receiver returned <%s>" % returned
... | [
"def",
"dataReceived",
"(",
"self",
",",
"data",
")",
":",
"# print \"receiver dataReceived: <%s>\" % data",
"msg",
"=",
"stomper",
".",
"unpack_frame",
"(",
"data",
")",
"returned",
"=",
"self",
".",
"sm",
".",
"react",
"(",
"msg",
")",
"# print \... | 28 | 0.013298 |
def find_best_rsquared(list_of_fits):
"""Return the best fit, based on rsquared"""
res = sorted(list_of_fits, key=lambda x: x.rsquared)
return res[-1] | [
"def",
"find_best_rsquared",
"(",
"list_of_fits",
")",
":",
"res",
"=",
"sorted",
"(",
"list_of_fits",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"rsquared",
")",
"return",
"res",
"[",
"-",
"1",
"]"
] | 42.75 | 0.011494 |
def get_compiler_flags():
"""Set fortran flags depending on the compiler."""
compiler = get_default_fcompiler()
if compiler == 'absoft':
flags = ['-m64', '-O3', '-YEXT_NAMES=LCS', '-YEXT_SFX=_',
'-fpic', '-speed_math=10']
elif compiler == 'gnu95':
flags = ['-m64', '-fPIC... | [
"def",
"get_compiler_flags",
"(",
")",
":",
"compiler",
"=",
"get_default_fcompiler",
"(",
")",
"if",
"compiler",
"==",
"'absoft'",
":",
"flags",
"=",
"[",
"'-m64'",
",",
"'-O3'",
",",
"'-YEXT_NAMES=LCS'",
",",
"'-YEXT_SFX=_'",
",",
"'-fpic'",
",",
"'-speed_ma... | 35.529412 | 0.001613 |
def __save_plots_of_the_current_page(self, section, page, output_path):
"""This method saves plots in the appropriate section folder.
As a consequence two plots cannot have the same name within the same section."""
for key in self.sections[section].pages[page].elements.keys():
... | [
"def",
"__save_plots_of_the_current_page",
"(",
"self",
",",
"section",
",",
"page",
",",
"output_path",
")",
":",
"for",
"key",
"in",
"self",
".",
"sections",
"[",
"section",
"]",
".",
"pages",
"[",
"page",
"]",
".",
"elements",
".",
"keys",
"(",
")",
... | 49.15 | 0.01996 |
def process_config(raw_path, cache_dir, cache_file, **kwargs):
"""
Read a build configuration and create it, storing the result in a build
cache.
Arguments
raw_path -- path to a build configuration
cache_dir -- the directory where cache should be written
cache_file -- The filename to write ... | [
"def",
"process_config",
"(",
"raw_path",
",",
"cache_dir",
",",
"cache_file",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"_create_cache",
"(",
"raw_path",
",",
"cache_dir",
",",
"cache_file",
")",
"for",
"modifier",
"in",
"_CONFIG_MODIFIERS",
":",
"m... | 36.26087 | 0.001168 |
def UpdateFlow(self,
client_id,
flow_id,
flow_obj=db.Database.unchanged,
flow_state=db.Database.unchanged,
client_crash_info=db.Database.unchanged,
pending_termination=db.Database.unchanged,
processing... | [
"def",
"UpdateFlow",
"(",
"self",
",",
"client_id",
",",
"flow_id",
",",
"flow_obj",
"=",
"db",
".",
"Database",
".",
"unchanged",
",",
"flow_state",
"=",
"db",
".",
"Database",
".",
"unchanged",
",",
"client_crash_info",
"=",
"db",
".",
"Database",
".",
... | 39.852941 | 0.014409 |
def save_point(self) -> str:
"""
Indexes the measured data with the current point as a key and saves the
current position once the 'Enter' key is pressed to the 'actual points'
vector.
"""
if self._current_mount is left:
msg = self.save_mount_offset()
... | [
"def",
"save_point",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_current_mount",
"is",
"left",
":",
"msg",
"=",
"self",
".",
"save_mount_offset",
"(",
")",
"self",
".",
"_current_mount",
"=",
"right",
"elif",
"self",
".",
"_current_mount",
"... | 41.5 | 0.002356 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.