_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q272000 | login | test | def login(provider_name):
"""
Login handler, must accept both GET and POST to be able to use OpenID.
"""
# We need response object for the WerkzeugAdapter.
response = make_response()
# Log the user in, pass it the adapter and the provider name.
result = authomatic.login(
WerkzeugAd... | python | {
"resource": ""
} |
q272001 | normalize_dict | test | def normalize_dict(dict_):
"""
Replaces all values that are single-item iterables with the value of its
index 0.
:param dict dict_:
Dictionary to normalize.
:returns:
Normalized dictionary.
"""
return dict([(k, v[0] if not isinstance(v, str) and len(v) == 1 else v)
... | python | {
"resource": ""
} |
q272002 | items_to_dict | test | def items_to_dict(items):
"""
Converts list of tuples to dictionary with duplicate keys converted to
lists.
:param list items:
List of tuples.
:returns:
:class:`dict`
"""
res = collections.defaultdict(list)
for k, v in items:
res[k].append(v)
return norm... | python | {
"resource": ""
} |
q272003 | json_qs_parser | test | def json_qs_parser(body):
"""
Parses response body from JSON, XML or query string.
:param body:
string
:returns:
:class:`dict`, :class:`list` if input is JSON or query string,
:class:`xml.etree.ElementTree.Element` if XML.
"""
try:
# Try JSON first.
ret... | python | {
"resource": ""
} |
q272004 | resolve_provider_class | test | def resolve_provider_class(class_):
"""
Returns a provider class.
:param class_name: :class:`string` or
:class:`authomatic.providers.BaseProvider` subclass.
"""
if isinstance(class_, str):
# prepare path for authomatic.providers package
path = '.'.join([__package__, 'providers... | python | {
"resource": ""
} |
q272005 | Session.create_cookie | test | def create_cookie(self, delete=None):
"""
Creates the value for ``Set-Cookie`` HTTP header.
:param bool delete:
If ``True`` the cookie value will be ``deleted`` and the
Expires value will be ``Thu, 01-Jan-1970 00:00:01 GMT``.
"""
value = 'deleted' if del... | python | {
"resource": ""
} |
q272006 | Session.save | test | def save(self):
"""
Adds the session cookie to headers.
"""
if self.data:
cookie = self.create_cookie()
cookie_len = len(cookie)
if cookie_len > 4093:
raise SessionError('Cookie too long! The cookie size {0} '
... | python | {
"resource": ""
} |
q272007 | Session._get_data | test | def _get_data(self):
"""
Extracts the session data from cookie.
"""
cookie = self.adapter.cookies.get(self.name)
return self._deserialize(cookie) if cookie else {} | python | {
"resource": ""
} |
q272008 | Session.data | test | def data(self):
"""
Gets session data lazily.
"""
if not self._data:
self._data = self._get_data()
# Always return a dict, even if deserialization returned nothing
if self._data is None:
self._data = {}
return self._data | python | {
"resource": ""
} |
q272009 | Session._signature | test | def _signature(self, *parts):
"""
Creates signature for the session.
"""
signature = hmac.new(six.b(self.secret), digestmod=hashlib.sha1)
signature.update(six.b('|'.join(parts)))
return signature.hexdigest() | python | {
"resource": ""
} |
q272010 | Session._serialize | test | def _serialize(self, value):
"""
Converts the value to a signed string with timestamp.
:param value:
Object to be serialized.
:returns:
Serialized value.
"""
# data = copy.deepcopy(value)
data = value
# 1. Serialize
ser... | python | {
"resource": ""
} |
q272011 | Credentials.valid | test | def valid(self):
"""
``True`` if credentials are valid, ``False`` if expired.
"""
if self.expiration_time:
return self.expiration_time > int(time.time())
else:
return True | python | {
"resource": ""
} |
q272012 | Credentials.expire_soon | test | def expire_soon(self, seconds):
"""
Returns ``True`` if credentials expire sooner than specified.
:param int seconds:
Number of seconds.
:returns:
``True`` if credentials expire sooner than specified,
else ``False``.
"""
if self.exp... | python | {
"resource": ""
} |
q272013 | Credentials.serialize | test | def serialize(self):
"""
Converts the credentials to a percent encoded string to be stored for
later use.
:returns:
:class:`string`
"""
if self.provider_id is None:
raise ConfigError(
'To serialize credentials you need to specify... | python | {
"resource": ""
} |
q272014 | Response.is_binary_string | test | def is_binary_string(content):
"""
Return true if string is binary data.
"""
textchars = (bytearray([7, 8, 9, 10, 12, 13, 27]) +
bytearray(range(0x20, 0x100)))
return bool(content.translate(None, textchars)) | python | {
"resource": ""
} |
q272015 | Response.content | test | def content(self):
"""
The whole response content.
"""
if not self._content:
content = self.httplib_response.read()
if self.is_binary_string(content):
self._content = content
else:
self._content = content.decode('utf-8'... | python | {
"resource": ""
} |
q272016 | OAuth1.create_request_elements | test | def create_request_elements(
cls, request_type, credentials, url, params=None, headers=None,
body='', method='GET', verifier='', callback=''
):
"""
Creates |oauth1| request elements.
"""
params = params or {}
headers = headers or {}
consumer_... | python | {
"resource": ""
} |
q272017 | Bitbucket._access_user_info | test | def _access_user_info(self):
"""
Email is available in separate method so second request is needed.
"""
response = super(Bitbucket, self)._access_user_info()
response.data.setdefault("email", None)
email_response = self.access(self.user_email_url)
if email_respo... | python | {
"resource": ""
} |
q272018 | FlaskAuthomatic.login | test | def login(self, *login_args, **login_kwargs):
"""
Decorator for Flask view functions.
"""
def decorator(f):
@wraps(f)
def decorated(*args, **kwargs):
self.response = make_response()
adapter = WerkzeugAdapter(request, self.response)... | python | {
"resource": ""
} |
q272019 | GAEOpenID.login | test | def login(self):
"""
Launches the OpenID authentication procedure.
"""
if self.params.get(self.identifier_param):
# =================================================================
# Phase 1 before redirect.
# ========================================... | python | {
"resource": ""
} |
q272020 | BaseProvider._session_key | test | def _session_key(self, key):
"""
Generates session key string.
:param str key:
e.g. ``"authomatic:facebook:key"``
"""
return '{0}:{1}:{2}'.format(self.settings.prefix, self.name, key) | python | {
"resource": ""
} |
q272021 | BaseProvider._session_set | test | def _session_set(self, key, value):
"""
Saves a value to session.
"""
self.session[self._session_key(key)] = value | python | {
"resource": ""
} |
q272022 | BaseProvider.csrf_generator | test | def csrf_generator(secret):
"""
Generates CSRF token.
Inspired by this article:
http://blog.ptsecurity.com/2012/10/random-number-security-in-python.html
:returns:
:class:`str` Random unguessable string.
"""
# Create hash from random string plus sal... | python | {
"resource": ""
} |
q272023 | BaseProvider._log | test | def _log(cls, level, msg, **kwargs):
"""
Logs a message with pre-formatted prefix.
:param int level:
Logging level as specified in the
`login module <http://docs.python.org/2/library/logging.html>`_ of
Python standard library.
:param str msg:
... | python | {
"resource": ""
} |
q272024 | BaseProvider._http_status_in_category | test | def _http_status_in_category(status, category):
"""
Checks whether a HTTP status code is in the category denoted by the
hundreds digit.
"""
assert category < 10, 'HTTP status category must be a one-digit int!'
cat = category * 100
return status >= cat and status ... | python | {
"resource": ""
} |
q272025 | AuthorizationProvider._split_url | test | def _split_url(url):
"""
Splits given url to url base and params converted to list of tuples.
"""
split = parse.urlsplit(url)
base = parse.urlunsplit((split.scheme, split.netloc, split.path, 0, 0))
params = parse.parse_qsl(split.query, True)
return base, params | python | {
"resource": ""
} |
q272026 | cross_origin | test | def cross_origin(app, *args, **kwargs):
"""
This function is the decorator which is used to wrap a Sanic route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs authentication whi... | python | {
"resource": ""
} |
q272027 | set_cors_headers | test | def set_cors_headers(req, resp, context, options):
"""
Performs the actual evaluation of Sanic-CORS options and actually
modifies the response object.
This function is used both in the decorator and the after_request
callback
:param sanic.request.Request req:
"""
try:
request_c... | python | {
"resource": ""
} |
q272028 | get_app_kwarg_dict | test | def get_app_kwarg_dict(appInstance):
"""Returns the dictionary of CORS specific app configurations."""
# In order to support blueprints which do not have a config attribute
app_config = getattr(appInstance, 'config', {})
return dict(
(k.lower().replace('cors_', ''), app_config.get(k))
fo... | python | {
"resource": ""
} |
q272029 | flexible_str | test | def flexible_str(obj):
"""
A more flexible str function which intelligently handles stringifying
strings, lists and other iterables. The results are lexographically sorted
to ensure generated responses are consistent when iterables such as Set
are used.
"""
if obj is None:
return Non... | python | {
"resource": ""
} |
q272030 | ensure_iterable | test | def ensure_iterable(inst):
"""
Wraps scalars or string types as a list, or returns the iterable instance.
"""
if isinstance(inst, str):
return [inst]
elif not isinstance(inst, collections.abc.Iterable):
return [inst]
else:
return inst | python | {
"resource": ""
} |
q272031 | isclose | test | def isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0):
"""
Python 3.4 does not have math.isclose, so we need to steal it and add it here.
"""
try:
return math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)
except AttributeError:
# Running on older version of python, fall back to hand-rol... | python | {
"resource": ""
} |
q272032 | deprecated | test | def deprecated(func):
"""
Deprecator decorator.
"""
@functools.wraps(func)
def new_func(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
return new_func | python | {
"resource": ""
} |
q272033 | deserialize | test | def deserialize(bstr):
"""
Attempts to deserialize a bytestring into an audiosegment.
:param bstr: The bytestring serialized via an audiosegment's serialize() method.
:returns: An AudioSegment object deserialized from `bstr`.
"""
d = pickle.loads(bstr)
seg = pickle.loads(d['seg'])
retur... | python | {
"resource": ""
} |
q272034 | from_file | test | def from_file(path):
"""
Returns an AudioSegment object from the given file based on its file extension.
If the extension is wrong, this will throw some sort of error.
:param path: The path to the file, including the file extension.
:returns: An AudioSegment instance from the file.
"""
_nam... | python | {
"resource": ""
} |
q272035 | from_numpy_array | test | def from_numpy_array(nparr, framerate):
"""
Returns an AudioSegment created from the given numpy array.
The numpy array must have shape = (num_samples, num_channels).
:param nparr: The numpy array to create an AudioSegment from.
:returns: An AudioSegment created from the given array.
"""
#... | python | {
"resource": ""
} |
q272036 | AudioSegment._execute_sox_cmd | test | def _execute_sox_cmd(self, cmd, console_output=False):
"""
Executes a Sox command in a platform-independent manner.
`cmd` must be a format string that includes {inputfile} and {outputfile}.
"""
on_windows = platform.system().lower() == "windows"
# On Windows, a temporar... | python | {
"resource": ""
} |
q272037 | AudioSegment.filter_silence | test | def filter_silence(self, duration_s=1, threshold_percentage=1, console_output=False):
"""
Returns a copy of this AudioSegment, but whose silence has been removed.
.. note:: This method requires that you have the program 'sox' installed.
.. warning:: This method uses the program 'sox' t... | python | {
"resource": ""
} |
q272038 | AudioSegment.fft | test | def fft(self, start_s=None, duration_s=None, start_sample=None, num_samples=None, zero_pad=False):
"""
Transforms the indicated slice of the AudioSegment into the frequency domain and returns the bins
and the values.
If neither `start_s` or `start_sample` is specified, the first sample ... | python | {
"resource": ""
} |
q272039 | AudioSegment.generate_frames | test | def generate_frames(self, frame_duration_ms, zero_pad=True):
"""
Yields self's data in chunks of frame_duration_ms.
This function adapted from pywebrtc's example [https://github.com/wiseman/py-webrtcvad/blob/master/example.py].
:param frame_duration_ms: The length of each frame in ms.
... | python | {
"resource": ""
} |
q272040 | AudioSegment.normalize_spl_by_average | test | def normalize_spl_by_average(self, db):
"""
Normalize the values in the AudioSegment so that its `spl` property
gives `db`.
.. note:: This method is currently broken - it returns an AudioSegment whose
values are much smaller than reasonable, yet which yield an SPL valu... | python | {
"resource": ""
} |
q272041 | AudioSegment.reduce | test | def reduce(self, others):
"""
Reduces others into this one by concatenating all the others onto this one and
returning the result. Does not modify self, instead, makes a copy and returns that.
:param others: The other AudioSegment objects to append to this one.
:returns: The con... | python | {
"resource": ""
} |
q272042 | AudioSegment.resample | test | def resample(self, sample_rate_Hz=None, sample_width=None, channels=None, console_output=False):
"""
Returns a new AudioSegment whose data is the same as this one, but which has been resampled to the
specified characteristics. Any parameter left None will be unchanged.
.. note:: This me... | python | {
"resource": ""
} |
q272043 | AudioSegment.serialize | test | def serialize(self):
"""
Serializes into a bytestring.
:returns: An object of type Bytes.
"""
d = self.__getstate__()
return pickle.dumps({
'name': d['name'],
'seg': pickle.dumps(d['seg'], protocol=-1),
}, protocol=-1) | python | {
"resource": ""
} |
q272044 | AudioSegment.spectrogram | test | def spectrogram(self, start_s=None, duration_s=None, start_sample=None, num_samples=None,
window_length_s=None, window_length_samples=None, overlap=0.5, window=('tukey', 0.25)):
"""
Does a series of FFTs from `start_s` or `start_sample` for `duration_s` or `num_samples`.
Effe... | python | {
"resource": ""
} |
q272045 | _choose_front_id_from_candidates | test | def _choose_front_id_from_candidates(candidate_offset_front_ids, offset_fronts, offsets_corresponding_to_onsets):
"""
Returns a front ID which is the id of the offset front that contains the most overlap
with offsets that correspond to the given onset front ID.
"""
noverlaps = [] # will contain tup... | python | {
"resource": ""
} |
q272046 | _get_offset_front_id_after_onset_sample_idx | test | def _get_offset_front_id_after_onset_sample_idx(onset_sample_idx, offset_fronts):
"""
Returns the offset_front_id which corresponds to the offset front which occurs
first entirely after the given onset sample_idx.
"""
# get all the offset_front_ids
offset_front_ids = [i for i in np.unique(offset... | python | {
"resource": ""
} |
q272047 | _get_offset_front_id_after_onset_front | test | def _get_offset_front_id_after_onset_front(onset_front_id, onset_fronts, offset_fronts):
"""
Get the ID corresponding to the offset which occurs first after the given onset_front_id.
By `first` I mean the front which contains the offset which is closest to the latest point
in the onset front. By `after`... | python | {
"resource": ""
} |
q272048 | _match_offset_front_id_to_onset_front_id | test | def _match_offset_front_id_to_onset_front_id(onset_front_id, onset_fronts, offset_fronts, onsets, offsets):
"""
Find all offset fronts which are composed of at least one offset which corresponds to one of the onsets in the
given onset front.
The offset front which contains the most of such offsets is th... | python | {
"resource": ""
} |
q272049 | _get_consecutive_and_overlapping_fronts | test | def _get_consecutive_and_overlapping_fronts(onset_fronts, offset_fronts, onset_front_id, offset_front_id):
"""
Gets an onset_front and an offset_front such that they both occupy at least some of the same
frequency channels, then returns the portion of each that overlaps with the other.
"""
# Get the... | python | {
"resource": ""
} |
q272050 | _update_segmentation_mask | test | def _update_segmentation_mask(segmentation_mask, onset_fronts, offset_fronts, onset_front_id, offset_front_id_most_overlap):
"""
Returns an updated segmentation mask such that the input `segmentation_mask` has been updated by segmenting between
`onset_front_id` and `offset_front_id`, as found in `onset_fron... | python | {
"resource": ""
} |
q272051 | _front_id_from_idx | test | def _front_id_from_idx(front, index):
"""
Returns the front ID found in `front` at the given `index`.
:param front: An onset or offset front array of shape [nfrequencies, nsamples]
:index: A tuple of the form (frequency index, sample index)
:returns: ... | python | {
"resource": ""
} |
q272052 | _get_front_ids_one_at_a_time | test | def _get_front_ids_one_at_a_time(onset_fronts):
"""
Yields one onset front ID at a time until they are gone. All the onset fronts from a
frequency channel are yielded, then all of the next channel's, etc., though one at a time.
"""
yielded_so_far = set()
for row in onset_fronts:
for id i... | python | {
"resource": ""
} |
q272053 | _get_corresponding_offsets | test | def _get_corresponding_offsets(onset_fronts, onset_front_id, onsets, offsets):
"""
Gets the offsets that occur as close as possible to the onsets in the given onset-front.
"""
corresponding_offsets = []
for index in _get_front_idxs_from_id(onset_fronts, onset_front_id):
offset_fidx, offset_s... | python | {
"resource": ""
} |
q272054 | _remove_overlaps | test | def _remove_overlaps(segmentation_mask, fronts):
"""
Removes all points in the fronts that overlap with the segmentation mask.
"""
fidxs, sidxs = np.where((segmentation_mask != fronts) & (segmentation_mask != 0) & (fronts != 0))
fronts[fidxs, sidxs] = 0 | python | {
"resource": ""
} |
q272055 | _remove_fronts_that_are_too_small | test | def _remove_fronts_that_are_too_small(fronts, size):
"""
Removes all fronts from `fronts` which are strictly smaller than
`size` consecutive frequencies in length.
"""
ids = np.unique(fronts)
for id in ids:
if id == 0 or id == -1:
continue
front = _get_front_idxs_from... | python | {
"resource": ""
} |
q272056 | _break_poorly_matched_fronts | test | def _break_poorly_matched_fronts(fronts, threshold=0.1, threshold_overlap_samples=3):
"""
For each onset front, for each frequency in that front, break the onset front if the signals
between this frequency's onset and the next frequency's onset are not similar enough.
Specifically:
If we have the f... | python | {
"resource": ""
} |
q272057 | _merge_adjacent_segments | test | def _merge_adjacent_segments(mask):
"""
Merges all segments in `mask` which are touching.
"""
mask_ids = [id for id in np.unique(mask) if id != 0]
for id in mask_ids:
myfidxs, mysidxs = np.where(mask == id)
for other in mask_ids: # Ugh, brute force O(N^2) algorithm.. gross..
... | python | {
"resource": ""
} |
q272058 | _separate_masks | test | def _separate_masks(mask, threshold=0.025):
"""
Returns a list of segmentation masks each of the same dimension as the input one,
but where they each have exactly one segment in them and all other samples in them
are zeroed.
Only bothers to return segments that are larger in total area than `thresh... | python | {
"resource": ""
} |
q272059 | _downsample_one_or_the_other | test | def _downsample_one_or_the_other(mask, mask_indexes, stft, stft_indexes):
"""
Takes the given `mask` and `stft`, which must be matrices of shape `frequencies, times`
and downsamples one of them into the other one's times, so that the time dimensions
are equal. Leaves the frequency dimension untouched.
... | python | {
"resource": ""
} |
q272060 | _asa_task | test | def _asa_task(q, masks, stft, sample_width, frame_rate, nsamples_for_each_fft):
"""
Worker for the ASA algorithm's multiprocessing step.
"""
# Convert each mask to (1 or 0) rather than (ID or 0)
for mask in masks:
mask = np.where(mask > 0, 1, 0)
# Multiply the masks against STFTs
ma... | python | {
"resource": ""
} |
q272061 | bandpass_filter | test | def bandpass_filter(data, low, high, fs, order=5):
"""
Does a bandpass filter over the given data.
:param data: The data (numpy array) to be filtered.
:param low: The low cutoff in Hz.
:param high: The high cutoff in Hz.
:param fs: The sample rate (in Hz) of the data.
:param order: The orde... | python | {
"resource": ""
} |
q272062 | lowpass_filter | test | def lowpass_filter(data, cutoff, fs, order=5):
"""
Does a lowpass filter over the given data.
:param data: The data (numpy array) to be filtered.
:param cutoff: The high cutoff in Hz.
:param fs: The sample rate in Hz of the data.
:param order: The order of the filter. The higher the order, the ... | python | {
"resource": ""
} |
q272063 | list_to_tf_input | test | def list_to_tf_input(data, response_index, num_outcomes):
"""
Separates the outcome feature from the data and creates the onehot vector for each row.
"""
matrix = np.matrix([row[:response_index] + row[response_index+1:] for row in data])
outcomes = np.asarray([row[response_index] for row in data], dtype=np.ui... | python | {
"resource": ""
} |
q272064 | expand_and_standardize_dataset | test | def expand_and_standardize_dataset(response_index, response_header, data_set, col_vals, headers, standardizers, feats_to_ignore, columns_to_expand, outcome_trans_dict):
"""
Standardizes continuous features and expands categorical features.
"""
# expand and standardize
modified_set = []
for row_index, row in... | python | {
"resource": ""
} |
q272065 | equal_ignore_order | test | def equal_ignore_order(a, b):
"""
Used to check whether the two edge lists have the same edges
when elements are neither hashable nor sortable.
"""
unmatched = list(b)
for element in a:
try:
unmatched.remove(element)
except ValueError:
return False
return not unmatched | python | {
"resource": ""
} |
q272066 | group_audit_ranks | test | def group_audit_ranks(filenames, measurer, similarity_bound=0.05):
"""
Given a list of audit files, rank them using the `measurer` and
return the features that never deviate more than `similarity_bound`
across repairs.
"""
def _partition_groups(feature_scores):
groups = []
for feature, score in fea... | python | {
"resource": ""
} |
q272067 | load_audit_confusion_matrices | test | def load_audit_confusion_matrices(filename):
"""
Loads a confusion matrix in a two-level dictionary format.
For example, the confusion matrix of a 75%-accurate model
that predicted 15 values (and mis-classified 5) may look like:
{"A": {"A":10, "B": 5}, "B": {"B":5}}
Note that raw boolean values are transl... | python | {
"resource": ""
} |
q272068 | list_to_tf_input | test | def list_to_tf_input(data, response_index, num_outcomes):
"""
Separates the outcome feature from the data.
"""
matrix = np.matrix([row[:response_index] + row[response_index+1:] for row in data])
outcomes = np.asarray([row[response_index] for row in data], dtype=np.uint8)
return matrix, outcomes | python | {
"resource": ""
} |
q272069 | PackagesStatusDetector._update_index_url_from_configs | test | def _update_index_url_from_configs(self):
""" Checks for alternative index-url in pip.conf """
if 'VIRTUAL_ENV' in os.environ:
self.pip_config_locations.append(os.path.join(os.environ['VIRTUAL_ENV'], 'pip.conf'))
self.pip_config_locations.append(os.path.join(os.environ['VIRTUAL_... | python | {
"resource": ""
} |
q272070 | RequirementsDetector.autodetect_files | test | def autodetect_files(self):
""" Attempt to detect requirements files in the current working directory """
if self._is_valid_requirements_file('requirements.txt'):
self.filenames.append('requirements.txt')
if self._is_valid_requirements_file('requirements.pip'): # pragma: nocover
... | python | {
"resource": ""
} |
q272071 | resolve_streams | test | def resolve_streams(wait_time=1.0):
"""Resolve all streams on the network.
This function returns all currently available streams from any outlet on
the network. The network is usually the subnet specified at the local
router, but may also include a group of machines visible to each other via
mul... | python | {
"resource": ""
} |
q272072 | resolve_byprop | test | def resolve_byprop(prop, value, minimum=1, timeout=FOREVER):
"""Resolve all streams with a specific value for a given property.
If the goal is to resolve a specific stream, this method is preferred over
resolving all streams and then selecting the desired one.
Keyword arguments:
prop -- The S... | python | {
"resource": ""
} |
q272073 | resolve_bypred | test | def resolve_bypred(predicate, minimum=1, timeout=FOREVER):
"""Resolve all streams that match a given predicate.
Advanced query that allows to impose more conditions on the retrieved
streams; the given string is an XPath 1.0 predicate for the <description>
node (omitting the surrounding []'s), see also... | python | {
"resource": ""
} |
q272074 | handle_error | test | def handle_error(errcode):
"""Error handler function. Translates an error code into an exception."""
if type(errcode) is c_int:
errcode = errcode.value
if errcode == 0:
pass # no error
elif errcode == -1:
raise TimeoutError("the operation failed due to a timeout.")
elif errc... | python | {
"resource": ""
} |
q272075 | StreamOutlet.push_sample | test | def push_sample(self, x, timestamp=0.0, pushthrough=True):
"""Push a sample into the outlet.
Each entry in the list corresponds to one channel.
Keyword arguments:
x -- A list of values to push (one per channel).
timestamp -- Optionally the capture time of the sample, in agreeme... | python | {
"resource": ""
} |
q272076 | StreamOutlet.push_chunk | test | def push_chunk(self, x, timestamp=0.0, pushthrough=True):
"""Push a list of samples into the outlet.
samples -- A list of samples, either as a list of lists or a list of
multiplexed values.
timestamp -- Optionally the capture time of the most recent sample, in
... | python | {
"resource": ""
} |
q272077 | StreamInlet.info | test | def info(self, timeout=FOREVER):
"""Retrieve the complete information of the given stream.
This includes the extended description. Can be invoked at any time of
the stream's lifetime.
Keyword arguments:
timeout -- Timeout of the operation. (default FOREVER)
... | python | {
"resource": ""
} |
q272078 | StreamInlet.open_stream | test | def open_stream(self, timeout=FOREVER):
"""Subscribe to the data stream.
All samples pushed in at the other end from this moment onwards will be
queued and eventually be delivered in response to pull_sample() or
pull_chunk() calls. Pulling a sample without some preceding open_stream
... | python | {
"resource": ""
} |
q272079 | StreamInlet.time_correction | test | def time_correction(self, timeout=FOREVER):
"""Retrieve an estimated time correction offset for the given stream.
The first call to this function takes several miliseconds until a
reliable first estimate is obtained. Subsequent calls are instantaneous
(and rely on periodic background ... | python | {
"resource": ""
} |
q272080 | XMLElement.child | test | def child(self, name):
"""Get a child with a specified name."""
return XMLElement(lib.lsl_child(self.e, str.encode(name))) | python | {
"resource": ""
} |
q272081 | XMLElement.next_sibling | test | def next_sibling(self, name=None):
"""Get the next sibling in the children list of the parent node.
If a name is provided, the next sibling with the given name is returned.
"""
if name is None:
return XMLElement(lib.lsl_next_sibling(self.e))
else:
return... | python | {
"resource": ""
} |
q272082 | XMLElement.previous_sibling | test | def previous_sibling(self, name=None):
"""Get the previous sibling in the children list of the parent node.
If a name is provided, the previous sibling with the given name is
returned.
"""
if name is None:
return XMLElement(lib.lsl_previous_sibling(self.e))
... | python | {
"resource": ""
} |
q272083 | XMLElement.set_name | test | def set_name(self, name):
"""Set the element's name. Returns False if the node is empty."""
return bool(lib.lsl_set_name(self.e, str.encode(name))) | python | {
"resource": ""
} |
q272084 | XMLElement.set_value | test | def set_value(self, value):
"""Set the element's value. Returns False if the node is empty."""
return bool(lib.lsl_set_value(self.e, str.encode(value))) | python | {
"resource": ""
} |
q272085 | XMLElement.append_child | test | def append_child(self, name):
"""Append a child element with the specified name."""
return XMLElement(lib.lsl_append_child(self.e, str.encode(name))) | python | {
"resource": ""
} |
q272086 | XMLElement.prepend_child | test | def prepend_child(self, name):
"""Prepend a child element with the specified name."""
return XMLElement(lib.lsl_prepend_child(self.e, str.encode(name))) | python | {
"resource": ""
} |
q272087 | XMLElement.append_copy | test | def append_copy(self, elem):
"""Append a copy of the specified element as a child."""
return XMLElement(lib.lsl_append_copy(self.e, elem.e)) | python | {
"resource": ""
} |
q272088 | XMLElement.prepend_copy | test | def prepend_copy(self, elem):
"""Prepend a copy of the specified element as a child."""
return XMLElement(lib.lsl_prepend_copy(self.e, elem.e)) | python | {
"resource": ""
} |
q272089 | XMLElement.remove_child | test | def remove_child(self, rhs):
"""Remove a given child element, specified by name or as element."""
if type(rhs) is XMLElement:
lib.lsl_remove_child(self.e, rhs.e)
else:
lib.lsl_remove_child_n(self.e, rhs) | python | {
"resource": ""
} |
q272090 | ContinuousResolver.results | test | def results(self):
"""Obtain the set of currently present streams on the network.
Returns a list of matching StreamInfo objects (with empty desc
field), any of which can subsequently be used to open an inlet.
"""
# noinspection PyCallingNonCallable
buffer = (c_void_p*10... | python | {
"resource": ""
} |
q272091 | pair | test | def pair(cmd, word):
"""See all token associated with a given token.
PAIR lilas"""
word = list(preprocess_query(word))[0]
key = pair_key(word)
tokens = [t.decode() for t in DB.smembers(key)]
tokens.sort()
print(white(tokens))
print(magenta('(Total: {})'.format(len(tokens)))) | python | {
"resource": ""
} |
q272092 | do_AUTOCOMPLETE | test | def do_AUTOCOMPLETE(cmd, s):
"""Shows autocomplete results for a given token."""
s = list(preprocess_query(s))[0]
keys = [k.decode() for k in DB.smembers(edge_ngram_key(s))]
print(white(keys))
print(magenta('({} elements)'.format(len(keys)))) | python | {
"resource": ""
} |
q272093 | compute_edge_ngrams | test | def compute_edge_ngrams(token, min=None):
"""Compute edge ngram of token from min. Does not include token itself."""
if min is None:
min = config.MIN_EDGE_NGRAMS
token = token[:config.MAX_EDGE_NGRAMS + 1]
return [token[:i] for i in range(min, len(token))] | python | {
"resource": ""
} |
q272094 | iter_pipe | test | def iter_pipe(pipe, processors):
"""Allow for iterators to return either an item or an iterator of items."""
if isinstance(pipe, str):
pipe = [pipe]
for it in processors:
pipe = it(pipe)
yield from pipe | python | {
"resource": ""
} |
q272095 | ChunkedPool.imap_unordered | test | def imap_unordered(self, func, iterable, chunksize):
"""Customized version of imap_unordered.
Directly send chunks to func, instead of iterating in each process and
sending one by one.
Original:
https://hg.python.org/cpython/file/tip/Lib/multiprocessing/pool.py#l271
Ot... | python | {
"resource": ""
} |
q272096 | make_fuzzy | test | def make_fuzzy(word, max=1):
"""Naive neighborhoods algo."""
# inversions
neighbors = []
for i in range(0, len(word) - 1):
neighbor = list(word)
neighbor[i], neighbor[i+1] = neighbor[i+1], neighbor[i]
neighbors.append(''.join(neighbor))
# substitutions
for letter in strin... | python | {
"resource": ""
} |
q272097 | do_fuzzy | test | def do_fuzzy(self, word):
"""Compute fuzzy extensions of word.
FUZZY lilas"""
word = list(preprocess_query(word))[0]
print(white(make_fuzzy(word))) | python | {
"resource": ""
} |
q272098 | do_fuzzyindex | test | def do_fuzzyindex(self, word):
"""Compute fuzzy extensions of word that exist in index.
FUZZYINDEX lilas"""
word = list(preprocess_query(word))[0]
token = Token(word)
neighbors = make_fuzzy(token)
neighbors = [(n, DB.zcard(dbkeys.token_key(n))) for n in neighbors]
neighbors.sort(key=lambda n... | python | {
"resource": ""
} |
q272099 | extend_results_extrapoling_relations | test | def extend_results_extrapoling_relations(helper):
"""Try to extract the bigger group of interlinked tokens.
Should generally be used at last in the collectors chain.
"""
if not helper.bucket_dry:
return # No need.
tokens = set(helper.meaningful + helper.common)
for relation in _extract... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.