Search is not available for this dataset
text
stringlengths
75
104k
def to_dict(self): """ Converts the :class:`.User` instance to a :class:`dict`. :returns: :class:`dict` """ # copy the dictionary d = copy.copy(self.__dict__) # Keep only the provider name to avoid circular reference d['provider'] = self.pr...
def expire_in(self, value): """ Computes :attr:`.expiration_time` when the value is set. """ # pylint:disable=attribute-defined-outside-init if value: self._expiration_time = int(time.time()) + int(value) self._expire_in = value
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
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...
def refresh(self, force=False, soon=86400): """ Refreshes the credentials only if the **provider** supports it and if it will expire in less than one day. It does nothing in other cases. .. note:: The credentials will be refreshed only if it gives sense i.e. onl...
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...
def deserialize(cls, config, credentials): """ A *class method* which reconstructs credentials created by :meth:`serialize`. You can also pass it a :class:`.Credentials` instance. :param dict config: The same :doc:`config` used in the :func:`.login` to get the ...
def popup_js(self, callback_name=None, indent=None, custom=None, stay_open=False): """ Returns JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>` function of :ref:`javas...
def popup_html(self, callback_name=None, indent=None, title='Login | {0}', custom=None, stay_open=False): """ Returns a HTML with JavaScript that: #. Triggers the ``options.onLoginComplete(result, closer)`` handler set with the :ref:`authomatic.setup() <js_setup>...
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))
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'...
def data(self): """ A :class:`dict` of data parsed from :attr:`.content`. """ if not self._data: self._data = self.content_parser(self.content) return self._data
def login(self, adapter, provider_name, callback=None, session=None, session_saver=None, **kwargs): """ If :data:`provider_name` specified, launches the login procedure for corresponding :doc:`provider </reference/providers>` and returns :class:`.LoginResult`. If :...
def access(self, credentials, url, params=None, method='GET', headers=None, body='', max_redirects=5, content_parser=None): """ Accesses **protected resource** on behalf of the **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). ...
def request_elements( self, credentials=None, url=None, method='GET', params=None, headers=None, body='', json_input=None, return_json=False ): """ Creates request elements for accessing **protected resource of a user**. Required arguments are :data:`credentials` and ...
def backend(self, adapter): """ Converts a *request handler* to a JSON backend which you can use with :ref:`authomatic.js <js>`. Just call it inside a *request handler* like this: :: class JSONHandler(webapp2.RequestHandler): def get(self): ...
def _normalize_params(params): """ Returns a normalized query string sorted first by key, then by value excluding the ``realm`` and ``oauth_signature`` parameters as specified here: http://oauth.net/core/1.0a/#rfc.section.9.1.1. :param params: :class:`dict` or :class:`list` of tuples. ...
def _create_base_string(method, base, params): """ Returns base string for HMAC-SHA1 signature as specified in: http://oauth.net/core/1.0a/#rfc.section.9.1.3. """ normalized_qs = _normalize_params(params) return _join_by_ampersand(method, base, normalized_qs)
def create_signature(cls, method, base, params, consumer_secret, token_secret=''): """ Returns HMAC-SHA1 signature as specified at: http://oauth.net/core/1.0a/#rfc.section.9.2. :param str method: HTTP method of the request to be signed. :par...
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_...
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...
def _access_user_info(self): """ Vimeo requires the user ID to access the user info endpoint, so we need to make two requests: one to get user ID and second to get user info. """ response = super(Vimeo, self)._access_user_info() uid = response.data.get('oauth', {}).get('u...
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)...
def get(cls, key, default=None): """ Resembles the :meth:`dict.get` method. :returns: A configuration dictionary for specified provider. """ # Query datastore. result = cls.query(cls.provider_name == key).get() if result: result_dict = ...
def values(cls): """ Resembles the :meth:`dict.values` method. """ # get all items results = cls.query().fetch() # return list of dictionaries return [result.to_dict() for result in results]
def initialize(cls): """ Creates an **"Example"** entity of kind **"NDBConfig"** in the datastore if the model is empty and raises and error to inform you that you should populate the model with data. .. note:: The *Datastore Viewer* in the ``_ah/admin/`` won't let ...
def login(self): """ Launches the OpenID authentication procedure. """ if self.params.get(self.identifier_param): # ================================================================= # Phase 1 before redirect. # ========================================...
def _error_traceback_html(exc_info, traceback_): """ Generates error traceback HTML. :param tuple exc_info: Output of :func:`sys.exc_info` function. :param traceback: Output of :func:`traceback.format_exc` function. """ html = """ <html> <head> <title>...
def login_decorator(func): """ Decorate the :meth:`.BaseProvider.login` implementations with this decorator. Provides mechanism for error reporting and returning result which makes the :meth:`.BaseProvider.login` implementation cleaner. """ def wrap(provider, *args, **kwargs): err...
def to_dict(self): """ Converts the provider instance to a :class:`dict`. :returns: :class:`dict` """ return dict(name=self.name, id=getattr(self, 'id', None), type_id=self.type_id, type=self.get_type(), ...
def _kwarg(self, kwargs, kwname, default=None): """ Resolves keyword arguments from constructor or :doc:`config`. .. note:: The keyword arguments take this order of precedence: 1. Arguments passed to constructor through the :func:`authomatic.login`. ...
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)
def _session_set(self, key, value): """ Saves a value to session. """ self.session[self._session_key(key)] = value
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...
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: ...
def _fetch(self, url, method='GET', params=None, headers=None, body='', max_redirects=5, content_parser=None): """ Fetches a URL. :param str url: The URL to fetch. :param str method: HTTP method of the request. :param dict params: ...
def _update_or_create_user(self, data, credentials=None, content=None): """ Updates or creates :attr:`.user`. :returns: :class:`.User` """ if not self.user: self.user = authomatic.core.User(self, credentials=credentials) self.user.content = con...
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 ...
def type_id(self): """ A short string representing the provider implementation id used for serialization of :class:`.Credentials` and to identify the type of provider in JavaScript. The part before hyphen denotes the type of the provider, the part after hyphen denotes th...
def access(self, url, params=None, method='GET', headers=None, body='', max_redirects=5, content_parser=None): """ Fetches the **protected resource** of an authenticated **user**. :param credentials: The **user's** :class:`.Credentials` (serialized or normal). ...
def async_access(self, *args, **kwargs): """ Same as :meth:`.access` but runs asynchronously in a separate thread. .. warning:: |async| :returns: :class:`.Future` instance representing the separate thread. """ return authomatic.core.Future(sel...
def update_user(self): """ Updates the :attr:`.BaseProvider.user`. .. warning:: Fetches the :attr:`.user_info_url`! :returns: :class:`.UserInfoResponse` """ if self.user_info_url: response = self._access_user_info() self....
def _authorization_header(cls, credentials): """ Creates authorization headers if the provider supports it. See: http://en.wikipedia.org/wiki/Basic_access_authentication. :param credentials: :class:`.Credentials` :returns: Headers as :class:`dict`. ...
def _check_consumer(self): """ Validates the :attr:`.consumer`. """ # 'magic' using _kwarg method # pylint:disable=no-member if not self.consumer.key: raise ConfigError( 'Consumer key not specified for provider {0}!'.format( ...
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
def _access_user_info(self): """ Accesses the :attr:`.user_info_url`. :returns: :class:`.UserInfoResponse` """ url = self.user_info_url.format(**self.user.__dict__) return self.access(url)
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...
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...
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...
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...
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
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...
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
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...
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...
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. """ #...
def silent(duration=1000, frame_rate=11025): """ Creates an AudioSegment object of the specified duration/frame_rate filled with digital silence. :param duration: The duration of the returned object in ms. :param frame_rate: The samples per second of the returned object. :returns: AudioSegment obje...
def spl(self): """ Sound Pressure Level - defined as 20 * log10(p/p0), where p is the RMS of the sound wave in Pascals and p0 is 20 micro Pascals. Since we would need to know calibration information about the microphone used to record the sound in order to transform ...
def filter_bank(self, lower_bound_hz=50, upper_bound_hz=8E3, nfilters=128, mode='mel'): """ Returns a numpy array of shape (nfilters, nsamples), where each row of data is the result of bandpass filtering the audiosegment around a particular frequency. The frequencies are spaced f...
def auditory_scene_analysis(self, debug=False, debugplot=False): """ Algorithm based on paper: Auditory Segmentation Based on Onset and Offset Analysis, by Hu and Wang, 2007. Returns a list of AudioSegments, each of which is all the sound during this AudioSegment's duration from ...
def detect_voice(self, prob_detect_voice=0.5): """ Returns self as a list of tuples: [('v', voiced segment), ('u', unvoiced segment), (etc.)] The overall order of the AudioSegment is preserved. :param prob_detect_voice: The raw probability that any random 20ms window of the aud...
def dice(self, seconds, zero_pad=False): """ Cuts the AudioSegment into `seconds` segments (at most). So for example, if seconds=10, this will return a list of AudioSegments, in order, where each one is at most 10 seconds long. If `zero_pad` is True, the last item AudioSegment object wil...
def detect_event(self, model, ms_per_input, transition_matrix, model_stats, event_length_s, start_as_yes=False, prob_raw_yes=0.5): """ A list of tuples of the form [('n', AudioSegment), ('y', AudioSegment), etc.] is returned, where tuples of the form ('n', AudioSegment) are ...
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...
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...
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 ...
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. ...
def generate_frames_as_segments(self, frame_duration_ms, zero_pad=True): """ Does the same thing as `generate_frames`, but yields tuples of (AudioSegment, timestamp) instead of Frames. """ for frame in self.generate_frames(frame_duration_ms, zero_pad=zero_pad): seg = AudioSeg...
def human_audible(self): """ Returns an estimate of whether this AudioSegment is mostly human audible or not. This is done by taking an FFT of the segment and checking if the SPL of the segment falls below the function `f(x) = 40.11453 - 0.01683697x + 1.406211e-6x^2 - 2.371512e-11x^3`, ...
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...
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...
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...
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)
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...
def to_numpy_array(self): """ Convenience function for `np.array(self.get_array_of_samples())` while keeping the appropriate dtype. """ dtype_dict = { 1: np.int8, 2: np.int16, 4: np.int32 ...
def zero_extend(self, duration_s=None, num_samples=None): """ Adds a number of zeros (digital silence) to the AudioSegment (returning a new one). :param duration_s: The number of seconds of zeros to add. If this is specified, `num_samples` must be None. :param num_samples: The number of...
def _compute_peaks_or_valleys_of_first_derivative(s, do_peaks=True): """ Takes a spectrogram and returns a 2D array of the form: 0 0 0 1 0 0 1 0 0 0 1 <-- Frequency 0 0 0 1 0 0 0 0 0 0 1 0 <-- Frequency 1 0 0 0 0 0 0 1 0 1 0 0 <-- Frequency 2 *** Time axis ******* Where a 1 means tha...
def _correlate_onsets_and_offsets(onsets, offsets, gradients): """ Takes an array of onsets and an array of offsets, of the shape [nfrequencies, nsamples], where each item in these arrays is either a 0 (not an on/offset) or a 1 (a possible on/offset). This function returns a new offsets array, where th...
def _form_onset_offset_fronts(ons_or_offs, sample_rate_hz, threshold_ms=20): """ Takes an array of onsets or offsets (shape = [nfrequencies, nsamples], where a 1 corresponds to an on/offset, and samples are 0 otherwise), and returns a new array of the same shape, where each 1 has been replaced by either...
def _lookup_offset_by_onset_idx(onset_idx, onsets, offsets): """ Takes an onset index (freq, sample) and returns the offset index (freq, sample) such that frequency index is the same, and sample index is the minimum of all offsets ocurring after the given onset. If there are no offsets after the given ...
def _get_front_idxs_from_id(fronts, id): """ Return a list of tuples of the form (frequency_idx, sample_idx), corresponding to all the indexes of the given front. """ if id == -1: # This is the only special case. # -1 is the index of the catch-all final column offset front. f...
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...
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...
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`...
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...
def _get_consecutive_portions_of_front(front): """ Yields lists of the form [(f, s), (f, s)], one at a time from the given front (which is a list of the same form), such that each list yielded is consecutive in frequency. """ last_f = None ls = [] for f, s in front: if last_f is not ...
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...
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...
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: ...
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...
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...
def _get_all_offset_fronts_from_offsets(offset_fronts, corresponding_offsets): """ Returns all the offset fronts that are composed of at least one of the given offset indexes. Also returns a dict of the form {offset_front_id: ntimes saw} """ all_offset_fronts_of_interest = [] ids_ntimes_seen = {...
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
def _match_fronts(onset_fronts, offset_fronts, onsets, offsets, debug=False): """ Returns a segmentation mask, which looks like this: frequency 1: 0 0 4 4 4 4 4 0 0 5 5 5 frequency 2: 0 4 4 4 4 4 0 0 0 0 5 5 frequency 3: 0 4 4 4 4 4 4 4 5 5 5 5 That is, each item in the array is either a 0 (not...
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...
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...
def _update_segmentation_mask_if_overlap(toupdate, other, id, otherid): """ Merges the segments specified by `id` (found in `toupdate`) and `otherid` (found in `other`) if they overlap at all. Updates `toupdate` accordingly. """ # If there is any overlap or touching, merge the two, otherwise just re...
def _segments_are_adjacent(seg1, seg2): """ Checks if seg1 and seg2 are adjacent at any point. Each is a tuple of the form (fidxs, sidxs). """ # TODO: This is unnacceptably slow lsf1, lss1 = seg1 lsf2, lss2 = seg2 for i, f1 in enumerate(lsf1): for j, f2 in enumerate(lsf2): ...
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.. ...
def _integrate_segmentation_masks(segmasks): """ `segmasks` should be in sorted order of [coarsest, ..., finest]. Integrates the given list of segmentation masks together to form one segmentation mask by having each segment subsume ones that exist in the finer masks. """ if len(segmasks) == 1: ...