text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _to_docstring(doc):
"""
format from Markdown to docstring
"""
def format_fn(line, status):
""" format function """
# swap < > to < >
line = re_to_tag.sub(r"<\1>", line)
if re_to_data.match(line):
line = re_to_data.sub(r"@\1 ", line)
stat... | [
"def",
"_to_docstring",
"(",
"doc",
")",
":",
"def",
"format_fn",
"(",
"line",
",",
"status",
")",
":",
"\"\"\" format function \"\"\"",
"# swap < > to < >",
"line",
"=",
"re_to_tag",
".",
"sub",
"(",
"r\"<\\1>\"",
",",
"line",
")",
"if",
"re_to_data",
"... | 31.931034 | 0.001048 |
def load(self, model):
"""Load pickled model."""
self.perceptron.weights, self.tagdict, self.classes, self.clusters = load_model(model)
self.perceptron.classes = self.classes | [
"def",
"load",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"perceptron",
".",
"weights",
",",
"self",
".",
"tagdict",
",",
"self",
".",
"classes",
",",
"self",
".",
"clusters",
"=",
"load_model",
"(",
"model",
")",
"self",
".",
"perceptron",
".... | 48.75 | 0.015152 |
def toStringProto(self, inObject, proto):
"""
Wraps the object in a list, and then defers to ``amp.AmpList``.
"""
return amp.AmpList.toStringProto(self, [inObject], proto) | [
"def",
"toStringProto",
"(",
"self",
",",
"inObject",
",",
"proto",
")",
":",
"return",
"amp",
".",
"AmpList",
".",
"toStringProto",
"(",
"self",
",",
"[",
"inObject",
"]",
",",
"proto",
")"
] | 39.8 | 0.009852 |
def _process_single_doc(self, single_doc):
"""
Make sure the provided value for --single is a path to an existing
.rst/.ipynb file, or a pandas object that can be imported.
For example, categorial.rst or pandas.DataFrame.head. For the latter,
return the corresponding file path
... | [
"def",
"_process_single_doc",
"(",
"self",
",",
"single_doc",
")",
":",
"base_name",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"single_doc",
")",
"if",
"extension",
"in",
"(",
"'.rst'",
",",
"'.ipynb'",
")",
":",
"if",
"os",
".",
... | 45.633333 | 0.001431 |
def report_validation(self, status):
"""Return run total value."""
# only one fail/pass count per profile
if status:
self.report['results']['validations']['pass'] += 1
else:
self.report['results']['validations']['fail'] += 1
if self.selected_profile.na... | [
"def",
"report_validation",
"(",
"self",
",",
"status",
")",
":",
"# only one fail/pass count per profile",
"if",
"status",
":",
"self",
".",
"report",
"[",
"'results'",
"]",
"[",
"'validations'",
"]",
"[",
"'pass'",
"]",
"+=",
"1",
"else",
":",
"self",
".",... | 50.777778 | 0.008602 |
async def filterindex(source, func):
"""Filter an asynchronous sequence using the index of the elements.
The given function is synchronous, takes the index as an argument,
and returns ``True`` if the corresponding should be forwarded,
``False`` otherwise.
"""
source = transform.enumerate.raw(so... | [
"async",
"def",
"filterindex",
"(",
"source",
",",
"func",
")",
":",
"source",
"=",
"transform",
".",
"enumerate",
".",
"raw",
"(",
"source",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"i",
",",
"i... | 37.833333 | 0.002151 |
def sparse(numRows, numCols, colPtrs, rowIndices, values):
"""
Create a SparseMatrix
"""
return SparseMatrix(numRows, numCols, colPtrs, rowIndices, values) | [
"def",
"sparse",
"(",
"numRows",
",",
"numCols",
",",
"colPtrs",
",",
"rowIndices",
",",
"values",
")",
":",
"return",
"SparseMatrix",
"(",
"numRows",
",",
"numCols",
",",
"colPtrs",
",",
"rowIndices",
",",
"values",
")"
] | 36.6 | 0.010695 |
def get_popular_clans(self, **params: keys):
"""Get a list of most queried clans
\*\*keys: Optional[list] = None
Filter which keys should be included in the
response
\*\*exclude: Optional[list] = None
Filter which keys should be excluded from the
... | [
"def",
"get_popular_clans",
"(",
"self",
",",
"*",
"*",
"params",
":",
"keys",
")",
":",
"url",
"=",
"self",
".",
"api",
".",
"POPULAR",
"+",
"'/clans'",
"return",
"self",
".",
"_get_model",
"(",
"url",
",",
"PartialClan",
",",
"*",
"*",
"params",
")... | 38.736842 | 0.015915 |
def get_cmdclass():
''' A ``cmdclass`` that works around a setuptools deficiency.
There is no need to build wheels when installing a package, however some
versions of setuptools seem to mandate this. This is a hacky workaround
that modifies the ``cmdclass`` returned by versioneer so that not having
... | [
"def",
"get_cmdclass",
"(",
")",
":",
"cmdclass",
"=",
"versioneer",
".",
"get_cmdclass",
"(",
")",
"try",
":",
"from",
"wheel",
".",
"bdist_wheel",
"import",
"bdist_wheel",
"except",
"ImportError",
":",
"# pip is not claiming for bdist_wheel when wheel is not installed... | 32.047619 | 0.001443 |
def _get_limit_check_id(self):
"""
Query currently-available TA checks, return the check ID and metadata
of the 'performance/Service Limits' check.
:returns: 2-tuple of Service Limits TA check ID (string),
metadata (list), or (None, None).
:rtype: tuple
"""
... | [
"def",
"_get_limit_check_id",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Querying Trusted Advisor checks\"",
")",
"try",
":",
"checks",
"=",
"self",
".",
"conn",
".",
"describe_trusted_advisor_checks",
"(",
"language",
"=",
"'en'",
")",
"[",
"'checks... | 37.216216 | 0.001415 |
def plot(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data, title=''):
"""
Plot distributed array
@param nxG number of global cells in x
@param nyG number of global cells in y
@param iBeg global starting index in x
@param iEnd global ending index in x
@param jBeg global starting index in y
@param j... | [
"def",
"plot",
"(",
"nxG",
",",
"nyG",
",",
"iBeg",
",",
"iEnd",
",",
"jBeg",
",",
"jEnd",
",",
"data",
",",
"title",
"=",
"''",
")",
":",
"sz",
"=",
"MPI",
".",
"COMM_WORLD",
".",
"Get_size",
"(",
")",
"rk",
"=",
"MPI",
".",
"COMM_WORLD",
".",... | 38.967742 | 0.000808 |
def rmdir(path):
"""
Recursively deletes a directory. Includes an error handler to retry with
different permissions on Windows. Otherwise, removing directories (eg.
cloned via git) can cause rmtree to throw a PermissionError exception
"""
logger.debug("DEBUG** Window rmdir sys.platform: {}".form... | [
"def",
"rmdir",
"(",
"path",
")",
":",
"logger",
".",
"debug",
"(",
"\"DEBUG** Window rmdir sys.platform: {}\"",
".",
"format",
"(",
"sys",
".",
"platform",
")",
")",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"onerror",
"=",
"_windows_rmdir_readonly"... | 37 | 0.002028 |
def invite(name, emails, perm):
"""Invite other users to access the virtual folder.
\b
NAME: Name of a virtual folder.
EMAIL: Emails to invite.
"""
with Session() as session:
try:
assert perm in ['rw', 'ro'], \
'Invalid permission: {}'.format(perm)
... | [
"def",
"invite",
"(",
"name",
",",
"emails",
",",
"perm",
")",
":",
"with",
"Session",
"(",
")",
"as",
"session",
":",
"try",
":",
"assert",
"perm",
"in",
"[",
"'rw'",
",",
"'ro'",
"]",
",",
"'Invalid permission: {}'",
".",
"format",
"(",
"perm",
")"... | 33.954545 | 0.001302 |
def reset(self):
"If your convolutional window is greater than 1 and you save previous xs, you must reset at the beginning of each new sequence."
for layer in self.layers: layer.reset()
if self.bidirectional:
for layer in self.layers_bwd: layer.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"layer",
".",
"reset",
"(",
")",
"if",
"self",
".",
"bidirectional",
":",
"for",
"layer",
"in",
"self",
".",
"layers_bwd",
":",
"layer",
".",
"reset",
"(",
")"... | 57.6 | 0.017123 |
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | [
"def",
"conv1x1",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"1",
",",
"stride",
"=",
"stride",
",",
"bias",
"=",
"False",
")"
] | 51.666667 | 0.012739 |
def set_sla(obj, metric, sub_metric, rules):
"""
Extract SLAs from a set of rules
"""
if not hasattr(obj, 'sla_map'):
return False
rules_list = rules.split()
for rule in rules_list:
if '<' in rule:
stat, threshold = rule.split('<')
sla = SLA(metric, sub_metric, stat, threshold, 'lt')
... | [
"def",
"set_sla",
"(",
"obj",
",",
"metric",
",",
"sub_metric",
",",
"rules",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'sla_map'",
")",
":",
"return",
"False",
"rules_list",
"=",
"rules",
".",
"split",
"(",
")",
"for",
"rule",
"in",
"rules... | 33.681818 | 0.018373 |
def from_storage(self, storage):
"""
To use a different storage
:param storage: flask_cloudy.Storage instance
"""
self._storage_obj = storage.get(self._data["name"])
self._storage_loaded = True | [
"def",
"from_storage",
"(",
"self",
",",
"storage",
")",
":",
"self",
".",
"_storage_obj",
"=",
"storage",
".",
"get",
"(",
"self",
".",
"_data",
"[",
"\"name\"",
"]",
")",
"self",
".",
"_storage_loaded",
"=",
"True"
] | 33.571429 | 0.008299 |
async def run_task(self) -> None:
'''Initialize the queue and spawn extra worker tasks if this if the
first task. Then wait for work items to enter the task queue, and
execute the `run()` method with the current work item.'''
while self.running:
try:
item = ... | [
"async",
"def",
"run_task",
"(",
"self",
")",
"->",
"None",
":",
"while",
"self",
".",
"running",
":",
"try",
":",
"item",
"=",
"self",
".",
"QUEUE",
".",
"get_nowait",
"(",
")",
"Log",
".",
"debug",
"(",
"'%s processing work item'",
",",
"self",
".",
... | 34 | 0.001845 |
def split_full_path(path):
"""Return pair of bucket without protocol and path
Arguments:
path - valid S3 path, such as s3://somebucket/events
>>> split_full_path('s3://mybucket/path-to-events')
('mybucket', 'path-to-events/')
>>> split_full_path('s3://mybucket')
('mybucket', None)
>>> ... | [
"def",
"split_full_path",
"(",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'s3://'",
")",
":",
"path",
"=",
"path",
"[",
"5",
":",
"]",
"elif",
"path",
".",
"startswith",
"(",
"'s3n://'",
")",
":",
"path",
"=",
"path",
"[",
"6",
":",
... | 31.5 | 0.001185 |
def run(exe, args, capturestd=False, env=None):
"""
Runs an executable with an array of arguments, optionally in the
specified environment.
Returns stdout and stderr
"""
command = [exe] + args
if env:
log.info("Executing [custom environment]: %s", " ".... | [
"def",
"run",
"(",
"exe",
",",
"args",
",",
"capturestd",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"command",
"=",
"[",
"exe",
"]",
"+",
"args",
"if",
"env",
":",
"log",
".",
"info",
"(",
"\"Executing [custom environment]: %s\"",
",",
"\" \"",
... | 35.456522 | 0.001193 |
def cycle(length, width=4):
"""
Generate a de Bruijn sequence of a given length (and width). A de Bruijn
sequence is a set of varying repetitions where each sequence of *n*
characters is unique within the sequence. This type of sequence can be
used to easily find the offset to the return pointer whe... | [
"def",
"cycle",
"(",
"length",
",",
"width",
"=",
"4",
")",
":",
"iter",
"=",
"deBruijn",
"(",
"width",
",",
"26",
")",
"return",
"''",
".",
"join",
"(",
"[",
"chr",
"(",
"ord",
"(",
"'A'",
")",
"+",
"next",
"(",
"iter",
")",
")",
"for",
"i",... | 33.782609 | 0.001252 |
def memoryit(group_by='lineno', limit=10):
"""
追踪函数内存消耗情况
:param group_by: 统计分组,有 'filename', 'lineno', 'traceback' 可选
:param limit: 限制输出行数
"""
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
tracemalloc.start()
_start = tracemalloc.take_snaps... | [
"def",
"memoryit",
"(",
"group_by",
"=",
"'lineno'",
",",
"limit",
"=",
"10",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tracemalloc",
"... | 30.210526 | 0.001689 |
def msjd(theta):
"""Mean squared jumping distance.
"""
s = 0.
for p in theta.dtype.names:
s += np.sum(np.diff(theta[p], axis=0) ** 2)
return s | [
"def",
"msjd",
"(",
"theta",
")",
":",
"s",
"=",
"0.",
"for",
"p",
"in",
"theta",
".",
"dtype",
".",
"names",
":",
"s",
"+=",
"np",
".",
"sum",
"(",
"np",
".",
"diff",
"(",
"theta",
"[",
"p",
"]",
",",
"axis",
"=",
"0",
")",
"**",
"2",
")... | 23.571429 | 0.011696 |
def write_keys(self, records_in, clean=True):
"""
Write the keywords to the header.
parameters
----------
records: FITSHDR or list or dict
Can be one of these:
- FITSHDR object
- list of dictionaries containing 'name','value' and optio... | [
"def",
"write_keys",
"(",
"self",
",",
"records_in",
",",
"clean",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"records_in",
",",
"FITSHDR",
")",
":",
"hdr",
"=",
"records_in",
"else",
":",
"hdr",
"=",
"FITSHDR",
"(",
"records_in",
")",
"if",
"clea... | 34.319149 | 0.001206 |
def force_extrapolation(self):
"""Force the underlying model to extrapolate.
An example where this is useful: You create a source spectrum
with non-default extrapolation behavior and you wish to force
the underlying empirical model to extrapolate based on nearest point.
.. note... | [
"def",
"force_extrapolation",
"(",
"self",
")",
":",
"# We use _model here in case the spectrum is redshifted.",
"if",
"isinstance",
"(",
"self",
".",
"_model",
",",
"Empirical1D",
")",
":",
"self",
".",
"_model",
".",
"fill_value",
"=",
"np",
".",
"nan",
"is_forc... | 31.964286 | 0.002169 |
def check_validity(self, checks=None, report=True):
""" Runs a Symbol's validity checks.
Parameters
----------
checks : str, [str,], optional
Only run certain checks.
report : bool, optional
If set to False, the method will return only t... | [
"def",
"check_validity",
"(",
"self",
",",
"checks",
"=",
"None",
",",
"report",
"=",
"True",
")",
":",
"if",
"report",
":",
"reportpoints",
"=",
"[",
"]",
"allchecks",
"=",
"[",
"]",
"checks_specified",
"=",
"False",
"if",
"isinstance",
"(",
"checks",
... | 32.981132 | 0.01 |
def geigh(H,S):
"Solve the generalized eigensystem Hc = ESc"
A = cholorth(S)
E,U = np.linalg.eigh(simx(H,A))
return E,np.dot(A,U) | [
"def",
"geigh",
"(",
"H",
",",
"S",
")",
":",
"A",
"=",
"cholorth",
"(",
"S",
")",
"E",
",",
"U",
"=",
"np",
".",
"linalg",
".",
"eigh",
"(",
"simx",
"(",
"H",
",",
"A",
")",
")",
"return",
"E",
",",
"np",
".",
"dot",
"(",
"A",
",",
"U"... | 28.2 | 0.041379 |
def to_pybel(self):
"""
Produce a Pybel Molecule object.
It is based on the capabilities of OpenBabel through Pybel. The present
object must have at least `atomcoords`, `atomnos`, `charge` and `mult`
defined.
Returns
-------
`pybel.Molecule`
Exa... | [
"def",
"to_pybel",
"(",
"self",
")",
":",
"# TODO: This only exports last geometry by default.",
"obmol",
"=",
"_makeopenbabel",
"(",
"self",
".",
"atomcoords",
",",
"self",
".",
"atomnos",
",",
"self",
".",
"charge",
",",
"self",
".",
"mult",
")",
"title",
"=... | 31.945946 | 0.001642 |
def app(environ, start_response):
"""The WSGI Application Server.
Arguments:
environ {dict} -- The WSGI environ dictionary
start_response {WSGI callable}
Returns:
WSGI Response
"""
from wsgi import container
"""Add Environ To Service Container
Add the environ to th... | [
"def",
"app",
"(",
"environ",
",",
"start_response",
")",
":",
"from",
"wsgi",
"import",
"container",
"\"\"\"Add Environ To Service Container\n Add the environ to the service container. The environ is generated by the\n the WSGI server above and used by a service provider to manipulate... | 30.782609 | 0.000684 |
def on_start_at_login_toggled(self, chk):
"""Changes the activity of start_at_login in dconf
"""
self.settings.general.set_boolean('start-at-login', chk.get_active())
refresh_user_start(self.settings) | [
"def",
"on_start_at_login_toggled",
"(",
"self",
",",
"chk",
")",
":",
"self",
".",
"settings",
".",
"general",
".",
"set_boolean",
"(",
"'start-at-login'",
",",
"chk",
".",
"get_active",
"(",
")",
")",
"refresh_user_start",
"(",
"self",
".",
"settings",
")"... | 45.6 | 0.008621 |
def weather(query):
"""weather(query) -- use Name Entity Recogniser (nltk-stanford-ner), to
determine location entity in query and fetch weather info for that location
(using yahoo apis).
"""
print 'Identifying the location . . .'
try:
response = unirest.post("https://textanalysis.p.mashape.com/nltk-stanford-... | [
"def",
"weather",
"(",
"query",
")",
":",
"print",
"'Identifying the location . . .'",
"try",
":",
"response",
"=",
"unirest",
".",
"post",
"(",
"\"https://textanalysis.p.mashape.com/nltk-stanford-ner\"",
",",
"headers",
"=",
"{",
"\"X-Mashape-Key\"",
":",
"\"E7WffsNDbN... | 35.181818 | 0.039598 |
def median_low(data):
"""Return the low median of numeric data.
When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median f... | [
"def",
"median_low",
"(",
"data",
")",
":",
"data",
"=",
"sorted",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"==",
"0",
":",
"raise",
"StatisticsError",
"(",
"\"no median for empty data\"",
")",
"if",
"n",
"%",
"2",
"==",
"1",
... | 29.357143 | 0.002358 |
def add_delta_deltas(filterbanks, name=None):
"""Compute time first and second-order derivative channels.
Args:
filterbanks: float32 tensor with shape [batch_size, len, num_bins, 1]
name: scope name
Returns:
float32 tensor with shape [batch_size, len, num_bins, 3]
"""
delta_filter = np.array([2,... | [
"def",
"add_delta_deltas",
"(",
"filterbanks",
",",
"name",
"=",
"None",
")",
":",
"delta_filter",
"=",
"np",
".",
"array",
"(",
"[",
"2",
",",
"1",
",",
"0",
",",
"-",
"1",
",",
"-",
"2",
"]",
")",
"delta_delta_filter",
"=",
"scipy",
".",
"signal"... | 32.8 | 0.011848 |
def tar_archive(context):
"""Archive specified path to a tar archive.
Args:
context: dictionary-like. context is mandatory.
context['tar']['archive'] must exist. It's a dictionary.
keys are the paths to archive.
values are the destination output paths.
Example:
... | [
"def",
"tar_archive",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"start\"",
")",
"mode",
"=",
"get_file_mode_for_writing",
"(",
"context",
")",
"for",
"item",
"in",
"context",
"[",
"'tar'",
"]",
"[",
"'archive'",
"]",
":",
"# value is the desti... | 34.444444 | 0.000784 |
def hash_to_unsigned(data):
"""If ``data`` is a string or unicode string, return an unsigned 4-byte int
hash of it. If ``data`` is already an int that fits those parameters,
return it verbatim.
If ``data`` is an int outside that range, behavior is undefined at the
moment. We rely on the ``PositiveI... | [
"def",
"hash_to_unsigned",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"string_types",
")",
":",
"# Return a CRC32 value identical across Python versions and platforms",
"# by stripping the sign bit as on",
"# http://docs.python.org/library/zlib.html.",
"return",
... | 47.821429 | 0.000732 |
def translate_cds(seq, full_codons=True, ter_symbol="*"):
"""translate a DNA or RNA sequence into a single-letter amino acid sequence
using the standard translation table
If full_codons is True, a sequence whose length isn't a multiple of three
generates a ValueError; else an 'X' will be added as the l... | [
"def",
"translate_cds",
"(",
"seq",
",",
"full_codons",
"=",
"True",
",",
"ter_symbol",
"=",
"\"*\"",
")",
":",
"if",
"seq",
"is",
"None",
":",
"return",
"None",
"if",
"len",
"(",
"seq",
")",
"==",
"0",
":",
"return",
"\"\"",
"if",
"full_codons",
"an... | 27.05 | 0.001189 |
def _main():
"""
Some demo.
"""
if sys.argv[1:] == ["test"]:
for k, v in sorted(globals().items()):
if not k.startswith("test_"):
continue
print("running: %s()" % k)
v()
print("ok.")
sys.exit()
elif sys.argv[1:] == ["debug... | [
"def",
"_main",
"(",
")",
":",
"if",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"==",
"[",
"\"test\"",
"]",
":",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"globals",
"(",
")",
".",
"items",
"(",
")",
")",
":",
"if",
"not",
"k",
".",
"startswi... | 24.188235 | 0.000467 |
def read_init(key):
"""Parse the package __init__ file to find a variable so that it's not
in multiple places.
"""
filename = os.path.join("traces", "__init__.py")
result = None
with open(filename) as stream:
for line in stream:
if key in line:
result = line.... | [
"def",
"read_init",
"(",
"key",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"traces\"",
",",
"\"__init__.py\"",
")",
"result",
"=",
"None",
"with",
"open",
"(",
"filename",
")",
"as",
"stream",
":",
"for",
"line",
"in",
"stream",
... | 29.705882 | 0.001919 |
def set(self, name, arg=UNSET):
"""Modify the instruction in-place.
Replace name and arg attributes. Don't modify lineno.
"""
self._set(name, arg, self._lineno) | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"arg",
"=",
"UNSET",
")",
":",
"self",
".",
"_set",
"(",
"name",
",",
"arg",
",",
"self",
".",
"_lineno",
")"
] | 31.333333 | 0.010363 |
def undo(self):
"""
Undo the last command by adding its inverse action to the stack.
This method automatically takes care of applying the correct
inverse action when it is called consecutively (ie. without a
calling ``push`` in between).
The ``qtesigSavedState`` signal ... | [
"def",
"undo",
"(",
"self",
")",
":",
"# If it is the first call to this method after a ``push`` then",
"# reset ``qteIndex`` to the last element, otherwise just",
"# decrease it.",
"if",
"not",
"self",
".",
"_wasUndo",
":",
"self",
".",
"_qteIndex",
"=",
"len",
"(",
"self"... | 37.072464 | 0.000762 |
def postponed_to(self):
"""
Date that the event was postponed to (in the local time zone).
"""
toDate = getLocalDate(self.date, self.time_from, self.tz)
return dateFormat(toDate) | [
"def",
"postponed_to",
"(",
"self",
")",
":",
"toDate",
"=",
"getLocalDate",
"(",
"self",
".",
"date",
",",
"self",
".",
"time_from",
",",
"self",
".",
"tz",
")",
"return",
"dateFormat",
"(",
"toDate",
")"
] | 35.5 | 0.009174 |
def match_list(query_list, string):
"""Return True if all words in a word list are in the string.
:param query_list: list of words to match
:param string: the word or words to be matched against
"""
# Get rid of 'the' word to ease string matching
match = False
index = 0
string = ' '.joi... | [
"def",
"match_list",
"(",
"query_list",
",",
"string",
")",
":",
"# Get rid of 'the' word to ease string matching",
"match",
"=",
"False",
"index",
"=",
"0",
"string",
"=",
"' '",
".",
"join",
"(",
"filter_stopwords",
"(",
"string",
")",
")",
"if",
"not",
"isi... | 27.083333 | 0.001486 |
def _colorize_single_line(line, regexp, color_def):
"""Print single line to console with ability to colorize parts of it."""
match = regexp.match(line)
groupdict = match.groupdict()
groups = match.groups()
if not groupdict:
# no named groups, just colorize whole line
color = c... | [
"def",
"_colorize_single_line",
"(",
"line",
",",
"regexp",
",",
"color_def",
")",
":",
"match",
"=",
"regexp",
".",
"match",
"(",
"line",
")",
"groupdict",
"=",
"match",
".",
"groupdict",
"(",
")",
"groups",
"=",
"match",
".",
"groups",
"(",
")",
"if"... | 36.956522 | 0.001147 |
def unfollow(user, obj, send_action=False, flag=''):
"""
Removes a "follow" relationship.
Set ``send_action`` to ``True`` (``False is default) to also send a
``<user> stopped following <object>`` action signal.
Pass a string value to ``flag`` to determine which type of "follow" relationship you wa... | [
"def",
"unfollow",
"(",
"user",
",",
"obj",
",",
"send_action",
"=",
"False",
",",
"flag",
"=",
"''",
")",
":",
"check",
"(",
"obj",
")",
"qs",
"=",
"apps",
".",
"get_model",
"(",
"'actstream'",
",",
"'follow'",
")",
".",
"objects",
".",
"filter",
... | 30.172414 | 0.002215 |
def find_debugged_frame(frame):
"""Find the first frame that is a debugged frame. We do this
Generally we want traceback information without polluting it with
debugger frames. We can tell these because those are frames on the
top which don't have f_trace set. So we'll look back from the top
to find ... | [
"def",
"find_debugged_frame",
"(",
"frame",
")",
":",
"f_prev",
"=",
"f",
"=",
"frame",
"while",
"f",
"is",
"not",
"None",
"and",
"f",
".",
"f_trace",
"is",
"None",
":",
"f_prev",
"=",
"f",
"f",
"=",
"f",
".",
"f_back",
"pass",
"if",
"f_prev",
":",... | 31.73913 | 0.00133 |
def extract_points(self, pid, points):
"""Extract values at certain points in the grid from a given parameter
set. Cells are selected by interpolating the centroids of the cells
towards the line using a "nearest" scheme.
Note that data is only returned for the points provided. If you wa... | [
"def",
"extract_points",
"(",
"self",
",",
"pid",
",",
"points",
")",
":",
"xy",
"=",
"self",
".",
"grid",
".",
"get_element_centroids",
"(",
")",
"data",
"=",
"self",
".",
"parsets",
"[",
"pid",
"]",
"iobj",
"=",
"spi",
".",
"NearestNDInterpolator",
"... | 33.888889 | 0.002125 |
def readBlock(self, length, pool_id, block_id, generation_stamp, offset, block_token, check_crc):
'''Send a read request to given block. If we receive a successful response,
we start reading packets.
Send read request:
+-------------------------------------------------------------------... | [
"def",
"readBlock",
"(",
"self",
",",
"length",
",",
"pool_id",
",",
"block_id",
",",
"generation_stamp",
",",
"offset",
",",
"block_token",
",",
"check_crc",
")",
":",
"log",
".",
"debug",
"(",
"\"%s sending readBlock request\"",
"%",
"self",
")",
"# Send ver... | 49.79021 | 0.002341 |
def just_log(*texts, sep = ""):
"""Log a text without adding the current time."""
if config.silent:
return
text = _color_sep + "default" + _color_sep2 + sep.join(texts)
array = text.split(_color_sep)
for part in array:
parts = part.split(_color_sep2, 1)
if len(parts) != 2 or not parts[1]:
continue
if... | [
"def",
"just_log",
"(",
"*",
"texts",
",",
"sep",
"=",
"\"\"",
")",
":",
"if",
"config",
".",
"silent",
":",
"return",
"text",
"=",
"_color_sep",
"+",
"\"default\"",
"+",
"_color_sep2",
"+",
"sep",
".",
"join",
"(",
"texts",
")",
"array",
"=",
"text"... | 22.363636 | 0.038986 |
def read_struct(self, struct_class):
"""Parse and return a structure from the current buffer offset."""
struct = struct_class.unpack_from(bytearray_to_buff(self._data), self._offset)
self.skip(struct_class.size)
return struct | [
"def",
"read_struct",
"(",
"self",
",",
"struct_class",
")",
":",
"struct",
"=",
"struct_class",
".",
"unpack_from",
"(",
"bytearray_to_buff",
"(",
"self",
".",
"_data",
")",
",",
"self",
".",
"_offset",
")",
"self",
".",
"skip",
"(",
"struct_class",
".",
... | 50.6 | 0.011673 |
def labeled_accumulate(sequence, keygetter=operator.itemgetter(0), valuegetter=operator.itemgetter(1), accumulator=operator.add):
"""
Accumulates input elements according to accumulate(), but keeping certain data (per element, from the original
sequence/iterable) in the target elements, like behaving as k... | [
"def",
"labeled_accumulate",
"(",
"sequence",
",",
"keygetter",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
",",
"valuegetter",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"accumulator",
"=",
"operator",
".",
"add",
")",
":",
"return",
... | 50.181818 | 0.008897 |
def init_logging(verbose=False, format='%(asctime)s %(message)s'):
""" Common utility for setting up logging in PyCBC.
Installs a signal handler such that verbosity can be activated at
run-time by sending a SIGUSR1 to the process.
"""
def sig_handler(signum, frame):
logger = logging.getLogg... | [
"def",
"init_logging",
"(",
"verbose",
"=",
"False",
",",
"format",
"=",
"'%(asctime)s %(message)s'",
")",
":",
"def",
"sig_handler",
"(",
"signum",
",",
"frame",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"log_level",
"=",
"logger",
"... | 34.28 | 0.001135 |
def _get_input_data(self, var, start_date, end_date):
"""Get the data for a single variable over the desired date range."""
logging.info(self._print_verbose("Getting input data:", var))
if isinstance(var, (float, int)):
return var
else:
cond_pfull = ((not hasattr... | [
"def",
"_get_input_data",
"(",
"self",
",",
"var",
",",
"start_date",
",",
"end_date",
")",
":",
"logging",
".",
"info",
"(",
"self",
".",
"_print_verbose",
"(",
"\"Getting input data:\"",
",",
"var",
")",
")",
"if",
"isinstance",
"(",
"var",
",",
"(",
"... | 47.030303 | 0.001263 |
def import_obj(cls, dashboard_to_import, import_time=None):
"""Imports the dashboard from the object to the database.
Once dashboard is imported, json_metadata field is extended and stores
remote_id and import_time. It helps to decide if the dashboard has to
be overridden or just cop... | [
"def",
"import_obj",
"(",
"cls",
",",
"dashboard_to_import",
",",
"import_time",
"=",
"None",
")",
":",
"def",
"alter_positions",
"(",
"dashboard",
",",
"old_to_new_slc_id_dict",
")",
":",
"\"\"\" Updates slice_ids in the position json.\n\n Sample position_json dat... | 45.804688 | 0.000501 |
def _summarize_accessible_fields(field_descriptions, width=40,
section_title='Accessible fields'):
"""
Create a summary string for the accessible fields in a model. Unlike
`_toolkit_repr_print`, this function does not look up the values of the
fields, it just formats the... | [
"def",
"_summarize_accessible_fields",
"(",
"field_descriptions",
",",
"width",
"=",
"40",
",",
"section_title",
"=",
"'Accessible fields'",
")",
":",
"key_str",
"=",
"\"{:<{}}: {}\"",
"items",
"=",
"[",
"]",
"items",
".",
"append",
"(",
"section_title",
")",
"i... | 31 | 0.00092 |
def import_modules(modules, safe=True):
'''Safely import a list of *modules*
'''
all = []
for mname in modules:
if mname.endswith('.*'):
to_load = expand_star(mname)
else:
to_load = [mname]
for module in to_load:
try:
all.append... | [
"def",
"import_modules",
"(",
"modules",
",",
"safe",
"=",
"True",
")",
":",
"all",
"=",
"[",
"]",
"for",
"mname",
"in",
"modules",
":",
"if",
"mname",
".",
"endswith",
"(",
"'.*'",
")",
":",
"to_load",
"=",
"expand_star",
"(",
"mname",
")",
"else",
... | 26.875 | 0.002247 |
def get_file_hexdigest(filename, blocksize=1024*1024*10):
'''Get a hex digest of a file.'''
if hashlib.__name__ == 'hashlib':
m = hashlib.md5() # new - 'hashlib' module
else:
m = hashlib.new() # old - 'md5' module - remove once py2.4 gone
fd = open(filename, 'r')
while ... | [
"def",
"get_file_hexdigest",
"(",
"filename",
",",
"blocksize",
"=",
"1024",
"*",
"1024",
"*",
"10",
")",
":",
"if",
"hashlib",
".",
"__name__",
"==",
"'hashlib'",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"# new - 'hashlib' module",
"else",
":",
"... | 26.588235 | 0.002137 |
def load(cls, model, opt, meta, flag_gpu=None):
'''Loads in model as a class instance with with the specified
model and optimizer states.
Parameters
----------
model : str
Path to the model state file.
opt : str
Path to the optimizer state file... | [
"def",
"load",
"(",
"cls",
",",
"model",
",",
"opt",
",",
"meta",
",",
"flag_gpu",
"=",
"None",
")",
":",
"mess",
"=",
"\"Model file {0} does not exist. Please check the file path.\"",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"model",
")",
",",
"mess... | 31.461538 | 0.001581 |
def code_to_sjis(code):
u"""Convert character code(hex) to string"""
if code and isinstance(code, basestring):
clean_code = code.replace('>', '')
if clean_code:
_code_to_sjis_char = lambda c: ''.join([chr(int("%c%c"%(a, b), 16)) for a, b in izip(c[0::2], c[1::2])])
return... | [
"def",
"code_to_sjis",
"(",
"code",
")",
":",
"if",
"code",
"and",
"isinstance",
"(",
"code",
",",
"basestring",
")",
":",
"clean_code",
"=",
"code",
".",
"replace",
"(",
"'>'",
",",
"''",
")",
"if",
"clean_code",
":",
"_code_to_sjis_char",
"=",
"lambda"... | 52.75 | 0.011655 |
def disable(name, no_block=False, root=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
contro... | [
"def",
"disable",
"(",
"name",
",",
"no_block",
"=",
"False",
",",
"root",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"_check_for_unit_changes",
"(",
"name",
")",
"if",
"name",
"in",
"_get_sysv_services",
"(",
"root",
... | 42.44898 | 0.00141 |
def _proc_uri(self, request, result):
"""
Process the URI rules for the request. Both the desired API
version and desired content type can be determined from those
rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the... | [
"def",
"_proc_uri",
"(",
"self",
",",
"request",
",",
"result",
")",
":",
"if",
"result",
":",
"# Result has already been fully determined",
"return",
"# First, determine the version based on the URI prefix",
"for",
"prefix",
",",
"version",
"in",
"self",
".",
"uris",
... | 36.828571 | 0.001512 |
def trust(self, scope, vk):
"""Start trusting a particular key for given scope."""
self.data['verifiers'].append({'scope': scope, 'vk': vk})
return self | [
"def",
"trust",
"(",
"self",
",",
"scope",
",",
"vk",
")",
":",
"self",
".",
"data",
"[",
"'verifiers'",
"]",
".",
"append",
"(",
"{",
"'scope'",
":",
"scope",
",",
"'vk'",
":",
"vk",
"}",
")",
"return",
"self"
] | 43.25 | 0.011364 |
def _extrac_qtl(peak, block, headers):
""" Given a row containing the peak of the QTL and all the rows of
the linkage group of the said QTL (splitted per trait), determine
the QTL interval and find the start and stop marker of the said
interval.
The interval is a LOD 2 interval.
The approach is ... | [
"def",
"_extrac_qtl",
"(",
"peak",
",",
"block",
",",
"headers",
")",
":",
"qtls",
"=",
"[",
"]",
"if",
"not",
"peak",
":",
"return",
"qtls",
"threshold",
"=",
"2",
"for",
"trait",
"in",
"peak",
":",
"blockcnt",
"=",
"headers",
".",
"index",
"(",
"... | 34.75 | 0.000466 |
def bovy_dens2d(X,**kwargs):
"""
NAME:
bovy_dens2d
PURPOSE:
plot a 2d density with optional contours
INPUT:
first argument is the density
matplotlib.pyplot.imshow keywords (see http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.imshow)
xlab... | [
"def",
"bovy_dens2d",
"(",
"X",
",",
"*",
"*",
"kwargs",
")",
":",
"overplot",
"=",
"kwargs",
".",
"pop",
"(",
"'overplot'",
",",
"False",
")",
"gcf",
"=",
"kwargs",
".",
"pop",
"(",
"'gcf'",
",",
"False",
")",
"if",
"not",
"overplot",
"and",
"not"... | 33.973568 | 0.019274 |
def set_policy_alert_threshold(self, policy_ids, alert_threshold):
"""Set the alert theshold for the given policies."""
for policy_id in policy_ids:
self.logger.debug('Setting alert threshold for policy {0} to {1}'.format(policy_id, alert_threshold))
result = self.zap.ascan.set_p... | [
"def",
"set_policy_alert_threshold",
"(",
"self",
",",
"policy_ids",
",",
"alert_threshold",
")",
":",
"for",
"policy_id",
"in",
"policy_ids",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Setting alert threshold for policy {0} to {1}'",
".",
"format",
"(",
"poli... | 73.142857 | 0.009653 |
def find_tree_root(tree, key):
"""Find a root in a tree by it's key
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:param str key: key of the root node to find
:returns: a root node if found else None
:rtype: mixed
"""
result = ... | [
"def",
"find_tree_root",
"(",
"tree",
",",
"key",
")",
":",
"result",
"=",
"[",
"p",
"for",
"p",
"in",
"tree",
".",
"keys",
"(",
")",
"if",
"p",
".",
"key",
"==",
"key",
"]",
"assert",
"len",
"(",
"result",
")",
"in",
"[",
"0",
",",
"1",
"]",... | 33.230769 | 0.002252 |
def save(self):
"""The save function for a breeding cage has to automatic over-rides, Active and the Cage for the Breeder.
In the case of Active, if an End field is specified, then the Active field is set to False.
In the case of Cage, if a Cage is provided, and animals are specified un... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"End",
":",
"self",
".",
"Active",
"=",
"False",
"#if self.Cage:",
"# if self.Females: ",
"# for female_breeder in self.Females:",
"# female_breeder.Cage = self.Cage",
"# fe... | 55.823529 | 0.00829 |
def main_real(usercode, netobj, options):
'''
Entrypoint function for non-test ("real") mode. At this point
we assume that we are running as root and have pcap module.
'''
usercode_entry_point = import_or_die(usercode, ('main', 'switchy_main'))
if options.dryrun:
log_info("Imported your... | [
"def",
"main_real",
"(",
"usercode",
",",
"netobj",
",",
"options",
")",
":",
"usercode_entry_point",
"=",
"import_or_die",
"(",
"usercode",
",",
"(",
"'main'",
",",
"'switchy_main'",
")",
")",
"if",
"options",
".",
"dryrun",
":",
"log_info",
"(",
"\"Importe... | 31.153846 | 0.002394 |
def lastmod(self, tag):
"""Return the last modification of the entry."""
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(tags=tag).only('modification_date')
return lastitems[0].modification_date | [
"def",
"lastmod",
"(",
"self",
",",
"tag",
")",
":",
"lastitems",
"=",
"EntryModel",
".",
"objects",
".",
"published",
"(",
")",
".",
"order_by",
"(",
"'-modification_date'",
")",
".",
"filter",
"(",
"tags",
"=",
"tag",
")",
".",
"only",
"(",
"'modific... | 62 | 0.011952 |
async def auth_crammd5(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
CRAM-MD5 auth uses the password as a shared secret to MD5 the server's
response.
Example::
250 AUTH CRAM-MD5
auth cram-md5
... | [
"async",
"def",
"auth_crammd5",
"(",
"self",
",",
"username",
":",
"str",
",",
"password",
":",
"str",
",",
"timeout",
":",
"DefaultNumType",
"=",
"_default",
")",
"->",
"SMTPResponse",
":",
"async",
"with",
"self",
".",
"_command_lock",
":",
"initial_respon... | 33.615385 | 0.002224 |
def from_pb(cls, instance_pb, client):
"""Creates an instance from a protobuf.
:type instance_pb:
:class:`google.spanner.v2.spanner_instance_admin_pb2.Instance`
:param instance_pb: A instance protobuf object.
:type client: :class:`~google.cloud.spanner_v1.client.Client`
... | [
"def",
"from_pb",
"(",
"cls",
",",
"instance_pb",
",",
"client",
")",
":",
"match",
"=",
"_INSTANCE_NAME_RE",
".",
"match",
"(",
"instance_pb",
".",
"name",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Instance protobuf name was not in... | 40.151515 | 0.002211 |
def _do_resumable_upload(self, stream, metadata, num_retries):
"""Perform a resumable upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type num_retries: in... | [
"def",
"_do_resumable_upload",
"(",
"self",
",",
"stream",
",",
"metadata",
",",
"num_retries",
")",
":",
"upload",
",",
"transport",
"=",
"self",
".",
"_initiate_resumable_upload",
"(",
"stream",
",",
"metadata",
",",
"num_retries",
")",
"while",
"not",
"uplo... | 33.8 | 0.002301 |
def move_backward(self, seconds=None):
"""Move robot backward."""
self._move(speed=-SPEED_MAX, steering=0, seconds=seconds) | [
"def",
"move_backward",
"(",
"self",
",",
"seconds",
"=",
"None",
")",
":",
"self",
".",
"_move",
"(",
"speed",
"=",
"-",
"SPEED_MAX",
",",
"steering",
"=",
"0",
",",
"seconds",
"=",
"seconds",
")"
] | 45.666667 | 0.014388 |
def load_data_table(file,
index_col,
show_progress=False):
""" Load data table from zip file provided by Quandl.
"""
with ZipFile(file) as zip_file:
file_names = zip_file.namelist()
assert len(file_names) == 1, "Expected a single file from Quandl."
... | [
"def",
"load_data_table",
"(",
"file",
",",
"index_col",
",",
"show_progress",
"=",
"False",
")",
":",
"with",
"ZipFile",
"(",
"file",
")",
"as",
"zip_file",
":",
"file_names",
"=",
"zip_file",
".",
"namelist",
"(",
")",
"assert",
"len",
"(",
"file_names",... | 29.368421 | 0.000867 |
def get(self, column, default_value=None):
"""Get an item from the Row by column name.
Args:
column: Tuple of column names, or a (str) column name, or positional
column number, 0-indexed.
default_value: The value to use if the key is not found.
Returns:
A list or string with ... | [
"def",
"get",
"(",
"self",
",",
"column",
",",
"default_value",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"column",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"col",
"in",
"column",
":",
"ret",
".",
"append"... | 32.08 | 0.002421 |
def edit_distance(seq1, seq2, action_function=lowest_cost_action, test=operator.eq):
"""Computes the edit distance between the two given sequences.
This uses the relatively fast method that only constructs
two columns of the 2d array for edits. This function actually uses four columns
because we track ... | [
"def",
"edit_distance",
"(",
"seq1",
",",
"seq2",
",",
"action_function",
"=",
"lowest_cost_action",
",",
"test",
"=",
"operator",
".",
"eq",
")",
":",
"m",
"=",
"len",
"(",
"seq1",
")",
"n",
"=",
"len",
"(",
"seq2",
")",
"# Special, easy cases:",
"if",
... | 34 | 0.001618 |
def do_file(self, filename):
""" Read and execute a .dql file """
with open(filename, "r") as infile:
self._run_cmd(infile.read()) | [
"def",
"do_file",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"infile",
":",
"self",
".",
"_run_cmd",
"(",
"infile",
".",
"read",
"(",
")",
")"
] | 38.75 | 0.012658 |
def terminate(self):
"""
Terminate the instance
"""
rs = self.connection.terminate_instances([self.id])
if len(rs) > 0:
self._update(rs[0]) | [
"def",
"terminate",
"(",
"self",
")",
":",
"rs",
"=",
"self",
".",
"connection",
".",
"terminate_instances",
"(",
"[",
"self",
".",
"id",
"]",
")",
"if",
"len",
"(",
"rs",
")",
">",
"0",
":",
"self",
".",
"_update",
"(",
"rs",
"[",
"0",
"]",
")... | 26.428571 | 0.010471 |
def container_remove_objects(object_id, input_params={}, always_retry=False, **kwargs):
"""
Invokes the /container-xxxx/removeObjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FremoveObjects
"""
return DXHTTP... | [
"def",
"container_remove_objects",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/removeObjects'",
"%",
"object_id",
",",
"input_params",
",",
"a... | 57.857143 | 0.009732 |
def simple_lmdb_settings(path, map_size=1e9, user_supplied_id=False):
"""
Creates a decorator that can be used to configure sane default LMDB
persistence settings for a model
Args:
path (str): The path where the LMDB database files will be created
map_size (int): The amount of space to ... | [
"def",
"simple_lmdb_settings",
"(",
"path",
",",
"map_size",
"=",
"1e9",
",",
"user_supplied_id",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"provider",
"=",
"ff",
".",
"UserSpecifiedIdProvider",
"(",
"key",
"=",
"'_id'",
")",
"if",
... | 31.275862 | 0.00107 |
def get(url, max_backoff=32, verbose=False, **kwargs):
"""Adding retries to requests.get with exponential backoff.
Args:
url (str): The URL to fetch
max_backoff (int): The number of seconds to sleep at maximums
verbose (bool): Whether to print exceptions.
Returns:
Response:... | [
"def",
"get",
"(",
"url",
",",
"max_backoff",
"=",
"32",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"sleep_seconds",
"=",
"1",
"while",
"sleep_seconds",
"<=",
"max_backoff",
":",
"try",
":",
"# you may overwrite `timeout` via `kwargs`",
... | 34.833333 | 0.001862 |
def to_key(literal_or_identifier):
''' returns string representation of this object'''
if literal_or_identifier['type'] == 'Identifier':
return literal_or_identifier['name']
elif literal_or_identifier['type'] == 'Literal':
k = literal_or_identifier['value']
if isinstance(k, float):
... | [
"def",
"to_key",
"(",
"literal_or_identifier",
")",
":",
"if",
"literal_or_identifier",
"[",
"'type'",
"]",
"==",
"'Identifier'",
":",
"return",
"literal_or_identifier",
"[",
"'name'",
"]",
"elif",
"literal_or_identifier",
"[",
"'type'",
"]",
"==",
"'Literal'",
":... | 37.6875 | 0.001618 |
def transformer_tall_finetune_tied():
"""Tied means fine-tune CNN/DM summarization as LM."""
hparams = transformer_tall()
hparams.multiproblem_max_input_length = 750
hparams.multiproblem_max_target_length = 100
hparams.multiproblem_schedule_max_examples = 0
hparams.learning_rate_schedule = ("linear_warmup*c... | [
"def",
"transformer_tall_finetune_tied",
"(",
")",
":",
"hparams",
"=",
"transformer_tall",
"(",
")",
"hparams",
".",
"multiproblem_max_input_length",
"=",
"750",
"hparams",
".",
"multiproblem_max_target_length",
"=",
"100",
"hparams",
".",
"multiproblem_schedule_max_exam... | 43.5625 | 0.022472 |
def delete_outbox_fax(self, outbox_fax_id, **kwargs): # noqa: E501
"""Delete a fax from outbox # noqa: E501
Delete a fax that is being sent and is still in your outbox # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please p... | [
"def",
"delete_outbox_fax",
"(",
"self",
",",
"outbox_fax_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"self",
".",
"del... | 44.761905 | 0.002083 |
def create_replication_schedule(self,
start_time, end_time, interval_unit, interval, paused, arguments,
alert_on_start=False, alert_on_success=False, alert_on_fail=False,
alert_on_abort=False):
"""
Create a new replication schedule for this service.
The replication argument type varies pe... | [
"def",
"create_replication_schedule",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"interval_unit",
",",
"interval",
",",
"paused",
",",
"arguments",
",",
"alert_on_start",
"=",
"False",
",",
"alert_on_success",
"=",
"False",
",",
"alert_on_fail",
"=",
... | 49.615385 | 0.009502 |
def state(self):
"""Main state of sensor."""
if self.lightlevel is None:
return None
lux = round(10 ** (float(self.lightlevel - 1) / 10000), 1)
return lux | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"lightlevel",
"is",
"None",
":",
"return",
"None",
"lux",
"=",
"round",
"(",
"10",
"**",
"(",
"float",
"(",
"self",
".",
"lightlevel",
"-",
"1",
")",
"/",
"10000",
")",
",",
"1",
")",
"r... | 32.166667 | 0.010101 |
def _make_subclasshook(cls):
"""Construct a __subclasshook__ callable that incorporates
the associated __extra__ class in subclass checks performed
against cls.
"""
if isinstance(cls.__extra__, abc.ABCMeta):
# The logic mirrors that of ABCMeta.__subclasscheck__.
# Registered classes ... | [
"def",
"_make_subclasshook",
"(",
"cls",
")",
":",
"if",
"isinstance",
"(",
"cls",
".",
"__extra__",
",",
"abc",
".",
"ABCMeta",
")",
":",
"# The logic mirrors that of ABCMeta.__subclasscheck__.",
"# Registered classes need not be checked here because",
"# cls and its extra s... | 43.032258 | 0.000733 |
def bulk_submit(cls, imports, api=None):
"""
Submit imports in bulk
:param imports: Imports to be retrieved.
:param api: Api instance.
:return: List of ImportBulkRecord objects.
"""
if not imports:
raise SbgError('Imports are required')
api = ... | [
"def",
"bulk_submit",
"(",
"cls",
",",
"imports",
",",
"api",
"=",
"None",
")",
":",
"if",
"not",
"imports",
":",
"raise",
"SbgError",
"(",
"'Imports are required'",
")",
"api",
"=",
"api",
"or",
"cls",
".",
"_API",
"items",
"=",
"[",
"]",
"for",
"im... | 30.575 | 0.001585 |
def shell(self, name='default', user=None, password=None, root=0, verbose=1, write_password=1, no_db=0, no_pw=0):
"""
Opens a SQL shell to the given database, assuming the configured database
and user supports this feature.
"""
raise NotImplementedError | [
"def",
"shell",
"(",
"self",
",",
"name",
"=",
"'default'",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"root",
"=",
"0",
",",
"verbose",
"=",
"1",
",",
"write_password",
"=",
"1",
",",
"no_db",
"=",
"0",
",",
"no_pw",
"=",
"0",
... | 48 | 0.013652 |
def remove_tags(self, tags, afterwards=None):
"""
remove `tags` (list of str) from all messages in this thread
.. note::
This only adds the requested operation to this objects
:class:`DBManager's <alot.db.DBManager>` write queue.
You need to call :meth:`DBMa... | [
"def",
"remove_tags",
"(",
"self",
",",
"tags",
",",
"afterwards",
"=",
"None",
")",
":",
"rmtags",
"=",
"set",
"(",
"tags",
")",
".",
"intersection",
"(",
"self",
".",
"_tags",
")",
"if",
"rmtags",
":",
"def",
"myafterwards",
"(",
")",
":",
"self",
... | 38.192308 | 0.001965 |
def add_annotation_value(graph, annotation, value):
"""Add the given annotation/value pair to all qualified edges.
:param pybel.BELGraph graph:
:param str annotation:
:param str value:
"""
if annotation not in graph.defined_annotation_keywords:
raise ValueError('annotation not defined: ... | [
"def",
"add_annotation_value",
"(",
"graph",
",",
"annotation",
",",
"value",
")",
":",
"if",
"annotation",
"not",
"in",
"graph",
".",
"defined_annotation_keywords",
":",
"raise",
"ValueError",
"(",
"'annotation not defined: {}'",
".",
"format",
"(",
"annotation",
... | 34.222222 | 0.00158 |
def stop_workers_async(self):
"""Signal that all workers should stop without waiting."""
self._started = False
for worker in self._workers:
worker.signal_stop() | [
"def",
"stop_workers_async",
"(",
"self",
")",
":",
"self",
".",
"_started",
"=",
"False",
"for",
"worker",
"in",
"self",
".",
"_workers",
":",
"worker",
".",
"signal_stop",
"(",
")"
] | 32 | 0.010152 |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
gmm = make_ring_dicts(library=args['library'], basedir='.')
for galkey in gmm.galkeys():
ring_dict = gmm.ring_dict(galkey)
for ring_key, ring_info in ring_dict.it... | [
"def",
"build_job_configs",
"(",
"self",
",",
"args",
")",
":",
"job_configs",
"=",
"{",
"}",
"gmm",
"=",
"make_ring_dicts",
"(",
"library",
"=",
"args",
"[",
"'library'",
"]",
",",
"basedir",
"=",
"'.'",
")",
"for",
"galkey",
"in",
"gmm",
".",
"galkey... | 39.25 | 0.002488 |
def get_recipients(self, ar):
"""Return the AR recipients in the same format like the AR Report
expects in the records field `Recipients`
"""
plone_utils = api.get_tool("plone_utils")
def is_email(email):
if not plone_utils.validateSingleEmailAddress(email):
... | [
"def",
"get_recipients",
"(",
"self",
",",
"ar",
")",
":",
"plone_utils",
"=",
"api",
".",
"get_tool",
"(",
"\"plone_utils\"",
")",
"def",
"is_email",
"(",
"email",
")",
":",
"if",
"not",
"plone_utils",
".",
"validateSingleEmailAddress",
"(",
"email",
")",
... | 33.268293 | 0.001425 |
def should_transform(self):
"""Determine if we should transform the response
:returns: A boolean value
"""
if not HAS_DIAZO:
self.log.info("HAS_DIAZO: false")
return False
if asbool(self.request.META.get(DIAZO_OFF_REQUEST_HEADER)):
self.log... | [
"def",
"should_transform",
"(",
"self",
")",
":",
"if",
"not",
"HAS_DIAZO",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"HAS_DIAZO: false\"",
")",
"return",
"False",
"if",
"asbool",
"(",
"self",
".",
"request",
".",
"META",
".",
"get",
"(",
"DIAZO_OFF_R... | 32.122449 | 0.001233 |
def _var_uint_field_handler(handler, ctx):
"""Handler co-routine for variable unsigned integer fields that.
Invokes the given ``handler`` function with the read field and context,
then immediately yields to the resulting co-routine.
"""
_, self = yield
queue = ctx.queue
value = 0
while ... | [
"def",
"_var_uint_field_handler",
"(",
"handler",
",",
"ctx",
")",
":",
"_",
",",
"self",
"=",
"yield",
"queue",
"=",
"ctx",
".",
"queue",
"value",
"=",
"0",
"while",
"True",
":",
"if",
"len",
"(",
"queue",
")",
"==",
"0",
":",
"# We don't know when th... | 36.578947 | 0.001403 |
def __add_loaded_module(self, event):
"""
Private method to automatically add new module objects from debug events.
@type event: L{Event}
@param event: Event object.
"""
lpBaseOfDll = event.get_module_base()
hFile = event.get_file_handle()
## if not... | [
"def",
"__add_loaded_module",
"(",
"self",
",",
"event",
")",
":",
"lpBaseOfDll",
"=",
"event",
".",
"get_module_base",
"(",
")",
"hFile",
"=",
"event",
".",
"get_file_handle",
"(",
")",
"## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan",
... | 43.916667 | 0.009282 |
def abs_path(path, format_kwargs={}, relative_to=None, keep_slash=False):
"""Get abs. path for ``path``.
``path`` may be a relative or absolute file system path or an asset
path. If ``path`` is already an abs. path, it will be returned as
is. Otherwise, it will be converted into a normalized abs. path.... | [
"def",
"abs_path",
"(",
"path",
",",
"format_kwargs",
"=",
"{",
"}",
",",
"relative_to",
"=",
"None",
",",
"keep_slash",
"=",
"False",
")",
":",
"if",
"format_kwargs",
":",
"path",
"=",
"path",
".",
"format_map",
"(",
"format_kwargs",
")",
"has_slash",
"... | 32.087719 | 0.001061 |
def find_outliers(data, predictor, sigma,
method=mad):
"""find_outliers(data, predictor, sigma, method=mad)
Returns a boolean array indicating the outliers in the given *data* array.
**Parameters**
data : array-like, shape = [n_samples, 2] or [n_samples, 3]
Photometry array ... | [
"def",
"find_outliers",
"(",
"data",
",",
"predictor",
",",
"sigma",
",",
"method",
"=",
"mad",
")",
":",
"phase",
",",
"mag",
",",
"",
"*",
"err",
"=",
"data",
".",
"T",
"residuals",
"=",
"numpy",
".",
"absolute",
"(",
"predictor",
".",
"predict",
... | 38.266667 | 0.00085 |
def call(operation_name, *args, **kwargs):
"""Call a libvips operation.
Use this method to call any libvips operation. For example::
black_image = pyvips.Operation.call('black', 10, 10)
See the Introduction for notes on how this works.
"""
logger.debug('VipsOpera... | [
"def",
"call",
"(",
"operation_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'VipsOperation.call: operation_name = %s'",
",",
"operation_name",
")",
"# logger.debug('VipsOperation.call: args = %s, kwargs =%s',",
"# ... | 32.818841 | 0.000429 |
def load_file(self, path=None, first_data_line='auto', filters='*.*', text='Select a file, FACEPANTS.', default_directory=None, header_only=False, quiet=False):
"""
This will clear the databox, load a file, storing the header info in
self.headers, and the data in self.columns
If first_... | [
"def",
"load_file",
"(",
"self",
",",
"path",
"=",
"None",
",",
"first_data_line",
"=",
"'auto'",
",",
"filters",
"=",
"'*.*'",
",",
"text",
"=",
"'Select a file, FACEPANTS.'",
",",
"default_directory",
"=",
"None",
",",
"header_only",
"=",
"False",
",",
"qu... | 36.712991 | 0.013139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.