text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _make_elastic_range(begin, end):
"""Generate an S-curved range of pages.
Start from both left and right, adding exponentially growing indexes,
until the two trends collide.
"""
# Limit growth for huge numbers of pages.
starting_factor = max(1, (end - begin) // 100)
factor = _iter_factor... | [
"def",
"_make_elastic_range",
"(",
"begin",
",",
"end",
")",
":",
"# Limit growth for huge numbers of pages.",
"starting_factor",
"=",
"max",
"(",
"1",
",",
"(",
"end",
"-",
"begin",
")",
"//",
"100",
")",
"factor",
"=",
"_iter_factors",
"(",
"starting_factor",
... | 35.478261 | 0.001193 |
def cov_error(self, comp_cov, score_metric="frobenius"):
"""Computes the covariance error vs. comp_cov.
May require self.path_
Parameters
----------
comp_cov : array-like, shape = (n_features, n_features)
The precision to compare with.
This should normal... | [
"def",
"cov_error",
"(",
"self",
",",
"comp_cov",
",",
"score_metric",
"=",
"\"frobenius\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"precision_",
",",
"list",
")",
":",
"return",
"_compute_error",
"(",
"comp_cov",
",",
"self",
".",
"covaria... | 34.418182 | 0.001027 |
def tile_read(source, bounds, tilesize, **kwargs):
"""
Read data and mask.
Attributes
----------
source : str or rasterio.io.DatasetReader
input file path or rasterio.io.DatasetReader object
bounds : list
Mercator tile bounds (left, bottom, right, top)
tilesize : int
... | [
"def",
"tile_read",
"(",
"source",
",",
"bounds",
",",
"tilesize",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"DatasetReader",
")",
":",
"return",
"_tile_read",
"(",
"source",
",",
"bounds",
",",
"tilesize",
",",
"*",
"*... | 27.269231 | 0.001362 |
def RetryQuestion(question_text, output_re="", default_val=None):
"""Continually ask a question until the output_re is matched."""
while True:
if default_val is not None:
new_text = "%s [%s]: " % (question_text, default_val)
else:
new_text = "%s: " % question_text
# pytype: disable=wrong-arg... | [
"def",
"RetryQuestion",
"(",
"question_text",
",",
"output_re",
"=",
"\"\"",
",",
"default_val",
"=",
"None",
")",
":",
"while",
"True",
":",
"if",
"default_val",
"is",
"not",
"None",
":",
"new_text",
"=",
"\"%s [%s]: \"",
"%",
"(",
"question_text",
",",
"... | 36.3125 | 0.013423 |
def app_cache_restorer():
"""
A context manager that restore model cache state as it was before
entering context.
"""
state = _app_cache_deepcopy(apps.__dict__)
try:
yield state
finally:
with apps_lock():
apps.__dict__ = state
# Rebind the app registry... | [
"def",
"app_cache_restorer",
"(",
")",
":",
"state",
"=",
"_app_cache_deepcopy",
"(",
"apps",
".",
"__dict__",
")",
"try",
":",
"yield",
"state",
"finally",
":",
"with",
"apps_lock",
"(",
")",
":",
"apps",
".",
"__dict__",
"=",
"state",
"# Rebind the app reg... | 32 | 0.001898 |
def mock(self, url=None, **kw):
"""
Creates and registers a new HTTP mock in the current engine.
Arguments:
url (str): request URL to mock.
activate (bool): force mock engine activation.
Defaults to ``False``.
**kw (mixed): variadic keyword ar... | [
"def",
"mock",
"(",
"self",
",",
"url",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"# Activate mock engine, if explicitly requested",
"if",
"kw",
".",
"get",
"(",
"'activate'",
")",
":",
"kw",
".",
"pop",
"(",
"'activate'",
")",
"self",
".",
"activate",... | 31.518519 | 0.002281 |
def __request_mark_sent(self, requestId):
"""Set send time & clear exception from request if set, ignoring non-existent requests"""
with self.__requests:
try:
req = self.__requests[requestId]
except KeyError:
# request might have had a response alr... | [
"def",
"__request_mark_sent",
"(",
"self",
",",
"requestId",
")",
":",
"with",
"self",
".",
"__requests",
":",
"try",
":",
"req",
"=",
"self",
".",
"__requests",
"[",
"requestId",
"]",
"except",
"KeyError",
":",
"# request might have had a response already have be... | 43 | 0.008282 |
def authenticate(self, password):
"""Authenticate a tag with a *password*.
A tag that was once protected with a password requires
authentication before write, potentially also read, operations
may be performed. The *password* must be the same as the
password provided to :meth:`p... | [
"def",
"authenticate",
"(",
"self",
",",
"password",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_authenticate\"",
")",
":",
"args",
"=",
"\"password={0!r}\"",
".",
"format",
"(",
"password",
")",
"log",
".",
"debug",
"(",
"\"authenticate({0})\"",
".",
... | 43.363636 | 0.002051 |
def distros_for_location(location, basename, metadata=None):
"""Yield egg or source distribution objects based on basename"""
if basename.endswith('.egg.zip'):
basename = basename[:-4] # strip the .zip
if basename.endswith('.egg') and '-' in basename:
# only one, unambiguous interpretatio... | [
"def",
"distros_for_location",
"(",
"location",
",",
"basename",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"basename",
".",
"endswith",
"(",
"'.egg.zip'",
")",
":",
"basename",
"=",
"basename",
"[",
":",
"-",
"4",
"]",
"# strip the .zip",
"if",
"basena... | 44.65 | 0.001096 |
def write_short(self, number):
""" Writes a short integer to the underlying output file as a 2-byte value. """
buf = pack(self.byte_order + "h", number)
self.write(buf) | [
"def",
"write_short",
"(",
"self",
",",
"number",
")",
":",
"buf",
"=",
"pack",
"(",
"self",
".",
"byte_order",
"+",
"\"h\"",
",",
"number",
")",
"self",
".",
"write",
"(",
"buf",
")"
] | 47.25 | 0.015625 |
def build_where_part(self, wheres):
"""
Recursive method that builds the where parts. Any Q objects that have children will
also be built with ``self.build_where_part()``
:rtype: str
:return: The composed where string
"""
where_parts = []
# loop through ... | [
"def",
"build_where_part",
"(",
"self",
",",
"wheres",
")",
":",
"where_parts",
"=",
"[",
"]",
"# loop through each child of the Q condition",
"for",
"where",
"in",
"wheres",
".",
"children",
":",
"# if this child is another Q object, recursively build the where part",
"if"... | 40.705263 | 0.001767 |
def pairwise_dists_on_cols(df_in, earth_mover_dist=True, energy_dist=True):
"""Computes pairwise statistical distance measures.
parameters
----------
df_in: pandas data frame
Columns represent estimators and rows represent runs.
Each data frane element is an array of values which are us... | [
"def",
"pairwise_dists_on_cols",
"(",
"df_in",
",",
"earth_mover_dist",
"=",
"True",
",",
"energy_dist",
"=",
"True",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"for",
"col",
"in",
"df_in",
".",
"columns",
":",
"df",
"[",
"col",
"]",
"=",
... | 35.083333 | 0.001156 |
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id) | [
"def",
"flavor_delete",
"(",
"self",
",",
"flavor_id",
")",
":",
"# pylint: disable=C0103",
"nt_ks",
"=",
"self",
".",
"compute_conn",
"nt_ks",
".",
"flavors",
".",
"delete",
"(",
"flavor_id",
")",
"return",
"'Flavor deleted: {0}'",
".",
"format",
"(",
"flavor_i... | 33 | 0.008439 |
def make_request(name, params=None, version="V001", key=None, api_type="web",
fetcher=get_page, base=None, language="en_us"):
"""
Make an API request
"""
params = params or {}
params["key"] = key or API_KEY
params["language"] = language
if not params["key"]:
raise ... | [
"def",
"make_request",
"(",
"name",
",",
"params",
"=",
"None",
",",
"version",
"=",
"\"V001\"",
",",
"key",
"=",
"None",
",",
"api_type",
"=",
"\"web\"",
",",
"fetcher",
"=",
"get_page",
",",
"base",
"=",
"None",
",",
"language",
"=",
"\"en_us\"",
")"... | 30.666667 | 0.00211 |
def route(self, origin, message):
'''\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass... | [
"def",
"route",
"(",
"self",
",",
"origin",
",",
"message",
")",
":",
"# side-effect: we have to know all the routes before we can route. But",
"# we can't resolve them while the object is initializing, so we have to",
"# do it just in time to route.",
"self",
".",
"resolve_node_module... | 37 | 0.002395 |
def run_wsgi(settings_module):
"""Run CLAM in WSGI mode"""
global settingsmodule, DEBUG #pylint: disable=global-statement
printdebug("Initialising WSGI service")
globals()['settings'] = settings_module
settingsmodule = settings_module.__name__
try:
if settings.DEBUG:
DEBUG ... | [
"def",
"run_wsgi",
"(",
"settings_module",
")",
":",
"global",
"settingsmodule",
",",
"DEBUG",
"#pylint: disable=global-statement",
"printdebug",
"(",
"\"Initialising WSGI service\"",
")",
"globals",
"(",
")",
"[",
"'settings'",
"]",
"=",
"settings_module",
"settingsmod... | 24.242424 | 0.008413 |
def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"SEEK_SET",
")",
":",
"if",
"not",
"self",
".",
"_seekable",
":",
"raise",
"UnsupportedOperation",
"(",
"'seek'",
")",
"seek",
"=",
"self",
".",
"_update_seek",
"(",
"offset",
",",
"whence",
... | 35.064516 | 0.001791 |
def get(self, group, default=None):
'''Get a group or parameter.
Parameters
----------
group : str
If this string contains a period (.), then the part before the
period will be used to retrieve a group, and the part after the
period will be used to re... | [
"def",
"get",
"(",
"self",
",",
"group",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"group",
",",
"int",
")",
":",
"return",
"self",
".",
"groups",
".",
"get",
"(",
"group",
",",
"default",
")",
"group",
"=",
"group",
".",
"u... | 35.941176 | 0.00239 |
def p_params_begin(self, p):
'params_begin : params_begin param'
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_params_begin",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"2",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 34 | 0.014388 |
def _make_cz_layer(qubits: Iterable[devices.GridQubit], layer_index: int
) -> Iterable[ops.Operation]:
"""
Each layer index corresponds to a shift/transpose of this CZ pattern:
●───● ● ● ●───● ● ● . . .
● ● ●───● ● ● ●───● . . .
●───● ● ● ●... | [
"def",
"_make_cz_layer",
"(",
"qubits",
":",
"Iterable",
"[",
"devices",
".",
"GridQubit",
"]",
",",
"layer_index",
":",
"int",
")",
"->",
"Iterable",
"[",
"ops",
".",
"Operation",
"]",
":",
"# map to an internal layer index to match the cycle order of public circuits... | 32.285714 | 0.001074 |
def having(self, column, operator=None, value=None, boolean="and"):
"""
Add a "having" clause to the query
:param column: The column
:type column: str
:param operator: The having clause operator
:type operator: str
:param value: The having clause value
... | [
"def",
"having",
"(",
"self",
",",
"column",
",",
"operator",
"=",
"None",
",",
"value",
"=",
"None",
",",
"boolean",
"=",
"\"and\"",
")",
":",
"type",
"=",
"\"basic\"",
"self",
".",
"havings",
".",
"append",
"(",
"{",
"\"type\"",
":",
"type",
",",
... | 24.257143 | 0.002265 |
def _phiforce(self,R,phi=0.,t=0.):
"""
NAME:
_phiforce
PURPOSE:
evaluate the azimuthal force for this potential
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
the azimuthal force
... | [
"def",
"_phiforce",
"(",
"self",
",",
"R",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"if",
"R",
"<",
"self",
".",
"_rb",
":",
"return",
"self",
".",
"_mphio",
"*",
"math",
".",
"sin",
"(",
"self",
".",
"_m",
"*",
"phi",
"-",
"se... | 30.6 | 0.009509 |
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Load Activation Profiles (requires classic mode)."""
cpc_oid = uri_parms[0]
query_str = uri_parms[1]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid)
except KeyError:
raise InvalidResourceE... | [
"def",
"get",
"(",
"method",
",",
"hmc",
",",
"uri",
",",
"uri_parms",
",",
"logon_required",
")",
":",
"cpc_oid",
"=",
"uri_parms",
"[",
"0",
"]",
"query_str",
"=",
"uri_parms",
"[",
"1",
"]",
"try",
":",
"cpc",
"=",
"hmc",
".",
"cpcs",
".",
"look... | 48.111111 | 0.002265 |
def load_file(path):
"""
Load file
:param path: Path to file
:type path: str | unicode
:return: Loaded data
:rtype: None | int | float | str | unicode | list | dict
:raises IOError: If file not found or error accessing file
"""
res = {}
if not path:
IOError("No path spe... | [
"def",
"load_file",
"(",
"path",
")",
":",
"res",
"=",
"{",
"}",
"if",
"not",
"path",
":",
"IOError",
"(",
"\"No path specified to save\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"raise",
"IOError",
"(",
"\"File not ... | 25.862069 | 0.001285 |
def parse_play_details(details):
"""Parses play details from play-by-play string and returns structured
data.
:details: detail string for play
:returns: dictionary of play attributes
"""
# if input isn't a string, return None
if not isinstance(details, basestring):
return None
... | [
"def",
"parse_play_details",
"(",
"details",
")",
":",
"# if input isn't a string, return None",
"if",
"not",
"isinstance",
"(",
"details",
",",
"basestring",
")",
":",
"return",
"None",
"rushOptRE",
"=",
"r'(?P<rushDir>{})'",
".",
"format",
"(",
"r'|'",
".",
"joi... | 34.584158 | 0.000186 |
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> conf... | [
"def",
"loads",
"(",
"string",
",",
"filename",
"=",
"None",
",",
"includedir",
"=",
"''",
")",
":",
"try",
":",
"f",
"=",
"io",
".",
"StringIO",
"(",
"string",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"libconf.loads() input string mus... | 29.285714 | 0.001575 |
def _ast_with_loc(
py_ast: GeneratedPyAST, env: NodeEnv, include_dependencies: bool = False
) -> GeneratedPyAST:
"""Hydrate Generated Python AST nodes with line numbers and column offsets
if they exist in the node environment."""
if env.line is not None:
py_ast.node.lineno = env.line
if... | [
"def",
"_ast_with_loc",
"(",
"py_ast",
":",
"GeneratedPyAST",
",",
"env",
":",
"NodeEnv",
",",
"include_dependencies",
":",
"bool",
"=",
"False",
")",
"->",
"GeneratedPyAST",
":",
"if",
"env",
".",
"line",
"is",
"not",
"None",
":",
"py_ast",
".",
"node",
... | 30.65 | 0.001582 |
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object or None if not available.
"""
stat_object = super(OSFileEntry, self)._GetStat()
if not self._is_windows_device:
# File data stat information.
stat_object.size = self._stat_info.st_s... | [
"def",
"_GetStat",
"(",
"self",
")",
":",
"stat_object",
"=",
"super",
"(",
"OSFileEntry",
",",
"self",
")",
".",
"_GetStat",
"(",
")",
"if",
"not",
"self",
".",
"_is_windows_device",
":",
"# File data stat information.",
"stat_object",
".",
"size",
"=",
"se... | 29 | 0.015965 |
def abi_splitext(filename):
"""
Split the ABINIT extension from a filename.
"Extension" are found by searching in an internal database.
Returns "(root, ext)" where ext is the registered ABINIT extension
The final ".nc" is included (if any)
>>> assert abi_splitext("foo_WFK") == ('foo_', 'WFK')
... | [
"def",
"abi_splitext",
"(",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"is_ncfile",
"=",
"False",
"if",
"filename",
".",
"endswith",
"(",
"\".nc\"",
")",
":",
"is_ncfile",
"=",
"True",
"filename",
"="... | 28.441176 | 0.002 |
def get_user_home(self, user):
"""Returns the default URL for a particular user.
This method can be used to customize where a user is sent when
they log in, etc. By default it returns the value of
:meth:`get_absolute_url`.
An alternative function can be supplied to customize th... | [
"def",
"get_user_home",
"(",
"self",
",",
"user",
")",
":",
"user_home",
"=",
"self",
".",
"_conf",
"[",
"'user_home'",
"]",
"if",
"user_home",
":",
"if",
"callable",
"(",
"user_home",
")",
":",
"return",
"user_home",
"(",
"user",
")",
"elif",
"isinstanc... | 46.297297 | 0.001144 |
def valid_config_exists(config_path=CONFIG_PATH):
"""Verify that a valid config file exists.
Args:
config_path (str): Path to the config file.
Returns:
boolean: True if there is a valid config file, false if not.
"""
if os.path.isfile(config_path):
try:
config =... | [
"def",
"valid_config_exists",
"(",
"config_path",
"=",
"CONFIG_PATH",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"try",
":",
"config",
"=",
"read_config",
"(",
"config_path",
")",
"check_config",
"(",
"config",
")",
"ex... | 26.611111 | 0.002016 |
def _run(self):
"""Run the worker function with some custom exception handling."""
try:
# Run the worker
self.worker()
except SystemExit as ex:
# sys.exit() was called
if isinstance(ex.code, int):
if ex.code is not None and ex.code ... | [
"def",
"_run",
"(",
"self",
")",
":",
"try",
":",
"# Run the worker",
"self",
".",
"worker",
"(",
")",
"except",
"SystemExit",
"as",
"ex",
":",
"# sys.exit() was called",
"if",
"isinstance",
"(",
"ex",
".",
"code",
",",
"int",
")",
":",
"if",
"ex",
"."... | 40.074074 | 0.001805 |
def icqt(C, sr=22050, hop_length=512, fmin=None, bins_per_octave=12,
tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann',
scale=True, length=None, amin=util.Deprecated(), res_type='fft'):
'''Compute the inverse constant-Q transform.
Given a constant-Q transform representation `C`... | [
"def",
"icqt",
"(",
"C",
",",
"sr",
"=",
"22050",
",",
"hop_length",
"=",
"512",
",",
"fmin",
"=",
"None",
",",
"bins_per_octave",
"=",
"12",
",",
"tuning",
"=",
"0.0",
",",
"filter_scale",
"=",
"1",
",",
"norm",
"=",
"1",
",",
"sparsity",
"=",
"... | 33.524096 | 0.001396 |
def render(template, dest, **kwargs):
'''Using jinja2, render `template` to the filename `dest`, supplying the
keyword arguments as template parameters.
'''
dest_dir = dirname(dest)
if dest_dir and not exists(dest_dir):
makedirs(dest_dir)
template = environment.get_template(template)
... | [
"def",
"render",
"(",
"template",
",",
"dest",
",",
"*",
"*",
"kwargs",
")",
":",
"dest_dir",
"=",
"dirname",
"(",
"dest",
")",
"if",
"dest_dir",
"and",
"not",
"exists",
"(",
"dest_dir",
")",
":",
"makedirs",
"(",
"dest_dir",
")",
"template",
"=",
"e... | 25.9375 | 0.002326 |
def create_database(self, instance, name, character_set=None,
collate=None):
"""Creates a database with the specified name on the given instance."""
return instance.create_database(name, character_set=character_set,
collate=collate) | [
"def",
"create_database",
"(",
"self",
",",
"instance",
",",
"name",
",",
"character_set",
"=",
"None",
",",
"collate",
"=",
"None",
")",
":",
"return",
"instance",
".",
"create_database",
"(",
"name",
",",
"character_set",
"=",
"character_set",
",",
"collat... | 54.4 | 0.014493 |
def paint(self):
"""
Renders a javascript snippet suitable for use as a mapbox-gl line paint entry
Returns:
A dict that can be converted to a mapbox-gl javascript paint snippet
"""
# TODO Figure out why i cant use some of these props
snippet = {
'... | [
"def",
"paint",
"(",
"self",
")",
":",
"# TODO Figure out why i cant use some of these props",
"snippet",
"=",
"{",
"'line-opacity'",
":",
"VectorStyle",
".",
"get_style_value",
"(",
"self",
".",
"opacity",
")",
",",
"'line-color'",
":",
"VectorStyle",
".",
"get_sty... | 36.333333 | 0.010056 |
def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
if hasattr(app, 'cli'):
app.cli.add_command(files_cmd)
app.extensions['invenio-files-rest'] = _FilesRESTState(app) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"init_config",
"(",
"app",
")",
"if",
"hasattr",
"(",
"app",
",",
"'cli'",
")",
":",
"app",
".",
"cli",
".",
"add_command",
"(",
"files_cmd",
")",
"app",
".",
"extensions",
"[",
"'i... | 40 | 0.008163 |
def _pdf_guess_version(input_file, search_window=1024):
"""Try to find version signature at start of file.
Not robust enough to deal with appended files.
Returns empty string if not found, indicating file is probably not PDF.
"""
with open(input_file, 'rb') as f:
signature = f.read(search... | [
"def",
"_pdf_guess_version",
"(",
"input_file",
",",
"search_window",
"=",
"1024",
")",
":",
"with",
"open",
"(",
"input_file",
",",
"'rb'",
")",
"as",
"f",
":",
"signature",
"=",
"f",
".",
"read",
"(",
"search_window",
")",
"m",
"=",
"re",
".",
"searc... | 29.5 | 0.002347 |
def build_connection(url):
"""
Build an Elasticsearch connection with the given url
Elastic.co's Heroku addon doesn't create credientials with access to the
cluster by default so they aren't exposed in the URL they provide either.
This function works around the situation by grabbing our credentials... | [
"def",
"build_connection",
"(",
"url",
")",
":",
"username",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'ELASTICSEARCH_USERNAME'",
")",
"password",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'ELASTICSEARCH_PASSWORD'",
")",
"if",
"username",
"and",
"passw... | 39.6875 | 0.001538 |
def invertible_flatten2_numpy(unflat_arrs, axis=0):
""" more numpy version
TODO: move to vtool
Args:
unflat_arrs (list): list of ndarrays
Returns:
tuple: (flat_list, cumlen_list)
CommandLine:
python -m utool.util_list --test-invertible_flatten2_numpy
Example:
... | [
"def",
"invertible_flatten2_numpy",
"(",
"unflat_arrs",
",",
"axis",
"=",
"0",
")",
":",
"cumlen_list",
"=",
"np",
".",
"cumsum",
"(",
"[",
"arr",
".",
"shape",
"[",
"axis",
"]",
"for",
"arr",
"in",
"unflat_arrs",
"]",
")",
"flat_list",
"=",
"np",
".",... | 31.653846 | 0.001179 |
def log_entry_send(self, id, num_logs, last_log_num, time_utc, size, force_mavlink1=False):
'''
Reply to LOG_REQUEST_LIST
id : Log id (uint16_t)
num_logs : Total number of logs (uint16_t)
last_log_nu... | [
"def",
"log_entry_send",
"(",
"self",
",",
"id",
",",
"num_logs",
",",
"last_log_num",
",",
"time_utc",
",",
"size",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"log_entry_encode",
"(",
"id",
",",
"num_... | 60.5 | 0.008141 |
def search(filter, # pylint: disable=C0103
dn=None, # pylint: disable=C0103
scope=None,
attrs=None,
**kwargs):
'''
Run an arbitrary LDAP query and return the results.
CLI Example:
.. code-block:: bash
salt 'ldaphost' ldap.search "filter=cn=... | [
"def",
"search",
"(",
"filter",
",",
"# pylint: disable=C0103",
"dn",
"=",
"None",
",",
"# pylint: disable=C0103",
"scope",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"dn",
":",
"dn",
"=",
"_config",
"(",
"'... | 31.55 | 0.000512 |
def branches(self):
"""Return list of (name and urls) only branches."""
return [(r['name'], self.vpathto(r['name'])) for r in self.remotes if r['kind'] == 'heads'] | [
"def",
"branches",
"(",
"self",
")",
":",
"return",
"[",
"(",
"r",
"[",
"'name'",
"]",
",",
"self",
".",
"vpathto",
"(",
"r",
"[",
"'name'",
"]",
")",
")",
"for",
"r",
"in",
"self",
".",
"remotes",
"if",
"r",
"[",
"'kind'",
"]",
"==",
"'heads'"... | 59 | 0.01676 |
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except ... | [
"def",
"badgify_badges",
"(",
"*",
"*",
"kwargs",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"user",
"=",
"kwargs",
".",
"get",
"(",
"'user'",
",",
"None",
")",
"username",
"=",
"kwargs",
".",
"get",
"(",
"'username'",
",",
"None",
")",
"if",... | 31.117647 | 0.001835 |
def get_roles_request(request):
"""Returns a list of accepting roles."""
uuid_ = request.matchdict['uuid']
user_id = request.matchdict.get('uid')
args = [uuid_]
if user_id is not None:
fmt_conditional = "AND user_id = %s"
args.append(user_id)
else:
fmt_conditional = ""
... | [
"def",
"get_roles_request",
"(",
"request",
")",
":",
"uuid_",
"=",
"request",
".",
"matchdict",
"[",
"'uuid'",
"]",
"user_id",
"=",
"request",
".",
"matchdict",
".",
"get",
"(",
"'uid'",
")",
"args",
"=",
"[",
"uuid_",
"]",
"if",
"user_id",
"is",
"not... | 32.921053 | 0.000776 |
def get_service_from_port(port, all_services=None):
"""Gets the name of the service from the port
all_services allows you to feed in the services to look through, pass
in a dict of service names to service information eg.
{
'service_name': {
'port': port_number
}
}
... | [
"def",
"get_service_from_port",
"(",
"port",
",",
"all_services",
"=",
"None",
")",
":",
"if",
"port",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"port",
",",
"int",
")",
":",
"return",
"None",
"if",
"all_services",
"is",
"None",
":",
"all_services",
... | 31.518519 | 0.002281 |
def join(self, shape, body_a, body_b=None, name=None, **kwargs):
'''Create a new joint that connects two bodies together.
Parameters
----------
shape : str
The "shape" of the joint to use for joining together two bodies.
This should name a type of joint, such as ... | [
"def",
"join",
"(",
"self",
",",
"shape",
",",
"body_a",
",",
"body_b",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ba",
"=",
"self",
".",
"get_body",
"(",
"body_a",
")",
"bb",
"=",
"self",
".",
"get_body",
"(",
"... | 41.636364 | 0.001422 |
def load_airpassengers(as_series=False):
"""Monthly airline passengers.
The classic Box & Jenkins airline data. Monthly totals of international
airline passengers, 1949 to 1960.
Parameters
----------
as_series : bool, optional (default=False)
Whether to return a Pandas series. If False... | [
"def",
"load_airpassengers",
"(",
"as_series",
"=",
"False",
")",
":",
"rslt",
"=",
"np",
".",
"array",
"(",
"[",
"112",
",",
"118",
",",
"132",
",",
"129",
",",
"121",
",",
"135",
",",
"148",
",",
"148",
",",
"136",
",",
"119",
",",
"104",
","... | 38.055556 | 0.000356 |
def fix_w291(self, result):
"""Remove trailing whitespace."""
fixed_line = self.source[result['line'] - 1].rstrip()
self.source[result['line'] - 1] = fixed_line + '\n' | [
"def",
"fix_w291",
"(",
"self",
",",
"result",
")",
":",
"fixed_line",
"=",
"self",
".",
"source",
"[",
"result",
"[",
"'line'",
"]",
"-",
"1",
"]",
".",
"rstrip",
"(",
")",
"self",
".",
"source",
"[",
"result",
"[",
"'line'",
"]",
"-",
"1",
"]",... | 47 | 0.010471 |
def where_method(self, cond, other=dtypes.NA):
"""Return elements from `self` or `other` depending on `cond`.
Parameters
----------
cond : DataArray or Dataset with boolean dtype
Locations at which to preserve this objects values.
other : scalar, DataArray or Dataset, optional
Value... | [
"def",
"where_method",
"(",
"self",
",",
"cond",
",",
"other",
"=",
"dtypes",
".",
"NA",
")",
":",
"from",
".",
"computation",
"import",
"apply_ufunc",
"# alignment for three arguments is complicated, so don't support it yet",
"join",
"=",
"'inner'",
"if",
"other",
... | 36.666667 | 0.001107 |
def _isDissipative(obj):
"""
NAME:
_isDissipative
PURPOSE:
Determine whether this combination of potentials and forces is Dissipative
INPUT:
obj - Potential/DissipativeForce instance or list of such instances
OUTPUT:
True or False depending on whether the object is... | [
"def",
"_isDissipative",
"(",
"obj",
")",
":",
"from",
".",
"Potential",
"import",
"flatten",
"obj",
"=",
"flatten",
"(",
"obj",
")",
"isList",
"=",
"isinstance",
"(",
"obj",
",",
"list",
")",
"if",
"isList",
":",
"isCons",
"=",
"[",
"not",
"isinstance... | 20.9375 | 0.014265 |
def root(self, pattern, current):
"""Start parsing the pattern."""
self.set_after_start()
i = util.StringIter(pattern)
iter(i)
root_specified = False
if self.win_drive_detect:
m = RE_WIN_PATH.match(pattern)
if m:
drive = m.group(0)... | [
"def",
"root",
"(",
"self",
",",
"pattern",
",",
"current",
")",
":",
"self",
".",
"set_after_start",
"(",
")",
"i",
"=",
"util",
".",
"StringIter",
"(",
"pattern",
")",
"iter",
"(",
"i",
")",
"root_specified",
"=",
"False",
"if",
"self",
".",
"win_d... | 36.246575 | 0.001472 |
def close(self):
'''Stop running timers.'''
if self._call_later_handle:
self._call_later_handle.cancel()
self._running = False | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_call_later_handle",
":",
"self",
".",
"_call_later_handle",
".",
"cancel",
"(",
")",
"self",
".",
"_running",
"=",
"False"
] | 26.333333 | 0.01227 |
def delete_collection_namespaced_limit_range(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_limit_range # noqa: E501
delete collection of LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, p... | [
"def",
"delete_collection_namespaced_limit_range",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
... | 164.4 | 0.000403 |
def change_location(self, old_location_name, new_location_name, new_parent_name=None,
new_er_data=None, new_pmag_data=None, replace_data=False):
"""
Find actual data object for location with old_location_name.
Then call Location class change method to update location name... | [
"def",
"change_location",
"(",
"self",
",",
"old_location_name",
",",
"new_location_name",
",",
"new_parent_name",
"=",
"None",
",",
"new_er_data",
"=",
"None",
",",
"new_pmag_data",
"=",
"None",
",",
"replace_data",
"=",
"False",
")",
":",
"location",
"=",
"s... | 57.333333 | 0.011445 |
def grow(script, iterations=1):
""" Grow (dilate, expand) the current set of selected faces
Args:
script: the FilterScript object or script filename to write
the filter to.
iterations (int): the number of times to grow the selection.
Layer stack:
No impacts
MeshLab... | [
"def",
"grow",
"(",
"script",
",",
"iterations",
"=",
"1",
")",
":",
"filter_xml",
"=",
"' <filter name=\"Dilate Selection\"/>\\n'",
"for",
"_",
"in",
"range",
"(",
"iterations",
")",
":",
"util",
".",
"write_filter",
"(",
"script",
",",
"filter_xml",
")",
... | 26.578947 | 0.001912 |
def move_window(pymux, variables):
"""
Move window to a new index.
"""
dst_window = variables['<dst-window>']
try:
new_index = int(dst_window)
except ValueError:
raise CommandException('Invalid window index: %r' % (dst_window, ))
# Check first whether the index was not yet t... | [
"def",
"move_window",
"(",
"pymux",
",",
"variables",
")",
":",
"dst_window",
"=",
"variables",
"[",
"'<dst-window>'",
"]",
"try",
":",
"new_index",
"=",
"int",
"(",
"dst_window",
")",
"except",
"ValueError",
":",
"raise",
"CommandException",
"(",
"'Invalid wi... | 32.117647 | 0.001779 |
def footrule_dist(params1, params2=None):
r"""Compute Spearman's footrule distance between two models.
This function computes Spearman's footrule distance between the rankings
induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item
``i`` in the model described by ``params1``, and :ma... | [
"def",
"footrule_dist",
"(",
"params1",
",",
"params2",
"=",
"None",
")",
":",
"assert",
"params2",
"is",
"None",
"or",
"len",
"(",
"params1",
")",
"==",
"len",
"(",
"params2",
")",
"ranks1",
"=",
"rankdata",
"(",
"params1",
",",
"method",
"=",
"\"aver... | 33.076923 | 0.000753 |
def postprocess(self):
"""
Postprocessing includes renaming and gzipping where necessary.
"""
# Add suffix to all sub_dir/{items}
for path in self.neb_dirs:
for f in VASP_NEB_OUTPUT_SUB_FILES:
f = os.path.join(path, f)
if os.path.exists... | [
"def",
"postprocess",
"(",
"self",
")",
":",
"# Add suffix to all sub_dir/{items}",
"for",
"path",
"in",
"self",
".",
"neb_dirs",
":",
"for",
"f",
"in",
"VASP_NEB_OUTPUT_SUB_FILES",
":",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"f",
")",... | 43.190476 | 0.002157 |
def _c3_mro(cls, abcs=None):
"""Computes the method resolution order using extended C3 linearization.
If no *abcs* are given, the algorithm works exactly like the built-in C3
linearization used for method resolution.
If given, *abcs* is a list of abstract base classes that should be inserted
into ... | [
"def",
"_c3_mro",
"(",
"cls",
",",
"abcs",
"=",
"None",
")",
":",
"for",
"i",
",",
"base",
"in",
"enumerate",
"(",
"reversed",
"(",
"cls",
".",
"__bases__",
")",
")",
":",
"if",
"hasattr",
"(",
"base",
",",
"'__abstractmethods__'",
")",
":",
"boundar... | 51.175 | 0.001438 |
def convolve_spatial2(im, hs,
mode = "constant",
plan = None,
return_plan = False):
"""
spatial varying convolution of an 2d image with a 2d grid of psfs
shape(im_ = (Ny,Nx)
shape(hs) = (Gy,Gx, Hy,Hx)
the input image im is subdivide... | [
"def",
"convolve_spatial2",
"(",
"im",
",",
"hs",
",",
"mode",
"=",
"\"constant\"",
",",
"plan",
"=",
"None",
",",
"return_plan",
"=",
"False",
")",
":",
"if",
"im",
".",
"ndim",
"!=",
"2",
"or",
"hs",
".",
"ndim",
"!=",
"4",
":",
"raise",
"ValueEr... | 29.942308 | 0.024557 |
def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem and return the
OT matrix from empirical data
The function solves the following optimization pr... | [
"def",
"empirical_sinkhorn",
"(",
"X_s",
",",
"X_t",
",",
"reg",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"metric",
"=",
"'sqeuclidean'",
",",
"numIterMax",
"=",
"10000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log"... | 31.681818 | 0.009043 |
def write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir):
"""Write text to files."""
def write_to_file(all_files, urls_path, tmp_dir, filename):
"""Write text to files."""
with io.open(
os.path.join(tmp_dir, filename + ".source"), "w",
encoding="utf-8") as fstory:
wit... | [
"def",
"write_raw_text_to_files",
"(",
"all_files",
",",
"urls_path",
",",
"dataset_split",
",",
"tmp_dir",
")",
":",
"def",
"write_to_file",
"(",
"all_files",
",",
"urls_path",
",",
"tmp_dir",
",",
"filename",
")",
":",
"\"\"\"Write text to files.\"\"\"",
"with",
... | 36.68 | 0.014878 |
def initLogging(verbosity=0, name="SCOOP"):
"""Creates a logger."""
global loggingConfig
verbose_levels = {
-2: "CRITICAL",
-1: "ERROR",
0: "WARNING",
1: "INFO",
2: "DEBUG",
3: "DEBUG",
4: "NOSET",
}
... | [
"def",
"initLogging",
"(",
"verbosity",
"=",
"0",
",",
"name",
"=",
"\"SCOOP\"",
")",
":",
"global",
"loggingConfig",
"verbose_levels",
"=",
"{",
"-",
"2",
":",
"\"CRITICAL\"",
",",
"-",
"1",
":",
"\"ERROR\"",
",",
"0",
":",
"\"WARNING\"",
",",
"1",
":... | 28.953488 | 0.001554 |
def expand_paths(paths, marker='*'):
"""
:param paths:
A glob path pattern string or pathlib.Path object holding such path, or
a list consists of path strings or glob path pattern strings or
pathlib.Path object holding such ones, or file objects
:param marker: Glob marker character o... | [
"def",
"expand_paths",
"(",
"paths",
",",
"marker",
"=",
"'*'",
")",
":",
"if",
"is_path",
"(",
"paths",
")",
"and",
"marker",
"in",
"paths",
":",
"return",
"sglob",
"(",
"paths",
")",
"if",
"is_path_obj",
"(",
"paths",
")",
"and",
"marker",
"in",
"p... | 39.866667 | 0.000816 |
def getMissionXML(summary):
''' Build an XML mission string.'''
spawn_end_tag = ' type="mob_spawner" variant="' + MOB_TYPE + '"/>'
return '''<?xml version="1.0" encoding="UTF-8" ?>
<Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<About>
... | [
"def",
"getMissionXML",
"(",
"summary",
")",
":",
"spawn_end_tag",
"=",
"' type=\"mob_spawner\" variant=\"'",
"+",
"MOB_TYPE",
"+",
"'\"/>'",
"return",
"'''<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <Mission xmlns=\"http://ProjectMalmo.microsoft.com\" xmlns:xsi=\"http://www.w3.org/... | 49.1 | 0.014309 |
def remove_keys(d, keys=None, use_wildcards=True,
list_of_dicts=False, deepcopy=True):
"""remove certain keys from nested dict, retaining preceeding paths
Parameters
----------
keys: list
use_wildcards : bool
if true, can use * (matches everything)
and ? (matches any... | [
"def",
"remove_keys",
"(",
"d",
",",
"keys",
"=",
"None",
",",
"use_wildcards",
"=",
"True",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
")",
":",
"keys",
"=",
"[",
"]",
"if",
"keys",
"is",
"None",
"else",
"keys",
"list_of_dicts",... | 27.907692 | 0.000532 |
def prepare_communication (self):
"""
Prepare the buffers to be used for later communications
"""
RectPartitioner.prepare_communication (self)
self.in_lower_buffers = [[], []]
self.out_lower_buffers = [[], []]
self.in_upper_buffers = [[], []]
... | [
"def",
"prepare_communication",
"(",
"self",
")",
":",
"RectPartitioner",
".",
"prepare_communication",
"(",
"self",
")",
"self",
".",
"in_lower_buffers",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"self",
".",
"out_lower_buffers",
"=",
"[",
"[",
"]",
",",
... | 39.925926 | 0.009058 |
def setdict(self, D=None):
"""Set dictionary array."""
Di = np.concatenate((D, sl.atleast_nd(D.ndim, self.imp)),
axis=D.ndim-1)
self.cbpdn.setdict(Di) | [
"def",
"setdict",
"(",
"self",
",",
"D",
"=",
"None",
")",
":",
"Di",
"=",
"np",
".",
"concatenate",
"(",
"(",
"D",
",",
"sl",
".",
"atleast_nd",
"(",
"D",
".",
"ndim",
",",
"self",
".",
"imp",
")",
")",
",",
"axis",
"=",
"D",
".",
"ndim",
... | 33 | 0.009852 |
def load_json_or_yaml(string, is_path=False, file_type='json',
exception=ScriptWorkerTaskException,
message="Failed to load %(file_type)s: %(exc)s"):
"""Load json or yaml from a filehandle or string, and raise a custom exception on failure.
Args:
string (str)... | [
"def",
"load_json_or_yaml",
"(",
"string",
",",
"is_path",
"=",
"False",
",",
"file_type",
"=",
"'json'",
",",
"exception",
"=",
"ScriptWorkerTaskException",
",",
"message",
"=",
"\"Failed to load %(file_type)s: %(exc)s\"",
")",
":",
"if",
"file_type",
"==",
"'json'... | 37.615385 | 0.001993 |
def _create_tracked_field(event, instance, field, fieldname=None):
"""
Create a TrackedFieldModification for the instance.
:param event: The TrackingEvent on which to add TrackingField
:param instance: The instance on which the field is
:param field: The field name to track
:param fieldname: Th... | [
"def",
"_create_tracked_field",
"(",
"event",
",",
"instance",
",",
"field",
",",
"fieldname",
"=",
"None",
")",
":",
"fieldname",
"=",
"fieldname",
"or",
"field",
"if",
"isinstance",
"(",
"instance",
".",
"_meta",
".",
"get_field",
"(",
"field",
")",
",",... | 39.576923 | 0.000949 |
def extract_sponsor(bill):
"""
Return a list of the fields we need to map a sponser to a bill
"""
logger.debug("Extracting Sponsor")
sponsor_map = []
sponsor = bill.get('sponsor', None)
if sponsor:
sponsor_map.append(sponsor.get('type'))
sponsor_map.append(sponsor.get('thomas... | [
"def",
"extract_sponsor",
"(",
"bill",
")",
":",
"logger",
".",
"debug",
"(",
"\"Extracting Sponsor\"",
")",
"sponsor_map",
"=",
"[",
"]",
"sponsor",
"=",
"bill",
".",
"get",
"(",
"'sponsor'",
",",
"None",
")",
"if",
"sponsor",
":",
"sponsor_map",
".",
"... | 36.8 | 0.001767 |
def validate_quantity(self, value):
"""Validate that the value is of the `Quantity` type."""
if not isinstance(value, pq.quantity.Quantity):
self._error('%s' % value, "Must be a Python quantity.") | [
"def",
"validate_quantity",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"pq",
".",
"quantity",
".",
"Quantity",
")",
":",
"self",
".",
"_error",
"(",
"'%s'",
"%",
"value",
",",
"\"Must be a Python quantity.\"",
")"
] | 55.25 | 0.008929 |
def cdx_collapse_time_status(cdx_iter, timelen=10):
"""
collapse by timestamp and status code.
"""
timelen = int(timelen)
last_token = None
for cdx in cdx_iter:
curr_token = (cdx[TIMESTAMP][:timelen], cdx.get(STATUSCODE, ''))
# yield if last_dedup_time is diff, otherwise skip
... | [
"def",
"cdx_collapse_time_status",
"(",
"cdx_iter",
",",
"timelen",
"=",
"10",
")",
":",
"timelen",
"=",
"int",
"(",
"timelen",
")",
"last_token",
"=",
"None",
"for",
"cdx",
"in",
"cdx_iter",
":",
"curr_token",
"=",
"(",
"cdx",
"[",
"TIMESTAMP",
"]",
"["... | 26.666667 | 0.002415 |
def start_recording(self, file='mingus_dump.wav'):
"""Initialize a new wave file for recording."""
w = wave.open(file, 'wb')
w.setnchannels(2)
w.setsampwidth(2)
w.setframerate(44100)
self.wav = w | [
"def",
"start_recording",
"(",
"self",
",",
"file",
"=",
"'mingus_dump.wav'",
")",
":",
"w",
"=",
"wave",
".",
"open",
"(",
"file",
",",
"'wb'",
")",
"w",
".",
"setnchannels",
"(",
"2",
")",
"w",
".",
"setsampwidth",
"(",
"2",
")",
"w",
".",
"setfr... | 33.857143 | 0.00823 |
def _render_conditions(conditions):
"""Render the conditions part of a query.
Parameters
----------
conditions : list
A list of dictionary items to filter a table.
Returns
-------
str
A string that represents the "where" part of a query
See Also
--------
render... | [
"def",
"_render_conditions",
"(",
"conditions",
")",
":",
"if",
"not",
"conditions",
":",
"return",
"\"\"",
"rendered_conditions",
"=",
"[",
"]",
"for",
"condition",
"in",
"conditions",
":",
"field",
"=",
"condition",
".",
"get",
"(",
"'field'",
")",
"field_... | 24.717949 | 0.000998 |
def sum_of_squares(obs, pred):
"""
Sum of squares between observed and predicted data
Parameters
----------
obs : iterable
Observed data
pred : iterable
Predicted data
Returns
-------
float
Sum of squares
Notes
-----
The length of observed and p... | [
"def",
"sum_of_squares",
"(",
"obs",
",",
"pred",
")",
":",
"return",
"np",
".",
"sum",
"(",
"(",
"np",
".",
"array",
"(",
"obs",
")",
"-",
"np",
".",
"array",
"(",
"pred",
")",
")",
"**",
"2",
")"
] | 16.956522 | 0.002427 |
def fetch_and_execute_function_to_run(self, key):
"""Run on arbitrary function on the worker."""
(driver_id, serialized_function,
run_on_other_drivers) = self.redis_client.hmget(
key, ["driver_id", "function", "run_on_other_drivers"])
if (utils.decode(run_on_other_drivers)... | [
"def",
"fetch_and_execute_function_to_run",
"(",
"self",
",",
"key",
")",
":",
"(",
"driver_id",
",",
"serialized_function",
",",
"run_on_other_drivers",
")",
"=",
"self",
".",
"redis_client",
".",
"hmget",
"(",
"key",
",",
"[",
"\"driver_id\"",
",",
"\"function... | 42.730769 | 0.001761 |
def _strip_top_comments(lines):
"""Strips # comments that exist at the top of the given lines"""
lines = copy.copy(lines)
while lines and lines[0].startswith("#"):
lines = lines[1:]
return "\n".join(lines) | [
"def",
"_strip_top_comments",
"(",
"lines",
")",
":",
"lines",
"=",
"copy",
".",
"copy",
"(",
"lines",
")",
"while",
"lines",
"and",
"lines",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"lines",
"=",
"lines",
"[",
"1",
":",
"]",
"retu... | 40.666667 | 0.008032 |
def add_item_metadata(self, handle, key, value):
"""Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value
"""
... | [
"def",
"add_item_metadata",
"(",
"self",
",",
"handle",
",",
"key",
",",
"value",
")",
":",
"identifier",
"=",
"generate_identifier",
"(",
"handle",
")",
"metadata_blob_suffix",
"=",
"\"{}.{}.json\"",
".",
"format",
"(",
"identifier",
",",
"key",
")",
"metadat... | 31.222222 | 0.002301 |
def normalize_allele_name(raw_allele, omit_dra1=False, infer_class2_pair=True):
"""MHC alleles are named with a frustratingly loose system. It's not uncommon
to see dozens of different forms for the same allele.
Note: this function works with both class I and class II allele names (including
alpha/beta... | [
"def",
"normalize_allele_name",
"(",
"raw_allele",
",",
"omit_dra1",
"=",
"False",
",",
"infer_class2_pair",
"=",
"True",
")",
":",
"cache_key",
"=",
"(",
"raw_allele",
",",
"omit_dra1",
",",
"infer_class2_pair",
")",
"if",
"cache_key",
"in",
"_normalized_allele_c... | 33.945946 | 0.001161 |
def is_dirty(using=None):
"""
Returns True if the current transaction requires a commit for changes to
happen.
"""
if using is None:
dirty = False
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
if connection.is_dirty():
... | [
"def",
"is_dirty",
"(",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"None",
":",
"dirty",
"=",
"False",
"for",
"using",
"in",
"tldap",
".",
"backend",
".",
"connections",
":",
"connection",
"=",
"tldap",
".",
"backend",
".",
"connections",
"["... | 31.285714 | 0.002217 |
def bank_identifier(self):
"""Return the IBAN's Bank Identifier."""
end = get_iban_spec(self.country_code).bban_split_pos + 4
return self._id[4:end] | [
"def",
"bank_identifier",
"(",
"self",
")",
":",
"end",
"=",
"get_iban_spec",
"(",
"self",
".",
"country_code",
")",
".",
"bban_split_pos",
"+",
"4",
"return",
"self",
".",
"_id",
"[",
"4",
":",
"end",
"]"
] | 42.25 | 0.011628 |
def _F_hyperedge_cardinality_ratio(H, F):
"""Returns the result of a function F applied to the set of cardinality
ratios between the tail and the head sets (specifically, |tail|/|head|) of
hyperedges in the hypergraph.
:param H: the hypergraph whose cardinality ratios will be
operat... | [
"def",
"_F_hyperedge_cardinality_ratio",
"(",
"H",
",",
"F",
")",
":",
"if",
"not",
"isinstance",
"(",
"H",
",",
"DirectedHypergraph",
")",
":",
"raise",
"TypeError",
"(",
"\"Algorithm only applicable to directed hypergraphs\"",
")",
"# Since |head| can potentially be 0 (... | 47.52381 | 0.000982 |
def intervaljoin(left, right, lstart='start', lstop='stop', rstart='start',
rstop='stop', lkey=None, rkey=None, include_stop=False,
lprefix=None, rprefix=None):
"""
Join two tables by overlapping intervals. E.g.::
>>> import petl as etl
>>> left = [['begin', 'e... | [
"def",
"intervaljoin",
"(",
"left",
",",
"right",
",",
"lstart",
"=",
"'start'",
",",
"lstop",
"=",
"'stop'",
",",
"rstart",
"=",
"'start'",
",",
"rstop",
"=",
"'stop'",
",",
"lkey",
"=",
"None",
",",
"rkey",
"=",
"None",
",",
"include_stop",
"=",
"F... | 49 | 0.000885 |
def indent_lines(lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line,
indentation_method, get_block):
"""Returns None.
The way this function produces output is by adding strings to the
list that's passed in as the second parameter.
Paramete... | [
"def",
"indent_lines",
"(",
"lines",
",",
"output",
",",
"branch_method",
",",
"leaf_method",
",",
"pass_syntax",
",",
"flush_left_syntax",
",",
"flush_left_empty_line",
",",
"indentation_method",
",",
"get_block",
")",
":",
"append",
"=",
"output",
".",
"append",... | 31.127273 | 0.001133 |
def jsonGraph(fdefs,calls,outfile='nout.json'):
'''For reference, each node has:
node.name (string)
node.source (string)
node.weight (int)
node.pclass (class node object)
Each call contains a node in call.source and call.target
'''
outpath = os.path.join('data',outfile)
... | [
"def",
"jsonGraph",
"(",
"fdefs",
",",
"calls",
",",
"outfile",
"=",
"'nout.json'",
")",
":",
"outpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'data'",
",",
"outfile",
")",
"data",
"=",
"dict",
"(",
")",
"ids",
"=",
"dict",
"(",
")",
"nodelist... | 29.634146 | 0.011155 |
def get_wxa_code(self,
path,
width=430,
auto_color=False,
line_color={"r": "0", "g": "0", "b": "0"},
is_hyaline=False):
"""
创建小程序码(接口A: 适用于需要的码数量较少的业务场景)
详情请参考
https://mp.weixin.qq.co... | [
"def",
"get_wxa_code",
"(",
"self",
",",
"path",
",",
"width",
"=",
"430",
",",
"auto_color",
"=",
"False",
",",
"line_color",
"=",
"{",
"\"r\"",
":",
"\"0\"",
",",
"\"g\"",
":",
"\"0\"",
",",
"\"b\"",
":",
"\"0\"",
"}",
",",
"is_hyaline",
"=",
"Fals... | 30.190476 | 0.010703 |
def _process_session(self):
"""Process the outputs of the nailgun session.
:raises: :class:`NailgunProtocol.ProcessStreamTimeout` if a timeout set from a signal handler
with .set_exit_timeout() completes.
:raises: :class:`Exception` if the session ... | [
"def",
"_process_session",
"(",
"self",
")",
":",
"try",
":",
"for",
"chunk_type",
",",
"payload",
"in",
"self",
".",
"iter_chunks",
"(",
"self",
".",
"_sock",
",",
"return_bytes",
"=",
"True",
",",
"timeout_object",
"=",
"self",
")",
":",
"# TODO(#6579): ... | 54.298246 | 0.013329 |
def add_property_response(multistatusEL, href, propList):
"""Append <response> element to <multistatus> element.
<prop> node depends on the value type:
- str or unicode: add element with this content
- None: add an empty element
- etree.Element: add XML element as child
- DAVError: add ... | [
"def",
"add_property_response",
"(",
"multistatusEL",
",",
"href",
",",
"propList",
")",
":",
"# Split propList by status code and build a unique list of namespaces",
"nsCount",
"=",
"1",
"nsDict",
"=",
"{",
"}",
"nsMap",
"=",
"{",
"}",
"propDict",
"=",
"{",
"}",
... | 40.274194 | 0.001955 |
def enqueue(self, s):
"""
Append `s` to the queue.
Equivalent to::
queue += s
if `queue` where a regular string.
"""
self._parts.append(s)
self._len += len(s) | [
"def",
"enqueue",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"_parts",
".",
"append",
"(",
"s",
")",
"self",
".",
"_len",
"+=",
"len",
"(",
"s",
")"
] | 20.5 | 0.019455 |
def get_host(name):
"""
Prints the public dns name of `name`, if it exists.
:param name: The instance name.
:type name: ``str``
"""
f = {'instance-state-name': 'running', 'tag:Name': name}
ec2 = boto.connect_ec2(region=get_region())
rs = ec2.get_all_instances(filters=f)
if len(rs) =... | [
"def",
"get_host",
"(",
"name",
")",
":",
"f",
"=",
"{",
"'instance-state-name'",
":",
"'running'",
",",
"'tag:Name'",
":",
"name",
"}",
"ec2",
"=",
"boto",
".",
"connect_ec2",
"(",
"region",
"=",
"get_region",
"(",
")",
")",
"rs",
"=",
"ec2",
".",
"... | 31.692308 | 0.002358 |
def get_key(dotenv_path, key_to_get, verbose=False):
"""
Gets the value of a given key from the given .env
If the .env path given doesn't exist, fails
:param dotenv_path: path
:param key_to_get: key
:param verbose: verbosity flag, raise warning if path does not exist
:return: value of varia... | [
"def",
"get_key",
"(",
"dotenv_path",
",",
"key_to_get",
",",
"verbose",
"=",
"False",
")",
":",
"key_to_get",
"=",
"str",
"(",
"key_to_get",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dotenv_path",
")",
":",
"if",
"verbose",
":",
"warni... | 35.409091 | 0.00125 |
def render_attrs(attrs):
"""
Render HTML attributes, or return '' if no attributes needs to be rendered.
"""
if attrs is not None:
def parts():
for key, value in sorted(attrs.items()):
if value is None:
continue
if value is True:
... | [
"def",
"render_attrs",
"(",
"attrs",
")",
":",
"if",
"attrs",
"is",
"not",
"None",
":",
"def",
"parts",
"(",
")",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"attrs",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
"is",
"None",
":",
... | 37.652174 | 0.001126 |
def _configure_logging(self):
"""
Setting up logging from logging config in settings
"""
if not self.LOGGING_CONFIG:
#Fallback to default logging in global settings if needed
dictConfig(self.DEFAULT_LOGGING)
else:
dictConfig(self.LOGGING_CONFIG... | [
"def",
"_configure_logging",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"LOGGING_CONFIG",
":",
"#Fallback to default logging in global settings if needed",
"dictConfig",
"(",
"self",
".",
"DEFAULT_LOGGING",
")",
"else",
":",
"dictConfig",
"(",
"self",
".",
"LO... | 34.777778 | 0.009346 |
def loads(s, single=False, version=_default_version,
strict=False, errors='warn'):
"""
Deserialize SimpleMRS string representations
Args:
s (str): a SimpleMRS string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unles... | [
"def",
"loads",
"(",
"s",
",",
"single",
"=",
"False",
",",
"version",
"=",
"_default_version",
",",
"strict",
"=",
"False",
",",
"errors",
"=",
"'warn'",
")",
":",
"ms",
"=",
"deserialize",
"(",
"s",
",",
"version",
"=",
"version",
",",
"strict",
"=... | 29.5 | 0.002053 |
def compute_frame(self, **kwargs):
r"""Compute the associated frame.
A filter bank defines a frame, which is a generalization of a basis to
sets of vectors that may be linearly dependent. See
`Wikipedia <https://en.wikipedia.org/wiki/Frame_(linear_algebra)>`_.
The frame of a fi... | [
"def",
"compute_frame",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"G",
".",
"N",
">",
"2000",
":",
"_logger",
".",
"warning",
"(",
"'Creating a big matrix. '",
"'You should prefer the filter method.'",
")",
"# Filter one delta per vertex."... | 35.553191 | 0.000582 |
def findpaths(CIJ, qmax, sources, savepths=False):
'''
Paths are sequences of linked nodes, that never visit a single node
more than once. This function finds all paths that start at a set of
source nodes, up to a specified length. Warning: very memory-intensive.
Parameters
----------
CIJ :... | [
"def",
"findpaths",
"(",
"CIJ",
",",
"qmax",
",",
"sources",
",",
"savepths",
"=",
"False",
")",
":",
"CIJ",
"=",
"binarize",
"(",
"CIJ",
",",
"copy",
"=",
"True",
")",
"# ensure CIJ is binary",
"n",
"=",
"len",
"(",
"CIJ",
")",
"k",
"=",
"np",
"."... | 35.554054 | 0.00037 |
def equate_nickname(name1, name2):
"""
Evaluates whether names match based on common nickname patterns
This is not currently used in any name comparison
"""
# Convert '-ie' and '-y' to the root name
nickname_regex = r'(.)\1(y|ie)$'
root_regex = r'\1'
name1 = re.sub(nickname_regex, root... | [
"def",
"equate_nickname",
"(",
"name1",
",",
"name2",
")",
":",
"# Convert '-ie' and '-y' to the root name",
"nickname_regex",
"=",
"r'(.)\\1(y|ie)$'",
"root_regex",
"=",
"r'\\1'",
"name1",
"=",
"re",
".",
"sub",
"(",
"nickname_regex",
",",
"root_regex",
",",
"name1... | 26.294118 | 0.00216 |
def list_holds(pattern=__HOLD_PATTERN, full=True):
r'''
.. versionchanged:: 2016.3.0,2015.8.4,2015.5.10
Function renamed from ``pkg.get_locked_pkgs`` to ``pkg.list_holds``.
List information on locked packages
.. note::
Requires the appropriate ``versionlock`` plugin package to be insta... | [
"def",
"list_holds",
"(",
"pattern",
"=",
"__HOLD_PATTERN",
",",
"full",
"=",
"True",
")",
":",
"_check_versionlock",
"(",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"[",
"_yum",
"(",
")",
",",
"'versionlock'",
",",
"'list'",
"]",
",",
"p... | 29.974359 | 0.001657 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.