text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def to_jd(year, month, day):
'''Convert a Positivist date to Julian day count.'''
legal_date(year, month, day)
gyear = year + YEAR_EPOCH - 1
return (
gregorian.EPOCH - 1 + (365 * (gyear - 1)) +
floor((gyear - 1) / 4) + (-floor((gyear - 1) / 100)) +
floor((gyear - 1) / 400) + (mo... | [
"def",
"to_jd",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"legal_date",
"(",
"year",
",",
"month",
",",
"day",
")",
"gyear",
"=",
"year",
"+",
"YEAR_EPOCH",
"-",
"1",
"return",
"(",
"gregorian",
".",
"EPOCH",
"-",
"1",
"+",
"(",
"365",
"*"... | 33.6 | 19.6 |
def discover_json(self):
"""Discovers the JSON format and registers it if available.
To speed up JSON parsing and composing, install `simplejson`::
pip install simplejson
The standard library module `json` will be used by default.
"""
try:
import simple... | [
"def",
"discover_json",
"(",
"self",
")",
":",
"try",
":",
"import",
"simplejson",
"as",
"json",
"except",
"ImportError",
":",
"import",
"json",
"self",
".",
"register",
"(",
"'json'",
",",
"json",
".",
"loads",
",",
"json",
".",
"dumps",
")"
] | 30.357143 | 19.5 |
def install_os_snaps(snaps, refresh=False):
"""Install OpenStack snaps from channel and with mode
@param snaps: Dictionary of snaps with channels and modes of the form:
{'snap_name': {'channel': 'snap_channel',
'mode': 'snap_mode'}}
Where channel is a snapstore channel an... | [
"def",
"install_os_snaps",
"(",
"snaps",
",",
"refresh",
"=",
"False",
")",
":",
"def",
"_ensure_flag",
"(",
"flag",
")",
":",
"if",
"flag",
".",
"startswith",
"(",
"'--'",
")",
":",
"return",
"flag",
"return",
"'--{}'",
".",
"format",
"(",
"flag",
")"... | 35.962963 | 18.62963 |
def add_status_line(self, label):
"""Add a status bar line to the table.
This function returns the status bar and it can be modified
from this return value.
"""
status_line = StatusBar(label,
self._sep_start, self._sep_end,
... | [
"def",
"add_status_line",
"(",
"self",
",",
"label",
")",
":",
"status_line",
"=",
"StatusBar",
"(",
"label",
",",
"self",
".",
"_sep_start",
",",
"self",
".",
"_sep_end",
",",
"self",
".",
"_fill_char",
")",
"self",
".",
"_lines",
".",
"append",
"(",
... | 36.545455 | 11.909091 |
def do_region(self, x, y, w, h):
"""Apply region selection."""
if (x is None):
self.logger.debug("region: full (nop)")
else:
self.logger.debug("region: (%d,%d,%d,%d)" % (x, y, w, h))
self.image = self.image.crop((x, y, x + w, y + h))
self.width = w... | [
"def",
"do_region",
"(",
"self",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
":",
"if",
"(",
"x",
"is",
"None",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"region: full (nop)\"",
")",
"else",
":",
"self",
".",
"logger",
".",
"debug",
... | 37.777778 | 15.666667 |
def _wait_new_conf(self):
"""Ask the daemon to drop its configuration and wait for a new one
This overrides the default method from GenericInterface
:return: None
"""
with self.app.conf_lock:
logger.warning("My master Arbiter wants me to wait for a new configuration... | [
"def",
"_wait_new_conf",
"(",
"self",
")",
":",
"with",
"self",
".",
"app",
".",
"conf_lock",
":",
"logger",
".",
"warning",
"(",
"\"My master Arbiter wants me to wait for a new configuration.\"",
")",
"self",
".",
"app",
".",
"cur_conf",
"=",
"{",
"}"
] | 34.9 | 20 |
def handle_purge(environ, start_response):
"""
Handle a PURGE request.
"""
from utils import is_valid_security, get_cached_files
from settings import DEBUG
server = environ['SERVER_NAME']
try:
request_uri = get_path(environ)
path_and_query = request_uri.lstrip("/")
qu... | [
"def",
"handle_purge",
"(",
"environ",
",",
"start_response",
")",
":",
"from",
"utils",
"import",
"is_valid_security",
",",
"get_cached_files",
"from",
"settings",
"import",
"DEBUG",
"server",
"=",
"environ",
"[",
"'SERVER_NAME'",
"]",
"try",
":",
"request_uri",
... | 36.833333 | 13 |
def check_manifest ():
"""Snatched from roundup.sf.net.
Check that the files listed in the MANIFEST are present when the
source is unpacked."""
try:
f = open('MANIFEST')
except Exception:
print('\n*** SOURCE WARNING: The MANIFEST file is missing!')
return
try:
man... | [
"def",
"check_manifest",
"(",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"'MANIFEST'",
")",
"except",
"Exception",
":",
"print",
"(",
"'\\n*** SOURCE WARNING: The MANIFEST file is missing!'",
")",
"return",
"try",
":",
"manifest",
"=",
"[",
"l",
".",
"strip"... | 34.368421 | 21.210526 |
def send_batches(self, batch_list):
"""Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict
"""
if isinstance(batch_list, BaseMessage):
batch_list = ... | [
"def",
"send_batches",
"(",
"self",
",",
"batch_list",
")",
":",
"if",
"isinstance",
"(",
"batch_list",
",",
"BaseMessage",
")",
":",
"batch_list",
"=",
"batch_list",
".",
"SerializeToString",
"(",
")",
"return",
"self",
".",
"_post",
"(",
"'/batches'",
",",... | 29.923077 | 18.307692 |
def knock_out(self):
"""Knockout gene by marking it as non-functional and setting all
associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as
context.
"""
self.functional = False
for reaction in self.reactions:
... | [
"def",
"knock_out",
"(",
"self",
")",
":",
"self",
".",
"functional",
"=",
"False",
"for",
"reaction",
"in",
"self",
".",
"reactions",
":",
"if",
"not",
"reaction",
".",
"functional",
":",
"reaction",
".",
"bounds",
"=",
"(",
"0",
",",
"0",
")"
] | 34.909091 | 11.909091 |
def concat_same_type(self, to_concat, placement=None):
"""
Concatenate list of single blocks of the same type.
"""
values = self._holder._concat_same_type(
[blk.values for blk in to_concat])
placement = placement or slice(0, len(values), 1)
return self.make_bl... | [
"def",
"concat_same_type",
"(",
"self",
",",
"to_concat",
",",
"placement",
"=",
"None",
")",
":",
"values",
"=",
"self",
".",
"_holder",
".",
"_concat_same_type",
"(",
"[",
"blk",
".",
"values",
"for",
"blk",
"in",
"to_concat",
"]",
")",
"placement",
"=... | 45.888889 | 12.333333 |
def bounding_box_from_annotation(source=None, padding=None, **kwargs):
"""bounding_box_from_annotation(source, padding, **kwargs) -> bounding_box
Creates a bounding box from the given parameters, which are, in general, annotations read using :py:func:`bob.ip.facedetect.read_annotation_file`.
Different kinds of a... | [
"def",
"bounding_box_from_annotation",
"(",
"source",
"=",
"None",
",",
"padding",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"source",
"is",
"None",
":",
"# try to estimate the source",
"for",
"s",
",",
"k",
"in",
"available_sources",
".",
"items... | 45.673684 | 30.905263 |
def auto_thaw(vault_client, opt):
"""Will thaw into a temporary location"""
icefile = opt.thaw_from
if not os.path.exists(icefile):
raise aomi.exceptions.IceFile("%s missing" % icefile)
thaw(vault_client, icefile, opt)
return opt | [
"def",
"auto_thaw",
"(",
"vault_client",
",",
"opt",
")",
":",
"icefile",
"=",
"opt",
".",
"thaw_from",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"icefile",
")",
":",
"raise",
"aomi",
".",
"exceptions",
".",
"IceFile",
"(",
"\"%s missing\"",
... | 31.375 | 14.5 |
def transition(value, maximum, start, end):
""" Transition between two values.
:param value: Current iteration.
:param maximum: Maximum number of iterations.
:param start: Start value.
:param end: End value.
:returns: Transitional value.
"""
return round(start + (end - start) * value / ... | [
"def",
"transition",
"(",
"value",
",",
"maximum",
",",
"start",
",",
"end",
")",
":",
"return",
"round",
"(",
"start",
"+",
"(",
"end",
"-",
"start",
")",
"*",
"value",
"/",
"maximum",
",",
"2",
")"
] | 32.2 | 10.7 |
def _write_config(self):
'''Write the parameters to a file for PhantomJS to read.'''
param_dict = {
'url': self._params.url,
'snapshot_paths': self._params.snapshot_paths,
'wait_time': self._params.wait_time,
'num_scrolls': self._params.num_scrolls,
... | [
"def",
"_write_config",
"(",
"self",
")",
":",
"param_dict",
"=",
"{",
"'url'",
":",
"self",
".",
"_params",
".",
"url",
",",
"'snapshot_paths'",
":",
"self",
".",
"_params",
".",
"snapshot_paths",
",",
"'wait_time'",
":",
"self",
".",
"_params",
".",
"w... | 41.16129 | 18.967742 |
def _substitute(self, str):
"""
Substitute words in the string, according to the specified reflections,
e.g. "I'm" -> "you are"
:type str: str
:param str: The string to be mapped
:rtype: str
"""
if not self.attr.get("substitute",True):return str
r... | [
"def",
"_substitute",
"(",
"self",
",",
"str",
")",
":",
"if",
"not",
"self",
".",
"attr",
".",
"get",
"(",
"\"substitute\"",
",",
"True",
")",
":",
"return",
"str",
"return",
"self",
".",
"_regex",
".",
"sub",
"(",
"lambda",
"mo",
":",
"self",
"."... | 33.846154 | 15.076923 |
def infer(self, data, initial_proposal=None, full_output=False,**kwargs):
"""
Infer the model parameters, given the data.
auto_convergence=True,
walkers=100, burn=2000, sample=2000, minimum_sample=2000,
convergence_check_frequency=1000, a=2.0, threads=1,
"""
# ... | [
"def",
"infer",
"(",
"self",
",",
"data",
",",
"initial_proposal",
"=",
"None",
",",
"full_output",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Apply data masks now so we don't have to do it on the fly.",
"data",
",",
"pixels_affected",
"=",
"self",
".",
... | 43.625786 | 22.745283 |
def list_active_vms(cwd=None):
'''
Return a list of machine names for active virtual machine on the host,
which are defined in the Vagrantfile at the indicated path.
CLI Example:
.. code-block:: bash
salt '*' vagrant.list_active_vms cwd=/projects/project_1
'''
vms = []
cmd = ... | [
"def",
"list_active_vms",
"(",
"cwd",
"=",
"None",
")",
":",
"vms",
"=",
"[",
"]",
"cmd",
"=",
"'vagrant status'",
"reply",
"=",
"__salt__",
"[",
"'cmd.shell'",
"]",
"(",
"cmd",
",",
"cwd",
"=",
"cwd",
")",
"log",
".",
"info",
"(",
"'--->\\n%s'",
","... | 29.666667 | 21.47619 |
def redraw_current_line(self):
""" Redraw the highlighted line """
if self.no_streams:
return
row = self.pads[self.current_pad].getyx()[0]
s = self.filtered_streams[row]
pad = self.pads['streams']
pad.move(row, 0)
pad.clrtoeol()
pad.addstr(row,... | [
"def",
"redraw_current_line",
"(",
"self",
")",
":",
"if",
"self",
".",
"no_streams",
":",
"return",
"row",
"=",
"self",
".",
"pads",
"[",
"self",
".",
"current_pad",
"]",
".",
"getyx",
"(",
")",
"[",
"0",
"]",
"s",
"=",
"self",
".",
"filtered_stream... | 34.846154 | 12.153846 |
def cmd_wp_movemulti(self, args):
'''handle wp move of multiple waypoints'''
if len(args) < 3:
print("usage: wp movemulti WPNUM WPSTART WPEND <rotation>")
return
idx = int(args[0])
if idx < 1 or idx > self.wploader.count():
print("Invalid wp number %u"... | [
"def",
"cmd_wp_movemulti",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"3",
":",
"print",
"(",
"\"usage: wp movemulti WPNUM WPSTART WPEND <rotation>\"",
")",
"return",
"idx",
"=",
"int",
"(",
"args",
"[",
"0",
"]",
")",
"if",
... | 41.930556 | 19.791667 |
def skew_y(self, y):
"""Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
"""
self.root.set("transform", "%s skewY(%f)" %
(self.root.get("transform") or '', y))
return ... | [
"def",
"skew_y",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s skewY(%f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
",",
"y",
")",
")",
"return",
"self"... | 28.545455 | 16.272727 |
def enable(step: 'projects.ProjectStep'):
"""
Create a print equivalent function that also writes the output to the
project page. The write_through is enabled so that the TextIOWrapper
immediately writes all of its input data directly to the underlying
BytesIO buffer. This is needed so that we can s... | [
"def",
"enable",
"(",
"step",
":",
"'projects.ProjectStep'",
")",
":",
"# Prevent anything unusual from causing buffer issues",
"restore_default_configuration",
"(",
")",
"stdout_interceptor",
"=",
"RedirectBuffer",
"(",
"sys",
".",
"stdout",
")",
"sys",
".",
"stdout",
... | 36.28 | 19.96 |
def classify_segmented_recording(recording, result_format=None):
"""Use this function if you are sure you have a single symbol.
Parameters
----------
recording : string
The recording in JSON format
Returns
-------
list of dictionaries
Each dictionary contains the keys 'symb... | [
"def",
"classify_segmented_recording",
"(",
"recording",
",",
"result_format",
"=",
"None",
")",
":",
"global",
"single_symbol_classifier",
"if",
"single_symbol_classifier",
"is",
"None",
":",
"single_symbol_classifier",
"=",
"SingleClassificer",
"(",
")",
"return",
"si... | 32.722222 | 19 |
def have_graph(self, graph):
"""Return whether I have a graph by this name."""
graph = self.pack(graph)
return bool(self.sql('graphs_named', graph).fetchone()[0]) | [
"def",
"have_graph",
"(",
"self",
",",
"graph",
")",
":",
"graph",
"=",
"self",
".",
"pack",
"(",
"graph",
")",
"return",
"bool",
"(",
"self",
".",
"sql",
"(",
"'graphs_named'",
",",
"graph",
")",
".",
"fetchone",
"(",
")",
"[",
"0",
"]",
")"
] | 45.75 | 11.5 |
def _build_model_factories(store):
"""Generate factories to construct objects from schemata"""
result = {}
for schemaname in store:
schema = None
try:
schema = store[schemaname]['schema']
except KeyError:
schemata_log("No schema found for ", schemaname, lv... | [
"def",
"_build_model_factories",
"(",
"store",
")",
":",
"result",
"=",
"{",
"}",
"for",
"schemaname",
"in",
"store",
":",
"schema",
"=",
"None",
"try",
":",
"schema",
"=",
"store",
"[",
"schemaname",
"]",
"[",
"'schema'",
"]",
"except",
"KeyError",
":",... | 27.95 | 27.5 |
def remove_timex3s(self, list_timex_ids):
"""
Removes a list of terms from the layer
@type list_timex_ids: list (of strings)
@param list_timex_ids: list of timex identifier to be removed
"""
nodes_to_remove = set()
for timex in self:
if timex.get_id() ... | [
"def",
"remove_timex3s",
"(",
"self",
",",
"list_timex_ids",
")",
":",
"nodes_to_remove",
"=",
"set",
"(",
")",
"for",
"timex",
"in",
"self",
":",
"if",
"timex",
".",
"get_id",
"(",
")",
"in",
"list_timex_ids",
":",
"nodes_to_remove",
".",
"add",
"(",
"t... | 40 | 12.588235 |
def createsnippet(self, project_id, title, file_name, code, visibility_level=0):
"""
Creates an snippet
:param project_id: project id to create the snippet under
:param title: title of the snippet
:param file_name: filename for the snippet
:param code: content of the sni... | [
"def",
"createsnippet",
"(",
"self",
",",
"project_id",
",",
"title",
",",
"file_name",
",",
"code",
",",
"visibility_level",
"=",
"0",
")",
":",
"data",
"=",
"{",
"'id'",
":",
"project_id",
",",
"'title'",
":",
"title",
",",
"'file_name'",
":",
"file_na... | 40.5 | 22.416667 |
def windowed_run_count(da, window, dim='time'):
"""Return the number of consecutive true values in array for runs at least as long as given duration.
Parameters
----------
da: N-dimensional Xarray data array (boolean)
Input data array
window : int
Minimum run le... | [
"def",
"windowed_run_count",
"(",
"da",
",",
"window",
",",
"dim",
"=",
"'time'",
")",
":",
"d",
"=",
"rle",
"(",
"da",
",",
"dim",
"=",
"dim",
")",
"out",
"=",
"d",
".",
"where",
"(",
"d",
">=",
"window",
",",
"0",
")",
".",
"sum",
"(",
"dim... | 33 | 19.952381 |
def _get_encoder_method(stream_type):
"""A function to get the python type to device cloud type converter function.
:param stream_type: The streams data type
:return: A function that when called with the python object will return the serializable
type for sending to the cloud. If there is no function f... | [
"def",
"_get_encoder_method",
"(",
"stream_type",
")",
":",
"if",
"stream_type",
"is",
"not",
"None",
":",
"return",
"DSTREAM_TYPE_MAP",
".",
"get",
"(",
"stream_type",
".",
"upper",
"(",
")",
",",
"(",
"lambda",
"x",
":",
"x",
",",
"lambda",
"x",
":",
... | 49.166667 | 24.666667 |
def start(track_file,
twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret,
poll_interval=15,
unfiltered=False,
languages=None,
debug=False,
outfile=None):
"""Start the stream."""
listener... | [
"def",
"start",
"(",
"track_file",
",",
"twitter_api_key",
",",
"twitter_api_secret",
",",
"twitter_access_token",
",",
"twitter_access_token_secret",
",",
"poll_interval",
"=",
"15",
",",
"unfiltered",
"=",
"False",
",",
"languages",
"=",
"None",
",",
"debug",
"=... | 31.346154 | 17.076923 |
def fromurl(url):
""" Parse patch from an URL, return False
if an error occured. Note that this also
can throw urlopen() exceptions.
"""
ps = PatchSet( urllib_request.urlopen(url) )
if ps.errors == 0:
return ps
return False | [
"def",
"fromurl",
"(",
"url",
")",
":",
"ps",
"=",
"PatchSet",
"(",
"urllib_request",
".",
"urlopen",
"(",
"url",
")",
")",
"if",
"ps",
".",
"errors",
"==",
"0",
":",
"return",
"ps",
"return",
"False"
] | 26.777778 | 12.333333 |
def shift_christmas_boxing_days(self, year):
""" When Christmas and/or Boxing Day falls on a weekend, it is rolled
forward to the next weekday.
"""
christmas = date(year, 12, 25)
boxing_day = date(year, 12, 26)
boxing_day_label = "{} Shift".format(self.boxing_day_labe... | [
"def",
"shift_christmas_boxing_days",
"(",
"self",
",",
"year",
")",
":",
"christmas",
"=",
"date",
"(",
"year",
",",
"12",
",",
"25",
")",
"boxing_day",
"=",
"date",
"(",
"year",
",",
"12",
",",
"26",
")",
"boxing_day_label",
"=",
"\"{} Shift\"",
".",
... | 48.875 | 13.5 |
def reply_to(self) -> Optional[Sequence[AddressHeader]]:
"""The ``Reply-To`` header."""
try:
return cast(Sequence[AddressHeader], self[b'reply-to'])
except KeyError:
return None | [
"def",
"reply_to",
"(",
"self",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"AddressHeader",
"]",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"Sequence",
"[",
"AddressHeader",
"]",
",",
"self",
"[",
"b'reply-to'",
"]",
")",
"except",
"KeyError",
":",
... | 36.666667 | 17.333333 |
def logged_in():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
state = request.args.get('state')
if error:
return render_template('login_error.html', error=error)
else:
code = request.... | [
"def",
"logged_in",
"(",
")",
":",
"error",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'error'",
")",
"state",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'state'",
")",
"if",
"error",
":",
"return",
"render_template",
"(",
"'login_error.html'",
... | 40 | 25.238095 |
def factorize(self, show_progress=False, compute_w=True, compute_h=True,
compute_err=True, robust_cluster=3, niter=1, robust_nselect=-1):
""" Factorize s.t. WH = data
Parameters
----------
show_progress : bool
print some extra informatio... | [
"def",
"factorize",
"(",
"self",
",",
"show_progress",
"=",
"False",
",",
"compute_w",
"=",
"True",
",",
"compute_h",
"=",
"True",
",",
"compute_err",
"=",
"True",
",",
"robust_cluster",
"=",
"3",
",",
"niter",
"=",
"1",
",",
"robust_nselect",
"=",
"-",
... | 40.02439 | 16.292683 |
def reduce_number(num):
"""Reduces the string representation of a number.
If the number is of the format n.00..., returns n.
If the decimal portion of the number has a repeating decimal, followed by up to two trailing
numbers, such as:
0.3333333
or
0.343434346
It will return just one instance of th... | [
"def",
"reduce_number",
"(",
"num",
")",
":",
"parts",
"=",
"str",
"(",
"num",
")",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
"or",
"parts",
"[",
"1",
"]",
"==",
"\"0\"",
":",
"return",
"int",
"(",
"parts",
"["... | 21.852941 | 26.323529 |
def cartesian_to_spherical_azimuthal(x, y):
""" Calculates the azimuthal angle in spherical coordinates from Cartesian
coordinates. The azimuthal angle is in [0,2*pi].
Parameters
----------
x : {numpy.array, float}
X-coordinate.
y : {numpy.array, float}
Y-coordinate.
Return... | [
"def",
"cartesian_to_spherical_azimuthal",
"(",
"x",
",",
"y",
")",
":",
"y",
"=",
"float",
"(",
"y",
")",
"if",
"isinstance",
"(",
"y",
",",
"int",
")",
"else",
"y",
"phi",
"=",
"numpy",
".",
"arctan2",
"(",
"y",
",",
"x",
")",
"return",
"phi",
... | 25.842105 | 16.526316 |
def simplify_graph(graph):
"""
strips out everything but connectivity
Args:
graph (nx.Graph):
Returns:
nx.Graph: new_graph
CommandLine:
python3 -m utool.util_graph simplify_graph --show
python2 -m utool.util_graph simplify_graph --show
python2 -c "import n... | [
"def",
"simplify_graph",
"(",
"graph",
")",
":",
"import",
"utool",
"as",
"ut",
"nodes",
"=",
"sorted",
"(",
"list",
"(",
"graph",
".",
"nodes",
"(",
")",
")",
")",
"node_lookup",
"=",
"ut",
".",
"make_index_lookup",
"(",
"nodes",
")",
"if",
"graph",
... | 33.294118 | 19.45098 |
def get_collection(self, qs, view_kwargs):
"""Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list ... | [
"def",
"get_collection",
"(",
"self",
",",
"qs",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_get_collection",
"(",
"qs",
",",
"view_kwargs",
")",
"query",
"=",
"self",
".",
"query",
"(",
"view_kwargs",
")",
"if",
"qs",
".",
"filters",
":",
"query"... | 32.344828 | 23.62069 |
def expose(rule, **options):
"""Decorator to add an url rule to a function
"""
def decorator(f):
if not hasattr(f, "urls"):
f.urls = []
if isinstance(rule, (list, tuple)):
f.urls.extend(rule)
else:
f.urls.append((rule, options))
return f
... | [
"def",
"expose",
"(",
"rule",
",",
"*",
"*",
"options",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"not",
"hasattr",
"(",
"f",
",",
"\"urls\"",
")",
":",
"f",
".",
"urls",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"rule",
",",
"(",
... | 27.25 | 11.583333 |
def _initialize_attributes(model_class, name, bases, attrs):
"""Initialize the attributes of the model."""
model_class._attributes = {}
for k, v in attrs.iteritems():
if isinstance(v, Attribute):
model_class._attributes[k] = v
v.name = v.name or k | [
"def",
"_initialize_attributes",
"(",
"model_class",
",",
"name",
",",
"bases",
",",
"attrs",
")",
":",
"model_class",
".",
"_attributes",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v"... | 40.714286 | 6.857143 |
def active(self):
"""
Return the currently active :class:`~opentracing.Scope` which
can be used to access the currently active
:attr:`Scope.span`.
:return: the :class:`~opentracing.Scope` that is active,
or ``None`` if not available.
"""
context = se... | [
"def",
"active",
"(",
"self",
")",
":",
"context",
"=",
"self",
".",
"_get_context",
"(",
")",
"if",
"not",
"context",
":",
"return",
"super",
"(",
"TornadoScopeManager",
",",
"self",
")",
".",
"active",
"return",
"context",
".",
"active"
] | 29.133333 | 17.933333 |
def _process_pong(self):
"""
Process PONG sent by server.
"""
if len(self._pongs) > 0:
future = self._pongs.pop(0)
future.set_result(True)
self._pongs_received += 1
self._pings_outstanding -= 1 | [
"def",
"_process_pong",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_pongs",
")",
">",
"0",
":",
"future",
"=",
"self",
".",
"_pongs",
".",
"pop",
"(",
"0",
")",
"future",
".",
"set_result",
"(",
"True",
")",
"self",
".",
"_pongs_receive... | 29.444444 | 4.111111 |
def maybe_put_task(self):
"""Enqueue the next task, if there are any waiting."""
try:
task = next(self.tasks)
except StopIteration:
pass
else:
log.debug('Putting %s on queue', task)
self.task_queue.put(task) | [
"def",
"maybe_put_task",
"(",
"self",
")",
":",
"try",
":",
"task",
"=",
"next",
"(",
"self",
".",
"tasks",
")",
"except",
"StopIteration",
":",
"pass",
"else",
":",
"log",
".",
"debug",
"(",
"'Putting %s on queue'",
",",
"task",
")",
"self",
".",
"tas... | 31 | 13.666667 |
def buildMaskImage(rootname, bitvalue, output, extname='DQ', extver=1):
""" Builds mask image from rootname's DQ array
If there is no valid 'DQ' array in image, then return
an empty string.
"""
# If no bitvalue is set or rootname given, assume no mask is desired
# However, this name wou... | [
"def",
"buildMaskImage",
"(",
"rootname",
",",
"bitvalue",
",",
"output",
",",
"extname",
"=",
"'DQ'",
",",
"extver",
"=",
"1",
")",
":",
"# If no bitvalue is set or rootname given, assume no mask is desired",
"# However, this name would be useful as the output mask from",
"#... | 34.318182 | 19.787879 |
def comments(self): # pylint: disable=E0202
"""Return forest of comments, with top-level comments as tree roots.
May contain instances of MoreComment objects. To easily replace these
objects with Comment objects, use the replace_more_comments method then
fetch this attribute. Use comme... | [
"def",
"comments",
"(",
"self",
")",
":",
"# pylint: disable=E0202",
"if",
"self",
".",
"_comments",
"is",
"None",
":",
"self",
".",
"comments",
"=",
"Submission",
".",
"from_url",
"(",
"# pylint: disable=W0212",
"self",
".",
"reddit_session",
",",
"self",
"."... | 47.785714 | 22.714286 |
def p_return_expr(p):
""" statement : RETURN expr
"""
if not FUNCTION_LEVEL: # At less one level
syntax_error(p.lineno(1), 'Syntax Error: Returning value out of FUNCTION')
p[0] = None
return
if FUNCTION_LEVEL[-1].kind is None: # This function was not correctly declared.
... | [
"def",
"p_return_expr",
"(",
"p",
")",
":",
"if",
"not",
"FUNCTION_LEVEL",
":",
"# At less one level",
"syntax_error",
"(",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"'Syntax Error: Returning value out of FUNCTION'",
")",
"p",
"[",
"0",
"]",
"=",
"None",
"return... | 35.866667 | 27.533333 |
def delete(filething):
""" delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file.
"""
t = OggTheora(filething)
filething.fileobj.seek(0)
t.delete(filething) | [
"def",
"delete",
"(",
"filething",
")",
":",
"t",
"=",
"OggTheora",
"(",
"filething",
")",
"filething",
".",
"fileobj",
".",
"seek",
"(",
"0",
")",
"t",
".",
"delete",
"(",
"filething",
")"
] | 17.428571 | 19.142857 |
def pdf(self, f, y, Y_metadata=None):
"""
Evaluates the link function link(f) then computes the likelihood (pdf) using it
.. math:
p(y|\\lambda(f))
:param f: latent variables f
:type f: Nx1 array
:param y: data
:type y: Nx1 array
:param Y_met... | [
"def",
"pdf",
"(",
"self",
",",
"f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"gp_link",
",",
"link_functions",
".",
"Identity",
")",
":",
"return",
"self",
".",
"pdf_link",
"(",
"f",
",",
"y",
",",
... | 35.9 | 20.3 |
def list_tokens(opts):
'''
List all tokens in the store.
:param opts: Salt master config options
:returns: List of dicts (tokens)
'''
ret = []
for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(opts['token_dir']):
for token in filenames:
ret.append(token)
... | [
"def",
"list_tokens",
"(",
"opts",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"(",
"dirpath",
",",
"dirnames",
",",
"filenames",
")",
"in",
"salt",
".",
"utils",
".",
"path",
".",
"os_walk",
"(",
"opts",
"[",
"'token_dir'",
"]",
")",
":",
"for",
"token... | 26.583333 | 21.416667 |
def cwtmorlet(points, width):
"""complex morlet wavelet function compatible with scipy.signal.cwt
Parameters: points: int
Number of points in `vector`.
width: scalar
Width parameter of wavelet.
Equals (sample rate / fundamental frequenc... | [
"def",
"cwtmorlet",
"(",
"points",
",",
"width",
")",
":",
"omega",
"=",
"5.0",
"s",
"=",
"points",
"/",
"(",
"2.0",
"*",
"omega",
"*",
"width",
")",
"return",
"wavelets",
".",
"morlet",
"(",
"points",
",",
"omega",
",",
"s",
",",
"complete",
"=",
... | 42.5 | 13 |
def main():
'''main routine'''
# process arguments
if len(sys.argv) < 3:
usage()
rgname = sys.argv[1]
vmss_name = sys.argv[2]
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotF... | [
"def",
"main",
"(",
")",
":",
"# process arguments",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"3",
":",
"usage",
"(",
")",
"rgname",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"vmss_name",
"=",
"sys",
".",
"argv",
"[",
"2",
"]",
"# Load Azure... | 36 | 23.625 |
def get_adjustments(self,
zero_qtr_data,
requested_qtr_data,
last_per_qtr,
dates,
assets,
columns,
**kwargs):
"""
Creates an AdjustedArr... | [
"def",
"get_adjustments",
"(",
"self",
",",
"zero_qtr_data",
",",
"requested_qtr_data",
",",
"last_per_qtr",
",",
"dates",
",",
"assets",
",",
"columns",
",",
"*",
"*",
"kwargs",
")",
":",
"zero_qtr_data",
".",
"sort_index",
"(",
"inplace",
"=",
"True",
")",... | 38.666667 | 18.7 |
def _get_config_file_in_folder(cls, path):
"""Look for a configuration file in `path`.
If exists return its full path, otherwise None.
"""
if os.path.isfile(path):
path = os.path.dirname(path)
for fn in cls.PROJECT_CONFIG_FILES:
config = RawConfigParser... | [
"def",
"_get_config_file_in_folder",
"(",
"cls",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"for",
"fn",
"in",
"cls",
".",
"PROJECT_CONFIG_FI... | 33 | 14 |
def _parse_settings_bond_1(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond1.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '1'}
for binding in ['miim... | [
"def",
"_parse_settings_bond_1",
"(",
"opts",
",",
"iface",
",",
"bond_def",
")",
":",
"bond",
"=",
"{",
"'mode'",
":",
"'1'",
"}",
"for",
"binding",
"in",
"[",
"'miimon'",
",",
"'downdelay'",
",",
"'updelay'",
"]",
":",
"if",
"binding",
"in",
"opts",
... | 34.054054 | 20.972973 |
def create_prj(self, atypes=None, deps=None):
"""Create and return a new project
:param atypes: add the given atypes to the project
:type atypes: list | None
:param deps: add the given departmetns to the project
:type deps: list | None
:returns: The created project or No... | [
"def",
"create_prj",
"(",
"self",
",",
"atypes",
"=",
"None",
",",
"deps",
"=",
"None",
")",
":",
"dialog",
"=",
"ProjectCreatorDialog",
"(",
"parent",
"=",
"self",
")",
"dialog",
".",
"exec_",
"(",
")",
"prj",
"=",
"dialog",
".",
"project",
"if",
"p... | 34.346154 | 13.923077 |
def comparator(self, x, y):
'''
simple comparator method
'''
indX=0
indY=0
for i in range(len(self.stable_names)):
if self.stable_names[i] == x[0].split('-')[0]:
indX=i
if self.stable_names[i] == y[0].split('-')[0]:
... | [
"def",
"comparator",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"indX",
"=",
"0",
"indY",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"stable_names",
")",
")",
":",
"if",
"self",
".",
"stable_names",
"[",
"i",
"]",
"==",
... | 22.05 | 22.25 |
def detach(self):
"""
Detach from parent.
@return: This element removed from its parent's
child list and I{parent}=I{None}
@rtype: L{Element}
"""
if self.parent is not None:
if self in self.parent.children:
self.parent.children.remo... | [
"def",
"detach",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"if",
"self",
"in",
"self",
".",
"parent",
".",
"children",
":",
"self",
".",
"parent",
".",
"children",
".",
"remove",
"(",
"self",
")",
"self",
".",
... | 30.666667 | 9.833333 |
def play(state):
""" Play sound for a given state.
:param state: a State value.
"""
filename = None
if state == SoundService.State.welcome:
filename = "pad_glow_welcome1.wav"
elif state == SoundService.State.goodbye:
filename = "pad_glow_power_off... | [
"def",
"play",
"(",
"state",
")",
":",
"filename",
"=",
"None",
"if",
"state",
"==",
"SoundService",
".",
"State",
".",
"welcome",
":",
"filename",
"=",
"\"pad_glow_welcome1.wav\"",
"elif",
"state",
"==",
"SoundService",
".",
"State",
".",
"goodbye",
":",
... | 38.157895 | 13.631579 |
def prepare_adiabatic_limit(slh, k=None):
"""Prepare the adiabatic elimination on an SLH object
Args:
slh: The SLH object to take the limit for
k: The scaling parameter $k \rightarrow \infty$. The default is a
positive symbol 'k'
Returns:
tuple: The objects ``Y, A, B, F... | [
"def",
"prepare_adiabatic_limit",
"(",
"slh",
",",
"k",
"=",
"None",
")",
":",
"if",
"k",
"is",
"None",
":",
"k",
"=",
"symbols",
"(",
"'k'",
",",
"positive",
"=",
"True",
")",
"Ld",
"=",
"slh",
".",
"L",
".",
"dag",
"(",
")",
"LdL",
"=",
"(",
... | 29.818182 | 16.363636 |
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
:param must_create:
... | [
"def",
"save",
"(",
"self",
",",
"must_create",
"=",
"False",
")",
":",
"if",
"self",
".",
"session_key",
"is",
"None",
":",
"return",
"self",
".",
"create",
"(",
")",
"data",
"=",
"self",
".",
"_get_session",
"(",
"no_load",
"=",
"must_create",
")",
... | 36.285714 | 17.285714 |
def create_combination(list_of_sentences):
"""Generates all possible pair combinations for the input list of sentences.
For example:
input = ["paraphrase1", "paraphrase2", "paraphrase3"]
output = [("paraphrase1", "paraphrase2"),
("paraphrase1", "paraphrase3"),
("paraphrase2", "paraphr... | [
"def",
"create_combination",
"(",
"list_of_sentences",
")",
":",
"num_sentences",
"=",
"len",
"(",
"list_of_sentences",
")",
"-",
"1",
"combinations",
"=",
"[",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"list_of_sentences",
")",
":",
"if",
"i",
"=... | 29.538462 | 16.576923 |
def register_service(self, short_name, long_name, allow_duplicate=True):
"""Register a new service with the service manager.
Args:
short_name (string): A unique short name for this service that functions
as an id
long_name (string): A user facing name for this se... | [
"def",
"register_service",
"(",
"self",
",",
"short_name",
",",
"long_name",
",",
"allow_duplicate",
"=",
"True",
")",
":",
"self",
".",
"_loop",
".",
"run_coroutine",
"(",
"self",
".",
"_client",
".",
"register_service",
"(",
"short_name",
",",
"long_name",
... | 49 | 30.857143 |
def load_paired_notebook(notebook, fmt, nb_file, log):
"""Update the notebook with the inputs and outputs of the most recent paired files"""
formats = notebook.metadata.get('jupytext', {}).get('formats')
if not formats:
raise ValueError("'{}' is not a paired notebook".format(nb_file))
max_mtim... | [
"def",
"load_paired_notebook",
"(",
"notebook",
",",
"fmt",
",",
"nb_file",
",",
"log",
")",
":",
"formats",
"=",
"notebook",
".",
"metadata",
".",
"get",
"(",
"'jupytext'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'formats'",
")",
"if",
"not",
"formats",... | 46 | 21.594595 |
def _get_files():
"""General script to download file from online sources. Each remote file
should be specified in the list of dict REMOTE_FILES. Each entry in
REMOTE_FILES contains:
filename : the filename which is used by the test scripts
cached : the filename which is stored in the cache directory... | [
"def",
"_get_files",
"(",
")",
":",
"for",
"remote",
"in",
"REMOTE_FILES",
":",
"final_file",
"=",
"DATA_PATH",
"/",
"remote",
"[",
"'filename'",
"]",
"if",
"not",
"final_file",
".",
"exists",
"(",
")",
":",
"temp_file",
"=",
"DOWNLOADS_PATH",
"/",
"remote... | 40.37037 | 23.12963 |
def parse(name, **kwargs):
""" Parse a C/C++ file
"""
idx = clang.cindex.Index.create()
assert os.path.exists(name)
tu = idx.parse(name, **kwargs)
return _ensure_parse_valid(tu) | [
"def",
"parse",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"idx",
"=",
"clang",
".",
"cindex",
".",
"Index",
".",
"create",
"(",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
"tu",
"=",
"idx",
".",
"parse",
"(",
"name"... | 27.857143 | 5.428571 |
def _generate_notebook_by_difficulty_body(notebook_object, dict_by_difficulty):
"""
Internal function that is used for generation of the page where notebooks are organized by
difficulty level.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" cl... | [
"def",
"_generate_notebook_by_difficulty_body",
"(",
"notebook_object",
",",
"dict_by_difficulty",
")",
":",
"difficulty_keys",
"=",
"list",
"(",
"dict_by_difficulty",
".",
"keys",
"(",
")",
")",
"difficulty_keys",
".",
"sort",
"(",
")",
"for",
"difficulty",
"in",
... | 47.425 | 27.675 |
def log_request(
self, request: str, trim_log_values: bool = False, **kwargs: Any
) -> None:
"""
Log a request.
Args:
request: The JSON-RPC request string.
trim_log_values: Log an abbreviated version of the request.
"""
return log_(request, re... | [
"def",
"log_request",
"(",
"self",
",",
"request",
":",
"str",
",",
"trim_log_values",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"return",
"log_",
"(",
"request",
",",
"request_log",
",",
"\"info\"",
",",
... | 32.727273 | 22.545455 |
def update_path(self):
"""
Tries to update the $PATH automatically.
"""
if WINDOWS:
return self.add_to_windows_path()
# Updating any profile we can on UNIX systems
export_string = self.get_export_string()
addition = "\n{}\n".format(export_string)
... | [
"def",
"update_path",
"(",
"self",
")",
":",
"if",
"WINDOWS",
":",
"return",
"self",
".",
"add_to_windows_path",
"(",
")",
"# Updating any profile we can on UNIX systems",
"export_string",
"=",
"self",
".",
"get_export_string",
"(",
")",
"addition",
"=",
"\"\\n{}\\n... | 27.923077 | 15.769231 |
def distinct_column_values_at_locus(
self,
column,
feature,
contig,
position,
end=None,
strand=None):
"""
Gather all the distinct values for a property/column at some specified
locus.
Parameters
... | [
"def",
"distinct_column_values_at_locus",
"(",
"self",
",",
"column",
",",
"feature",
",",
"contig",
",",
"position",
",",
"end",
"=",
"None",
",",
"strand",
"=",
"None",
")",
":",
"return",
"self",
".",
"column_values_at_locus",
"(",
"column",
",",
"feature... | 26.636364 | 20.545455 |
def normpath(path):
"""
Normalize ``path``, collapsing redundant separators and up-level refs.
"""
scheme, netloc, path_ = parse(path)
return unparse(scheme, netloc, os.path.normpath(path_)) | [
"def",
"normpath",
"(",
"path",
")",
":",
"scheme",
",",
"netloc",
",",
"path_",
"=",
"parse",
"(",
"path",
")",
"return",
"unparse",
"(",
"scheme",
",",
"netloc",
",",
"os",
".",
"path",
".",
"normpath",
"(",
"path_",
")",
")"
] | 34.166667 | 12.5 |
def cmd_changealt(self, args):
'''change target altitude'''
if len(args) < 1:
print("usage: changealt <relaltitude>")
return
relalt = float(args[0])
self.master.mav.mission_item_send(self.settings.target_system,
self.setti... | [
"def",
"cmd_changealt",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"print",
"(",
"\"usage: changealt <relaltitude>\"",
")",
"return",
"relalt",
"=",
"float",
"(",
"args",
"[",
"0",
"]",
")",
"self",
".",
"master",... | 48.928571 | 17.5 |
def read_fits_spec(filename, ext=1, wave_col='WAVELENGTH', flux_col='FLUX',
wave_unit=u.AA, flux_unit=units.FLAM):
"""Read FITS spectrum.
Wavelength and flux units are extracted from ``TUNIT1`` and ``TUNIT2``
keywords, respectively, from data table (not primary) header.
If these keyw... | [
"def",
"read_fits_spec",
"(",
"filename",
",",
"ext",
"=",
"1",
",",
"wave_col",
"=",
"'WAVELENGTH'",
",",
"flux_col",
"=",
"'FLUX'",
",",
"wave_unit",
"=",
"u",
".",
"AA",
",",
"flux_unit",
"=",
"units",
".",
"FLAM",
")",
":",
"fs",
"=",
"fits",
"."... | 34.913043 | 21.652174 |
def publish_topology_description_changed(self, previous_description,
new_description, topology_id):
"""Publish a TopologyDescriptionChangedEvent to all topology listeners.
:Parameters:
- `previous_description`: The previous topology description.
... | [
"def",
"publish_topology_description_changed",
"(",
"self",
",",
"previous_description",
",",
"new_description",
",",
"topology_id",
")",
":",
"event",
"=",
"TopologyDescriptionChangedEvent",
"(",
"previous_description",
",",
"new_description",
",",
"topology_id",
")",
"f... | 47.647059 | 20.705882 |
def _appendComponent(self, baseGlyph, transformation=None, identifier=None, **kwargs):
"""
baseGlyph will be a valid glyph name.
The baseGlyph may or may not be in the layer.
offset will be a valid offset (x, y).
scale will be a valid scale (x, y).
identifier will be a v... | [
"def",
"_appendComponent",
"(",
"self",
",",
"baseGlyph",
",",
"transformation",
"=",
"None",
",",
"identifier",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pointPen",
"=",
"self",
".",
"getPointPen",
"(",
")",
"pointPen",
".",
"addComponent",
"(",
... | 38 | 17.75 |
def _labeled_uniform_sample(self, sample_size):
"""sample labeled entries uniformly"""
labeled_entries = self.dataset.get_labeled_entries()
samples = [labeled_entries[
self.random_state_.randint(0, len(labeled_entries))
]for _ in range(sample_size)]
return Dataset(*zi... | [
"def",
"_labeled_uniform_sample",
"(",
"self",
",",
"sample_size",
")",
":",
"labeled_entries",
"=",
"self",
".",
"dataset",
".",
"get_labeled_entries",
"(",
")",
"samples",
"=",
"[",
"labeled_entries",
"[",
"self",
".",
"random_state_",
".",
"randint",
"(",
"... | 46.571429 | 8.571429 |
def envelope(component, **kwargs):
"""
Create parameters for an envelope (usually will be attached to two stars solRad
that they can share a common-envelope)
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_component`
:parameter **kw... | [
"def",
"envelope",
"(",
"component",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"[",
"]",
"params",
"+=",
"[",
"FloatParameter",
"(",
"qualifier",
"=",
"'abun'",
",",
"value",
"=",
"kwargs",
".",
"get",
"(",
"'abun'",
",",
"0.",
")",
",",
"d... | 92.522727 | 77.295455 |
def swipe_by_percent(self, start_x, start_y, end_x, end_y, duration=1000):
"""
Swipe from one percent of the screen to another percent, for an optional duration.
Normal swipe fails to scale for different screen resolutions, this can be avoided using percent.
Args:
- start... | [
"def",
"swipe_by_percent",
"(",
"self",
",",
"start_x",
",",
"start_y",
",",
"end_x",
",",
"end_y",
",",
"duration",
"=",
"1000",
")",
":",
"width",
"=",
"self",
".",
"get_window_width",
"(",
")",
"height",
"=",
"self",
".",
"get_window_height",
"(",
")"... | 42.363636 | 20.727273 |
def _CreateUserIdentifier(identifier_type=None, value=None):
"""Creates a user identifier from the specified type and value.
Args:
identifier_type: a str specifying the type of user identifier.
value: a str value of the identifier; to be hashed using SHA-256 if needed.
Returns:
A dict specifying a u... | [
"def",
"_CreateUserIdentifier",
"(",
"identifier_type",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"if",
"identifier_type",
"in",
"_HASHED_IDENTIFIER_TYPES",
":",
"# If the user identifier type is a hashed type, normalize and hash the",
"# value.",
"value",
"=",
"has... | 31.363636 | 25.454545 |
def write(context):
"""Starts a new article"""
config = context.obj
title = click.prompt('Title')
author = click.prompt('Author', default=config.get('DEFAULT_AUTHOR'))
slug = slugify(title)
creation_date = datetime.now()
basename = '{:%Y-%m-%d}_{}.md'.format(creation_date, slug)
meta ... | [
"def",
"write",
"(",
"context",
")",
":",
"config",
"=",
"context",
".",
"obj",
"title",
"=",
"click",
".",
"prompt",
"(",
"'Title'",
")",
"author",
"=",
"click",
".",
"prompt",
"(",
"'Author'",
",",
"default",
"=",
"config",
".",
"get",
"(",
"'DEFAU... | 30.030303 | 20.939394 |
def geo_contains(left, right):
"""
Check if the first geometry contains the second one
Parameters
----------
left : geometry
right : geometry
Returns
-------
contains : bool scalar
"""
op = ops.GeoContains(left, right)
return op.to_expr() | [
"def",
"geo_contains",
"(",
"left",
",",
"right",
")",
":",
"op",
"=",
"ops",
".",
"GeoContains",
"(",
"left",
",",
"right",
")",
"return",
"op",
".",
"to_expr",
"(",
")"
] | 18.266667 | 19.333333 |
def process_request(self, request, credential=None):
"""
Process a KMIP request message.
This routine is the main driver of the KmipEngine. It breaks apart and
processes the request header, handles any message errors that may
result, and then passes the set of request batch item... | [
"def",
"process_request",
"(",
"self",
",",
"request",
",",
"credential",
"=",
"None",
")",
":",
"self",
".",
"_client_identity",
"=",
"[",
"None",
",",
"None",
"]",
"header",
"=",
"request",
".",
"request_header",
"# Process the protocol version",
"self",
"."... | 36.352459 | 19.352459 |
def identify_protocol(method, value):
# type: (str, Union[str, RequestType]) -> str
"""
Loop through protocols, import the protocol module and try to identify the id or request.
"""
for protocol_name in PROTOCOLS:
protocol = importlib.import_module(f"federation.protocols.{protocol_name}.prot... | [
"def",
"identify_protocol",
"(",
"method",
",",
"value",
")",
":",
"# type: (str, Union[str, RequestType]) -> str",
"for",
"protocol_name",
"in",
"PROTOCOLS",
":",
"protocol",
"=",
"importlib",
".",
"import_module",
"(",
"f\"federation.protocols.{protocol_name}.protocol\"",
... | 41.636364 | 17.090909 |
def pack(self):
"""
Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value
"""
value = self._get_calculated_value(self.value)
packed... | [
"def",
"pack",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_get_calculated_value",
"(",
"self",
".",
"value",
")",
"packed_value",
"=",
"self",
".",
"_pack_value",
"(",
"value",
")",
"size",
"=",
"self",
".",
"_get_calculated_size",
"(",
"self",
"... | 39.823529 | 20.411765 |
def prune_urls(url_set, start_url, allowed_list, ignored_list):
"""Prunes URLs that should be ignored."""
result = set()
for url in url_set:
allowed = False
for allow_url in allowed_list:
if url.startswith(allow_url):
allowed = True
break
... | [
"def",
"prune_urls",
"(",
"url_set",
",",
"start_url",
",",
"allowed_list",
",",
"ignored_list",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"url",
"in",
"url_set",
":",
"allowed",
"=",
"False",
"for",
"allow_url",
"in",
"allowed_list",
":",
"if",
"... | 23.333333 | 19.966667 |
def show_messages(self):
"""Show all messages."""
string = ''
if self.static_message is not None:
string += self.static_message.to_text()
for message in self.dynamic_messages:
string += message.to_text()
print(string) | [
"def",
"show_messages",
"(",
"self",
")",
":",
"string",
"=",
"''",
"if",
"self",
".",
"static_message",
"is",
"not",
"None",
":",
"string",
"+=",
"self",
".",
"static_message",
".",
"to_text",
"(",
")",
"for",
"message",
"in",
"self",
".",
"dynamic_mess... | 27.4 | 15.6 |
def console_user(username=False):
'''
Gets the UID or Username of the current console user.
:return: The uid or username of the console user.
:param bool username: Whether to return the username of the console
user instead of the UID. Defaults to False
:rtype: Interger of the UID, or a string... | [
"def",
"console_user",
"(",
"username",
"=",
"False",
")",
":",
"try",
":",
"# returns the 'st_uid' stat from the /dev/console file.",
"uid",
"=",
"os",
".",
"stat",
"(",
"'/dev/console'",
")",
"[",
"4",
"]",
"except",
"(",
"OSError",
",",
"IndexError",
")",
"... | 27.28125 | 24.71875 |
def _run_checks(self):
'''basic sanity checks for the file name (and others if needed) before
attempting parsing.
'''
if self.recipe is not None:
# Does the recipe provided exist?
if not os.path.exists(self.recipe):
bot.error("Cannot find %s, i... | [
"def",
"_run_checks",
"(",
"self",
")",
":",
"if",
"self",
".",
"recipe",
"is",
"not",
"None",
":",
"# Does the recipe provided exist?",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"recipe",
")",
":",
"bot",
".",
"error",
"(",
"\"C... | 35.769231 | 19.923077 |
def get_labels(input_dir):
"""Get a list of labels from preprocessed output dir."""
data_dir = _get_latest_data_dir(input_dir)
labels_file = os.path.join(data_dir, 'labels')
with file_io.FileIO(labels_file, 'r') as f:
labels = f.read().rstrip().split('\n')
return labels | [
"def",
"get_labels",
"(",
"input_dir",
")",
":",
"data_dir",
"=",
"_get_latest_data_dir",
"(",
"input_dir",
")",
"labels_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"'labels'",
")",
"with",
"file_io",
".",
"FileIO",
"(",
"labels_file",
... | 39.714286 | 8.285714 |
def get_file_extension_type(filename):
"""
Return the group associated to the file
:param filename:
:return: str
"""
ext = get_file_extension(filename)
if ext:
for name, group in EXTENSIONS.items():
if ext in group:
return name
return "OTHER" | [
"def",
"get_file_extension_type",
"(",
"filename",
")",
":",
"ext",
"=",
"get_file_extension",
"(",
"filename",
")",
"if",
"ext",
":",
"for",
"name",
",",
"group",
"in",
"EXTENSIONS",
".",
"items",
"(",
")",
":",
"if",
"ext",
"in",
"group",
":",
"return"... | 24.916667 | 11.083333 |
def cors(origins,
methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'],
max_age=None):
"""
Adds CORS headers to the decorated view function.
:param origins: Allowed origins... | [
"def",
"cors",
"(",
"origins",
",",
"methods",
"=",
"[",
"'HEAD'",
",",
"'OPTIONS'",
",",
"'GET'",
",",
"'POST'",
",",
"'PUT'",
",",
"'PATCH'",
",",
"'DELETE'",
"]",
",",
"headers",
"=",
"[",
"'Accept'",
",",
"'Accept-Language'",
",",
"'Content-Language'",... | 34.686047 | 21.593023 |
def ntoreturn(self):
"""Extract ntoreturn counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._ntoreturn | [
"def",
"ntoreturn",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_counters_calculated",
":",
"self",
".",
"_counters_calculated",
"=",
"True",
"self",
".",
"_extract_counters",
"(",
")",
"return",
"self",
".",
"_ntoreturn"
] | 33 | 11.285714 |
def list_machine_group(self, project_name, offset=0, size=100):
""" list machine group names in a project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type offset: int
:param offset: the of... | [
"def",
"list_machine_group",
"(",
"self",
",",
"project_name",
",",
"offset",
"=",
"0",
",",
"size",
"=",
"100",
")",
":",
"# need to use extended method to get more\r",
"if",
"int",
"(",
"size",
")",
"==",
"-",
"1",
"or",
"int",
"(",
"size",
")",
">",
"... | 35.827586 | 21.275862 |
def set_meta_rdf(self, rdf, fmt='n3'):
"""Set the metadata for this Point in rdf fmt
"""
evt = self._client._request_point_meta_set(self._type, self.__lid, self.__pid, rdf, fmt=fmt)
self._client._wait_and_except_if_failed(evt) | [
"def",
"set_meta_rdf",
"(",
"self",
",",
"rdf",
",",
"fmt",
"=",
"'n3'",
")",
":",
"evt",
"=",
"self",
".",
"_client",
".",
"_request_point_meta_set",
"(",
"self",
".",
"_type",
",",
"self",
".",
"__lid",
",",
"self",
".",
"__pid",
",",
"rdf",
",",
... | 50.8 | 14.8 |
def saturation(self, value):
"""Volume of water to volume of voids"""
value = clean_float(value)
if value is None:
return
try:
unit_moisture_weight = self.unit_moist_weight - self.unit_dry_weight
unit_moisture_volume = unit_moisture_weight / self._pw
... | [
"def",
"saturation",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"clean_float",
"(",
"value",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"unit_moisture_weight",
"=",
"self",
".",
"unit_moist_weight",
"-",
"self",
".",
"unit_dry_wei... | 44.090909 | 20.181818 |
def _find_conflicts_within_selection_set(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_typ... | [
"def",
"_find_conflicts_within_selection_set",
"(",
"context",
",",
"# type: ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"compared_fra... | 40.625 | 23.160714 |
def _key(self, block, name):
"""
Resolves `name` to a key, in the following form:
KeyValueStore.Key(
scope=field.scope,
user_id=student_id,
block_scope_id=block_id,
field_name=name,
block_family=block.entry_point,
)
"""... | [
"def",
"_key",
"(",
"self",
",",
"block",
",",
"name",
")",
":",
"field",
"=",
"self",
".",
"_getfield",
"(",
"block",
",",
"name",
")",
"if",
"field",
".",
"scope",
"in",
"(",
"Scope",
".",
"children",
",",
"Scope",
".",
"parent",
")",
":",
"blo... | 31.390244 | 13.97561 |
def add_waveform(self, waveform):
"""
Add a waveform to the plot.
:param waveform: the waveform to be added
:type waveform: :class:`~aeneas.plotter.PlotWaveform`
:raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform`
"""
... | [
"def",
"add_waveform",
"(",
"self",
",",
"waveform",
")",
":",
"if",
"not",
"isinstance",
"(",
"waveform",
",",
"PlotWaveform",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"waveform must be an instance of PlotWaveform\"",
",",
"None",
",",
"True",
",",
"TypeError"... | 43.083333 | 18.75 |
def make_sgf(
move_history,
result_string,
ruleset="Chinese",
komi=7.5,
white_name=PROGRAM_IDENTIFIER,
black_name=PROGRAM_IDENTIFIER,
comments=[]
):
"""Turn a game into SGF.
Doesn't handle handicap games or positions with incomplete history.
Args:
move_history: iterable... | [
"def",
"make_sgf",
"(",
"move_history",
",",
"result_string",
",",
"ruleset",
"=",
"\"Chinese\"",
",",
"komi",
"=",
"7.5",
",",
"white_name",
"=",
"PROGRAM_IDENTIFIER",
",",
"black_name",
"=",
"PROGRAM_IDENTIFIER",
",",
"comments",
"=",
"[",
"]",
")",
":",
"... | 28.782609 | 20.043478 |
def update(self, rid, data, raise_on_error=True):
"""Write updated cache data to the DataStore.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
... | [
"def",
"update",
"(",
"self",
",",
"rid",
",",
"data",
",",
"raise_on_error",
"=",
"True",
")",
":",
"cache_data",
"=",
"{",
"'cache-date'",
":",
"self",
".",
"_dt_to_epoch",
"(",
"datetime",
".",
"now",
"(",
")",
")",
",",
"'cache-data'",
":",
"data",... | 39.692308 | 21.076923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.