text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def ls(checks):
"""List active or available environments."""
if checks:
checks = sorted(get_testable_checks() & set(checks))
for check in checks:
envs = get_available_tox_envs(check, e2e_only=True)
if envs:
echo_success('{}:'.format(check))
... | [
"def",
"ls",
"(",
"checks",
")",
":",
"if",
"checks",
":",
"checks",
"=",
"sorted",
"(",
"get_testable_checks",
"(",
")",
"&",
"set",
"(",
"checks",
")",
")",
"for",
"check",
"in",
"checks",
":",
"envs",
"=",
"get_available_tox_envs",
"(",
"check",
","... | 29.666667 | 0.001555 |
def config(self, key, value=None, **kwargs):
"""Controls configuration variables.
.. code-block:: python
>>> c.config("Addresses.Gateway")
{'Key': 'Addresses.Gateway', 'Value': '/ip4/127.0.0.1/tcp/8080'}
>>> c.config("Addresses.Gateway", "/ip4/127.0.0.1/tcp/8081")
... | [
"def",
"config",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"key",
",",
"value",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/config'",
",",
"args",
",",
"decoder",
"... | 34.347826 | 0.002463 |
def fit_mle(self,
init_vals,
num_draws,
seed=None,
constrained_pos=None,
print_res=True,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=... | [
"def",
"fit_mle",
"(",
"self",
",",
"init_vals",
",",
"num_draws",
",",
"seed",
"=",
"None",
",",
"constrained_pos",
"=",
"None",
",",
"print_res",
"=",
"True",
",",
"method",
"=",
"\"BFGS\"",
",",
"loss_tol",
"=",
"1e-06",
",",
"gradient_tol",
"=",
"1e-... | 45.308271 | 0.002273 |
def get_weight(self, weight=operator.attrgetter('weight')):
"""
:param weight: source weight function
:returns: total weight of the source model
"""
return sum(weight(src) for src in self.get_sources()) | [
"def",
"get_weight",
"(",
"self",
",",
"weight",
"=",
"operator",
".",
"attrgetter",
"(",
"'weight'",
")",
")",
":",
"return",
"sum",
"(",
"weight",
"(",
"src",
")",
"for",
"src",
"in",
"self",
".",
"get_sources",
"(",
")",
")"
] | 39.5 | 0.008264 |
def print_exception(etype, value, tb, limit=None, file=None):
"""Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
This differs from print_tb() in the following ways: (1) if
traceback is not None, it prints a header "Traceback (most recent
call last):"; (2) it prints the exception ... | [
"def",
"print_exception",
"(",
"etype",
",",
"value",
",",
"tb",
",",
"limit",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"# TODO: Use sys.stderr when that's implemented.",
"file",
"=",
"open",
"(",
"'/dev/stderr'",
","... | 43.190476 | 0.002157 |
def set_thumbnail(self, thumbnail):
'''Sets the listitem's thumbnail image'''
self._thumbnail = thumbnail
return self._listitem.setThumbnailImage(thumbnail) | [
"def",
"set_thumbnail",
"(",
"self",
",",
"thumbnail",
")",
":",
"self",
".",
"_thumbnail",
"=",
"thumbnail",
"return",
"self",
".",
"_listitem",
".",
"setThumbnailImage",
"(",
"thumbnail",
")"
] | 44.25 | 0.011111 |
def _children(self):
"""Yield all direct children of this object."""
for codeobj in self.parameters:
yield codeobj
for codeobj in self.body._children():
yield codeobj | [
"def",
"_children",
"(",
"self",
")",
":",
"for",
"codeobj",
"in",
"self",
".",
"parameters",
":",
"yield",
"codeobj",
"for",
"codeobj",
"in",
"self",
".",
"body",
".",
"_children",
"(",
")",
":",
"yield",
"codeobj"
] | 34.833333 | 0.009346 |
def p_pkg_home_2(self, p):
"""pkg_home : PKG_HOME error"""
self.error = True
msg = ERROR_MESSAGES['PKG_HOME_VALUE']
self.logger.log(msg) | [
"def",
"p_pkg_home_2",
"(",
"self",
",",
"p",
")",
":",
"self",
".",
"error",
"=",
"True",
"msg",
"=",
"ERROR_MESSAGES",
"[",
"'PKG_HOME_VALUE'",
"]",
"self",
".",
"logger",
".",
"log",
"(",
"msg",
")"
] | 32.8 | 0.011905 |
def main(device_type):
"""Parse command-line arguments."""
epilog = ('See https://github.com/romanz/trezor-agent/blob/master/'
'doc/README-GPG.md for usage examples.')
parser = argparse.ArgumentParser(epilog=epilog)
agent_package = device_type.package_name()
resources_map = {r.key: r ... | [
"def",
"main",
"(",
"device_type",
")",
":",
"epilog",
"=",
"(",
"'See https://github.com/romanz/trezor-agent/blob/master/'",
"'doc/README-GPG.md for usage examples.'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"epilog",
"=",
"epilog",
")",
"agent_packag... | 47.847826 | 0.000445 |
def remove_link_type_vlan(enode, name, shell=None):
"""
Delete a virtual link.
Deletes a vlan device with the name {name}.
Will raise an expection if the port is not already present.
:param enode: Engine node to communicate with.
:type enode: topology.platforms.base.BaseNode
:param str nam... | [
"def",
"remove_link_type_vlan",
"(",
"enode",
",",
"name",
",",
"shell",
"=",
"None",
")",
":",
"assert",
"name",
"if",
"name",
"not",
"in",
"enode",
".",
"ports",
":",
"raise",
"ValueError",
"(",
"'Port {name} doesn\\'t exists'",
".",
"format",
"(",
"name",... | 33 | 0.001227 |
def _validate(wrapped):
'''
Decorator for common function argument validation
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
container_type = kwargs.get('container_type')
exec_driver = kwargs.get('exec_driver')
valid_driver = {
'docker': ('lxc-attach'... | [
"def",
"_validate",
"(",
"wrapped",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"wrapped",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"container_type",
"=",
"kwargs",
".",
"get",
"(",
"'container_type'",
")",
"exec_d... | 42.5 | 0.001534 |
def get_branches(self):
"""
:calls: `GET /repos/:owner/:repo/branches <http://developer.github.com/v3/repos>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Branch.Branch`
"""
return github.PaginatedList.PaginatedList(
github.Branch.Branch,
... | [
"def",
"get_branches",
"(",
"self",
")",
":",
"return",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"(",
"github",
".",
"Branch",
".",
"Branch",
",",
"self",
".",
"_requester",
",",
"self",
".",
"url",
"+",
"\"/branches\"",
",",
"None",
")"
] | 36.181818 | 0.009804 |
def _by_columns(self, columns):
"""
Allow select.group and select.order accepting string and list
"""
return columns if self.isstr(columns) else self._backtick_columns(columns) | [
"def",
"_by_columns",
"(",
"self",
",",
"columns",
")",
":",
"return",
"columns",
"if",
"self",
".",
"isstr",
"(",
"columns",
")",
"else",
"self",
".",
"_backtick_columns",
"(",
"columns",
")"
] | 40.8 | 0.014423 |
def __option(self):
""" Check and return option from section from configuration. Option name is equal to option prefix
:return: tuple of section name and option prefix
"""
section = self.section()
option = self.option_prefix()
if self.config().has_option(section, option) is False:
raise NoOptionError(op... | [
"def",
"__option",
"(",
"self",
")",
":",
"section",
"=",
"self",
".",
"section",
"(",
")",
"option",
"=",
"self",
".",
"option_prefix",
"(",
")",
"if",
"self",
".",
"config",
"(",
")",
".",
"has_option",
"(",
"section",
",",
"option",
")",
"is",
"... | 35 | 0.030641 |
def minimize(self, model, session=None, var_list=None, feed_dict=None,
maxiter=1000, initialize=True, anchor=True, step_callback=None, **kwargs):
"""
:param model: GPflow model with objective tensor.
:param session: Session where optimization will be run.
:param var_list... | [
"def",
"minimize",
"(",
"self",
",",
"model",
",",
"session",
"=",
"None",
",",
"var_list",
"=",
"None",
",",
"feed_dict",
"=",
"None",
",",
"maxiter",
"=",
"1000",
",",
"initialize",
"=",
"True",
",",
"anchor",
"=",
"True",
",",
"step_callback",
"=",
... | 62 | 0.010033 |
def _setup_potential(self, R, z, use_pkdgrav = False, dr = 0.0001) :
"""
Calculates the potential and force grids for the snapshot for
use with other galpy functions.
**Input**:
*R*: R grid coordinates (numpy array)
*z*: z grid coordinates (nu... | [
"def",
"_setup_potential",
"(",
"self",
",",
"R",
",",
"z",
",",
"use_pkdgrav",
"=",
"False",
",",
"dr",
"=",
"0.0001",
")",
":",
"# set up the four points per R,z pair to mimic axisymmetry",
"points",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"R",
")",... | 44.548611 | 0.020738 |
def _github_count(self, url):
"""
Get counts for requests that return 'total_count' in the json response.
"""
url = self.url_api + url + "&per_page=1"
# if we have authentication details use them as we get better
# rate-limiting.
if self.username and self.auth_tok... | [
"def",
"_github_count",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"self",
".",
"url_api",
"+",
"url",
"+",
"\"&per_page=1\"",
"# if we have authentication details use them as we get better",
"# rate-limiting.",
"if",
"self",
".",
"username",
"and",
"self",
".",... | 37.227273 | 0.002381 |
def fburl(parser, token):
"""
Returns an absolute URL matching given view with its parameters.
This is a way to define links that aren't tied to a particular URL
configuration::
{% url path.to.some_view arg1,arg2,name1=value1 %}
The first argument is a path to a view. It can be an absolut... | [
"def",
"fburl",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
"' '",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"'%s' takes at least one ar... | 34.654545 | 0.001531 |
def fftr(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the real part of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less... | [
"def",
"fftr",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"return",
"real",
"(",
"fft",
"(",
"wave",
",",
"npoints",
",",
"indep_min",
",",
"indep_max",
")",
")"
] | 33.023256 | 0.000684 |
def getCert(username, password,
certHost=_SERVER,
certfile=None,
certQuery=_PROXY):
"""Access the cadc certificate server."""
if certfile is None:
certfile = tempfile.NamedTemporaryFile()
# Add the username and password.
# If we knew the realm, we could use ... | [
"def",
"getCert",
"(",
"username",
",",
"password",
",",
"certHost",
"=",
"_SERVER",
",",
"certfile",
"=",
"None",
",",
"certQuery",
"=",
"_PROXY",
")",
":",
"if",
"certfile",
"is",
"None",
":",
"certfile",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
... | 27.702128 | 0.001484 |
def deep_equal(a, b):
"""
Because of things in python like:
>>> 1 == 1.0
True
>>> 1 == True
True
>>> b'test' == 'test' # python3
False
"""
if is_any_string_type(a) and is_any_string_type(b):
if isinstance(a, six.binary_type):
a = six.t... | [
"def",
"deep_equal",
"(",
"a",
",",
"b",
")",
":",
"if",
"is_any_string_type",
"(",
"a",
")",
"and",
"is_any_string_type",
"(",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"six",
".",
"binary_type",
")",
":",
"a",
"=",
"six",
".",
"text_type",
... | 30.647059 | 0.001862 |
def spots_at(self, x, y):
"""Iterate over spots that collide the given point."""
for spot in self.spot.values():
if spot.collide_point(x, y):
yield spot | [
"def",
"spots_at",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"for",
"spot",
"in",
"self",
".",
"spot",
".",
"values",
"(",
")",
":",
"if",
"spot",
".",
"collide_point",
"(",
"x",
",",
"y",
")",
":",
"yield",
"spot"
] | 38.4 | 0.010204 |
def b64decode(s, altchars=None):
"""Decode a Base64 encoded string.
s is the string to decode. Optional altchars must be a string of at least
length 2 (additional characters are ignored) which specifies the
alternative alphabet used instead of the '+' and '/' characters.
The decoded string is ret... | [
"def",
"b64decode",
"(",
"s",
",",
"altchars",
"=",
"None",
")",
":",
"if",
"altchars",
"is",
"not",
"None",
":",
"s",
"=",
"s",
".",
"translate",
"(",
"string",
".",
"maketrans",
"(",
"altchars",
"[",
":",
"2",
"]",
",",
"'+/'",
")",
")",
"try",... | 40 | 0.001285 |
def create_record_srv(self, zone_id, record, data, protocol, port, service,
ttl=60, priority=20, weight=10):
"""Create a resource record on a domain.
:param integer id: the zone's ID
:param record: the name of the record to add
:param data: the record's value
... | [
"def",
"create_record_srv",
"(",
"self",
",",
"zone_id",
",",
"record",
",",
"data",
",",
"protocol",
",",
"port",
",",
"service",
",",
"ttl",
"=",
"60",
",",
"priority",
"=",
"20",
",",
"weight",
"=",
"10",
")",
":",
"resource_record",
"=",
"self",
... | 57.565217 | 0.008172 |
def inject_target(self, target, dependencies=None, derived_from=None, synthetic=False):
"""Injects a fully realized Target into the BuildGraph.
:API: public
:param Target target: The Target to inject.
:param list<Address> dependencies: The Target addresses that `target` depends on.
:param Target d... | [
"def",
"inject_target",
"(",
"self",
",",
"target",
",",
"dependencies",
"=",
"None",
",",
"derived_from",
"=",
"None",
",",
"synthetic",
"=",
"False",
")",
":",
"if",
"self",
".",
"contains_address",
"(",
"target",
".",
"address",
")",
":",
"raise",
"Va... | 49.77551 | 0.008444 |
def open(self):
""" Daemonize this process
Do everything that is needed to become a Unix daemon.
:return: None
:raise: DaemonError
"""
if self.is_open:
return
try:
os.chdir(self.working_directory)
if self.chroot_directory:
... | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_open",
":",
"return",
"try",
":",
"os",
".",
"chdir",
"(",
"self",
".",
"working_directory",
")",
"if",
"self",
".",
"chroot_directory",
":",
"os",
".",
"chroot",
"(",
"self",
".",
"chroot_... | 30.814815 | 0.001165 |
def download_example_datasets(self):
""" Download example datasets from `openSNP <https://opensnp.org>`_.
Per openSNP, "the data is donated into the public domain using `CC0 1.0
<http://creativecommons.org/publicdomain/zero/1.0/>`_."
Returns
-------
paths : list of str ... | [
"def",
"download_example_datasets",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"paths",
".",
"append",
"(",
"self",
".",
"_download_file",
"(",
"\"https://opensnp.org/data/662.23andme.304\"",
",",
"\"662.23andme.304.txt.gz\"",
",",
"compress",
"=",
"True",
",",
... | 34.216867 | 0.002053 |
def anonymous_login(services):
"""Initialize services without authenticating to Globus Auth.
Note:
Clients may have reduced functionality without authentication.
Arguments:
services (str or list of str): The services to initialize clients for.
Returns:
dict: The clients reques... | [
"def",
"anonymous_login",
"(",
"services",
")",
":",
"if",
"isinstance",
"(",
"services",
",",
"str",
")",
":",
"services",
"=",
"[",
"services",
"]",
"clients",
"=",
"{",
"}",
"# Initialize valid services",
"for",
"serv",
"in",
"services",
":",
"try",
":"... | 33.148148 | 0.001086 |
def main():
"""
NAME
plotdi_a.py
DESCRIPTION
plots equal area projection from dec inc data and fisher mean, cone of confidence
INPUT FORMAT
takes dec, inc, alpha95 as first three columns in space delimited file
SYNTAX
plotdi_a.py [-i][-f FILE]
OPTIONS
-f ... | [
"def",
"main",
"(",
")",
":",
"fmt",
",",
"plot",
"=",
"'svg'",
",",
"0",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"0",
":",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"# check if help is needed",
"print",
"(",
"main",
".",
"__doc__",
")... | 32.105263 | 0.025447 |
def derivativeY(self,mLvl,pLvl,MedShk):
'''
Evaluate the derivative of consumption and medical care with respect to
permanent income at given levels of market resources, permanent income,
and medical need shocks.
Parameters
----------
mLvl : np.array
... | [
"def",
"derivativeY",
"(",
"self",
",",
"mLvl",
",",
"pLvl",
",",
"MedShk",
")",
":",
"xLvl",
"=",
"self",
".",
"xFunc",
"(",
"mLvl",
",",
"pLvl",
",",
"MedShk",
")",
"dxdp",
"=",
"self",
".",
"xFunc",
".",
"derivativeY",
"(",
"mLvl",
",",
"pLvl",
... | 35.6 | 0.010939 |
def to_dataframe(self, columns=None):
"""Convert a multi-dim to a pandas dataframe."""
if not isinstance(self.measured_value, DimensionedMeasuredValue):
raise TypeError(
'Only a dimensioned measurement can be converted to a DataFrame')
if columns is None:
columns = [d.name for d in self... | [
"def",
"to_dataframe",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"measured_value",
",",
"DimensionedMeasuredValue",
")",
":",
"raise",
"TypeError",
"(",
"'Only a dimensioned measurement can be converted to a DataF... | 35.615385 | 0.008421 |
def set_array(longarray, shortarray):
"""
:param longarray: a numpy array of floats of length L >= l
:param shortarray: a numpy array of floats of length l
Fill `longarray` with the values of `shortarray`, starting from the left.
If `shortarry` is shorter than `longarray`, then the remaining elemen... | [
"def",
"set_array",
"(",
"longarray",
",",
"shortarray",
")",
":",
"longarray",
"[",
":",
"len",
"(",
"shortarray",
")",
"]",
"=",
"shortarray",
"longarray",
"[",
"len",
"(",
"shortarray",
")",
":",
"]",
"=",
"numpy",
".",
"nan"
] | 42 | 0.002119 |
def file_code(function_index=1, function_name=None):
"""
This will return the code of the calling function
function_index of 2 will give the parent of the caller
function_name should not be used with function_index
:param function_index: int of how many frames back the program should look
:para... | [
"def",
"file_code",
"(",
"function_index",
"=",
"1",
",",
"function_name",
"=",
"None",
")",
":",
"info",
"=",
"function_info",
"(",
"function_index",
"+",
"1",
",",
"function_name",
")",
"with",
"open",
"(",
"info",
"[",
"'file'",
"]",
",",
"'r'",
")",
... | 41.846154 | 0.001799 |
def cycle_focus(self):
"""
Cycle through all windows.
"""
windows = self.windows()
new_index = (windows.index(self.active_window) + 1) % len(windows)
self.active_window = windows[new_index] | [
"def",
"cycle_focus",
"(",
"self",
")",
":",
"windows",
"=",
"self",
".",
"windows",
"(",
")",
"new_index",
"=",
"(",
"windows",
".",
"index",
"(",
"self",
".",
"active_window",
")",
"+",
"1",
")",
"%",
"len",
"(",
"windows",
")",
"self",
".",
"act... | 33 | 0.008439 |
def frequency(self, context):
""" Frequency data source """
channels = self._manager.spectral_window_table.getcol(MS.CHAN_FREQ)
return channels.reshape(context.shape).astype(context.dtype) | [
"def",
"frequency",
"(",
"self",
",",
"context",
")",
":",
"channels",
"=",
"self",
".",
"_manager",
".",
"spectral_window_table",
".",
"getcol",
"(",
"MS",
".",
"CHAN_FREQ",
")",
"return",
"channels",
".",
"reshape",
"(",
"context",
".",
"shape",
")",
"... | 52.25 | 0.009434 |
def binomial(n,k):
"""
Binomial coefficient
>>> binomial(5,2)
10
>>> binomial(10,5)
252
"""
if n==k: return 1
assert n>k, "Attempting to call binomial(%d,%d)" % (n,k)
return factorial(n)//(factorial(k)*factorial(n-k)) | [
"def",
"binomial",
"(",
"n",
",",
"k",
")",
":",
"if",
"n",
"==",
"k",
":",
"return",
"1",
"assert",
"n",
">",
"k",
",",
"\"Attempting to call binomial(%d,%d)\"",
"%",
"(",
"n",
",",
"k",
")",
"return",
"factorial",
"(",
"n",
")",
"//",
"(",
"facto... | 22.454545 | 0.023346 |
def user_cache_dir(appname):
r"""
Return full path to the user-specific cache dir for this application.
"appname" is the name of application.
Typical user cache directories are:
Mac OS X: ~/Library/Caches/<AppName>
Unix: ~/.cache/<AppName> (XDG default)
Windows: ... | [
"def",
"user_cache_dir",
"(",
"appname",
")",
":",
"if",
"WINDOWS",
":",
"# Get the base path",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"_get_win_folder",
"(",
"\"CSIDL_LOCAL_APPDATA\"",
")",
")",
"# Add our app name and Cache directory to it",
"path",
... | 35.268293 | 0.000673 |
def hello(self):
"""http://docs.fiesta.cc/index.html#getting-started"""
path = 'hello'
response = self.request(path, do_authentication=False)
return response | [
"def",
"hello",
"(",
"self",
")",
":",
"path",
"=",
"'hello'",
"response",
"=",
"self",
".",
"request",
"(",
"path",
",",
"do_authentication",
"=",
"False",
")",
"return",
"response"
] | 37 | 0.010582 |
def _radixPass(a, b, r, n, K):
"""
Stable sort of the sequence a according to the keys given in r.
>>> a=range(5)
>>> b=[0]*5
>>> r=[2,1,3,0,4]
>>> _radixPass(a, b, r, 5, 5)
>>> b
[3, 1, 0, 2, 4]
When n is less than the length of a, the end of b must be left unaltered.
>>> b=[... | [
"def",
"_radixPass",
"(",
"a",
",",
"b",
",",
"r",
",",
"n",
",",
"K",
")",
":",
"c",
"=",
"_array",
"(",
"\"i\"",
",",
"[",
"0",
"]",
"*",
"(",
"K",
"+",
"1",
")",
")",
"# counter array",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"#... | 18.37037 | 0.000957 |
def setup_partitioning(portal):
"""Setups the enhanced partitioning system
"""
logger.info("Setting up the enhanced partitioning system")
# Add "Create partition" transition
add_create_partition_transition(portal)
# Add getAncestorsUIDs index in analyses catalog
add_partitioning_indexes(po... | [
"def",
"setup_partitioning",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Setting up the enhanced partitioning system\"",
")",
"# Add \"Create partition\" transition",
"add_create_partition_transition",
"(",
"portal",
")",
"# Add getAncestorsUIDs index in analyses catalo... | 30.3125 | 0.002 |
def ext_pillar(minion_id, pillar, conf):
'''
Return an existing set of certificates
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
ret = {}
dns_names = cache.fetch('venafi/minions', minion_id)
for dns_name in dns_names:
data = cache.fetch('venafi/domains', dns_name)
... | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"conf",
")",
":",
"cache",
"=",
"salt",
".",
"cache",
".",
"Cache",
"(",
"__opts__",
",",
"syspaths",
".",
"CACHE_DIR",
")",
"ret",
"=",
"{",
"}",
"dns_names",
"=",
"cache",
".",
"fetch",
"("... | 30.153846 | 0.002475 |
def from_list(commands):
"""
Given a list of tuples of form (depth, text)
that represents a DFS traversal of a command tree,
returns a dictionary representing command tree.
"""
def subtrees(commands, level):
if not commands:
return
acc = []
parent, *commands ... | [
"def",
"from_list",
"(",
"commands",
")",
":",
"def",
"subtrees",
"(",
"commands",
",",
"level",
")",
":",
"if",
"not",
"commands",
":",
"return",
"acc",
"=",
"[",
"]",
"parent",
",",
"",
"*",
"commands",
"=",
"commands",
"for",
"command",
"in",
"com... | 26.151515 | 0.001117 |
def _get_neutron_endpoint(cls, json_resp):
"""
Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service
Sends a CRITICAL service check when none are found registered in the Catalog
"""
valid_endpoint = cls._get_valid_endpoint(json_resp, ... | [
"def",
"_get_neutron_endpoint",
"(",
"cls",
",",
"json_resp",
")",
":",
"valid_endpoint",
"=",
"cls",
".",
"_get_valid_endpoint",
"(",
"json_resp",
",",
"'neutron'",
",",
"'network'",
")",
"if",
"valid_endpoint",
":",
"return",
"valid_endpoint",
"raise",
"MissingN... | 48.111111 | 0.011338 |
def _decode_preferred_encoding(s):
"""Decode the supplied byte string using the preferred encoding
for the locale (`locale.getpreferredencoding`) or, if the default encoding
is invalid, fall back first on utf-8, then on latin-1 if the message cannot
be decoded with utf-8.
"""
enc = locale.getpr... | [
"def",
"_decode_preferred_encoding",
"(",
"s",
")",
":",
"enc",
"=",
"locale",
".",
"getpreferredencoding",
"(",
")",
"try",
":",
"try",
":",
"return",
"s",
".",
"decode",
"(",
"enc",
")",
"except",
"LookupError",
":",
"enc",
"=",
"_DEFAULT_ENCODING",
"ret... | 33.5 | 0.001815 |
def __step4(self):
"""
Find a noncovered zero and prime it. If there is no starred zero
in the row containing this primed zero, Go to Step 5. Otherwise,
cover this row and uncover the column containing the starred
zero. Continue in this manner until there are no uncovered zeros
... | [
"def",
"__step4",
"(",
"self",
")",
":",
"step",
"=",
"0",
"done",
"=",
"False",
"row",
"=",
"-",
"1",
"col",
"=",
"-",
"1",
"star_col",
"=",
"-",
"1",
"while",
"not",
"done",
":",
"(",
"row",
",",
"col",
")",
"=",
"self",
".",
"__find_a_zero",... | 33.3125 | 0.001823 |
def setMinGapLat(self, typeID, minGapLat):
"""setMinGapLat(string, double) -> None
Sets the minimum lateral gap at 50km/h of this type.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_MINGAP_LAT, typeID, minGapLat) | [
"def",
"setMinGapLat",
"(",
"self",
",",
"typeID",
",",
"minGapLat",
")",
":",
"self",
".",
"_connection",
".",
"_sendDoubleCmd",
"(",
"tc",
".",
"CMD_SET_VEHICLETYPE_VARIABLE",
",",
"tc",
".",
"VAR_MINGAP_LAT",
",",
"typeID",
",",
"minGapLat",
")"
] | 40.285714 | 0.010417 |
def retry( delays=(0, 1, 1, 4, 16, 64), timeout=300, predicate=never ):
"""
Retry an operation while the failure matches a given predicate and until a given timeout
expires, waiting a given amount of time in between attempts. This function is a generator
that yields contextmanagers. See doctests below f... | [
"def",
"retry",
"(",
"delays",
"=",
"(",
"0",
",",
"1",
",",
"1",
",",
"4",
",",
"16",
",",
"64",
")",
",",
"timeout",
"=",
"300",
",",
"predicate",
"=",
"never",
")",
":",
"if",
"timeout",
">",
"0",
":",
"go",
"=",
"[",
"None",
"]",
"@",
... | 29.959184 | 0.01088 |
def stats(self, input_filepath):
'''Display time domain statistical information about the audio
channels. Audio is passed unmodified through the SoX processing chain.
Statistics are calculated and displayed for each audio channel
Unlike other Transformer methods, this does not modify th... | [
"def",
"stats",
"(",
"self",
",",
"input_filepath",
")",
":",
"effect_args",
"=",
"[",
"'channels'",
",",
"'1'",
",",
"'stats'",
"]",
"_",
",",
"_",
",",
"stats_output",
"=",
"self",
".",
"build",
"(",
"input_filepath",
",",
"None",
",",
"extra_args",
... | 31.357143 | 0.001473 |
def _format_localizable_token(self, dt, token, locale):
"""
Formats a DateTime instance
with a given localizable token and locale.
:param dt: The instance to format
:type dt: pendulum.DateTime
:param token: The token to use
:type token: str
:param local... | [
"def",
"_format_localizable_token",
"(",
"self",
",",
"dt",
",",
"token",
",",
"locale",
")",
":",
"if",
"token",
"==",
"\"MMM\"",
":",
"return",
"locale",
".",
"get",
"(",
"\"translations.months.abbreviated\"",
")",
"[",
"dt",
".",
"month",
"]",
"elif",
"... | 33.125 | 0.001222 |
def topDownCompute(self, encoded):
""" See the function description in base.py
"""
if self.ncategories==0:
return 0
topDownMappingM = self._getTopDownMapping()
categoryIndex = topDownMappingM.rightVecProd(encoded).argmax()
category = self.categories[categoryIndex]
encoding = topDown... | [
"def",
"topDownCompute",
"(",
"self",
",",
"encoded",
")",
":",
"if",
"self",
".",
"ncategories",
"==",
"0",
":",
"return",
"0",
"topDownMappingM",
"=",
"self",
".",
"_getTopDownMapping",
"(",
")",
"categoryIndex",
"=",
"topDownMappingM",
".",
"rightVecProd",
... | 30 | 0.009238 |
def count_extensions(img, extname='SCI'):
""" Return the number of 'extname' extensions. 'img' can be either a file
name, an HDU List object (from fits), or None (to get the number of all
HDU headers.
"""
if isinstance(img, str):
img = fits.open(img, memmap=False)
img.close()
eli... | [
"def",
"count_extensions",
"(",
"img",
",",
"extname",
"=",
"'SCI'",
")",
":",
"if",
"isinstance",
"(",
"img",
",",
"str",
")",
":",
"img",
"=",
"fits",
".",
"open",
"(",
"img",
",",
"memmap",
"=",
"False",
")",
"img",
".",
"close",
"(",
")",
"el... | 34.83871 | 0.009009 |
def findHTMLMeta(stream):
"""Look for a meta http-equiv tag with the YADIS header name.
@param stream: Source of the html text
@type stream: Object that implements a read() method that works
like file.read
@return: The URI from which to fetch the XRDS document
@rtype: str
@raises Meta... | [
"def",
"findHTMLMeta",
"(",
"stream",
")",
":",
"parser",
"=",
"YadisHTMLParser",
"(",
")",
"chunks",
"=",
"[",
"]",
"while",
"1",
":",
"chunk",
"=",
"stream",
".",
"read",
"(",
"CHUNK_SIZE",
")",
"if",
"not",
"chunk",
":",
"# End of file",
"break",
"c... | 26.95 | 0.000895 |
def evaluate_block(self, comments):
"""Evaluate block comments."""
if self.jsdocs:
m1 = RE_JSDOC.match(comments)
if m1:
lines = []
for line in m1.group(1).splitlines(True):
l = line.lstrip()
lines.append(l[1... | [
"def",
"evaluate_block",
"(",
"self",
",",
"comments",
")",
":",
"if",
"self",
".",
"jsdocs",
":",
"m1",
"=",
"RE_JSDOC",
".",
"match",
"(",
"comments",
")",
"if",
"m1",
":",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"m1",
".",
"group",
"(",
"... | 45.733333 | 0.008571 |
def showInvLines(rh):
"""
Produce help output related to command synopsis
Input:
Request Handle
"""
if rh.subfunction != '':
rh.printLn("N", "Usage:")
rh.printLn("N", " python " + rh.cmdName +
" ChangeVM <userid> add3390 <diskPool> <vAddr>")
rh.printLn("N", "... | [
"def",
"showInvLines",
"(",
"rh",
")",
":",
"if",
"rh",
".",
"subfunction",
"!=",
"''",
":",
"rh",
".",
"printLn",
"(",
"\"N\"",
",",
"\"Usage:\"",
")",
"rh",
".",
"printLn",
"(",
"\"N\"",
",",
"\" python \"",
"+",
"rh",
".",
"cmdName",
"+",
"\" Cha... | 45.72093 | 0.001992 |
def is_default(self):
"""
``True`` if values of all config items in this section and its subsections
have their values equal to defaults or have no value set.
"""
for _, item in self.iter_items(recursive=True):
if not item.is_default:
return False
... | [
"def",
"is_default",
"(",
"self",
")",
":",
"for",
"_",
",",
"item",
"in",
"self",
".",
"iter_items",
"(",
"recursive",
"=",
"True",
")",
":",
"if",
"not",
"item",
".",
"is_default",
":",
"return",
"False",
"return",
"True"
] | 36.333333 | 0.008955 |
def xmoe2_v1_l4k_global_only():
"""With sequence length 4096."""
hparams = xmoe2_v1_l4k()
hparams.decoder_layers = [
"att" if l == "local_att" else l for l in hparams.decoder_layers]
return hparams | [
"def",
"xmoe2_v1_l4k_global_only",
"(",
")",
":",
"hparams",
"=",
"xmoe2_v1_l4k",
"(",
")",
"hparams",
".",
"decoder_layers",
"=",
"[",
"\"att\"",
"if",
"l",
"==",
"\"local_att\"",
"else",
"l",
"for",
"l",
"in",
"hparams",
".",
"decoder_layers",
"]",
"return... | 34.333333 | 0.033175 |
def revoke_local_roles_for(brain_or_object, roles, user=None):
"""Revoke local roles for the object
Code extracted from `IRoleManager.manage_setLocalRoles`
:param brain_or_object: Catalog brain or object
:param roles: The local roles to revoke for the current user
:param user: A user ID, user obje... | [
"def",
"revoke_local_roles_for",
"(",
"brain_or_object",
",",
"roles",
",",
"user",
"=",
"None",
")",
":",
"user_id",
"=",
"get_user_id",
"(",
"user",
")",
"obj",
"=",
"api",
".",
"get_object",
"(",
"brain_or_object",
")",
"valid_roles",
"=",
"get_valid_roles_... | 33.517241 | 0.001 |
def _extract_remote_exception(self, pantsd_pid, nailgun_error):
"""Given a NailgunError, returns a Terminated exception with additional info (where possible).
This method will include the entire exception log for either the `pid` in the NailgunError, or
failing that, the `pid` of the pantsd instance.
"... | [
"def",
"_extract_remote_exception",
"(",
"self",
",",
"pantsd_pid",
",",
"nailgun_error",
")",
":",
"sources",
"=",
"[",
"pantsd_pid",
"]",
"if",
"nailgun_error",
".",
"pid",
"is",
"not",
"None",
":",
"sources",
"=",
"[",
"abs",
"(",
"nailgun_error",
".",
... | 43.05 | 0.010227 |
def _generate_footer(notebook_object, notebook_type):
"""
Internal function that is used for generation of the notebooks footer.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the footer will be created.
notebook_type : str
... | [
"def",
"_generate_footer",
"(",
"notebook_object",
",",
"notebook_type",
")",
":",
"footer_aux",
"=",
"FOOTER",
"if",
"\"Main_Files\"",
"in",
"notebook_type",
":",
"footer_aux",
"=",
"footer_aux",
".",
"replace",
"(",
"\"../MainFiles/\"",
",",
"\"\"",
")",
"# ====... | 36.088235 | 0.002381 |
def predict(self, predictdata: np.ndarray) -> np.ndarray:
""" predict given points """
return self.clf.predict(predictdata) | [
"def",
"predict",
"(",
"self",
",",
"predictdata",
":",
"np",
".",
"ndarray",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"self",
".",
"clf",
".",
"predict",
"(",
"predictdata",
")"
] | 45.666667 | 0.014388 |
def router_main(self):
'''
Main method for router; we stay in a loop in this method, receiving
packets until the end of time.
'''
while True:
gotpkt = True
try:
timestamp,dev,pkt = self.net.recv_packet(timeout=1.0)
except No... | [
"def",
"router_main",
"(",
"self",
")",
":",
"while",
"True",
":",
"gotpkt",
"=",
"True",
"try",
":",
"timestamp",
",",
"dev",
",",
"pkt",
"=",
"self",
".",
"net",
".",
"recv_packet",
"(",
"timeout",
"=",
"1.0",
")",
"except",
"NoPackets",
":",
"log_... | 33 | 0.008183 |
def strsettings(self, indent=0, maxindent=25, width=0):
"""Return user friendly help on positional arguments.
indent is the number of spaces preceeding the text on each line.
The indent of the documentation is dependent on the length of the
longest label that is short... | [
"def",
"strsettings",
"(",
"self",
",",
"indent",
"=",
"0",
",",
"maxindent",
"=",
"25",
",",
"width",
"=",
"0",
")",
":",
"out",
"=",
"[",
"]",
"makelabel",
"=",
"lambda",
"name",
":",
"' '",
"*",
"indent",
"+",
"name",
"+",
"': '",
"settingsinden... | 47.952381 | 0.011685 |
def get_expected_bindings(self):
"""Query the neutron DB for SG->switch interface bindings
Bindings are returned as a dict of bindings for each switch:
{<switch1>: set([(intf1, acl_name, direction),
(intf2, acl_name, direction)]),
<switch2>: set([(intf1, acl_na... | [
"def",
"get_expected_bindings",
"(",
"self",
")",
":",
"sg_bindings",
"=",
"db_lib",
".",
"get_baremetal_sg_bindings",
"(",
")",
"all_expected_bindings",
"=",
"collections",
".",
"defaultdict",
"(",
"set",
")",
"for",
"sg_binding",
",",
"port_binding",
"in",
"sg_b... | 45.178571 | 0.001548 |
def fixed_values(self):
"""
A flat tuple of all values corresponding to `scipy_data_fitting.Fit.fixed_parameters`
and `scipy_data_fitting.Fit.constants` after applying any prefixes.
The values mimic the order of those lists.
"""
values = []
values.extend([ prefix... | [
"def",
"fixed_values",
"(",
"self",
")",
":",
"values",
"=",
"[",
"]",
"values",
".",
"extend",
"(",
"[",
"prefix_factor",
"(",
"param",
")",
"*",
"param",
"[",
"'value'",
"]",
"for",
"param",
"in",
"self",
".",
"fixed_parameters",
"]",
")",
"values",
... | 42.916667 | 0.01711 |
def __clean_before_after(self, stateBefore, stateAfter, keepNoneEmptyDirectory=True):
"""clean repository given before and after states"""
# prepare after for faster search
errors = []
afterDict = {}
[afterDict.setdefault(list(aitem)[0],[]).append(aitem) for aitem in stateAfte... | [
"def",
"__clean_before_after",
"(",
"self",
",",
"stateBefore",
",",
"stateAfter",
",",
"keepNoneEmptyDirectory",
"=",
"True",
")",
":",
"# prepare after for faster search",
"errors",
"=",
"[",
"]",
"afterDict",
"=",
"{",
"}",
"[",
"afterDict",
".",
"setdefault",
... | 55.019608 | 0.015756 |
def project_create_event(self, proj_info):
"""Create project."""
LOG.debug("Processing create %(proj)s event.", {'proj': proj_info})
proj_id = proj_info.get('resource_info')
self.project_create_func(proj_id) | [
"def",
"project_create_event",
"(",
"self",
",",
"proj_info",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Processing create %(proj)s event.\"",
",",
"{",
"'proj'",
":",
"proj_info",
"}",
")",
"proj_id",
"=",
"proj_info",
".",
"get",
"(",
"'resource_info'",
")",
"se... | 33.571429 | 0.008299 |
def ipmi_method(self, command):
"""Use ipmitool to run commands with ipmi protocol
"""
ipmi = ipmitool(self.console, self.password, self.username)
if command == "reboot":
self.ipmi_method(command="status")
if self.output == "Chassis Power is off":
... | [
"def",
"ipmi_method",
"(",
"self",
",",
"command",
")",
":",
"ipmi",
"=",
"ipmitool",
"(",
"self",
".",
"console",
",",
"self",
".",
"password",
",",
"self",
".",
"username",
")",
"if",
"command",
"==",
"\"reboot\"",
":",
"self",
".",
"ipmi_method",
"(... | 33.352941 | 0.012007 |
def format_array_flat(array, max_width):
"""Return a formatted string for as many items in the flattened version of
array that will fit within max_width characters.
"""
# every item will take up at least two characters, but we always want to
# print at least first and last items
max_possibly_rel... | [
"def",
"format_array_flat",
"(",
"array",
",",
"max_width",
")",
":",
"# every item will take up at least two characters, but we always want to",
"# print at least first and last items",
"max_possibly_relevant",
"=",
"min",
"(",
"max",
"(",
"array",
".",
"size",
",",
"1",
"... | 45.555556 | 0.000597 |
def compile_pythrancode(module_name, pythrancode, specs=None,
opts=None, cpponly=False, pyonly=False,
output_file=None, module_dir=None, **kwargs):
'''Pythran code (string) -> c++ code -> native module
if `cpponly` is set to true, return the generated C++ filenam... | [
"def",
"compile_pythrancode",
"(",
"module_name",
",",
"pythrancode",
",",
"specs",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"cpponly",
"=",
"False",
",",
"pyonly",
"=",
"False",
",",
"output_file",
"=",
"None",
",",
"module_dir",
"=",
"None",
",",
"*... | 39.490909 | 0.000449 |
def guess_mime_type(content, deftype):
"""Description: Guess the mime type of a block of text
:param content: content we're finding the type of
:type str:
:param deftype: Default mime type
:type str:
:rtype: <type>:
:return: <description>
"""
#Mappings recognized by cloudinit
s... | [
"def",
"guess_mime_type",
"(",
"content",
",",
"deftype",
")",
":",
"#Mappings recognized by cloudinit",
"starts_with_mappings",
"=",
"{",
"'#include'",
":",
"'text/x-include-url'",
",",
"'#!'",
":",
"'text/x-shellscript'",
",",
"'#cloud-config'",
":",
"'text/cloud-config... | 30.269231 | 0.012315 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: CountryContext for this CountryInstance
:rtype: twilio.rest.pricing.v2.voice.country.CountryConte... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"CountryContext",
"(",
"self",
".",
"_version",
",",
"iso_country",
"=",
"self",
".",
"_solution",
"[",
"'iso_country'",
"]",
",",
"... | 44.545455 | 0.01 |
def plot_density(population, # pylint: disable=too-many-arguments, too-many-locals
bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
colorlabel='Nodes per unit area', labelfontsize=16,
color_map='Reds', no_colorbar=False, threshold=0.01,
n... | [
"def",
"plot_density",
"(",
"population",
",",
"# pylint: disable=too-many-arguments, too-many-locals",
"bins",
"=",
"100",
",",
"new_fig",
"=",
"True",
",",
"subplot",
"=",
"111",
",",
"levels",
"=",
"None",
",",
"plane",
"=",
"'xy'",
",",
"colorlabel",
"=",
... | 43.4375 | 0.002111 |
def data(self, table_name, metadata, persist_as=None, how='the_geom'):
"""Get an augmented CARTO dataset with `Data Observatory
<https://carto.com/data-observatory>`__ measures. Use
`CartoContext.data_discovery
<#context.CartoContext.data_discovery>`__ to search for available
mea... | [
"def",
"data",
"(",
"self",
",",
"table_name",
",",
"metadata",
",",
"persist_as",
"=",
"None",
",",
"how",
"=",
"'the_geom'",
")",
":",
"# if how != 'the_geom':",
"# raise NotImplementedError('Data gathering currently only works if '",
"# 'a geo... | 49.658824 | 0.000581 |
def get_port_for_ip_address(context, ip_id, id, fields=None):
"""Retrieve a port.
: param context: neutron api request context
: param id: UUID representing the port to fetch.
: param fields: a list of strings that are valid keys in a
port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
... | [
"def",
"get_port_for_ip_address",
"(",
"context",
",",
"ip_id",
",",
"id",
",",
"fields",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"(",
"\"get_port %s for tenant %s fields %s\"",
"%",
"(",
"id",
",",
"context",
".",
"tenant_id",
",",
"fields",
")",
")",
... | 38.083333 | 0.001067 |
def copy(self, empty=False):
"""returns an independent copy of the current object."""
# Create an empty object
newobject = self.__new__(self.__class__)
if empty:
return
# And fill it !
for prop in ["_properties","_side_properties",
... | [
"def",
"copy",
"(",
"self",
",",
"empty",
"=",
"False",
")",
":",
"# Create an empty object",
"newobject",
"=",
"self",
".",
"__new__",
"(",
"self",
".",
"__class__",
")",
"if",
"empty",
":",
"return",
"# And fill it !",
"for",
"prop",
"in",
"[",
"\"_prope... | 36.217391 | 0.012865 |
async def scale(self, scale=None, scale_change=None):
"""
Set or adjust the scale of this (K8s) application.
One or the other of scale or scale_change must be provided.
:param int scale: Scale to which to set this application.
:param int scale_change: Amount by which to adjust ... | [
"async",
"def",
"scale",
"(",
"self",
",",
"scale",
"=",
"None",
",",
"scale_change",
"=",
"None",
")",
":",
"app_facade",
"=",
"client",
".",
"ApplicationFacade",
".",
"from_connection",
"(",
"self",
".",
"connection",
")",
"if",
"(",
"scale",
",",
"sca... | 40.25 | 0.002022 |
def get_receiver(self, receiver=None):
"""
Returns a single receiver or a dictionary of receivers for this plugin.
"""
return self.__app.signals.get_receiver(receiver, self._plugin) | [
"def",
"get_receiver",
"(",
"self",
",",
"receiver",
"=",
"None",
")",
":",
"return",
"self",
".",
"__app",
".",
"signals",
".",
"get_receiver",
"(",
"receiver",
",",
"self",
".",
"_plugin",
")"
] | 41.8 | 0.00939 |
def remove_noise(time, magnitude, error, error_limit=3, std_limit=5):
"""Points within 'std_limit' standard deviations from the mean and with
errors greater than 'error_limit' times the error mean are
considered as noise and thus are eliminated.
"""
data, mjd = magnitude, time
data_len = len(m... | [
"def",
"remove_noise",
"(",
"time",
",",
"magnitude",
",",
"error",
",",
"error_limit",
"=",
"3",
",",
"std_limit",
"=",
"5",
")",
":",
"data",
",",
"mjd",
"=",
"magnitude",
",",
"time",
"data_len",
"=",
"len",
"(",
"mjd",
")",
"error_mean",
"=",
"np... | 31.366667 | 0.001031 |
def to_table(self, filter_function=None):
"""Return string with data in tabular form."""
table = []
for p in self:
if filter_function is not None and filter_function(p): continue
table.append([p.basename, p.symbol, p.Z_val, p.l_max, p.l_local, p.xc, p.type])
retur... | [
"def",
"to_table",
"(",
"self",
",",
"filter_function",
"=",
"None",
")",
":",
"table",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
":",
"if",
"filter_function",
"is",
"not",
"None",
"and",
"filter_function",
"(",
"p",
")",
":",
"continue",
"table",
".",
... | 55.875 | 0.013216 |
def plot_acquisition(bounds,input_dim,model,Xdata,Ydata,acquisition_function,suggested_sample, filename = None):
'''
Plots of the model and the acquisition function in 1D and 2D examples.
'''
# Plots in dimension 1
if input_dim ==1:
# X = np.arange(bounds[0][0], bounds[0][1], 0.001)
... | [
"def",
"plot_acquisition",
"(",
"bounds",
",",
"input_dim",
",",
"model",
",",
"Xdata",
",",
"Ydata",
",",
"acquisition_function",
",",
"suggested_sample",
",",
"filename",
"=",
"None",
")",
":",
"# Plots in dimension 1",
"if",
"input_dim",
"==",
"1",
":",
"# ... | 40.59633 | 0.014119 |
def _read_file(self, filename):
"""
:param filename: The location of the file to read
:type filename: str
"""
with open(filename, 'r') as stream:
return self._read_stream(stream=stream) | [
"def",
"_read_file",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"stream",
":",
"return",
"self",
".",
"_read_stream",
"(",
"stream",
"=",
"stream",
")"
] | 33 | 0.008439 |
def validate_collections(self, model, context=None):
"""
Validate collection properties
Performs validation on collection properties to return a result object.
:param model: object or dict
:param context: object, dict or None
:return: shiftschema.result.Result
""... | [
"def",
"validate_collections",
"(",
"self",
",",
"model",
",",
"context",
"=",
"None",
")",
":",
"result",
"=",
"Result",
"(",
")",
"for",
"property_name",
"in",
"self",
".",
"collections",
":",
"prop",
"=",
"self",
".",
"collections",
"[",
"property_name"... | 31.914286 | 0.001738 |
def _nsattr(self, attr, ns=None):
''' returns an attribute name w/ namespace prefix'''
if ns is None:
return attr
return '{' + self._ns[ns] + '}' + attr | [
"def",
"_nsattr",
"(",
"self",
",",
"attr",
",",
"ns",
"=",
"None",
")",
":",
"if",
"ns",
"is",
"None",
":",
"return",
"attr",
"return",
"'{'",
"+",
"self",
".",
"_ns",
"[",
"ns",
"]",
"+",
"'}'",
"+",
"attr"
] | 36.8 | 0.010638 |
def _get_basic_info(ca_name, cert, ca_dir=None):
'''
Get basic info to write out to the index.txt
'''
if ca_dir is None:
ca_dir = '{0}/{1}'.format(_cert_base_path(), ca_name)
index_file = "{0}/index.txt".format(ca_dir)
cert = _read_cert(cert)
expire_date = _four_digit_year_to_two_d... | [
"def",
"_get_basic_info",
"(",
"ca_name",
",",
"cert",
",",
"ca_dir",
"=",
"None",
")",
":",
"if",
"ca_dir",
"is",
"None",
":",
"ca_dir",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"_cert_base_path",
"(",
")",
",",
"ca_name",
")",
"index_file",
"=",
"\"{0}/in... | 27.68 | 0.001397 |
def _install_nuke(use_threaded_wrapper):
"""Helper function to The Foundry Nuke support"""
import nuke
not_nuke_launch = (
"--hiero" in nuke.rawArgs or
"--studio" in nuke.rawArgs or
"--nukeassist" in nuke.rawArgs
)
if not_nuke_launch:
raise ImportError
def threa... | [
"def",
"_install_nuke",
"(",
"use_threaded_wrapper",
")",
":",
"import",
"nuke",
"not_nuke_launch",
"=",
"(",
"\"--hiero\"",
"in",
"nuke",
".",
"rawArgs",
"or",
"\"--studio\"",
"in",
"nuke",
".",
"rawArgs",
"or",
"\"--nukeassist\"",
"in",
"nuke",
".",
"rawArgs",... | 28.764706 | 0.00198 |
def getNode(self, name, **context):
"""Return tree node found by name"""
if name == self.name:
return self
else:
return self.getBranch(name, **context).getNode(name, **context) | [
"def",
"getNode",
"(",
"self",
",",
"name",
",",
"*",
"*",
"context",
")",
":",
"if",
"name",
"==",
"self",
".",
"name",
":",
"return",
"self",
"else",
":",
"return",
"self",
".",
"getBranch",
"(",
"name",
",",
"*",
"*",
"context",
")",
".",
"get... | 36.5 | 0.008929 |
def lsem (inlist):
"""
Returns the estimated standard error of the mean (sx-bar) of the
values in the passed list. sem = stdev / sqrt(n)
Usage: lsem(inlist)
"""
sd = stdev(inlist)
n = len(inlist)
return sd/math.sqrt(n) | [
"def",
"lsem",
"(",
"inlist",
")",
":",
"sd",
"=",
"stdev",
"(",
"inlist",
")",
"n",
"=",
"len",
"(",
"inlist",
")",
"return",
"sd",
"/",
"math",
".",
"sqrt",
"(",
"n",
")"
] | 22.9 | 0.008403 |
def fsn2norm(path):
"""
Args:
path (fsnative): The path to normalize
Returns:
`fsnative`
Normalizes an fsnative path.
The same underlying path can have multiple representations as fsnative
(due to surrogate pairs and variable length encodings). When concatenating
fsnative t... | [
"def",
"fsn2norm",
"(",
"path",
")",
":",
"native",
"=",
"_fsn2native",
"(",
"path",
")",
"if",
"is_win",
":",
"return",
"_decode_surrogatepass",
"(",
"native",
".",
"encode",
"(",
"\"utf-16-le\"",
",",
"_surrogatepass",
")",
",",
"\"utf-16-le\"",
")",
"elif... | 31.090909 | 0.000945 |
async def process_ltd_doc(session, github_api_token, ltd_product_url,
mongo_collection=None):
"""Ingest any kind of LSST document hosted on LSST the Docs from its
source.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client sess... | [
"async",
"def",
"process_ltd_doc",
"(",
"session",
",",
"github_api_token",
",",
"ltd_product_url",
",",
"mongo_collection",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"ltd_product_data",
"=",
"await",
"get_ltd_product... | 41.691176 | 0.000345 |
def set_perplexity(self, new_perplexity):
"""Change the perplexity of the affinity matrix.
Note that we only allow lowering the perplexity or restoring it to its
original value. This restriction exists because setting a higher
perplexity value requires recomputing all the nearest neighb... | [
"def",
"set_perplexity",
"(",
"self",
",",
"new_perplexity",
")",
":",
"# If the value hasn't changed, there's nothing to do",
"if",
"new_perplexity",
"==",
"self",
".",
"perplexity",
":",
"return",
"# Verify that the perplexity isn't too large",
"new_perplexity",
"=",
"self"... | 42.7 | 0.001145 |
def delete_collection_namespaced_resource_quota(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_resource_quota # noqa: E501
delete collection of ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP r... | [
"def",
"delete_collection_namespaced_resource_quota",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return... | 165 | 0.000402 |
def get_rgbarray(self, idx, out=None, order='RGB', image_order=''):
"""
Parameters
----------
idx : index array
out : output array or None
The output array. If `None` one of the correct size and depth
will be created.
order : str
The... | [
"def",
"get_rgbarray",
"(",
"self",
",",
"idx",
",",
"out",
"=",
"None",
",",
"order",
"=",
"'RGB'",
",",
"image_order",
"=",
"''",
")",
":",
"# prepare output array",
"shape",
"=",
"idx",
".",
"shape",
"depth",
"=",
"len",
"(",
"order",
")",
"if",
"... | 30.23913 | 0.001393 |
def item(*args, **kwargs):
'''
.. versionadded:: 0.16.2
Return one or more pillar entries from the :ref:`in-memory pillar data
<pillar-in-memory>`.
delimiter
Delimiter used to traverse nested dictionaries.
.. note::
This is different from :py:func:`pillar.get
... | [
"def",
"item",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"default",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"''",
")",
"delimiter",
"=",
"kwargs",
".",
"get",
"(",
"'delimiter'",
",",
"DEFAULT_TARGET_DELIM",... | 36.162162 | 0.000364 |
def requires(self):
""" Returns the registers, operands, etc. required by an instruction.
"""
if self.asm in arch.zx48k.backend.ASMS:
return ALL_REGS
if self.inst == '#pragma':
tmp = self.__instr.split(' ')[1:]
if tmp[0] != 'opt':
retu... | [
"def",
"requires",
"(",
"self",
")",
":",
"if",
"self",
".",
"asm",
"in",
"arch",
".",
"zx48k",
".",
"backend",
".",
"ASMS",
":",
"return",
"ALL_REGS",
"if",
"self",
".",
"inst",
"==",
"'#pragma'",
":",
"tmp",
"=",
"self",
".",
"__instr",
".",
"spl... | 29.107914 | 0.000956 |
def hex_2_rgb(self, color):
"""
convert a hex color to rgb
"""
if not self.RE_HEX.match(color):
color = "#FFF"
if len(color) == 7:
return (int(color[i : i + 2], 16) / 255 for i in [1, 3, 5])
return (int(c, 16) / 15 for c in color) | [
"def",
"hex_2_rgb",
"(",
"self",
",",
"color",
")",
":",
"if",
"not",
"self",
".",
"RE_HEX",
".",
"match",
"(",
"color",
")",
":",
"color",
"=",
"\"#FFF\"",
"if",
"len",
"(",
"color",
")",
"==",
"7",
":",
"return",
"(",
"int",
"(",
"color",
"[",
... | 32.666667 | 0.009934 |
def delete_one(self, source=None, **kw):
"""Remove this document from the database, passing additional arguments through to PyMongo.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_one
"""
collection = self.get_collection(source)
return collection.... | [
"def",
"delete_one",
"(",
"self",
",",
"source",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"collection",
"=",
"self",
".",
"get_collection",
"(",
"source",
")",
"return",
"collection",
".",
"delete_one",
"(",
"self",
".",
"__class__",
".",
"id",
"=="... | 44.5 | 0.033058 |
def get_state_paths(cls, impl, working_dir):
"""
Get the set of state paths that point to the current chain and state info.
Returns a list of paths.
"""
return [config.get_db_filename(impl, working_dir), config.get_snapshots_filename(impl, working_dir)] | [
"def",
"get_state_paths",
"(",
"cls",
",",
"impl",
",",
"working_dir",
")",
":",
"return",
"[",
"config",
".",
"get_db_filename",
"(",
"impl",
",",
"working_dir",
")",
",",
"config",
".",
"get_snapshots_filename",
"(",
"impl",
",",
"working_dir",
")",
"]"
] | 48 | 0.013652 |
def handle_error(self, error=None):
"""Trap for TCPClient errors, otherwise continue."""
if _debug: TCPClientActor._debug("handle_error %r", error)
# pass along to the director
if error is not None:
self.director.actor_error(self, error)
else:
TCPClient.h... | [
"def",
"handle_error",
"(",
"self",
",",
"error",
"=",
"None",
")",
":",
"if",
"_debug",
":",
"TCPClientActor",
".",
"_debug",
"(",
"\"handle_error %r\"",
",",
"error",
")",
"# pass along to the director",
"if",
"error",
"is",
"not",
"None",
":",
"self",
"."... | 36.555556 | 0.008902 |
def _UTMLetterDesignator(Lat):
"""
This routine determines the correct UTM letter designator for the given latitude
returns 'Z' if latitude is outside the UTM limits of 84N to 80S
Written by Chuck Gantz- chuck.gantz@globalstar.com
"""
if 84 >= Lat >= 72: return 'X'
... | [
"def",
"_UTMLetterDesignator",
"(",
"Lat",
")",
":",
"if",
"84",
">=",
"Lat",
">=",
"72",
":",
"return",
"'X'",
"elif",
"72",
">",
"Lat",
">=",
"64",
":",
"return",
"'W'",
"elif",
"64",
">",
"Lat",
">=",
"56",
":",
"return",
"'V'",
"elif",
"56",
... | 39.607143 | 0.045775 |
def _extract_jar(self, coordinate, jar_path):
"""Extracts the jar to a subfolder of workdir/extracted and returns the path to it."""
with open(jar_path, 'rb') as f:
sha = sha1(f.read()).hexdigest()
outdir = os.path.join(self.workdir, 'extracted', sha)
if not os.path.exists(outdir):
ZIP.ext... | [
"def",
"_extract_jar",
"(",
"self",
",",
"coordinate",
",",
"jar_path",
")",
":",
"with",
"open",
"(",
"jar_path",
",",
"'rb'",
")",
"as",
"f",
":",
"sha",
"=",
"sha1",
"(",
"f",
".",
"read",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"outdir",
"... | 49.615385 | 0.010654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.