text
stringlengths
81
112k
This function extracts information from the /userinfo endpoint which will be consumed by allauth.socialaccount.adapter.populate_user(). Look there to find which key-value pairs that should be saved in the returned dict. Typical return dict: { "userid": "76a7a061-3c55...
Even when email verification is not mandatory during signup, there may be circumstances during which you really want to prevent unverified users to proceed. This decorator ensures the user is authenticated and has a verified email address. If the former is not the case then the behavior is identical to ...
Added because the Dropbox OAuth2 flow doesn't work when scope is passed in, which is empty. def _strip_empty_keys(self, params): """Added because the Dropbox OAuth2 flow doesn't work when scope is passed in, which is empty. """ keys = [k for k, v in params.items() if v == ''] ...
Django on py2 raises ValueError on large values. def int_to_base36(i): """ Django on py2 raises ValueError on large values. """ if six.PY2: char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if not isinst...
Saves a new account. Note that while the account is new, the user may be an existing one (when connecting accounts) def save(self, request, connect=False): """ Saves a new account. Note that while the account is new, the user may be an existing one (when connecting accounts) """...
Lookup existing account, if any. def lookup(self): """ Lookup existing account, if any. """ assert not self.is_existing try: a = SocialAccount.objects.get(provider=self.account.provider, uid=self.account.uid) # Up...
Instantiates and populates a `SocialLogin` model based on the data retrieved in `response`. The method does NOT save the model to the DB. Data for `SocialLogin` will be extracted from `response` with the help of the `.extract_uid()`, `.extract_extra_data()`, `.extract_common_fie...
Extract fields from a basic user query. def extract_common_fields(self, data): """Extract fields from a basic user query.""" email = None for curr_email in data.get("emails", []): email = email or curr_email.get("email") if curr_email.get("verified", False) and \ ...
Arguments: request - The get request to the callback URL /accounts/dataporten/login/callback. app - The corresponding SocialApp model instance token - A token object with access token given in token.token Returns: Should return a dict with ...
View to handle final steps of OAuth based authentication where the user gets redirected back to from the service provider def dispatch(self, request): """ View to handle final steps of OAuth based authentication where the user gets redirected back to from the service provider ""...
Simply logging in the user may become a security issue. If you do not take proper care (e.g. don't purge used email confirmations), a malicious person that got hold of the link will be able to login over and over again and the user is unable to do anything about it. Even restoring their ...
Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`. def extract_from_dict(data, path): """ Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`. """ value = data try: for key in path: ...
{'elements': [{'handle': 'urn:li:emailAddress:319371470', 'handle~': {'emailAddress': 'raymond.penners@intenct.nl'}}]} def _extract_email(data): """ {'elements': [{'handle': 'urn:li:emailAddress:319371470', 'handle~': {'emailAddress': 'raymond.penners@intenct.nl'}}]} """ r...
Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token def _get_request_token(self): """ Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token """ if self...
Obtain the access token to access private resources at the API endpoint. def get_access_token(self): """ Obtain the access token to access private resources at the API endpoint. """ if self.access_token is None: request_token = self._get_rt_from_session() ...
Returns a ``HttpResponseRedirect`` object to redirect the user to the URL the OAuth provider handles authorization. def get_redirect(self, authorization_url, extra_params): """ Returns a ``HttpResponseRedirect`` object to redirect the user to the URL the OAuth provider handles authoriza...
Get the saved access token for private resources from the session. def _get_at_from_session(self): """ Get the saved access token for private resources from the session. """ try: return self.request.session['oauth_%s_access_token' % ge...
Request a API endpoint at ``url`` with ``params`` being either the POST or GET data. def query(self, url, method="GET", params=dict(), headers=dict()): """ Request a API endpoint at ``url`` with ``params`` being either the POST or GET data. """ access_token = self._get_a...
Returns the next URL to redirect to, if it was explicitly passed via the request. def get_next_redirect_url(request, redirect_field_name="next"): """ Returns the next URL to redirect to, if it was explicitly passed via the request. """ redirect_to = get_request_param(request, redirect_field_nam...
Gets or sets (optional) user model fields. No-op if fields do not exist. def user_field(user, field, *args): """ Gets or sets (optional) user model fields. No-op if fields do not exist. """ if not field: return User = get_user_model() try: field_meta = User._meta.get_field(field...
Keyword arguments: signup -- Indicates whether or not sending the email is essential (during signup), or if it can be skipped (e.g. in case email verification is optional and we are only logging in). def perform_login(request, user, email_verification, redirect_url=None, signal_kwargs=No...
Takes a list of EmailAddress instances and cleans it up, making sure only valid ones remain, without multiple primaries etc. Order is important: e.g. if multiple primary e-mail addresses exist, the first one encountered will be kept as primary. def cleanup_email_addresses(request, addresses): """ ...
Creates proper EmailAddress for the user that was just signed up. Only sets up, doesn't do any other handling such as sending out email confirmation mails etc. def setup_user_email(request, user, addresses): """ Creates proper EmailAddress for the user that was just signed up. Only sets up, doesn't...
E-mail verification mails are sent: a) Explicitly: when a user signs up b) Implicitly: when a user attempts to log in using an unverified e-mail while EMAIL_VERIFICATION is mandatory. Especially in case of b), we want to limit the number of mails sent (consider a user retrying a few times), which i...
Keep user.email in sync with user.emailaddress_set. Under some circumstances the user.email may not have ended up as an EmailAddress record, e.g. in the case of manually created admin users. def sync_user_email_addresses(user): """ Keep user.email in sync with user.emailaddress_set. Under som...
Return list of users by email address Typically one, at most just a few in length. First we look through EmailAddress table, than customisable User model table. Add results together avoiding SQL joins and deduplicate. def filter_users_by_email(email): """Return list of users by email address Typ...
This should return a string. def user_pk_to_url_str(user): """ This should return a string. """ User = get_user_model() if issubclass(type(User._meta.pk), models.UUIDField): if isinstance(user.pk, six.string_types): return user.pk return user.pk.hex ret = user.pk ...
`allauth` needs tokens for OAuth based providers. So let's setup some dummy tokens def setup_dummy_social_apps(sender, **kwargs): """ `allauth` needs tokens for OAuth based providers. So let's setup some dummy tokens """ from allauth.socialaccount.providers import registry from allauth.soci...
Return value dumped to string. def value_from_object(self, obj): """Return value dumped to string.""" val = super(JSONField, self).value_from_object(obj) return self.get_prep_value(val)
See e-mail verification method def EMAIL_VERIFICATION(self): """ See e-mail verification method """ ret = self._setting("EMAIL_VERIFICATION", self.EmailVerificationMethod.OPTIONAL) # Deal with legacy (boolean based) setting if ret is True: ...
Minimum password Length def PASSWORD_MIN_LENGTH(self): """ Minimum password Length """ from django.conf import settings ret = None if not settings.AUTH_PASSWORD_VALIDATORS: ret = self._setting("PASSWORD_MIN_LENGTH", 6) return ret
Small helper function to call a function (map_function) on a list of data chunks (chunk_list) and convert the results into a flattened list. This function is used to send chunks of data with a size larger than 1 to the workers in parallel and process these on the worker. :param chunk_list: A l...
This generator chunks a list of data into slices of length chunk_size. If the chunk_size is not a divider of the data length, the last slice will be shorter than chunk_size. :param data: The data to chunk. :type data: list :param chunk_size: Each chunks size. The last chunk may be small...
Calculates the best chunk size for a list of length data_length. The current implemented formula is more or less an empirical result for multiprocessing case on one machine. :param data_length: A length which defines how many calculations there need to be. :type data_length: int ...
This method contains the core functionality of the DistributorBaseClass class. It maps the map_function to each element of the data and reduces the results to return a flattened list. How the jobs are calculated, is determined by the classes :func:`tsfresh.utilities.distribution.Distr...
Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of chunks - and should be processed by one worker. ...
Calculates the features in a parallel fashion by distributing the map command to the dask workers on a local machine :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of ch...
Uses the number of dask workers in the cluster (during execution time, meaning when you start the extraction) to find the optimal chunk_size. :param data_length: A length which defines how many calculations there need to be. :type data_length: int def calculate_best_chunk_size(self, data_lengt...
Calculates the features in a parallel fashion by distributing the map command to a thread pool :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of chunks - and should be processed...
Collects the result from the workers and closes the thread pool. def close(self): """ Collects the result from the workers and closes the thread pool. """ self.pool.close() self.pool.terminate() self.pool.join()
Creates a mapping from kind names to fc_parameters objects (which are itself mappings from feature calculators to settings) to extract only the features contained in the columns. To do so, for every feature name in columns this method 1. split the column name into col, feature, params part 2. decid...
Roll 1D array elements. Improves the performance of numpy.roll() by reducing the overhead introduced from the flexibility of the numpy.roll() method such as the support for rolling over multiple dimensions. Elements that roll beyond the last position are re-introduced at the beginning. Similarly, element...
This method calculates the length of all sub-sequences where the array x is either True or 1. Examples -------- >>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1] >>> _get_length_sequences_where(x) >>> [1, 3, 1, 2] >>> x = [0,True,0,0,True,True,True,0,0,True,0,True,True] >>> _get_length_sequences_where(x...
Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) As described by Friedrich et al. (2000): Physics Letters A 271, p. 217-222 *Extracting model equations from experimental ...
Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len :param x: the time series to calculate the aggregation of :type x: numpy.ndarray :param f_agg: The name of the aggregation function that should be an...
This method returns a decorator that sets the property key of the function to value def set_property(key, value): """ This method returns a decorator that sets the property key of the function to value """ def decorate_func(func): setattr(func, key, value) if func.__doc__ and key == "fc...
Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x being larger than 1 :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool def variance_larger_than_standard_...
Ratio of values that are more than r*std(x) (so r sigma) away from the mean of x. :param x: the time series to calculate the feature of :type x: iterable :return: the value of this feature :return type: float def ratio_beyond_r_sigma(x, r): """ Ratio of values that are more than r*std(x) (so r...
Boolean variable denoting if the standard dev of x is higher than 'r' times the range = difference between max and min of x. Hence it checks if .. math:: std(x) > r * (max(X)-min(X)) According to a rule of the thumb, the standard deviation should be a forth of the range of the values. :p...
Boolean variable denoting if the distribution of x *looks symmetric*. This is the case if .. math:: | mean(X)-median(X)| < r * (max(X)-min(X)) :param x: the time series to calculate the feature of :type x: numpy.ndarray :param r: the percentage of the range to compare with :type r: float ...
Checks if the maximum value of x is observed more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool def has_duplicate_max(x): """ Checks if the maximum value of x is observed more than once :param x...
Checks if the minimal value of x is observed more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool def has_duplicate_min(x): """ Checks if the minimal value of x is observed more than once :param x...
Checks if any value in x occurs more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool def has_duplicate(x): """ Checks if any value in x occurs more than once :param x: the time series to calculate...
r""" Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as .. math:: R(l) = \frac{1}{(n-l)\sigma^{2}} \sum_{t=1}^{n-l}(X_{t}-\mu )(X_...
Calculates the value of the partial autocorrelation function at the given lag. The lag `k` partial autocorrelation of a time series :math:`\\lbrace x_t, t = 1 \\ldots T \\rbrace` equals the partial correlation of :math:`x_t` and :math:`x_{t-k}`, adjusted for the intermediate variables :math:`\\lbrace x_{t-1...
The Augmented Dickey-Fuller test is a hypothesis test which checks whether a unit root is present in a time series sample. This feature calculator returns the value of the respective test statistic. See the statsmodels implementation for references and more details. :param x: the time series to calculate ...
Returns the absolute energy of the time series which is the sum over the squared values .. math:: E = \\sum_{i=1,\ldots, n} x_i^2 :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def abs_energy(x): """...
This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks, valleys etc.). It calculates the value of .. math:: \\sqrt{ \\sum_{i=0}^{n-2lag} ( x_{i} - x_{i+1})^2 } .. rubric:: References | [1] Batista, Gustavo EAPA, et al (2014). ...
Returns the mean value of a central approximation of the second derivative .. math:: \\frac{1}{n} \\sum_{i=1,\ldots, n-1} \\frac{1}{2} (x_{i+2} - 2 \\cdot x_{i+1} + x_i) :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :retur...
Returns the sample skewness of x (calculated with the adjusted Fisher-Pearson standardized moment coefficient G1). :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def skewness(x): """ Returns the sample ske...
Returns the kurtosis of x (calculated with the adjusted Fisher-Pearson standardized moment coefficient G2). :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def kurtosis(x): """ Returns the kurtosis of x (ca...
Returns the length of the longest consecutive subsequence in x that is smaller than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def longest_strike_below_mean(x): """ Returns the length of the ...
Returns the number of values in x that are higher than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def count_above_mean(x): """ Returns the number of values in x that are higher than the mean ...
Returns the number of values in x that are lower than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def count_below_mean(x): """ Returns the number of values in x that are lower than the mean of...
Returns the relative last location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def last_location_of_maximum(x): """ R...
Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def first_location_of_maximum(x): """ Returns ...
Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def last_location_of_minimum(x): """ Returns th...
Returns the first location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def first_location_of_minimum(x): """ Returns ...
Returns the percentage of unique values, that are present in the time series more than once. len(different values occurring more than once) / len(different values) This means the percentage is normalized to the number of unique values, in contrast to the percentage_of_reoccurring_values_to_all_val...
Returns the ratio of unique values, that are present in the time series more than once. # of data points occurring more than once / # of all data points This means the ratio is normalized to the number of data points in the time series, in contrast to the percentage_of_reoccurring_datapoints_to_al...
Returns the sum of all values, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def sum_of_reoccurring_values(x): """ Returns the sum of all values, that a...
Returns the sum of all data points, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float def sum_of_reoccurring_data_points(x): """ Returns the sum of all data...
Returns a factor which is 1 if all values in the time series occur only once, and below one if this is not the case. In principle, it just returns # unique values / # values :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature ...
Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast fourier transformation algorithm .. math:: A_k = \\sum_{m=0}^{n-1} a_m \\exp \\left \\{ -2 \\pi i \\frac{m k}{n} \\right \\}, \\qquad k = 0, \\ldots , n-1. The resulting coefficien...
Returns the spectral centroid (mean), variance, skew, and kurtosis of the absolute fourier transform spectrum. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param param: contains dictionaries {"aggtype": s} where s str and in ["centroid", "variance", "skew", "kurtosi...
Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined as a subsequence of x where a value occurs, which is bigger than its n neighbours to the left and to the right. Hence in the sequence >>> x = [3, 0, 0, 4, 0, 0, 13] 4 is a peak of support 1 and 2...
Those apply features calculate the relative index i where q% of the mass of the time series x lie left of i. For example for q = 50% this feature calculator will return the mass center of the time series :param x: the time series to calculate the feature of :type x: numpy.ndarray :param param: contains...
This feature calculator searches for different peaks in x. To do so, x is smoothed by a ricker wavelet and for widths ranging from 1 to n. This feature calculator returns the number of peaks that occur at enough width scales and with sufficiently high Signal-to-Noise-Ratio (SNR) :param x: the time series t...
Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model. The parameters control which of the characteristics are ...
Calculates a Continuous wavelet transform for the Ricker wavelet, also known as the "Mexican hat wavelet" which is defined by .. math:: \\frac{2}{\\sqrt{3a} \\pi^{\\frac{1}{4}}} (1 - \\frac{x^2}{a^2}) exp(-\\frac{x^2}{2a^2}) where :math:`a` is the width parameter of the wavelet function. This...
This feature calculator estimates the cross power spectral density of the time series x at different frequencies. To do so, the time series is first shifted from the time domain to the frequency domain. The feature calculators returns the power spectrum of the different frequencies. :param x: the time ser...
This feature calculator fits the unconditional maximum likelihood of an autoregressive AR(k) process. The k parameter is the maximum lag of the process .. math:: X_{t}=\\varphi_0 +\\sum _{{i=1}}^{k}\\varphi_{i}X_{{t-i}}+\\varepsilon_{t} For the configurations from param which should contain t...
First fixes a corridor given by the quantiles ql and qh of the distribution of x. Then calculates the average, absolute value of consecutive changes of the series x inside this corridor. Think about selecting a corridor on the y-Axis and only calculating the mean of the absolute change of the time series i...
This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} - x_{i + lag} \cdot x_{i}^2 which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) - L(X) \cdot X^2] where :math:`\\mathbb{E}` is the mean and :math:`L` is the...
This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i} which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X] where :math:`\\mathbb{E}` is the mean and :math:`L` is the lag operator. It was prop...
First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples in bin :math:`k`. :param x: the time series to calculate the fe...
Calculate and return sample entropy of x. .. rubric:: References | [1] http://en.wikipedia.org/wiki/Sample_Entropy | [2] https://www.ncbi.nlm.nih.gov/pubmed/10843903?dopt=Abstract :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this featur...
Calculates the autocorrelation of the specified lag, according to the formula [1] .. math:: \\frac{1}{(n-l)\sigma^{2}} \\sum_{t=1}^{n-l}(X_{t}-\\mu )(X_{t+l}-\\mu) where :math:`n` is the length of the time series :math:`X_i`, :math:`\sigma^2` its variance and :math:`\mu` its mean. `l` denotes the...
Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param q: the quantile to calculate :type q: float :return: the value of this feature :return type: float def quanti...
Calculates the number of crossings of x on m. A crossing is defined as two sequential values where the first value is lower than m and the next is greater, or vice-versa. If you set m to zero, you will get the number of zero crossings. :param x: the time series to calculate the feature of :type x: nump...
Count occurrences of `value` in time series x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param value: the value to be counted :type value: int or float :return: the count :rtype: int def value_count(x, value): """ Count occurrences of `value` in time...
Count observed values within the interval [min, max). :param x: the time series to calculate the feature of :type x: numpy.ndarray :param min: the inclusive lower bound of the range :type min: int or float :param max: the exclusive upper bound of the range :type max: int or float :return: t...
Implements a vectorized Approximate entropy algorithm. https://en.wikipedia.org/wiki/Approximate_entropy For short time-series this method is highly dependent on the parameters, but should be stable for N > 2000, see: Yentes et al. (2012) - *The Appropriate Use of Approximate Entropy ...
Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) as described by [1]. For short time-series this method is highly dependent on the parameters. .. rubric:: References | [1...
Largest fixed point of dynamics :math:argmax_x {h(x)=0}` estimated from polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot(x)(t) = h(x(t)) + R \mathcal(N)(0,1) as described by Friedrich et al. (2000): Physics Letters A 271, p. 21...
Calculates a linear least-squares regression for values of the time series that were aggregated over chunks versus the sequence from 0 up to the number of chunks minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model. The parameters attr contro...
Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole series. Takes as input parameters the number num_segments of segments to divide the series into and segment_focus which is the segment number (starting at zero) to return a feature on. ...
Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature uses the index of the time series to fit the model, which must be of a datetime dtype. The parameters control which of the characteristics are ret...
Extract the information, which of the features are relevent using the given target. For more information, please see the :func:`~tsfresh.festure_selection.festure_selector.check_fs_sig_bh` function. All columns in the input data sample are treated as feature. The index of all rows in X must be ...
Delete all features, which were not relevant in the fit phase. :param X: data sample with all features, which will be reduced to only those that are relevant :type X: pandas.DataSeries or numpy.array :return: same data sample as X, but with only the relevant features :rtype: pandas.Dat...