text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _CreateInput(structure) -> INPUT:
"""
Create Win32 struct `INPUT` for `SendInput`.
Return `INPUT`.
"""
if isinstance(structure, MOUSEINPUT):
return INPUT(InputType.Mouse, _INPUTUnion(mi=structure))
if isinstance(structure, KEYBDINPUT):
return INPUT(InputType.Keyboard, _INPUTU... | [
"def",
"_CreateInput",
"(",
"structure",
")",
"->",
"INPUT",
":",
"if",
"isinstance",
"(",
"structure",
",",
"MOUSEINPUT",
")",
":",
"return",
"INPUT",
"(",
"InputType",
".",
"Mouse",
",",
"_INPUTUnion",
"(",
"mi",
"=",
"structure",
")",
")",
"if",
"isin... | 41.25 | 0.001976 |
def _is_valid_integer(self, inpt, metadata):
"""Checks if input is a valid integer value"""
if not isinstance(inpt, int):
return False
if metadata.get_minimum_integer() and inpt < metadata.get_maximum_integer():
return False
if metadata.get_maximum_integer() and i... | [
"def",
"_is_valid_integer",
"(",
"self",
",",
"inpt",
",",
"metadata",
")",
":",
"if",
"not",
"isinstance",
"(",
"inpt",
",",
"int",
")",
":",
"return",
"False",
"if",
"metadata",
".",
"get_minimum_integer",
"(",
")",
"and",
"inpt",
"<",
"metadata",
".",... | 43 | 0.009488 |
def download_schema(uri, path, comment=None):
"""Download a schema from a specified URI and save it locally.
:param uri: url where the schema should be downloaded
:param path: local file path where the schema should be saved
:param comment: optional comment; if specified, will be added to
the d... | [
"def",
"download_schema",
"(",
"uri",
",",
"path",
",",
"comment",
"=",
"None",
")",
":",
"# if requests isn't available, warn and bail out",
"if",
"requests",
"is",
"None",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"req_requests_msg",
")",
"return",
"# shor... | 38.238095 | 0.001821 |
def getConfig(filepath=None): # pragma: no cover
"""
Get the Green config file settings.
All available config files are read. If settings are in multiple configs,
the last value encountered wins. Values specified on the command-line take
precedence over all config file settings.
Returns: A ... | [
"def",
"getConfig",
"(",
"filepath",
"=",
"None",
")",
":",
"# pragma: no cover",
"parser",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"filepaths",
"=",
"[",
"]",
"# Lowest priority goes first in the list",
"home",
"=",
"os",
".",
"getenv",
"(",
"\"HOME... | 32.803922 | 0.00058 |
def to_utf8(datas):
"""
Force utf8 string entries in the given datas
"""
res = datas
if isinstance(datas, dict):
res = {}
for key, value in datas.items():
key = to_utf8(key)
value = to_utf8(value)
res[key] = value
elif isinstance(datas, (list,... | [
"def",
"to_utf8",
"(",
"datas",
")",
":",
"res",
"=",
"datas",
"if",
"isinstance",
"(",
"datas",
",",
"dict",
")",
":",
"res",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"datas",
".",
"items",
"(",
")",
":",
"key",
"=",
"to_utf8",
"(",
"k... | 22.904762 | 0.001996 |
def posts(self):
"""Get posts, reloading the site if needed."""
rev = int(self.db.get('site:rev'))
if rev != self.revision:
self.reload_site()
return self._posts | [
"def",
"posts",
"(",
"self",
")",
":",
"rev",
"=",
"int",
"(",
"self",
".",
"db",
".",
"get",
"(",
"'site:rev'",
")",
")",
"if",
"rev",
"!=",
"self",
".",
"revision",
":",
"self",
".",
"reload_site",
"(",
")",
"return",
"self",
".",
"_posts"
] | 28.571429 | 0.009709 |
def drawPoint(self, x, y, silent=True):
"""
Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: Point X coordinate.
:param y1: Point Y coordinate.
:rtype: Nothing.
"""
start = tim... | [
"def",
"drawPoint",
"(",
"self",
",",
"x",
",",
"y",
",",
"silent",
"=",
"True",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"#Downsample the coordinates",
"x",
"=",
"int",
"(",
"x",
"/",
"config",
".",
"DOWNSAMPLING",
")",
"y",
"=",
"in... | 42 | 0.027716 |
def cluster_labels_A(hdf5_file, c, lock, I, rows_slice):
"""One of the task to be performed by a pool of subprocesses, as the first
step in identifying the cluster labels and indices of the cluster centers
for Affinity Propagation clustering.
"""
with Worker.hdf5_lock:
with tables.o... | [
"def",
"cluster_labels_A",
"(",
"hdf5_file",
",",
"c",
",",
"lock",
",",
"I",
",",
"rows_slice",
")",
":",
"with",
"Worker",
".",
"hdf5_lock",
":",
"with",
"tables",
".",
"open_file",
"(",
"hdf5_file",
",",
"'r+'",
")",
"as",
"fileh",
":",
"S",
"=",
... | 32.764706 | 0.015707 |
def create_assets_env(generator):
"""Define the assets environment and pass it to the generator."""
theme_static_dir = generator.settings['THEME_STATIC_DIR']
assets_destination = os.path.join(generator.output_path, theme_static_dir)
generator.env.assets_environment = Environment(
assets_destina... | [
"def",
"create_assets_env",
"(",
"generator",
")",
":",
"theme_static_dir",
"=",
"generator",
".",
"settings",
"[",
"'THEME_STATIC_DIR'",
"]",
"assets_destination",
"=",
"os",
".",
"path",
".",
"join",
"(",
"generator",
".",
"output_path",
",",
"theme_static_dir",... | 47.52 | 0.00165 |
def lambda_max(self):
"""Peak wavelength in Angstrom when the curve is expressed as
power density."""
return ((const.b_wien.value / self.temperature) * u.m).to(u.AA).value | [
"def",
"lambda_max",
"(",
"self",
")",
":",
"return",
"(",
"(",
"const",
".",
"b_wien",
".",
"value",
"/",
"self",
".",
"temperature",
")",
"*",
"u",
".",
"m",
")",
".",
"to",
"(",
"u",
".",
"AA",
")",
".",
"value"
] | 48 | 0.010256 |
def copy(self):
"""Create a shallow copy of self.
This runs in O(len(self.num_unique_elements()))
"""
out = self._from_iterable(None)
out._dict = self._dict.copy()
out._size = self._size
return out | [
"def",
"copy",
"(",
"self",
")",
":",
"out",
"=",
"self",
".",
"_from_iterable",
"(",
"None",
")",
"out",
".",
"_dict",
"=",
"self",
".",
"_dict",
".",
"copy",
"(",
")",
"out",
".",
"_size",
"=",
"self",
".",
"_size",
"return",
"out"
] | 22.666667 | 0.042453 |
def solidity_names(code): # pylint: disable=too-many-branches
""" Return the library and contract names in order of appearence. """
names = []
in_string = None
backslash = False
comment = None
# "parse" the code by hand to handle the corner cases:
# - the contract or library can be inside... | [
"def",
"solidity_names",
"(",
"code",
")",
":",
"# pylint: disable=too-many-branches",
"names",
"=",
"[",
"]",
"in_string",
"=",
"None",
"backslash",
"=",
"False",
"comment",
"=",
"None",
"# \"parse\" the code by hand to handle the corner cases:",
"# - the contract or libr... | 33.33871 | 0.00235 |
def get_enroll(self):
"""Returns new enroll seed"""
devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()]
enroll = start_register(self.__appid, devices)
enroll['status'] = 'ok'
session['_u2f_enroll_'] = enroll.json
return enroll | [
"def",
"get_enroll",
"(",
"self",
")",
":",
"devices",
"=",
"[",
"DeviceRegistration",
".",
"wrap",
"(",
"device",
")",
"for",
"device",
"in",
"self",
".",
"__get_u2f_devices",
"(",
")",
"]",
"enroll",
"=",
"start_register",
"(",
"self",
".",
"__appid",
... | 33.333333 | 0.012987 |
def validate(message, **config):
""" Return true or false if the message is signed appropriately. """
if not _validate_implementations:
init(**config)
cfg = copy.deepcopy(config)
if 'gpg_home' not in cfg:
cfg['gpg_home'] = os.path.expanduser('~/.gnupg/')
if 'ssldir' not in cfg:
... | [
"def",
"validate",
"(",
"message",
",",
"*",
"*",
"config",
")",
":",
"if",
"not",
"_validate_implementations",
":",
"init",
"(",
"*",
"*",
"config",
")",
"cfg",
"=",
"copy",
".",
"deepcopy",
"(",
"config",
")",
"if",
"'gpg_home'",
"not",
"in",
"cfg",
... | 34.605263 | 0.00074 |
def _psicomputations(self, kern, Z, variational_posterior, return_psi2_n=False):
"""
Z - MxQ
mu - NxQ
S - NxQ
"""
variance, lengthscale = kern.variance, kern.lengthscale
N,M,Q = self.get_dimensions(Z, variational_posterior)
self._initGPUCache(N,M,Q)
... | [
"def",
"_psicomputations",
"(",
"self",
",",
"kern",
",",
"Z",
",",
"variational_posterior",
",",
"return_psi2_n",
"=",
"False",
")",
":",
"variance",
",",
"lengthscale",
"=",
"kern",
".",
"variance",
",",
"kern",
".",
"lengthscale",
"N",
",",
"M",
",",
... | 58.567568 | 0.014526 |
def toTag(self, output):
''' This methods returns all data of this feed as feed xml tag
:param output: XML Document to which the data should be added
:type output: xml.dom.DOMImplementation.createDocument
'''
feed = output.createElement('feed')
feed.setAttribute('name', ... | [
"def",
"toTag",
"(",
"self",
",",
"output",
")",
":",
"feed",
"=",
"output",
".",
"createElement",
"(",
"'feed'",
")",
"feed",
".",
"setAttribute",
"(",
"'name'",
",",
"self",
".",
"name",
")",
"feed",
".",
"setAttribute",
"(",
"'priority'",
",",
"str"... | 36.354839 | 0.001729 |
def cov_from_trace(self, trace=slice(None)):
"""Define the jump distribution covariance matrix from the object's
stored trace.
:Parameters:
- `trace` : slice or int
A slice for the stochastic object's trace in the last chain, or a
an integer indicating the how many o... | [
"def",
"cov_from_trace",
"(",
"self",
",",
"trace",
"=",
"slice",
"(",
"None",
")",
")",
":",
"n",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"stochastics",
":",
"n",
".",
"append",
"(",
"s",
".",
"trace",
".",
"length",
"(",
")",
")",
"n",
... | 30.25 | 0.002288 |
def altimeter(alt: Number, unit: str = 'hPa') -> str:
"""
Formats the altimter element into a string with hPa and inHg values
Ex: 30.11 inHg (10.20 hPa)
"""
if not (alt and unit in ('hPa', 'inHg')):
return ''
if unit == 'hPa':
value = alt.repr
converted = alt.value / 33.... | [
"def",
"altimeter",
"(",
"alt",
":",
"Number",
",",
"unit",
":",
"str",
"=",
"'hPa'",
")",
"->",
"str",
":",
"if",
"not",
"(",
"alt",
"and",
"unit",
"in",
"(",
"'hPa'",
",",
"'inHg'",
")",
")",
":",
"return",
"''",
"if",
"unit",
"==",
"'hPa'",
... | 36.705882 | 0.001563 |
def deserialize(self, data=None):
""" Invoke the deserializer
If the payload is a collection (more than 1 records)
then a list will be returned of normalized dict's.
If the payload is a single item then the normalized
dict will be returned (not a list)
:return: list or... | [
"def",
"deserialize",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"data",
"=",
"[",
"]",
"if",
"self",
".",
"req",
".",
"content_type_params",
".",
"get",
"(",
"'header'",
")",
"!=",
"'present'",
":",
"abort",
"(",
"exceptions",
".",
"InvalidReque... | 30.894737 | 0.001652 |
def record(self, pipeline_name, from_study):
"""
Returns the provenance record for a given pipeline
Parameters
----------
pipeline_name : str
The name of the pipeline that generated the record
from_study : str
The name of the study that the pipeli... | [
"def",
"record",
"(",
"self",
",",
"pipeline_name",
",",
"from_study",
")",
":",
"try",
":",
"return",
"self",
".",
"_records",
"[",
"(",
"pipeline_name",
",",
"from_study",
")",
"]",
"except",
"KeyError",
":",
"found",
"=",
"[",
"]",
"for",
"sname",
"... | 38.84375 | 0.00157 |
def wash_and_repair_reference_line(line):
"""Wash a reference line of undesirable characters (such as poorly-encoded
letters, etc), and repair any errors (such as broken URLs) if possible.
@param line: (string) the reference line to be washed/repaired.
@return: (string) the washed reference lin... | [
"def",
"wash_and_repair_reference_line",
"(",
"line",
")",
":",
"# repair URLs in line:",
"line",
"=",
"repair_broken_urls",
"(",
"line",
")",
"# Replace various undesirable characters with their alternatives:",
"line",
"=",
"replace_undesirable_characters",
"(",
"line",
")",
... | 45.333333 | 0.002401 |
def set_sides(self, key, data, field, local=False):
"""
Assign data on the 'key' tile to all the edges
"""
for side in ['left', 'right', 'top', 'bottom']:
self.set(key, data, field, side, local) | [
"def",
"set_sides",
"(",
"self",
",",
"key",
",",
"data",
",",
"field",
",",
"local",
"=",
"False",
")",
":",
"for",
"side",
"in",
"[",
"'left'",
",",
"'right'",
",",
"'top'",
",",
"'bottom'",
"]",
":",
"self",
".",
"set",
"(",
"key",
",",
"data"... | 38.833333 | 0.008403 |
def _sections_to_variance_sections(self, sections_over_time):
'''Computes the variance of corresponding sections over time.
Returns:
a list of np arrays.
'''
variance_sections = []
for i in range(len(sections_over_time[0])):
time_sections = [sections[i] for sections in sections_over_ti... | [
"def",
"_sections_to_variance_sections",
"(",
"self",
",",
"sections_over_time",
")",
":",
"variance_sections",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sections_over_time",
"[",
"0",
"]",
")",
")",
":",
"time_sections",
"=",
"[",
"section... | 30.571429 | 0.00907 |
def config_parse(files=None, config=None, config_profile=".fissconfig", **kwargs):
'''
Read initial configuration state, from named config files; store
this state within a config dictionary (which may be nested) whose keys may
also be referenced as attributes (safely, defaulting to None if unset). A
... | [
"def",
"config_parse",
"(",
"files",
"=",
"None",
",",
"config",
"=",
"None",
",",
"config_profile",
"=",
"\".fissconfig\"",
",",
"*",
"*",
"kwargs",
")",
":",
"local_config",
"=",
"config",
"config",
"=",
"__fcconfig",
"cfgparser",
"=",
"configparser",
".",... | 39.064516 | 0.002014 |
def start_listener_thread(self, timeout_ms=30000, exception_handler=None):
""" Start a listener thread to listen for events in the background.
Args:
timeout (int): How long to poll the Home Server for before
retrying.
exception_handler (func(exception)): Optional ... | [
"def",
"start_listener_thread",
"(",
"self",
",",
"timeout_ms",
"=",
"30000",
",",
"exception_handler",
"=",
"None",
")",
":",
"try",
":",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"listen_forever",
",",
"args",
"=",
"(",
"timeout_ms",
",",... | 41.7 | 0.002345 |
def send_response(self, response_dict):
"""
Encode a response according to the request.
:param dict response_dict: the response to send
:raises: :class:`tornado.web.HTTPError` if no acceptable content
type exists
This method will encode `response_dict` using the mo... | [
"def",
"send_response",
"(",
"self",
",",
"response_dict",
")",
":",
"accept",
"=",
"headers",
".",
"parse_http_accept_header",
"(",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Accept'",
",",
"'*/*'",
")",
")",
"try",
":",
"selected",
",",
... | 44.956522 | 0.000947 |
def getDetectorClassConstructors(detectors):
"""
Takes in names of detectors. Collects class names that correspond to those
detectors and returns them in a dict. The dict maps detector name to class
names. Assumes the detectors have been imported.
"""
detectorConstructors = {
d : globals()[detectorNameToC... | [
"def",
"getDetectorClassConstructors",
"(",
"detectors",
")",
":",
"detectorConstructors",
"=",
"{",
"d",
":",
"globals",
"(",
")",
"[",
"detectorNameToClass",
"(",
"d",
")",
"]",
"for",
"d",
"in",
"detectors",
"}",
"return",
"detectorConstructors"
] | 37 | 0.015831 |
def validate(cls, mapper_spec):
"""Inherit docs."""
params = _get_params(mapper_spec)
if cls.ENTITY_KIND_PARAM not in params:
raise BadReaderParamsError("Missing input reader parameter 'entity_kind'")
if cls.BATCH_SIZE_PARAM in params:
try:
batch_size = int(params[cls.BATCH_SIZE_PARA... | [
"def",
"validate",
"(",
"cls",
",",
"mapper_spec",
")",
":",
"params",
"=",
"_get_params",
"(",
"mapper_spec",
")",
"if",
"cls",
".",
"ENTITY_KIND_PARAM",
"not",
"in",
"params",
":",
"raise",
"BadReaderParamsError",
"(",
"\"Missing input reader parameter 'entity_kin... | 45.782609 | 0.010228 |
def separate_directions(di_block):
"""
Separates set of directions into two modes based on principal direction
Parameters
_______________
di_block : block of nested dec,inc pairs
Return
mode_1_block,mode_2_block : two lists of nested dec,inc pairs
"""
ppars = doprinc(di_block)
... | [
"def",
"separate_directions",
"(",
"di_block",
")",
":",
"ppars",
"=",
"doprinc",
"(",
"di_block",
")",
"di_df",
"=",
"pd",
".",
"DataFrame",
"(",
"di_block",
")",
"# turn into a data frame for easy filtering",
"di_df",
".",
"columns",
"=",
"[",
"'dec'",
",",
... | 35.043478 | 0.001208 |
def save_used_registers(self):
"""Pushes all used working registers before function call"""
used = self.used_registers[:]
del self.used_registers[:]
self.used_registers_stack.append(used[:])
used.sort()
for reg in used:
self.newline_text("PUSH\t%s" % Sh... | [
"def",
"save_used_registers",
"(",
"self",
")",
":",
"used",
"=",
"self",
".",
"used_registers",
"[",
":",
"]",
"del",
"self",
".",
"used_registers",
"[",
":",
"]",
"self",
".",
"used_registers_stack",
".",
"append",
"(",
"used",
"[",
":",
"]",
")",
"u... | 43.3 | 0.00905 |
def token(config, token):
"""Store and fetch a GitHub access token"""
if not token:
info_out(
"To generate a personal API token, go to:\n\n\t"
"https://github.com/settings/tokens\n\n"
"To read more about it, go to:\n\n\t"
"https://help.github.com/articles/... | [
"def",
"token",
"(",
"config",
",",
"token",
")",
":",
"if",
"not",
"token",
":",
"info_out",
"(",
"\"To generate a personal API token, go to:\\n\\n\\t\"",
"\"https://github.com/settings/tokens\\n\\n\"",
"\"To read more about it, go to:\\n\\n\\t\"",
"\"https://help.github.com/artic... | 39.633333 | 0.002463 |
def batch(collection, method, processes=None, batch_size=None, quiet=False,
kwargs_to_dump=None, args=None, **kwargs):
'''Processes a collection in parallel batches,
each batch processes in series on a single process.
Running batches in parallel can be more effficient that splitting a list across... | [
"def",
"batch",
"(",
"collection",
",",
"method",
",",
"processes",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"kwargs_to_dump",
"=",
"None",
",",
"args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"proce... | 28.785714 | 0.002399 |
def form_valid_bridge(self, form, field, model, related_field, error_message):
"""
call from form_valid.
@form: it is form of form_valid (type: form)
@field: name of the form field referring to the brigde (type: string)
@model: form's model (type class)
@related_field: na... | [
"def",
"form_valid_bridge",
"(",
"self",
",",
"form",
",",
"field",
",",
"model",
",",
"related_field",
",",
"error_message",
")",
":",
"# get instance of selected external object",
"external",
"=",
"form",
".",
"cleaned_data",
"[",
"field",
"]",
"related_object",
... | 50.510638 | 0.002066 |
def get_context(self):
" Get context to render the template. "
return {
'content_type_name' : str(self.name),
'content_type_verbose_name' : self.verbose_name,
'content_type_verbose_name_plural' : self.verbose_name_plural,
'object' : self.ob... | [
"def",
"get_context",
"(",
"self",
")",
":",
"return",
"{",
"'content_type_name'",
":",
"str",
"(",
"self",
".",
"name",
")",
",",
"'content_type_verbose_name'",
":",
"self",
".",
"verbose_name",
",",
"'content_type_verbose_name_plural'",
":",
"self",
".",
"verb... | 39.333333 | 0.019337 |
def p_continue_statement_1(self, p):
"""continue_statement : CONTINUE SEMI
| CONTINUE AUTOSEMI
"""
p[0] = self.asttypes.Continue()
p[0].setpos(p) | [
"def",
"p_continue_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Continue",
"(",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | 33.666667 | 0.009662 |
def folder_path_for_package(cls, package: ecore.EPackage):
"""Returns path to folder holding generated artifact for given element."""
parent = package.eContainer()
if parent:
return os.path.join(cls.folder_path_for_package(parent), package.name)
return package.name | [
"def",
"folder_path_for_package",
"(",
"cls",
",",
"package",
":",
"ecore",
".",
"EPackage",
")",
":",
"parent",
"=",
"package",
".",
"eContainer",
"(",
")",
"if",
"parent",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"cls",
".",
"folder_path_for... | 50.666667 | 0.012945 |
def add_local_option(self, *args, **kw):
"""
Adds a local option to the parser.
This is initiated by a SetOption() call to add a user-defined
command-line option. We add the option to a separate option
group for the local options, creating the group if necessary.
"""
... | [
"def",
"add_local_option",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"group",
"=",
"self",
".",
"local_option_group",
"except",
"AttributeError",
":",
"group",
"=",
"SConsOptionGroup",
"(",
"self",
",",
"'Local Options'",
")... | 41.9 | 0.001555 |
def get_docstring(target) -> str:
"""
Retrieves the documentation string from the target object and returns it
after removing insignificant whitespace
:param target:
The object for which the doc string should be retrieved
:return:
The cleaned documentation string for the target. If ... | [
"def",
"get_docstring",
"(",
"target",
")",
"->",
"str",
":",
"raw",
"=",
"getattr",
"(",
"target",
",",
"'__doc__'",
")",
"if",
"raw",
"is",
"None",
":",
"return",
"''",
"return",
"textwrap",
".",
"dedent",
"(",
"raw",
")"
] | 27.277778 | 0.001969 |
def _build_option_description(k):
""" Builds a formatted description of a registered option and prints it """
o = _get_registered_option(k)
d = _get_deprecated_option(k)
s = '{k} '.format(k=k)
if o.doc:
s += '\n'.join(o.doc.strip().split('\n'))
else:
s += 'No description avail... | [
"def",
"_build_option_description",
"(",
"k",
")",
":",
"o",
"=",
"_get_registered_option",
"(",
"k",
")",
"d",
"=",
"_get_deprecated_option",
"(",
"k",
")",
"s",
"=",
"'{k} '",
".",
"format",
"(",
"k",
"=",
"k",
")",
"if",
"o",
".",
"doc",
":",
"s",... | 25.833333 | 0.001555 |
def _check_validity(self, i, j, height, width):
"""
check if a rectangle (i, j, height, width) can be put into self.output
"""
return all(self._check_cell_validity(ii, jj) for ii in range(i, i+height) for jj in range(j, j+width)) | [
"def",
"_check_validity",
"(",
"self",
",",
"i",
",",
"j",
",",
"height",
",",
"width",
")",
":",
"return",
"all",
"(",
"self",
".",
"_check_cell_validity",
"(",
"ii",
",",
"jj",
")",
"for",
"ii",
"in",
"range",
"(",
"i",
",",
"i",
"+",
"height",
... | 51.4 | 0.011494 |
def fetch_open_data(cls, flag, start, end, **kwargs):
"""Fetch Open Data timeline segments into a flag.
flag : `str`
the name of the flag to query
start : `int`, `str`
the GPS start time (or parseable date string) to query
end : `int`, `str`
the GPS... | [
"def",
"fetch_open_data",
"(",
"cls",
",",
"flag",
",",
"start",
",",
"end",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"=",
"to_gps",
"(",
"start",
")",
".",
"gpsSeconds",
"end",
"=",
"to_gps",
"(",
"end",
")",
".",
"gpsSeconds",
"known",
"=",
"[... | 37.816327 | 0.001052 |
def bound_weights(weights, minimum=None, maximum=None):
"""
Bound a weight list so that all outcomes fit within specified bounds.
The probability distribution within the ``minimum`` and ``maximum``
values remains the same. Weights in the list with outcomes outside of
``minimum`` and ``maximum`` are... | [
"def",
"bound_weights",
"(",
"weights",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
")",
":",
"# Copy weights to avoid side-effects",
"bounded_weights",
"=",
"weights",
"[",
":",
"]",
"# Remove weights outside of minimum and maximum",
"if",
"minimum",
"i... | 40.870968 | 0.000385 |
def get_entry_id(entry, fullpath, assign_id):
""" Get or generate an entry ID for an entry """
warn_duplicate = False
if 'Entry-ID' in entry:
entry_id = int(entry['Entry-ID'])
else:
entry_id = None
# See if we've inadvertently duplicated an entry ID
if entry_id:
try:
... | [
"def",
"get_entry_id",
"(",
"entry",
",",
"fullpath",
",",
"assign_id",
")",
":",
"warn_duplicate",
"=",
"False",
"if",
"'Entry-ID'",
"in",
"entry",
":",
"entry_id",
"=",
"int",
"(",
"entry",
"[",
"'Entry-ID'",
"]",
")",
"else",
":",
"entry_id",
"=",
"No... | 37.037037 | 0.001461 |
def segments_distance(segment1, segment2):
"""Calculate the distance between two line segments in the plane.
>>> a = LineSegment(Point(1,0), Point(2,0))
>>> b = LineSegment(Point(0,1), Point(0,2))
>>> "%0.2f" % segments_distance(a, b)
'1.41'
>>> c = LineSegment(Point(0,0), Point(5,5))
>>> d... | [
"def",
"segments_distance",
"(",
"segment1",
",",
"segment2",
")",
":",
"assert",
"isinstance",
"(",
"segment1",
",",
"LineSegment",
")",
",",
"\"segment1 is not a LineSegment, but a %s\"",
"%",
"type",
"(",
"segment1",
")",
"assert",
"isinstance",
"(",
"segment2",
... | 41.964286 | 0.000832 |
def main(arguments=None):
"""Command-line entry point.
:param arguments: List of strings that contain the command-line arguments.
When ``None``, the command-line arguments are looked up in ``sys.argv``
(``sys.argv[0]`` is ignored).
:return: This function has no return value.
:raise System... | [
"def",
"main",
"(",
"arguments",
"=",
"None",
")",
":",
"# Parse command-line arguments.",
"if",
"arguments",
"is",
"None",
":",
"arguments",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"arguments",
"=",
"cli",
".",
"parse_args",
"(",
"arguments",
")",
... | 31.658537 | 0.000747 |
def cancel(self, order_id):
"""Cancel an ordered SSL certificate."""
response = self.request(E.cancelSslCertRequest(
E.id(order_id)
))
return int(response.data.id) | [
"def",
"cancel",
"(",
"self",
",",
"order_id",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"E",
".",
"cancelSslCertRequest",
"(",
"E",
".",
"id",
"(",
"order_id",
")",
")",
")",
"return",
"int",
"(",
"response",
".",
"data",
".",
"id",
... | 25.25 | 0.009569 |
def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '' and 'ascii'.
If '' is specified, the primary d... | [
"def",
"list_files",
"(",
"tag",
"=",
"None",
",",
"sat_id",
"=",
"None",
",",
"data_path",
"=",
"None",
",",
"format_str",
"=",
"None",
")",
":",
"import",
"sys",
"#if tag == 'ionprf':",
"# # from_os constructor currently doesn't work because of the variable ",
"#... | 41.272727 | 0.009681 |
def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline):
"""Produce a plain-text representation of the table."""
lines = []
hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
pad = fmt.padding
headerrow = fmt.headerrow
padded_widths = [(w + 2 * pad) fo... | [
"def",
"_format_table",
"(",
"fmt",
",",
"headers",
",",
"rows",
",",
"colwidths",
",",
"colaligns",
",",
"is_multiline",
")",
":",
"lines",
"=",
"[",
"]",
"hidden",
"=",
"fmt",
".",
"with_header_hide",
"if",
"(",
"headers",
"and",
"fmt",
".",
"with_head... | 41.658537 | 0.001716 |
def initializing(self):
"""Subscribe to a channel. Received messages must be acknowledged."""
self.subid = self._transport.subscribe(
"transient.transaction", self.receive_message, acknowledgement=True
) | [
"def",
"initializing",
"(",
"self",
")",
":",
"self",
".",
"subid",
"=",
"self",
".",
"_transport",
".",
"subscribe",
"(",
"\"transient.transaction\"",
",",
"self",
".",
"receive_message",
",",
"acknowledgement",
"=",
"True",
")"
] | 47 | 0.008368 |
def init_db(self):
'''initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db
'''
# Database Setup, use default if uri not provided
if self.database == 'sqlite':
db_path = os.path.join(EXPFACTORY_DATA, '%s.db' % EXPFACTORY_SUBID... | [
"def",
"init_db",
"(",
"self",
")",
":",
"# Database Setup, use default if uri not provided",
"if",
"self",
".",
"database",
"==",
"'sqlite'",
":",
"db_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"EXPFACTORY_DATA",
",",
"'%s.db'",
"%",
"EXPFACTORY_SUBID",
"... | 40.84 | 0.001914 |
def from_array(cls, array):
"""Return a |Date| instance based on date information (year,
month, day, hour, minute, second) stored as the first entries of
the successive rows of a |numpy.ndarray|.
>>> from hydpy import Date
>>> import numpy
>>> array1d = numpy.array([1992... | [
"def",
"from_array",
"(",
"cls",
",",
"array",
")",
":",
"intarray",
"=",
"numpy",
".",
"array",
"(",
"array",
",",
"dtype",
"=",
"int",
")",
"for",
"dummy",
"in",
"range",
"(",
"1",
",",
"array",
".",
"ndim",
")",
":",
"intarray",
"=",
"intarray",... | 36.769231 | 0.002039 |
def add_missing_row(
df: pd.DataFrame,
id_cols: List[str],
reference_col: str,
complete_index: Union[Dict[str, str], List[str]] = None,
method: str = None,
cols_to_keep: List[str] = None
) -> pd.DataFrame:
"""
Add missing row to a df base on a reference column
---
### Parameter... | [
"def",
"add_missing_row",
"(",
"df",
":",
"pd",
".",
"DataFrame",
",",
"id_cols",
":",
"List",
"[",
"str",
"]",
",",
"reference_col",
":",
"str",
",",
"complete_index",
":",
"Union",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"List",
"[",
"str",
... | 33.054054 | 0.001852 |
def upload_to_picture(instance, filename):
"""
Uploads a picture for a user to the ``ACCOUNTS_PICTURE_PATH`` and
saving it under unique hash for the image. This is for privacy
reasons so others can't just browse through the picture directory.
"""
extension = filename.split('.')[-1].lower()
... | [
"def",
"upload_to_picture",
"(",
"instance",
",",
"filename",
")",
":",
"extension",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"salt",
",",
"hash",
"=",
"generate_sha1",
"(",
"instance",
".",
"id",
")... | 44.1875 | 0.009695 |
def compose_atom_list(*args):
"""
Return an `atom list` from elements and/or atom ids and coordinates.
An `atom list` is a special object that some pywindowfunctions uses.
It is a nested list of lists with each individual list containing:
1. [[element, coordinates (x, y, z)], ...]
2. ... | [
"def",
"compose_atom_list",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"atom_list",
"=",
"[",
"[",
"i",
"[",
"0",
"]",
",",
"round",
"(",
"float",
"(",
"i",
"[",
"1",
"]",
")",
",",
"8",
")",
",",
"round",
"(... | 29.25 | 0.000517 |
def validate_argmin_with_skipna(skipna, args, kwargs):
"""
If 'Series.argmin' is called via the 'numpy' library,
the third parameter in its signature is 'out', which
takes either an ndarray or 'None', so check if the
'skipna' parameter is either an instance of ndarray or
is None, since 'skipna' ... | [
"def",
"validate_argmin_with_skipna",
"(",
"skipna",
",",
"args",
",",
"kwargs",
")",
":",
"skipna",
",",
"args",
"=",
"process_skipna",
"(",
"skipna",
",",
"args",
")",
"validate_argmin",
"(",
"args",
",",
"kwargs",
")",
"return",
"skipna"
] | 37 | 0.002198 |
def DKL(arrays):
"""
Compute the Kullback-Leibler divergence from one distribution Q to another
P, where Q and P are represented by a set of samples.
Parameters
----------
arrays: tuple(1D numpy.array,1D numpy.array)
samples defining distributions P & Q respectively
Returns
---... | [
"def",
"DKL",
"(",
"arrays",
")",
":",
"samples",
",",
"prior_samples",
"=",
"arrays",
"samples",
"=",
"samples",
"[",
"~",
"numpy",
".",
"isnan",
"(",
"samples",
")",
"]",
"prior_samples",
"=",
"prior_samples",
"[",
"~",
"numpy",
".",
"isnan",
"(",
"p... | 29.318182 | 0.001502 |
def _send_scp(self, x, y, p, *args, **kwargs):
"""Determine the best connection to use to send an SCP packet and use
it to transmit.
This internal version of the method is identical to send_scp except it
has positional arguments for x, y and p.
See the arguments for
:py... | [
"def",
"_send_scp",
"(",
"self",
",",
"x",
",",
"y",
",",
"p",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Determine the size of packet we expect in return, this is usually the",
"# size that we are informed we should expect by SCAMP/SARK or else is",
"# the def... | 40.190476 | 0.002315 |
def login(request,
config_loader_path=None,
wayf_template='djangosaml2/wayf.html',
authorization_error_template='djangosaml2/auth_error.html',
post_binding_form_template='djangosaml2/post_binding_form.html'):
"""SAML Authorization Request initiator
This view initiates th... | [
"def",
"login",
"(",
"request",
",",
"config_loader_path",
"=",
"None",
",",
"wayf_template",
"=",
"'djangosaml2/wayf.html'",
",",
"authorization_error_template",
"=",
"'djangosaml2/auth_error.html'",
",",
"post_binding_form_template",
"=",
"'djangosaml2/post_binding_form.html'... | 46.538961 | 0.00123 |
def create_asset(self, project, atype=None, shot=None, asset=None):
"""Create and return a new asset
:param project: the project for the asset
:type project: :class:`jukeboxcore.djadapter.models.Project`
:param atype: the assettype of the asset
:type atype: :class:`jukeboxcore.d... | [
"def",
"create_asset",
"(",
"self",
",",
"project",
",",
"atype",
"=",
"None",
",",
"shot",
"=",
"None",
",",
"asset",
"=",
"None",
")",
":",
"element",
"=",
"shot",
"or",
"asset",
"dialog",
"=",
"AssetCreatorDialog",
"(",
"project",
"=",
"project",
",... | 42.909091 | 0.002073 |
def sort_resources(cls, request, resources, fail_enum, header_proto=None):
"""Sorts a list of resources based on a list of sort controls
Args:
request (object): The parsed protobuf request object
resources (list of objects): The resources to be sorted
fail_enum (int,... | [
"def",
"sort_resources",
"(",
"cls",
",",
"request",
",",
"resources",
",",
"fail_enum",
",",
"header_proto",
"=",
"None",
")",
":",
"if",
"not",
"request",
".",
"sorting",
":",
"return",
"resources",
"value_handlers",
"=",
"cls",
".",
"_get_handler_set",
"(... | 36.137931 | 0.001859 |
def xyz2rgb(x__, y__, z__):
"""XYZ colorspace to RGB
"""
x2_ = x__ / 100.0
y2_ = y__ / 100.0
z2_ = z__ / 100.0
r__ = x2_ * 3.2406 + y2_ * -1.5372 + z2_ * -0.4986
g__ = x2_ * -0.9689 + y2_ * 1.8758 + z2_ * 0.0415
b__ = x2_ * 0.0557 + y2_ * -0.2040 + z2_ * 1.0570
def finv(arr):
... | [
"def",
"xyz2rgb",
"(",
"x__",
",",
"y__",
",",
"z__",
")",
":",
"x2_",
"=",
"x__",
"/",
"100.0",
"y2_",
"=",
"y__",
"/",
"100.0",
"z2_",
"=",
"z__",
"/",
"100.0",
"r__",
"=",
"x2_",
"*",
"3.2406",
"+",
"y2_",
"*",
"-",
"1.5372",
"+",
"z2_",
"... | 28.105263 | 0.01087 |
def cond(pred, true_fn=None, false_fn=None, name=None):
"""Return either `true_fn()` if predicate `pred` is true else `false_fn()`.
If `pred` is a bool or has a constant value, we return either `true_fn()`
or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both.
Arguments:
pred: A scalar ... | [
"def",
"cond",
"(",
"pred",
",",
"true_fn",
"=",
"None",
",",
"false_fn",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"callable",
"(",
"true_fn",
")",
":",
"raise",
"TypeError",
"(",
"'`true_fn` must be callable.'",
")",
"if",
"not",
... | 33.9375 | 0.008057 |
def output_compose(info, image_info):
'''output as docker-compose format'''
container = info['Name'][1:]
conf = info['Config']
hconf = info['HostConfig']
compose = {}
compose['container_name'] = str(container)
compose['image'] = str(conf['Image'])
# Volumes
if 'Binds' in hconf an... | [
"def",
"output_compose",
"(",
"info",
",",
"image_info",
")",
":",
"container",
"=",
"info",
"[",
"'Name'",
"]",
"[",
"1",
":",
"]",
"conf",
"=",
"info",
"[",
"'Config'",
"]",
"hconf",
"=",
"info",
"[",
"'HostConfig'",
"]",
"compose",
"=",
"{",
"}",
... | 34.029703 | 0.000848 |
def create_wiki_page():
"""
for http://archive.worldofdragon.org/index.php?title=CharMap
"""
print (
'{| class="wikitable"'
' style="font-family: monospace;'
' background-color:#ffffcc;"'
' cellpadding="10"'
)
print("|-")
print("! POKE")
print("value")
... | [
"def",
"create_wiki_page",
"(",
")",
":",
"print",
"(",
"'{| class=\"wikitable\"'",
"' style=\"font-family: monospace;'",
"' background-color:#ffffcc;\"'",
"' cellpadding=\"10\"'",
")",
"print",
"(",
"\"|-\"",
")",
"print",
"(",
"\"! POKE\"",
")",
"print",
"(",
"\"value\"... | 25.972222 | 0.002062 |
def split_lines(source, maxline=79):
"""Split inputs according to lines.
If a line is short enough, just yield it.
Otherwise, fix it.
"""
result = []
extend = result.extend
append = result.append
line = []
multiline = False
count = 0
find = str.find
for item in sour... | [
"def",
"split_lines",
"(",
"source",
",",
"maxline",
"=",
"79",
")",
":",
"result",
"=",
"[",
"]",
"extend",
"=",
"result",
".",
"extend",
"append",
"=",
"result",
".",
"append",
"line",
"=",
"[",
"]",
"multiline",
"=",
"False",
"count",
"=",
"0",
... | 26.310345 | 0.001264 |
def from_neighbor_pores(target, pore_prop='pore.seed', mode='min'):
r"""
Adopt a value based on the values in neighboring pores
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also pr... | [
"def",
"from_neighbor_pores",
"(",
"target",
",",
"pore_prop",
"=",
"'pore.seed'",
",",
"mode",
"=",
"'min'",
")",
":",
"prj",
"=",
"target",
".",
"project",
"network",
"=",
"prj",
".",
"network",
"throats",
"=",
"network",
".",
"map_throats",
"(",
"target... | 32.484848 | 0.000906 |
def parse_dtype_info(flags):
"""Convert dtype string to tf dtype, and set loss_scale default as needed.
Args:
flags: namespace object returned by arg parser.
Raises:
ValueError: If an invalid dtype is provided.
"""
if flags.dtype in (i[0] for i in DTYPE_MAP.values()):
return # Make function ide... | [
"def",
"parse_dtype_info",
"(",
"flags",
")",
":",
"if",
"flags",
".",
"dtype",
"in",
"(",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"DTYPE_MAP",
".",
"values",
"(",
")",
")",
":",
"return",
"# Make function idempotent",
"try",
":",
"flags",
".",
"dtype",
... | 28.944444 | 0.011152 |
def sort(self, key_or_list, direction=None):
"""
Sorts a cursor object based on the input
:param key_or_list: a list/tuple containing the sort specification,
i.e. ('user_number': -1), or a basestring
:param direction: sorting direction, 1 or -1, needed if key_or_list
... | [
"def",
"sort",
"(",
"self",
",",
"key_or_list",
",",
"direction",
"=",
"None",
")",
":",
"# checking input format",
"sort_specifier",
"=",
"list",
"(",
")",
"if",
"isinstance",
"(",
"key_or_list",
",",
"list",
")",
":",
"if",
"direction",
"is",
"not",
"Non... | 35.590909 | 0.000414 |
def sanitize(self):
'''
Check if the current settings conform to the RFC and fix where possible
'''
# Check ports
if not isinstance(self.source_port, numbers.Integral) \
or self.source_port < 0 \
or self.source_port >= 2 ** 16:
raise ValueError('Invali... | [
"def",
"sanitize",
"(",
"self",
")",
":",
"# Check ports",
"if",
"not",
"isinstance",
"(",
"self",
".",
"source_port",
",",
"numbers",
".",
"Integral",
")",
"or",
"self",
".",
"source_port",
"<",
"0",
"or",
"self",
".",
"source_port",
">=",
"2",
"**",
... | 38.071429 | 0.010989 |
def writeToCheckpoint(self, checkpointDir):
"""Serializes model using capnproto and writes data to ``checkpointDir``"""
proto = self.getSchema().new_message()
self.write(proto)
checkpointPath = self._getModelCheckpointFilePath(checkpointDir)
# Clean up old saved state, if any
if os.path.exist... | [
"def",
"writeToCheckpoint",
"(",
"self",
",",
"checkpointDir",
")",
":",
"proto",
"=",
"self",
".",
"getSchema",
"(",
")",
".",
"new_message",
"(",
")",
"self",
".",
"write",
"(",
"proto",
")",
"checkpointPath",
"=",
"self",
".",
"_getModelCheckpointFilePath... | 39.037037 | 0.010185 |
def on_successful_login(self, subject, authc_token, account_id):
"""
Reacts to the successful login attempt by first always
forgetting any previously stored identity. Then if the authc_token
is a ``RememberMe`` type of token, the associated identity
will be remembered for later ... | [
"def",
"on_successful_login",
"(",
"self",
",",
"subject",
",",
"authc_token",
",",
"account_id",
")",
":",
"# always clear any previous identity:",
"self",
".",
"forget_identity",
"(",
"subject",
")",
"# now save the new identity:",
"if",
"authc_token",
".",
"is_rememb... | 46.375 | 0.001761 |
def code_memory_read(self, addr, num_bytes):
"""Reads bytes from code memory.
Note:
This is similar to calling ``memory_read`` or ``memory_read8``,
except that this uses a cache and reads ahead. This should be used
in instances where you want to read a small amount of byt... | [
"def",
"code_memory_read",
"(",
"self",
",",
"addr",
",",
"num_bytes",
")",
":",
"buf_size",
"=",
"num_bytes",
"buf",
"=",
"(",
"ctypes",
".",
"c_uint8",
"*",
"buf_size",
")",
"(",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_ReadCodeMem",
"(",
... | 34.884615 | 0.002146 |
def _chi_lr(self,r, phi, nl,nr,beta):
"""
computes the generalized polar basis function in the convention of Massey&Refregier eqn 8
:param nl: left basis
:type nl: int
:param nr: right basis
:type nr: int
:param beta: beta --the characteristic scale typically cho... | [
"def",
"_chi_lr",
"(",
"self",
",",
"r",
",",
"phi",
",",
"nl",
",",
"nr",
",",
"beta",
")",
":",
"m",
"=",
"int",
"(",
"(",
"nr",
"-",
"nl",
")",
".",
"real",
")",
"n",
"=",
"int",
"(",
"(",
"nr",
"+",
"nl",
")",
".",
"real",
")",
"p",... | 36.592593 | 0.02071 |
def load_oxts_packets_and_poses(oxts_files):
"""Generator to read OXTS ground truth data.
Poses are given in an East-North-Up coordinate system
whose origin is the first GPS position.
"""
# Scale for Mercator projection (from first lat value)
scale = None
# Origin of the global coord... | [
"def",
"load_oxts_packets_and_poses",
"(",
"oxts_files",
")",
":",
"# Scale for Mercator projection (from first lat value)",
"scale",
"=",
"None",
"# Origin of the global coordinate system (first GPS position)",
"origin",
"=",
"None",
"oxts",
"=",
"[",
"]",
"for",
"filename",
... | 30.138889 | 0.001786 |
def process_input_args(self, ifiles: sos_targets, **kwargs):
"""This function handles directive input and all its parameters.
It
determines and set __step_input__
determines and set pattern variables if needed
returns
_groups
_vars
which ar... | [
"def",
"process_input_args",
"(",
"self",
",",
"ifiles",
":",
"sos_targets",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ifiles",
".",
"unspecified",
"(",
")",
":",
"env",
".",
"sos_dict",
".",
"set",
"(",
"'step_input'",
",",
"sos_targets",
"(",
"[",
"]... | 34.459459 | 0.001526 |
def add_assay(self, name, assay):
"""
Add an assay to the material.
:param name: The name of the new assay.
:param assay: A list containing the compound mass fractions for
the assay. The sequence of the assay's elements must correspond to
the sequence of the material... | [
"def",
"add_assay",
"(",
"self",
",",
"name",
",",
"assay",
")",
":",
"if",
"not",
"type",
"(",
"assay",
")",
"is",
"list",
":",
"raise",
"Exception",
"(",
"'Invalid assay. It must be a list.'",
")",
"elif",
"not",
"len",
"(",
"assay",
")",
"==",
"self",... | 37.045455 | 0.002392 |
def _decdeg_distance(pt1, pt2):
"""
Earth surface distance (in km) between decimal latlong points using
Haversine approximation.
http://stackoverflow.com/questions/15736995/
how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-
points
"""
lat1, lon1 = pt1
lat2, lo... | [
"def",
"_decdeg_distance",
"(",
"pt1",
",",
"pt2",
")",
":",
"lat1",
",",
"lon1",
"=",
"pt1",
"lat2",
",",
"lon2",
"=",
"pt2",
"# Convert decimal degrees to radians",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
"=",
"map",
"(",
"np",
".",
"radians",
... | 26.333333 | 0.001527 |
def text_antialias(self, flag=True):
"""text antialias
:param flag: True or False. (default is True)
:type flag: bool
"""
antialias = pgmagick.DrawableTextAntialias(flag)
self.drawer.append(antialias) | [
"def",
"text_antialias",
"(",
"self",
",",
"flag",
"=",
"True",
")",
":",
"antialias",
"=",
"pgmagick",
".",
"DrawableTextAntialias",
"(",
"flag",
")",
"self",
".",
"drawer",
".",
"append",
"(",
"antialias",
")"
] | 30.25 | 0.008032 |
def findDottedModuleAndParentDir(file_path):
"""
I return a tuple (dotted_module, parent_dir) where dotted_module is the
full dotted name of the module with respect to the package it is in, and
parent_dir is the absolute path to the parent directory of the package.
If the python file is not part of... | [
"def",
"findDottedModuleAndParentDir",
"(",
"file_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"raise",
"ValueError",
"(",
"\"'{}' is not a file.\"",
".",
"format",
"(",
"file_path",
")",
")",
"parent_dir",
"=",
... | 45.238095 | 0.001031 |
def parse(region_string):
"""Parse DS9 region string into a ShapeList.
Parameters
----------
region_string : str
Region string
Returns
-------
shapes : `ShapeList`
List of `~pyregion.Shape`
"""
rp = RegionParser()
ss = rp.parse(region_string)
sss1 = rp.conve... | [
"def",
"parse",
"(",
"region_string",
")",
":",
"rp",
"=",
"RegionParser",
"(",
")",
"ss",
"=",
"rp",
".",
"parse",
"(",
"region_string",
")",
"sss1",
"=",
"rp",
".",
"convert_attr",
"(",
"ss",
")",
"sss2",
"=",
"_check_wcs",
"(",
"sss1",
")",
"shape... | 22.75 | 0.00211 |
async def catch_up(self):
"""
"Catches up" on the missed updates while the client was offline.
You should call this method after registering the event handlers
so that the updates it loads can by processed by your script.
This can also be used to forcibly fetch new updates if th... | [
"async",
"def",
"catch_up",
"(",
"self",
")",
":",
"pts",
",",
"date",
"=",
"self",
".",
"_state_cache",
"[",
"None",
"]",
"self",
".",
"session",
".",
"catching_up",
"=",
"True",
"try",
":",
"while",
"True",
":",
"d",
"=",
"await",
"self",
"(",
"f... | 45.216667 | 0.000722 |
def serial_udb_extra_f13_send(self, sue_week_no, sue_lat_origin, sue_lon_origin, sue_alt_origin, force_mavlink1=False):
'''
Backwards compatible version of SERIAL_UDB_EXTRA F13: format
sue_week_no : Serial UDB Extra GPS Week Number (int16_t)
... | [
"def",
"serial_udb_extra_f13_send",
"(",
"self",
",",
"sue_week_no",
",",
"sue_lat_origin",
",",
"sue_lon_origin",
",",
"sue_alt_origin",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"serial_udb_extra_f13_encode",
... | 69.181818 | 0.010376 |
def GetCustomerIDs(client):
"""Retrieves all CustomerIds in the account hierarchy.
Note that your configuration file must specify a client_customer_id belonging
to an AdWords manager account.
Args:
client: an AdWordsClient instance.
Raises:
Exception: if no CustomerIds could be found.
Returns:
... | [
"def",
"GetCustomerIDs",
"(",
"client",
")",
":",
"# For this example, we will use ManagedCustomerService to get all IDs in",
"# hierarchy that do not belong to MCC accounts.",
"managed_customer_service",
"=",
"client",
".",
"GetService",
"(",
"'ManagedCustomerService'",
",",
"versio... | 29.078431 | 0.009785 |
def get_commit_request(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a commit request for a staged import.
:param id: Staged import ID as an int.
:return: :class:`imports.Request <imports.Request>` object
:rtype: imports.Request
"""
schema = RequestS... | [
"def",
"get_commit_request",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"RequestSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"get",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")"... | 43 | 0.009112 |
def _write_passphrase(stream, passphrase, encoding):
"""Write the passphrase from memory to the GnuPG process' stdin.
:type stream: file, :class:`~io.BytesIO`, or :class:`~io.StringIO`
:param stream: The input file descriptor to write the password to.
:param str passphrase: The passphrase for the secre... | [
"def",
"_write_passphrase",
"(",
"stream",
",",
"passphrase",
",",
"encoding",
")",
":",
"passphrase",
"=",
"'%s\\n'",
"%",
"passphrase",
"passphrase",
"=",
"passphrase",
".",
"encode",
"(",
"encoding",
")",
"stream",
".",
"write",
"(",
"passphrase",
")",
"l... | 47.923077 | 0.001575 |
def convert_readme_to_rst():
""" Attempt to convert a README.md file into README.rst """
project_files = os.listdir('.')
for filename in project_files:
if filename.lower() == 'readme':
raise ProjectError(
'found {} in project directory...'.format(filename) +
... | [
"def",
"convert_readme_to_rst",
"(",
")",
":",
"project_files",
"=",
"os",
".",
"listdir",
"(",
"'.'",
")",
"for",
"filename",
"in",
"project_files",
":",
"if",
"filename",
".",
"lower",
"(",
")",
"==",
"'readme'",
":",
"raise",
"ProjectError",
"(",
"'foun... | 43.821429 | 0.001595 |
def report_urls(impact_function):
"""Get report urls for all report generated by the ImpactFunction.
:param impact_function: The ImpactFunction
:type impact_function: ImpactFunction
:return: Dictionary of all generated report urls by its product type
eg:
{
'html... | [
"def",
"report_urls",
"(",
"impact_function",
")",
":",
"report_path",
"=",
"impact_function",
".",
"impact_report",
".",
"output_folder",
"standard_report_metadata",
"=",
"impact_function",
".",
"report_metadata",
"def",
"retrieve_components",
"(",
"tags",
")",
":",
... | 36.703704 | 0.000328 |
def conf_budget(self, budget):
"""
Set limit on the number of conflicts.
"""
if self.maplesat:
pysolvers.maplechrono_cbudget(self.maplesat, budget) | [
"def",
"conf_budget",
"(",
"self",
",",
"budget",
")",
":",
"if",
"self",
".",
"maplesat",
":",
"pysolvers",
".",
"maplechrono_cbudget",
"(",
"self",
".",
"maplesat",
",",
"budget",
")"
] | 27.142857 | 0.010204 |
def extractSeqAndQuals(seq, quals, umi_bases, cell_bases, discard_bases,
retain_umi=False):
'''Remove selected bases from seq and quals
'''
new_seq = ""
new_quals = ""
umi_quals = ""
cell_quals = ""
ix = 0
for base, qual in zip(seq, quals):
if ((ix not in... | [
"def",
"extractSeqAndQuals",
"(",
"seq",
",",
"quals",
",",
"umi_bases",
",",
"cell_bases",
",",
"discard_bases",
",",
"retain_umi",
"=",
"False",
")",
":",
"new_seq",
"=",
"\"\"",
"new_quals",
"=",
"\"\"",
"umi_quals",
"=",
"\"\"",
"cell_quals",
"=",
"\"\""... | 26.470588 | 0.002144 |
def unbind(meta, name=None, dynamo_name=None) -> None:
"""Unconditionally remove any columns or indexes bound to the given name or dynamo_name.
.. code-block:: python
import bloop.models
class User(BaseModel):
id = Column(String, hash_key=True)
email = Column(String, ... | [
"def",
"unbind",
"(",
"meta",
",",
"name",
"=",
"None",
",",
"dynamo_name",
"=",
"None",
")",
"->",
"None",
":",
"if",
"name",
"is",
"not",
"None",
":",
"columns",
"=",
"{",
"x",
"for",
"x",
"in",
"meta",
".",
"columns",
"if",
"x",
".",
"name",
... | 34.917808 | 0.001908 |
def delete_binding(self, vhost, exchange, queue, rt_key):
"""
Deletes a binding between an exchange and a queue on a given vhost.
:param string vhost: vhost housing the exchange/queue to bind
:param string exchange: the target exchange of the binding
:param string queue: the que... | [
"def",
"delete_binding",
"(",
"self",
",",
"vhost",
",",
"exchange",
",",
"queue",
",",
"rt_key",
")",
":",
"vhost",
"=",
"quote",
"(",
"vhost",
",",
"''",
")",
"exchange",
"=",
"quote",
"(",
"exchange",
",",
"''",
")",
"queue",
"=",
"quote",
"(",
... | 46.947368 | 0.002198 |
def create_cmd_task(
ctx,
parts,
inputs=None,
outputs=None,
env=None,
cwd=None,
task_name=None,
cache_key=None,
always=False,
add_to_group=True,
):
"""
Create task that runs given command.
:param ctx: BuildContext object.
:param parts: Command parts list.
... | [
"def",
"create_cmd_task",
"(",
"ctx",
",",
"parts",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"env",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"task_name",
"=",
"None",
",",
"cache_key",
"=",
"None",
",",
"always",
"=",
"False",
... | 31.616393 | 0.000101 |
def bdp(tickers, flds, **kwargs):
"""
Bloomberg reference data
Args:
tickers: tickers
flds: fields to query
**kwargs: bbg overrides
Returns:
pd.DataFrame
Examples:
>>> bdp('IQ US Equity', 'Crncy', raw=True)
ticker field value
0 IQ... | [
"def",
"bdp",
"(",
"tickers",
",",
"flds",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
"=",
"logs",
".",
"get_logger",
"(",
"bdp",
",",
"level",
"=",
"kwargs",
".",
"pop",
"(",
"'log'",
",",
"logs",
".",
"LOG_LEVEL",
")",
")",
"con",
",",
"_",
... | 28.837209 | 0.00234 |
def _transform_row_wrapper(self, row):
"""
Transforms a single source row.
:param dict[str|str] row: The source row.
"""
self._count_total += 1
try:
# Transform the naturals keys in line to technical keys.
in_row = copy.copy(row)
out_... | [
"def",
"_transform_row_wrapper",
"(",
"self",
",",
"row",
")",
":",
"self",
".",
"_count_total",
"+=",
"1",
"try",
":",
"# Transform the naturals keys in line to technical keys.",
"in_row",
"=",
"copy",
".",
"copy",
"(",
"row",
")",
"out_row",
"=",
"{",
"}",
"... | 32.512821 | 0.001531 |
def on_stop_scene(self, event: events.StopScene, signal: Callable[[Any], None]):
"""
Stop a running scene. If there's a scene on the stack, it resumes.
"""
self.stop_scene()
if self.current_scene is not None:
signal(events.SceneContinued())
else:
s... | [
"def",
"on_stop_scene",
"(",
"self",
",",
"event",
":",
"events",
".",
"StopScene",
",",
"signal",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"None",
"]",
")",
":",
"self",
".",
"stop_scene",
"(",
")",
"if",
"self",
".",
"current_scene",
"is",
"not"... | 36.888889 | 0.008824 |
def write_data(fo, datum, schema):
"""Write a datum of data to output stream.
Paramaters
----------
fo: file-like
Output file
datum: object
Data to write
schema: dict
Schemda to use
"""
record_type = extract_record_type(schema)
logical_type = extract_logical... | [
"def",
"write_data",
"(",
"fo",
",",
"datum",
",",
"schema",
")",
":",
"record_type",
"=",
"extract_record_type",
"(",
"schema",
")",
"logical_type",
"=",
"extract_logical_type",
"(",
"schema",
")",
"fn",
"=",
"WRITERS",
".",
"get",
"(",
"record_type",
")",
... | 24.68 | 0.00156 |
def name(self, value):
"""
Setter for **self.__name** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("name", value)
self._... | [
"def",
"name",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"unicode",
",",
"\"'{0}' attribute: '{1}' type is not 'unicode'!\"",
".",
"format",
"(",
"\"name\"",
",",
"value",
")",
... | 29.363636 | 0.009009 |
def start_threads(self, n_threads):
"""
Terminate existing threads and create a
new set if the thread number doesn't match
the desired number.
Required:
n_threads: (int) number of threads to spawn
Returns: self
"""
if n_threads == len(self._threads):
return self
... | [
"def",
"start_threads",
"(",
"self",
",",
"n_threads",
")",
":",
"if",
"n_threads",
"==",
"len",
"(",
"self",
".",
"_threads",
")",
":",
"return",
"self",
"# Terminate all previous tasks with the existing",
"# event object, then create a new one for the next",
"# generati... | 25.4 | 0.010834 |
def show_top(minion=None, saltenv='base'):
'''
Returns the compiled top data for pillar for a specific minion. If no
minion is specified, we use the first minion we find.
CLI Example:
.. code-block:: bash
salt-run pillar.show_top
'''
id_, grains, _ = salt.utils.minions.get_minion... | [
"def",
"show_top",
"(",
"minion",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"id_",
",",
"grains",
",",
"_",
"=",
"salt",
".",
"utils",
".",
"minions",
".",
"get_minion_data",
"(",
"minion",
",",
"__opts__",
")",
"if",
"not",
"grains",
"an... | 27.677419 | 0.002252 |
def _args_from_dict(ddata: Mapping[str, Any]):
"""Allows to construct an instance of AnnData from a dictionary.
Acts as interface for the communication with the hdf5 file.
In particular, from a dict that has been written using
``AnnData._to_dict_fixed_width_arrays``.
"""
... | [
"def",
"_args_from_dict",
"(",
"ddata",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
":",
"d_true_keys",
"=",
"{",
"}",
"# backwards compat",
"uns_is_not_key",
"=",
"False",
"valid_keys",
"=",
"[",
"]",
"for",
"keys",
"in",
"AnnData",
".",
"_H5_ALIASE... | 39.5 | 0.001465 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.