code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
cached = True
if force or not os.path.exists(dest):
cached = False
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(dest, 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
return cached, dest | def fetch(url, dest, force=False) | Retrieve data from an url and store it into dest.
Parameters
----------
url: str
Link to the remote data
dest: str
Path where the file must be stored
force: bool (default=False)
Overwrite if the file exists
Returns
-------
cached: bool
True if the file a... | 1.905714 | 2.092752 | 0.910626 |
timef_params = (
{"start": 0., "stop": 1.}
if timef_params is None else
timef_params.copy())
timef_params.update(num=size)
magf_params = magf_params.copy()
magf_params.update(size=size)
errf_params = errf_params.copy()
errf_params.update(size=size)
data = {}
... | def create_random(magf, magf_params, errf, errf_params,
timef=np.linspace, timef_params=None, size=DEFAULT_SIZE,
id=None, ds_name=DS_NAME, description=DESCRIPTION,
bands=BANDS, metadata=METADATA) | Generate a data with any given random function.
Parameters
----------
magf : callable
Function to generate the magnitudes.
magf_params : dict-like
Parameters to feed the `magf` function.
errf : callable
Function to generate the magnitudes.
errf_params : dict-like
... | 1.941043 | 2.025256 | 0.958418 |
random = np.random.RandomState(seed)
return create_random(
magf=random.normal, magf_params={"loc": mu, "scale": sigma},
errf=random.normal, errf_params={"loc": mu_err, "scale": sigma_err},
**kwargs) | def create_normal(mu=0., sigma=1., mu_err=0.,
sigma_err=1., seed=None, **kwargs) | Generate a data with magnitudes that follows a Gaussian
distribution. Also their errors are gaussian.
Parameters
----------
mu : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma : float (default=1)
Standar deviation of the gaussian distribution of magnitude ... | 3.216863 | 3.989148 | 0.806404 |
random = np.random.RandomState(seed)
return create_random(
magf=random.uniform, magf_params={"low": low, "high": high},
errf=random.normal, errf_params={"loc": mu_err, "scale": sigma_err},
**kwargs) | def create_uniform(low=0., high=1., mu_err=0., sigma_err=1.,
seed=None, **kwargs) | Generate a data with magnitudes that follows a uniform
distribution; the error instead are gaussian.
Parameters
----------
low : float, optional
Lower boundary of the output interval. All values generated will be
greater than or equal to low. The default value is 0.
high : float... | 3.216046 | 4.954966 | 0.649055 |
random = np.random.RandomState(seed)
size = kwargs.get("size", DEFAULT_SIZE)
times, mags, errors = [], [], []
for b in kwargs.get("bands", BANDS):
time = 100 * random.rand(size)
error = random.normal(size=size, loc=mu_err, scale=sigma_err)
mag = np.sin(2 * np.pi * time) +... | def create_periodic(mu_err=0., sigma_err=1., seed=None, **kwargs) | Generate a data with magnitudes with periodic variability
distribution; the error instead are gaussian.
Parameters
----------
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of m... | 2.673726 | 2.910257 | 0.918725 |
if dK - dH != 2:
raise NotImplementedError("Degrees of freedom != 2")
Nk = N - dK
if normalization == 'psd':
return np.exp(-z)
elif normalization == 'standard':
return 0.5 * Nk * (1 - z) ** (0.5 * Nk - 1)
elif normalization == 'model':
return 0.5 * Nk * (1 + z) ... | def pdf_single(z, N, normalization, dH=1, dK=3) | Probability density function for Lomb-Scargle periodogram
Compute the expected probability density function of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data... | 2.965365 | 2.848321 | 1.041092 |
return 1 - fap_single(z, N, normalization=normalization, dH=dH, dK=dK) | def cdf_single(z, N, normalization, dH=1, dK=3) | Cumulative distribution for the Lomb-Scargle periodogram
Compute the expected cumulative distribution of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data point... | 3.51663 | 6.274255 | 0.560486 |
N = len(t)
NH = N - dH # DOF for null hypothesis
NK = N - dK # DOF for periodic hypothesis
Dt = _weighted_var(t, dy)
Teff = np.sqrt(4 * np.pi * Dt)
W = fmax * Teff
if normalization == 'psd':
# 'psd' normalization is same as Baluev's z
return W * np.exp(-Z) * np.sqrt(Z)... | def tau_davies(Z, fmax, t, y, dy, normalization='standard', dH=1, dK=3) | tau factor for estimating Davies bound (Baluev 2008, Table 1) | 3.811132 | 3.66558 | 1.039708 |
N = len(t)
T = max(t) - min(t)
N_eff = fmax * T
p_s = cdf_single(Z, N, normalization=normalization)
return 1 - p_s ** N_eff | def fap_simple(Z, fmax, t, y, dy, normalization='standard') | False Alarm Probability based on estimated number of indep frequencies | 5.089622 | 4.726036 | 1.076933 |
N = len(t)
fap_s = fap_single(Z, N, normalization=normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return fap_s + tau | def fap_davies(Z, fmax, t, y, dy, normalization='standard') | Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008) | 3.28379 | 3.565565 | 0.920973 |
cdf = cdf_single(Z, len(t), normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return 1 - cdf * np.exp(-tau) | def fap_baluev(Z, fmax, t, y, dy, normalization='standard') | Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008) | 5.3323 | 5.375833 | 0.991902 |
if method not in METHODS:
raise ValueError("Unrecognized method: {0}".format(method))
method = METHODS[method]
method_kwds = method_kwds or {}
return method(Z, fmax, t, y, dy, normalization, **method_kwds) | def false_alarm_probability(Z, fmax, t, y, dy, normalization,
method='baluev', method_kwds=None) | Approximate the False Alarm Probability
Parameters
----------
TODO
Returns
-------
TODO | 2.131804 | 2.540288 | 0.839198 |
tarfname = "{}.tar.bz2".format(macho_id)
tarpath = os.path.join(DATA_PATH, tarfname)
rpath = "{}.R.mjd".format(macho_id)
bpath = "{}.B.mjd".format(macho_id)
with tarfile.open(tarpath, mode="r:bz2") as tf:
rlc = np.loadtxt(tf.extractfile(rpath))
blc = np.loadtxt(tf.extractfile(b... | def load_MACHO(macho_id) | lightcurve of 2 bands (R, B) from the MACHO survey.
Notes
-----
The files are gathered from the original FATS project tutorial:
https://github.com/isadoranun/tsfeat | 3.554091 | 2.355527 | 1.508831 |
if fps is None and hasattr(anim, '_interval'):
# Convert interval in ms to frames per second
fps = 1000. / anim._interval
plt.close(anim._fig)
if hasattr(anim, "_html_representation"):
return anim._html_representation
else:
# tempfile can't be used here: we need a f... | def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop') | Generate HTML representation of the animation | 4.010853 | 3.960676 | 1.012669 |
from IPython.display import HTML
return HTML(anim_to_html(anim, **kwargs)) | def display_animation(anim, **kwargs) | Display the animation with an IPython HTML object | 3.680897 | 2.913955 | 1.263197 |
indentation = c * n
return "\n".join([indentation + l for l in s.splitlines()]) | def indent(s, c=" ", n=4) | Indent the string 's' with the character 'c', 'n' times.
Parameters
----------
s : str
String to indent
c : str, default space
String to use as indentation
n : int, default 4
Number of chars to indent | 3.525979 | 7.314019 | 0.482085 |
relative_to = relative_to or datetime.datetime.now()
times = {}
for timedelta, boost in timedeltas_and_boosts.items():
date = (relative_to - timedelta).date()
times[date] = boost
times = sorted(times.items(), key=lambda i: i[0])
queries = []
for (x, time) in enumerate(times... | def generate_date_tail_boost_queries(
field, timedeltas_and_boosts, relative_to=None) | Generate a list of RangeQueries usable to boost the scores of more
recent documents.
Example:
```
queries = generate_date_tail_boost_queries("publish_date", {
timedelta(days=90): 1,
timedelta(days=30): 2,
timedelta(days=10): 4,
})
s = Search(BoolQuery(must=.... | 2.584451 | 2.737817 | 0.943982 |
out = {}
for key, value in iteritems(in_dict):
if isinstance(value, dict):
value = _clean_dict(value)
if value is None:
continue
out[key] = value
return out | def _clean_dict(in_dict) | Recursively remove None-valued items from dict.
:param in_dict:
:return: | 2.046721 | 2.197864 | 0.931232 |
if count <= 0:
return
current_batch = []
for item in iterable:
if len(current_batch) == count:
yield current_batch
current_batch = []
current_batch.append(item)
if current_batch:
yield current_batch | def batch_iterable(iterable, count) | Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. If <= 0, nothing is yielded.
:type count: int
... | 1.889151 | 1.947095 | 0.970241 |
if not self:
return
if not queryset:
queryset = self[0].django_model.objects.all()
pks = [res.pk for res in self if res.django_model == queryset.model]
object_map = dict((text_type(obj.pk), obj)
for obj in queryset.filter(pk__in... | def get_objects(self, queryset=None) | Return an iterator of Django model objects in Elasticsearch order,
optionally using the given Django queryset. If no queryset is
given, a default queryset (Model.objects.all) is used.
:param queryset: Optional queryset to filter in.
:return: | 3.240977 | 3.111943 | 1.041464 |
self.connection.rebuild_index(
self.index, coll_name=self.target_coll_name) | def reset(self) | Reset target collection (rebuild index). | 15.590023 | 8.441564 | 1.846817 |
counts_by_uid = defaultdict(Counter)
for word, count in self._gather_words(
index, fields, tokenizer=tokenizer).items():
uid = hashlib.sha1(unicodedata.normalize(
"NFKD", word.lower()).encode("UTF-8")).hexdigest()
counts_by_uid[uid][word] ... | def update(self, index, fields, tokenizer=default_tokenizer, cutoff=1) | Update (upsert) the wordgatherer collection.
:param index: Source index.
:param fields: Fields to read.
:param tokenizer: Tokenizer callable. Should split unicode to words
:param cutoff: Ignore words with less than this many occurrences. | 3.297536 | 3.12677 | 1.054614 |
search = Search(PrefixQuery("word", word), sort={"count": "desc"})
for doc in self.connection.search(
search, indexes=[self.index], count=limit):
yield (doc["word"], doc["count"]) | def search(self, word, limit=30) | Search for a word within the wordgatherer collection.
:param word: Word to search for.
:param limit: Maximum number of results to return. | 7.043535 | 9.442422 | 0.745946 |
if nb['nbformat'] != 4:
return False
language_name = (nb.get('metadata', {})
.get('kernelspec', {})
.get('language', '').lower())
return language_name == 'python' | def validate_nb(nb) | Validate that given notebook JSON is importable
- Check for nbformat == 4
- Check that language is python
Do not re-implement nbformat here :D | 3.752465 | 3.242138 | 1.157404 |
def node_predicate(node):
for an in ALLOWED_NODES:
if isinstance(node, an):
return True
# Recurse through Assign node LHS targets when an id is not specified,
# otherwise check that the id is uppercase
if isinstance(node, ast.Assign):
... | def filter_ast(module_ast) | Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all caps | 4.253911 | 4.033635 | 1.05461 |
code = PREAMBLE
for cell in nb['cells']:
if cell['cell_type'] == 'code':
# transform the input to executable Python
code += ''.join(cell['source'])
if cell['cell_type'] == 'markdown':
code += '\n# ' + '# '.join(cell['source'])
# We want a blank ne... | def code_from_ipynb(nb, markdown=False) | Get the code for a given notebook
nb is passed in as a dictionary that's a parsed ipynb file | 5.052507 | 5.05635 | 0.99924 |
real_path = os.path.join(*fullname[len(self.package_prefix):].split('.'))
for base_path in sys.path:
if base_path == '':
# Empty string means process's cwd
base_path = os.getcwd()
path = os.path.join(base_path, real_path)
yield... | def _get_paths(self, fullname) | Generate ordered list of paths we should look for fullname module in | 3.173439 | 2.994497 | 1.059757 |
if fullname.startswith(self.package_prefix):
for path in self._get_paths(fullname):
if os.path.exists(path):
return ModuleSpec(
name=fullname,
loader=self.loader_class(fullname, path),
... | def find_spec(self, fullname, path, target=None) | Claims modules that are under ipynb.fs | 3.283079 | 2.934656 | 1.118727 |
@wraps(func)
def start(*args, **kwargs):
g = func(*args, **kwargs)
next(g)
return g
return start | def coroutine(func) | Decorator for priming generator-based coroutines. | 2.247511 | 2.063499 | 1.089174 |
for i in range(to):
yield i
await asyncio.sleep(delay) | async def ticker(delay, to) | Yield numbers from 0 to `to` every `delay` seconds. | 4.370367 | 2.469819 | 1.769509 |
try:
first_item = (yield)
file.write(str(first_item))
if flush:
file.flush()
while True:
item = (yield)
file.write(sep)
file.write(str(item))
if flush:
file.flush()
except GeneratorExit:
file... | def rprint(sep='\n', end='\n', file=sys.stdout, flush=False) | A coroutine sink which prints received items stdout
Args:
sep: Optional separator to be printed between received items.
end: Optional terminator to be printed after the last item.
file: Optional stream to which to print.
flush: Optional flag to force flushing after each item. | 2.058023 | 2.064214 | 0.997001 |
it = iter(iterable)
for item in it:
try:
target.send(item)
except StopIteration:
return prepend(item, it)
return empty_iter() | def iterable_source(iterable, target) | Convert an iterable into a stream of events.
Args:
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items. | 4.444308 | 6.020794 | 0.73816 |
if rate <= 0.0:
raise ValueError("poisson_source rate {} is not positive".format(rate))
it = iter(iterable)
for item in it:
duration = random.expovariate(rate)
sleep(duration)
try:
target.send(item)
except StopIteration:
return prepend(it... | def poisson_source(rate, iterable, target) | Send events at random times with uniform probability.
Args:
rate: The average number of events to send per second.
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items. | 4.093352 | 4.025037 | 1.016973 |
rfs = list(chain([f], fs))
rfs.reverse()
def composed(*args, **kwargs):
return reduce(
lambda result, fn: fn(result),
rfs[1:],
rfs[0](*args, **kwargs))
return composed | def compose(f, *fs) | Compose functions right to left.
compose(f, g, h)(x) -> f(g(h(x)))
Args:
f, *fs: The head and rest of a sequence of callables. The
rightmost function passed can accept any arguments and
the returned function will have the same signature as
this last prov... | 3.634247 | 4.32253 | 0.840768 |
reducer2 = reducer
def reducing_transducer(reducer):
return Reducing(reducer, reducer2, init)
return reducing_transducer | def reducing(reducer, init=UNSET) | Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream in the second argument.
Returns: A reducing transducer: A singl... | 6.727633 | 9.461368 | 0.711063 |
reducer2 = reducer
def scanning_transducer(reducer):
return Scanning(reducer, reducer2, init)
return scanning_transducer | def scanning(reducer, init=UNSET) | Create a scanning reducer. | 7.00577 | 6.408383 | 1.09322 |
if n < 0:
raise ValueError("Cannot take fewer than zero ({}) items".format(n))
def taking_transducer(reducer):
return Taking(reducer, n)
return taking_transducer | def taking(n) | Create a transducer which takes the first n items | 6.723866 | 4.302783 | 1.562678 |
if n < 0:
raise ValueError("Cannot drop fewer than zero ({}) items".format(n))
def dropping_transducer(reducer):
return Dropping(reducer, n)
return dropping_transducer | def dropping(n) | Create a transducer which drops the first n items | 5.685416 | 3.731179 | 1.523758 |
if size < 1:
raise ValueError("batching() size must be at least 1")
def batching_transducer(reducer):
return Batching(reducer, size)
return batching_transducer | def batching(size) | Create a transducer which produces non-overlapping batches. | 4.154135 | 3.051052 | 1.361542 |
if size < 1:
raise ValueError("windowing() size {} is not at least 1".format(size))
def windowing_transducer(reducer):
return Windowing(reducer, size, padding, window_type)
return windowing_transducer | def windowing(size, padding=UNSET, window_type=tuple) | Create a transducer which produces a moving window over items. | 4.46676 | 3.551559 | 1.25769 |
predicate = true if predicate is None else predicate
def first_transducer(reducer):
return First(reducer, predicate)
return first_transducer | def first(predicate=None) | Create a transducer which obtains the first item, then terminates. | 6.455264 | 5.345194 | 1.207676 |
predicate = true if predicate is None else predicate
def last_transducer(reducer):
return Last(reducer, predicate)
return last_transducer | def last(predicate=None) | Create a transducer which obtains the last item. | 7.476596 | 5.501101 | 1.359109 |
if index < 0:
raise IndexError("element_at used with illegal index {}".format(index))
def element_at_transducer(reducer):
return ElementAt(reducer, index)
return element_at_transducer | def element_at(index) | Create a transducer which obtains the item at the specified index. | 6.705956 | 4.518478 | 1.484118 |
_per_file_kwargs = {}
if per_file_kwargs is not None:
for k, v in per_file_kwargs.items():
if isinstance(k, Glob):
for path in glob.glob(k.pathname):
_per_file_kwargs[path] = v
elif isinstance(k, ArbitraryDepthGlob):
for p... | def compile_sources(files, CompilerRunner_=None,
destdir=None, cwd=None,
keep_dir_struct=False,
per_file_kwargs=None,
**kwargs) | Compile source code files to object files.
Parameters
----------
files: iterable of path strings
source files, if cwd is given, the paths are taken as relative.
CompilerRunner_: CompilerRunner instance (optional)
could be e.g. pycompilation.FortranCompilerRunner
Will be inferred... | 2.68957 | 2.735805 | 0.9831 |
if out_file is None:
out_file, ext = os.path.splitext(os.path.basename(obj_files[-1]))
if shared:
out_file += sharedext
if not CompilerRunner_:
if fort:
CompilerRunner_, extra_kwargs, vendor = \
get_mixed_fort_c_linker(
ve... | def link(obj_files, out_file=None, shared=False, CompilerRunner_=None,
cwd=None, cplus=False, fort=False, **kwargs) | Link object files.
Parameters
----------
obj_files: iterable of path strings
out_file: path string (optional)
path to executable/shared library, if missing
it will be deduced from the last item in obj_files.
shared: bool
Generate a shared library? default: False
Compiler... | 3.740312 | 3.760628 | 0.994598 |
libraries = libraries or []
include_dirs = kwargs.pop('include_dirs', [])
library_dirs = kwargs.pop('library_dirs', [])
# from distutils/command/build_ext.py:
if sys.platform == "win32":
warnings.warn("Windows not yet supported.")
elif sys.platform == 'darwin':
# Don't use... | def link_py_so(obj_files, so_file=None, cwd=None, libraries=None,
cplus=False, fort=False, **kwargs) | Link python extension module (shared object) for importing
Parameters
----------
obj_files: iterable of path strings
object files to be linked
so_file: path string
Name (path) of shared object file to create. If
not specified it will have the basname of the last object
f... | 3.108919 | 3.236874 | 0.96047 |
from Cython.Compiler.Main import (
default_options, CompilationOptions
)
from Cython.Compiler.Main import compile as cy_compile
assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
cwd = cwd or '.'
destdir = destdir or '.'
ext = '.cpp' if cy_kwargs.get('cplus', F... | def simple_cythonize(src, destdir=None, cwd=None, logger=None,
full_module_name=None, only_update=False,
**cy_kwargs) | Generates a C file from a Cython source file.
Parameters
----------
src: path string
path to Cython source
destdir: path string (optional)
Path to output directory (default: '.')
cwd: path string (optional)
Root of relative paths (default: '.')
logger: logging.Logger
... | 2.415665 | 2.332106 | 1.03583 |
name, ext = os.path.splitext(os.path.basename(srcpath))
if objpath is None:
if os.path.isabs(srcpath):
objpath = '.'
else:
objpath = os.path.dirname(srcpath)
objpath = objpath or '.' # avoid objpath == ''
out_ext = out_ext or objext
if os.path.is... | def src2obj(srcpath, CompilerRunner_=None, objpath=None,
only_update=False, cwd=None, out_ext=None, inc_py=False,
**kwargs) | Compiles a source code file to an object file.
Files ending with '.pyx' assumed to be cython files and
are dispatched to pyx2obj.
Parameters
----------
srcpath: path string
path to source file
CompilerRunner_: pycompilation.CompilerRunner subclass (optional)
Default: deduced fro... | 2.56607 | 2.579603 | 0.994754 |
build_dir = build_dir or '.'
if extname is None:
extname = os.path.splitext(os.path.basename(srcs[-1]))[0]
compile_kwargs = compile_kwargs or {}
compile_kwargs.update(kwargs)
link_kwargs = link_kwargs or {}
link_kwargs.update(kwargs)
try:
mod = import_module_from_fil... | def compile_link_import_py_ext(
srcs, extname=None, build_dir=None, compile_kwargs=None,
link_kwargs=None, **kwargs) | Compiles sources in `srcs` to a shared object (python extension)
which is imported. If shared object is newer than the sources, they
are not recompiled but instead it is imported.
Parameters
----------
srcs: string
list of paths to sources
extname: string
name of extension (defa... | 3.007108 | 2.861986 | 1.050707 |
build_dir = build_dir or tempfile.mkdtemp()
if not os.path.isdir(build_dir):
raise OSError("Non-existent directory: ", build_dir)
source_files = []
if kwargs.get('logger', False) is True:
import logging
logging.basicConfig(level=logging.DEBUG)
kwargs['logger'] = log... | def compile_link_import_strings(codes, build_dir=None, **kwargs) | Creates a temporary directory and dumps, compiles and links
provided source code.
Parameters
----------
codes: iterable of name/source pair tuples
build_dir: string (default: None)
path to cache_dir. None implies use a temporary directory.
**kwargs:
keyword arguments passed onto... | 2.52336 | 2.417207 | 1.043916 |
with app.app_context():
app.extensions['pymongo'][mongo.config_prefix] = mongo.cx, mongo.cx[name] | def switch_db(name) | Hack to switch Flask-Pymongo db
:param name: db name | 11.996808 | 11.466528 | 1.046246 |
if 'arguments' in self.attributes:
LOGGER.warning(
"WARNING: 'arguments' use in OSU yaml configuration file is deprecated. Please use 'options'!"
)
arguments = self.attributes['arguments']
if isinstance(arguments, dict):
re... | def arguments(self) | Dictionary providing the list of arguments for every
benchmark | 3.500542 | 3.4729 | 1.007959 |
tz_offset = obj.utcoffset()
if not tz_offset or tz_offset == UTC_ZERO:
iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
else:
iso_datetime = obj.isoformat()
return iso_datetime | def _(obj) | ISO 8601 format. Interprets naive datetime as UTC with zulu suffix. | 3.572451 | 2.942236 | 1.214196 |
from inspect import isgenerator
from rowgenerators import get_generator
g = get_generator(ref)
if not g:
raise GenerateError("Cant figure out how to generate rows from {} ref: {}".format(type(ref), ref))
else:
return g | def get_row_generator(self, ref, cache=None) | Return a row generator for a reference | 5.827416 | 5.453898 | 1.068486 |
combinations = (product([k], v) for k, v in properties.items())
return chain.from_iterable(combinations) | def create_key_filter(properties: Dict[str, list]) -> List[Tuple] | Generate combinations of key, value pairs for each key in properties.
Examples
--------
properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'}
>> create_key_filter(properties)
--> [('ent', 'geo_rev'), ('ent', 'supply_chain'), ('own', 'fi')] | 5.199818 | 6.573806 | 0.79099 |
if len(indexes) == 1:
index = indexes[0]
return lambda x: (x[index],)
else:
return itemgetter(*indexes) | def create_indexer(indexes: list) | Create indexer function to pluck values from list. | 4.332892 | 3.054325 | 1.418609 |
return (element for element in sequence
if self.indexer(element) in self.predicates) | def including(self, sequence) -> Generator | Include the sequence elements matching the filter set. | 14.30873 | 8.545113 | 1.674493 |
return (element for element in sequence
if self.indexer(element) not in self.predicates) | def excluding(self, sequence) -> Generator | Exclude the sequence elements matching the filter set. | 11.947558 | 7.652462 | 1.56127 |
assert isinstance(permission, (str, enum.Enum)), permission
assert permission
identify = await self.identity_policy.identify(identity)
# non-registered user still may has some permissions
access = await self.autz_policy.can(identify, permission)
return access | async def can(self, identity, permission) -> bool | Check user permissions.
:return: ``True`` if the identity is allowed the permission, else return ``False``. | 12.578696 | 12.143954 | 1.035799 |
identify = await self.identify(identity)
if identify is None:
raise UnauthorizedError()
return identify | async def check_authorized(self, identity) | Works like :func:`Security.identity`, but when check is failed
:func:`UnauthorizedError` exception is raised.
:param identity: Claim
:return: Checked claim or return ``None``
:raise: :func:`UnauthorizedError` | 6.782949 | 6.913826 | 0.98107 |
await self.check_authorized(identity)
allowed = await self.can(identity, permission)
if not allowed:
raise ForbiddenError() | async def check_permission(self, identity, permission) | Works like :func:`Security.can`, but when check is failed
:func:`ForbiddenError` exception is raised.
:param identity: Claim
:param permission: Permission
:return: Checked claim
:raise: :func:`ForbiddenError` | 5.397178 | 5.06754 | 1.065049 |
DESCRIPTION =
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=Raw)
parser.add_argument("--email", dest="email", action='store', required=False, default=False,
help="An email address is required for querying Entrez databases.")
parser.add_argume... | def arguments() | Pulls in command line arguments. | 2.799823 | 2.800446 | 0.999778 |
nodes = nodes or self.nodes
self._prelude(*nodes)
@write_yaml_report
def _run():
self._build_installer()
runner = functools.partial(run_on_host, self.campaign)
if self.campaign.network.max_concurrent_runs > 1:
pool = Pool(self... | def run(self, *nodes) | Execute benchmarks on every node specified in arguments.
If none are given, then execute benchmarks on every nodes
specified in the ``network.nodes`` campaign configuration. | 5.494887 | 5.289118 | 1.038904 |
with self._scp_bensh_runner():
self._execute_bensh_runner()
path = self._retrieve_tarball()
try:
self._aggregate_tarball(path)
finally:
os.remove(path) | def run(self) | Execute benchmark on the specified node | 10.280193 | 9.53111 | 1.078594 |
value = self.attributes['node_pairing']
if value not in IMB.NODE_PAIRING:
msg = 'Unexpected {0} value: got "{1}" but valid values are {2}'
msg = msg.format('node_pairing', value, IMB.NODE_PAIRING)
raise ValueError(msg)
return value | def node_pairing(self) | if "node" then test current node and next one
if "tag", then create tests for every pair of the current tag. | 4.022727 | 4.308785 | 0.93361 |
http_proxy = str(CFG["gentoo"]["http_proxy"])
ftp_proxy = str(CFG["gentoo"]["ftp_proxy"])
rsync_proxy = str(CFG["gentoo"]["rsync_proxy"])
path.mkfile_uchroot(local.path('/') / _path)
with open(_path, 'w') as makeconf:
lines = '''
PORTAGE_USERNAME=root
PORTAGE_GROUPNAME=root
CFLAGS="-O2... | def write_makeconfig(_path) | Write a valid gentoo make.conf file to :path:.
Args:
path - The output path of the make.conf | 3.656779 | 3.71524 | 0.984265 |
cfg_mounts = CFG["container"]["mounts"].value
cfg_prefix = CFG["container"]["prefixes"].value
path.mkfile_uchroot("/etc/portage/bashrc")
mounts = uchroot.mounts("mnt", cfg_mounts)
p_paths, p_libs = uchroot.env(cfg_prefix)
paths, libs = uchroot.env(mounts)
paths = paths + p_paths
l... | def write_bashrc(_path) | Write a valid gentoo bashrc file to :path:.
Args:
path - The output path of the make.conf | 4.474591 | 4.73788 | 0.944429 |
path.mkdir_uchroot("/etc/portage/metadata")
path.mkfile_uchroot("/etc/portage/metadata/layout.conf")
with open(_path, 'w') as layoutconf:
lines = '''masters = gentoo'''
layoutconf.write(lines) | def write_layout(_path) | Write a valid gentoo layout file to :path:.
Args:
path - The output path of the layout.conf | 8.983966 | 8.450371 | 1.063145 |
http_proxy = str(CFG["gentoo"]["http_proxy"])
ftp_proxy = str(CFG["gentoo"]["ftp_proxy"])
path.mkfile_uchroot("/etc/wgetrc")
with open(_path, 'w') as wgetrc:
if http_proxy is not None:
http_s = "http_proxy = {0}".format(http_proxy)
https_s = "https_proxy = {0}".form... | def write_wgetrc(_path) | Write a valid gentoo wgetrc file to :path:.
Args:
path - The output path of the wgetrc | 2.71656 | 2.868422 | 0.947057 |
LOG.debug("Setting up Benchbuild...")
venv_dir = local.path("/benchbuild")
prefixes = CFG["container"]["prefixes"].value
prefixes.append(venv_dir)
CFG["container"]["prefixes"] = prefixes
src_dir = str(CFG["source_dir"])
have_src = src_dir is not None
if have_src:
__mount_s... | def setup_benchbuild() | Setup benchbuild inside a container.
This will query a for an existing installation of benchbuild and
try to upgrade it to the latest version, if possible. | 4.830771 | 4.566227 | 1.057935 |
arguments = cli_common(__doc__, argv=argv)
benet = BeNet(arguments['CAMPAIGN_FILE'])
benet.run()
if argv is not None:
return benet | def main(argv=None) | ben-nett entry point | 15.578902 | 11.996917 | 1.298576 |
arguments = cli_common(__doc__, argv=argv)
es_export = ESExporter(arguments['CAMPAIGN-DIR'], arguments['--es'])
es_export.export()
if argv is not None:
return es_export | def main(argv=None) | ben-elastic entry point | 12.582047 | 10.345363 | 1.216202 |
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("name", value)
self.__name = value | def name(self, value) | Setter for **self.__name** attribute.
:param value: Attribute value.
:type value: unicode | 5.794951 | 4.14189 | 1.399108 |
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value)
self.component_activated.emit() if value else self.component_deactivated.emit()
self.__activated = value | def activated(self, value) | Setter for **self.__activated** attribute.
:param value: Attribute value.
:type value: bool | 4.780304 | 4.420198 | 1.081468 |
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("initialized", value)
self.component_initialized.emit() if value else self.component_uninitialized.emit()
self.__initialized = value | def initialized(self, value) | Setter for **self.__initialized** attribute.
:param value: Attribute value.
:type value: bool | 4.698746 | 4.556859 | 1.031137 |
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("deactivatable", value)
self.__deactivatable = value | def deactivatable(self, value) | Setter for **self.__deactivatable** attribute.
:param value: Attribute value.
:type value: bool | 4.70924 | 3.889426 | 1.21078 |
_request = request.args.get("request", None)
if _request is not None:
try:
if _request.lower() == "getcapabilities":
return self._get_capabilities(
urn=request.args.get("urn", None)
)
eli... | def r_cts(self) | Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route
:return: Response | 2.603232 | 2.470419 | 1.053761 |
self.nautilus_extension.logger.info(
"CTS error thrown {} for {} ({})".format(
error_name,
request.query_string.decode(),
message)
)
return render_template(
"cts/Error.xml",
errorType=error_name,
... | def cts_error(self, error_name, message=None) | Create a CTS Error reply
:param error_name: Name of the error
:param message: Message of the Error
:return: CTS Error Response with information (XML) | 5.53217 | 5.656997 | 0.977934 |
r = self.resolver.getMetadata(objectId=urn)
if len(r.parents) > 0:
r = r.parents[-1]
r = render_template(
"cts/GetCapabilities.xml",
filters="urn={}".format(urn),
inventory=Markup(r.export(Mimetypes.XML.CTS))
)
return r, 20... | def _get_capabilities(self, urn=None) | Provisional route for GetCapabilities request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetCapabilities response | 11.37797 | 10.119863 | 1.124321 |
urn = URN(urn)
subreference = None
if len(urn) < 4:
raise InvalidURN
if urn.reference is not None:
subreference = str(urn.reference)
node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference)
r = rende... | def _get_passage(self, urn) | Provisional route for GetPassage request
:param urn: URN to filter the resource
:return: GetPassage response | 8.91447 | 9.051892 | 0.984818 |
urn = URN(urn)
subreference = None
if len(urn) < 4:
raise InvalidURN
if urn.reference is not None:
subreference = str(urn.reference)
node = self.resolver.getTextualNode(textId=urn.upTo(URN.NO_PASSAGE), subreference=subreference)
r = render... | def _get_passage_plus(self, urn) | Provisional route for GetPassagePlus request
:param urn: URN to filter the resource
:return: GetPassagePlus response | 4.293571 | 4.31941 | 0.994018 |
urn = URN(urn)
subreference = None
textId=urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
reffs = self.resolver.getReffs(textId=textId, subreference=subreference, level=level)
r = render_template(
"... | def _get_valid_reff(self, urn, level) | Provisional route for GetValidReff request
:param urn: URN to filter the resource
:return: GetValidReff response | 5.432701 | 5.551239 | 0.978647 |
urn = URN(urn)
subreference = None
textId = urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
previous, nextious = self.resolver.getSiblings(textId=textId, subreference=subreference)
r = render_template(
... | def _get_prev_next(self, urn) | Provisional route for GetPrevNext request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetPrevNext response | 6.712746 | 7.261419 | 0.92444 |
urn = URN(urn)
subreference = None
textId = urn.upTo(URN.NO_PASSAGE)
if urn.reference is not None:
subreference = str(urn.reference)
firstId = self.resolver.getTextualNode(textId=textId, subreference=subreference).firstId
r = render_template(
... | def _get_first_urn(self, urn) | Provisional route for GetFirstUrn request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetFirstUrn response | 7.074952 | 7.583124 | 0.932987 |
node = self.resolver.getTextualNode(textId=urn)
r = render_template(
"cts/GetLabel.xml",
request_urn=str(urn),
full_urn=node.urn,
metadata={
"groupname": [(literal.language, str(literal)) for literal in node.metadata.get(RDF_NAMESP... | def _get_label(self, urn) | Provisional route for GetLabel request
:param urn: URN to filter the resource
:param inv: Inventory Identifier
:return: GetLabel response | 4.183389 | 4.271991 | 0.97926 |
while True:
events = self._selector.select()
for nevent in range(len(events) + 1):
self._libinput.libinput_dispatch(self._li)
hevent = self._libinput.libinput_get_event(self._li)
if hevent:
type_ = self._libinput.libinput_event_get_type(hevent)
self._libinput.libinput_dispatch(self._li... | def events(self) | Yield events from the internal libinput's queue.
Yields device events that are subclasses of
:class:`~libinput.event.Event`.
Yields:
:class:`~libinput.event.Event`: Device event. | 2.393977 | 2.226474 | 1.075233 |
type_ = self._libinput.libinput_next_event_type(self._li)
if type_ == 0:
return None
else:
return EventType(type_) | def next_event_type(self) | Return the type of the next event in the internal queue.
This method does not pop the event off the queue and the next call
to :attr:`events` returns that event.
Returns:
~libinput.constant.EventType: The event type of the next available
event or :obj:`None` if no event is available. | 5.589522 | 3.85918 | 1.44837 |
hdevice = self._libinput.libinput_path_add_device(
self._li, path.encode())
if hdevice:
return Device(hdevice, self._libinput)
return None | def add_device(self, path) | Add a device to a libinput context.
If successful, the device will be added to the internal list and
re-opened on :meth:`~libinput.LibInput.resume`. The device can be
removed with :meth:`remove_device`.
If the device was successfully initialized, it is returned.
Args:
path (str): Path to an input device.... | 5.613618 | 4.699896 | 1.194413 |
rc = self._libinput.libinput_udev_assign_seat(self._li, seat.encode())
assert rc == 0, 'Failed to assign {}'.format(seat) | def assign_seat(self, seat) | Assign a seat to this libinput context.
New devices or the removal of existing devices will appear as events
when iterating over :meth:`~libinput.LibInput.get_event`.
:meth:`assign_seat` succeeds even if no input devices are
currently available on this seat, or if devices are available but fail
to open. Dev... | 7.842352 | 7.322977 | 1.070924 |
try:
self._outdir = outdir
self._log_prefix = log_prefix
yield
finally:
self._log_prefix = None
self._outdir = None | def context(self, outdir, log_prefix) | Setup instance to extract metrics from the proper run
:param outdir: run directory
:param log_prefix: log filenames prefix | 2.834283 | 3.545023 | 0.79951 |
for subclass in cls.__subclasses__():
if subclass.name == name:
return subclass
raise NameError("Not a valid Benchmark class: " + name) | def get_subclass(cls, name) | Get Benchmark subclass by name
:param name: name returned by ``Benchmark.name`` property
:return: instance of ``Benchmark`` class | 4.573086 | 4.283965 | 1.067489 |
items = []
for key, value in dic.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(value, collections.MutableMapping):
items.extend(flatten_dict(value, new_key, sep=sep).items())
elif isinstance(value, list):
for idx, elt in enume... | def flatten_dict(dic, parent_key='', sep='.') | Flatten sub-keys of a dictionary | 1.471838 | 1.461372 | 1.007162 |
for key in merge_dct.keys():
if (
key in dct
and isinstance(dct[key], dict)
and isinstance(merge_dct[key], collections.Mapping)
):
dict_merge(dct[key], merge_dct[key])
else:
dct[key] = merge_dct[key] | def dict_merge(dct, merge_dct) | Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
updating only top-level keys, dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
``dct``.
:param dct: dict onto which the merge is executed
:param merge_dct: dct merge... | 1.589767 | 1.61159 | 0.986459 |
if isinstance(obj, collections.Mapping):
return FrozenDict({freeze(k): freeze(v) for k, v in six.iteritems(obj)})
elif isinstance(obj, list):
return FrozenList([freeze(e) for e in obj])
else:
return obj | def freeze(obj) | Transform tree of dict and list in read-only
data structure.
dict instances are transformed to FrozenDict, lists
in FrozenList. | 2.099705 | 1.914656 | 1.096649 |
if path == '-':
return Configuration(yaml.safe_load(sys.stdin))
if not osp.exists(path) and not osp.isabs(path):
path = osp.join(osp.dirname(osp.abspath(__file__)), path)
with open(path, 'r') as istr:
return Configuration(yaml.safe_load(istr)) | def from_file(cls, path) | Create a ``Configuration`` from a file
:param path: path to YAML file
:return: new configuration
:rtype: ``Configuration`` | 2.647716 | 2.658033 | 0.996119 |
'''
Convert a hex-formatted number (i.e., `"#RGB[A]"` or `"#RRGGBB[AA]"`) to an
RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`).
Args:
hex_color (str) : hex-formatted number (e.g., `"#2fc"`, `"#3c2f8611"`)
normalize_to (int, float) : Factor to normalize each channel by
Returns:
... | def hex_color_to_rgba(hex_color, normalize_to=255) | Convert a hex-formatted number (i.e., `"#RGB[A]"` or `"#RRGGBB[AA]"`) to an
RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`).
Args:
hex_color (str) : hex-formatted number (e.g., `"#2fc"`, `"#3c2f8611"`)
normalize_to (int, float) : Factor to normalize each channel by
Returns:
(tuple) : R... | 2.624894 | 1.699092 | 1.54488 |
if '.' in term:
parent_term, record_term = term.split('.')
parent_term, record_term = parent_term.strip(), record_term.strip()
if parent_term == '':
parent_term = ELIDED_TERM
else:
parent_term, record_term = ROOT_TERM, term.stri... | def split_term(cls, term) | Split a term in to parent and record term components
:param term: combined term text
:return: Tuple of parent and record term | 3.289344 | 2.744928 | 1.198335 |
return tuple(e.lower() for e in Term.split_term(term)) | def split_term_lower(cls, term) | Like split_term, but also lowercases both parent and record term
:param term: combined term text
:return: Tuple of parent and record term | 9.52849 | 9.459651 | 1.007277 |
from metatab.util import slugify
assert self.file_name is None or isinstance(self.file_name, str)
if self.file_name is not None and self.row is not None:
parts = split(self.file_name);
return "{} {}:{} ".format(parts[-1], self.row, self.col)
elif self.r... | def file_ref(self) | Return a string for the file, row and column of the term. | 4.124828 | 3.532834 | 1.167569 |
assert isinstance(child, Term)
self.children.append(child)
child.parent = self
assert not child.term_is("Datafile.Section") | def add_child(self, child) | Add a term to this term's children. Also sets the child term's parent | 10.58334 | 9.202269 | 1.150079 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.