def f_value_wilks_lambda(ER, EF, dfnum, dfden, a, b):

if isinstance(ER, (int, float)):<EOL><INDENT>ER = array([[ER]])<EOL><DEDENT>if isinstance(EF, (int, float)):<EOL><INDENT>EF = array([[EF]])<EOL><DEDENT>lmbda = linalg.det(EF) / linalg.det(ER)<EOL>if (a-<NUM_LIT:1>)**<NUM_LIT:2> + (b-<NUM_LIT:1>)**<NUM_LIT:2> == <NUM_LIT:5>:<EOL><INDENT>q = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>q = np.sqrt(((a-<NUM_LIT:1>)**<NUM_LIT:2>*(b-<NUM_LIT:1>)**<NUM_LIT:2> - <NUM_LIT:2>) / ((a-<NUM_LIT:1>)**<NUM_LIT:2> + (b-<NUM_LIT:1>)**<NUM_LIT:2> - <NUM_LIT:5>))<EOL><DEDENT>n_um = (<NUM_LIT:1> - lmbda**(<NUM_LIT:1.0>/q))*(a-<NUM_LIT:1>)*(b-<NUM_LIT:1>)<EOL>d_en = lmbda**(<NUM_LIT:1.0>/q) / (n_um*q - <NUM_LIT:0.5>*(a-<NUM_LIT:1>)*(b-<NUM_LIT:1>) + <NUM_LIT:1>)<EOL>return n_um / d_en<EOL>

Calculation of Wilks lambda F-statistic for multivarite data, per
    Maxwell & Delaney p.657.


return ((ER-EF)/float(dfR-dfF) / (EF/float(dfF)))<EOL>

Returns an F-statistic for a restricted vs. unrestricted model.

Parameters
----------
ER : float
     `ER` is the sum of squared residuals for the restricted model
      or null hypothesis

EF : float
     `EF` is the sum of squared residuals for the unrestricted model
      or alternate hypothesis

dfR : int
      `dfR` is the degrees of freedom in the restricted model

dfF : int
      `dfF` is the degrees of freedom in the unrestricted model

Returns
-------
F-statistic : float


def f_value_multivariate(ER, EF, dfnum, dfden):

if isinstance(ER, (int, float)):<EOL><INDENT>ER = array([[ER]])<EOL><DEDENT>if isinstance(EF, (int, float)):<EOL><INDENT>EF = array([[EF]])<EOL><DEDENT>n_um = (linalg.det(ER) - linalg.det(EF)) / float(dfnum)<EOL>d_en = linalg.det(EF) / float(dfden)<EOL>return n_um / d_en<EOL>

Returns a multivariate F-statistic.

Parameters
----------
ER : ndarray
    Error associated with the null hypothesis (the Restricted model).
    From a multivariate F calculation.
EF : ndarray
    Error associated with the alternate hypothesis (the Full model)
    From a multivariate F calculation.
dfnum : int
    Degrees of freedom the Restricted model.
dfden : int
    Degrees of freedom associated with the Restricted model.

Returns
-------
fstat : float
    The computed F-statistic.


a, axis = _chk_asarray(a, axis)<EOL>return np.sum(a*a, axis)<EOL>

Squares each element of the input array, and returns the sum(s) of that.

Parameters
----------
a : array_like
    Input array.
axis : int or None, optional
    The axis along which to calculate. If None, use whole array.
    Default is 0, i.e. along the first axis.

Returns
-------
ss : ndarray
    The sum along the given axis for (a**2).

See also
--------
square_of_sums : The square(s) of the sum(s) (the opposite of `ss`).

Examples
--------
>>> from scipy import stats
>>> a = np.array([1., 2., 5.])
>>> stats.ss(a)
30.0

And calculating along an axis:

>>> b = np.array([[1., 2., 5.], [2., 5., 6.]])
>>> stats.ss(b, axis=1)
array([ 30., 65.])


a, axis = _chk_asarray(a, axis)<EOL>s = np.sum(a,axis)<EOL>if not np.isscalar(s):<EOL><INDENT>return s.astype(float)*s<EOL><DEDENT>else:<EOL><INDENT>return float(s)*s<EOL><DEDENT>

Sums elements of the input array, and returns the square(s) of that sum.

Parameters
----------
a : array_like
    Input array.
axis : int or None, optional
    If axis is None, ravel `a` first. If `axis` is an integer, this will
    be the axis over which to operate. Defaults to 0.

Returns
-------
square_of_sums : float or ndarray
    The square of the sum over `axis`.

See also
--------
ss : The sum of squares (the opposite of `square_of_sums`).

Examples
--------
>>> from scipy import stats
>>> a = np.arange(20).reshape(5,4)
>>> stats.square_of_sums(a)
array([ 1600.,  2025.,  2500.,  3025.])
>>> stats.square_of_sums(a, axis=None)
36100.0


<EOL>it = np.argsort(a)<EOL>as_ = a[it]<EOL>return as_, it<EOL>

Sort an array and provide the argsort.

Parameters
----------
a : array_like
    Input array.

Returns
-------
fastsort : ndarray of type int
    sorted indices into the original array


if len(args) == <NUM_LIT:1> and not isinstance(args[<NUM_LIT:0>], ndarray):<EOL><INDENT>output = ma.asarray(args[<NUM_LIT:0>])<EOL>if output.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>n = len(args)<EOL>m = max([len(k) for k in args])<EOL>output = ma.array(np.empty((n,m), dtype=float), mask=True)<EOL>for (k,v) in enumerate(args):<EOL><INDENT>output[k,:len(v)] = v<EOL><DEDENT><DEDENT>output[np.logical_not(np.isfinite(output._data))] = masked<EOL>return output<EOL>

Constructs a 2D array from a group of sequences.

Sequences are filled with missing values to match the length of the longest
sequence.

Parameters
----------
args : sequences
    Group of sequences.

Returns
-------
argstoarray : MaskedArray
    A ( `m` x `n` ) masked array, where `m` is the number of arguments and
    `n` the length of the longest argument.

Notes
-----
`numpy.ma.row_stack` has identical behavior, but is called with a sequence
of sequences.


marr = ma.compressed(arr)<EOL>if not marr.size:<EOL><INDENT>return (np.array(<NUM_LIT:0>), np.array(<NUM_LIT:0>))<EOL><DEDENT>(v1, v2, n) = futil.dfreps(ma.array(ma.compressed(arr), copy=True))<EOL>return (v1[:n], v2[:n])<EOL>

Find repeats in arr and return a tuple (repeats, repeat_count).
    Masked values are discarded.

    Parameters
    ----------
    arr : sequence
        Input array. The array is flattened if it is not 1D.

    Returns
    -------
    repeats : ndarray
        Array of repeated values.
    counts : ndarray
        Array of counts.


nmasked = ma.getmask(x).sum()<EOL>data = ma.compressed(x).copy()<EOL>(ties, counts) = find_repeats(data)<EOL>nties = {}<EOL>if len(ties):<EOL><INDENT>nties = dict(zip(np.unique(counts), itertools.repeat(<NUM_LIT:1>)))<EOL>nties.update(dict(zip(*find_repeats(counts))))<EOL><DEDENT>if nmasked and use_missing:<EOL><INDENT>try:<EOL><INDENT>nties[nmasked] += <NUM_LIT:1><EOL><DEDENT>except KeyError:<EOL><INDENT>nties[nmasked] = <NUM_LIT:1><EOL><DEDENT><DEDENT>return nties<EOL>

Counts the number of tied values.

Parameters
----------
x : sequence
    Sequence of data on which to counts the ties
use_missing : boolean
    Whether to consider missing values as tied.

Returns
-------
count_tied_groups : dict
    Returns a dictionary (nb of ties: nb of groups).

Examples
--------
>>> from scipy.stats import mstats
>>> z = [0, 0, 0, 2, 2, 2, 3, 3, 4, 5, 6]
>>> mstats.count_tied_groups(z)
{2: 1, 3: 2}

In the above example, the ties were 0 (3x), 2 (3x) and 3 (2x).

>>> z = np.ma.array([0, 0, 1, 2, 2, 2, 3, 3, 4, 5, 6])
>>> mstats.count_tied_groups(z)
{2: 2, 3: 1}
>>> z[[1,-1]] = np.ma.masked
>>> mstats.count_tied_groups(z, use_missing=True)
{2: 2, 3: 1}


def rankdata(data, axis=None, use_missing=False):

def _rank1d(data, use_missing=False):<EOL><INDENT>n = data.count()<EOL>rk = np.empty(data.size, dtype=float)<EOL>idx = data.argsort()<EOL>rk[idx[:n]] = np.arange(<NUM_LIT:1>,n+<NUM_LIT:1>)<EOL>if use_missing:<EOL><INDENT>rk[idx[n:]] = (n+<NUM_LIT:1>)/<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>rk[idx[n:]] = <NUM_LIT:0><EOL><DEDENT>repeats = find_repeats(data.copy())<EOL>for r in repeats[<NUM_LIT:0>]:<EOL><INDENT>condition = (data == r).filled(False)<EOL>rk[condition] = rk[condition].mean()<EOL><DEDENT>return rk<EOL><DEDENT>data = ma.array(data, copy=False)<EOL>if axis is None:<EOL><INDENT>if data.ndim > <NUM_LIT:1>:<EOL><INDENT>return _rank1d(data.ravel(), use_missing).reshape(data.shape)<EOL><DEDENT>else:<EOL><INDENT>return _rank1d(data, use_missing)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return ma.apply_along_axis(_rank1d,axis,data,use_missing).view(ndarray)<EOL><DEDENT>

Returns the rank (also known as order statistics) of each data point
    along the given axis.

    If some values are tied, their rank is averaged.
    If some values are masked, their rank is set to 0 if use_missing is False,
    or set to the average rank of the unmasked values if use_missing is True.

    Parameters
    ----------
    data : sequence
        Input data. The data is transformed to a masked array
    axis : {None,int}, optional
        Axis along which to perform the ranking.
        If None, the array is first flattened. An exception is raised if
        the axis is specified for arrays with a dimension larger than 2
    use_missing : {boolean}, optional
        Whether the masked values have a rank of 0 (False) or equal to the
        average rank of the unmasked values (True).


return ma.filled(np.sign(x), <NUM_LIT:0>)<EOL>

Returns the sign of x, or 0 if x is masked.


(x, y, n) = _chk_size(x, y)<EOL>(x, y) = (x.ravel(), y.ravel())<EOL>m = ma.mask_or(ma.getmask(x), ma.getmask(y))<EOL>n -= m.sum()<EOL>df = n-<NUM_LIT:2><EOL>if df < <NUM_LIT:0>:<EOL><INDENT>return (masked, masked)<EOL><DEDENT>(mx, my) = (x.mean(), y.mean())<EOL>(xm, ym) = (x-mx, y-my)<EOL>r_num = ma.add.reduce(xm*ym)<EOL>r_den = ma.sqrt(ma.dot(xm,xm) * ma.dot(ym,ym))<EOL>r = r_num / r_den<EOL>r = min(r, <NUM_LIT:1.0>)<EOL>r = max(r, -<NUM_LIT:1.0>)<EOL>df = n - <NUM_LIT:2><EOL>if r is masked or abs(r) == <NUM_LIT:1.0>:<EOL><INDENT>prob = <NUM_LIT:0.><EOL><DEDENT>else:<EOL><INDENT>t_squared = (df / ((<NUM_LIT:1.0> - r) * (<NUM_LIT:1.0> + r))) * r * r<EOL>prob = betai(<NUM_LIT:0.5>*df, <NUM_LIT:0.5>, df/(df + t_squared))<EOL><DEDENT>return r, prob<EOL>

Calculates a Pearson correlation coefficient and the p-value for testing
non-correlation.

The Pearson correlation coefficient measures the linear relationship
between two datasets. Strictly speaking, Pearson's correlation requires
that each dataset be normally distributed. Like other correlation
coefficients, this one varies between -1 and +1 with 0 implying no
correlation. Correlations of -1 or +1 imply an exact linear
relationship. Positive correlations imply that as `x` increases, so does
`y`. Negative correlations imply that as `x` increases, `y` decreases.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Pearson correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.

Parameters
----------
x : 1-D array_like
    Input
y : 1-D array_like
    Input

Returns
-------
pearsonr : float
    Pearson's correlation coefficient, 2-tailed p-value.

References
----------
http://www.statsoft.com/textbook/glosp.html#Pearson%20Correlation


(x, y, n) = _chk_size(x, y)<EOL>(x, y) = (x.ravel(), y.ravel())<EOL>m = ma.mask_or(ma.getmask(x), ma.getmask(y))<EOL>n -= m.sum()<EOL>if m is not nomask:<EOL><INDENT>x = ma.array(x, mask=m, copy=True)<EOL>y = ma.array(y, mask=m, copy=True)<EOL><DEDENT>df = n-<NUM_LIT:2><EOL>if df < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>rankx = rankdata(x)<EOL>ranky = rankdata(y)<EOL>dsq = np.add.reduce((rankx-ranky)**<NUM_LIT:2>)<EOL>if use_ties:<EOL><INDENT>xties = count_tied_groups(x)<EOL>yties = count_tied_groups(y)<EOL>corr_x = np.sum(v*k*(k**<NUM_LIT:2>-<NUM_LIT:1>) for (k,v) in iteritems(xties))/<NUM_LIT><EOL>corr_y = np.sum(v*k*(k**<NUM_LIT:2>-<NUM_LIT:1>) for (k,v) in iteritems(yties))/<NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>corr_x = corr_y = <NUM_LIT:0><EOL><DEDENT>denom = n*(n**<NUM_LIT:2> - <NUM_LIT:1>)/<NUM_LIT><EOL>if corr_x != <NUM_LIT:0> or corr_y != <NUM_LIT:0>:<EOL><INDENT>rho = denom - dsq - corr_x - corr_y<EOL>rho /= ma.sqrt((denom-<NUM_LIT:2>*corr_x)*(denom-<NUM_LIT:2>*corr_y))<EOL><DEDENT>else:<EOL><INDENT>rho = <NUM_LIT:1.> - dsq/denom<EOL><DEDENT>t = ma.sqrt(ma.divide(df,(rho+<NUM_LIT:1.0>)*(<NUM_LIT:1.0>-rho))) * rho<EOL>if t is masked:<EOL><INDENT>prob = <NUM_LIT:0.><EOL><DEDENT>else:<EOL><INDENT>prob = betai(<NUM_LIT:0.5>*df,<NUM_LIT:0.5>,df/(df+t*t))<EOL><DEDENT>return rho, prob<EOL>

Calculates a Spearman rank-order correlation coefficient and the p-value
to test for non-correlation.

The Spearman correlation is a nonparametric measure of the linear
relationship between two datasets. Unlike the Pearson correlation, the
Spearman correlation does not assume that both datasets are normally
distributed. Like other correlation coefficients, this one varies
between -1 and +1 with 0 implying no correlation. Correlations of -1 or
+1 imply an exact linear relationship. Positive correlations imply that
as `x` increases, so does `y`. Negative correlations imply that as `x`
increases, `y` decreases.

Missing values are discarded pair-wise: if a value is missing in `x`, the
corresponding value in `y` is masked.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.

Parameters
----------
x : array_like
    The length of `x` must be > 2.
y : array_like
    The length of `y` must be > 2.
use_ties : bool, optional
    Whether the correction for ties should be computed.

Returns
-------
spearmanr : float
    Spearman correlation coefficient, 2-tailed p-value.

References
----------
[CRCProbStat2000] section 14.7


def kendalltau(x, y, use_ties=True, use_missing=False):

(x, y, n) = _chk_size(x, y)<EOL>(x, y) = (x.flatten(), y.flatten())<EOL>m = ma.mask_or(ma.getmask(x), ma.getmask(y))<EOL>if m is not nomask:<EOL><INDENT>x = ma.array(x, mask=m, copy=True)<EOL>y = ma.array(y, mask=m, copy=True)<EOL>n -= m.sum()<EOL><DEDENT>if n < <NUM_LIT:2>:<EOL><INDENT>return (np.nan, np.nan)<EOL><DEDENT>rx = ma.masked_equal(rankdata(x, use_missing=use_missing), <NUM_LIT:0>)<EOL>ry = ma.masked_equal(rankdata(y, use_missing=use_missing), <NUM_LIT:0>)<EOL>idx = rx.argsort()<EOL>(rx, ry) = (rx[idx], ry[idx])<EOL>C = np.sum([((ry[i+<NUM_LIT:1>:] > ry[i]) * (rx[i+<NUM_LIT:1>:] > rx[i])).filled(<NUM_LIT:0>).sum()<EOL>for i in range(len(ry)-<NUM_LIT:1>)], dtype=float)<EOL>D = np.sum([((ry[i+<NUM_LIT:1>:] < ry[i])*(rx[i+<NUM_LIT:1>:] > rx[i])).filled(<NUM_LIT:0>).sum()<EOL>for i in range(len(ry)-<NUM_LIT:1>)], dtype=float)<EOL>if use_ties:<EOL><INDENT>xties = count_tied_groups(x)<EOL>yties = count_tied_groups(y)<EOL>corr_x = np.sum([v*k*(k-<NUM_LIT:1>) for (k,v) in iteritems(xties)], dtype=float)<EOL>corr_y = np.sum([v*k*(k-<NUM_LIT:1>) for (k,v) in iteritems(yties)], dtype=float)<EOL>denom = ma.sqrt((n*(n-<NUM_LIT:1>)-corr_x)/<NUM_LIT> * (n*(n-<NUM_LIT:1>)-corr_y)/<NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>denom = n*(n-<NUM_LIT:1>)/<NUM_LIT><EOL><DEDENT>tau = (C-D) / denom<EOL>var_s = n*(n-<NUM_LIT:1>)*(<NUM_LIT:2>*n+<NUM_LIT:5>)<EOL>if use_ties:<EOL><INDENT>var_s -= np.sum(v*k*(k-<NUM_LIT:1>)*(<NUM_LIT:2>*k+<NUM_LIT:5>)*<NUM_LIT:1.> for (k,v) in iteritems(xties))<EOL>var_s -= np.sum(v*k*(k-<NUM_LIT:1>)*(<NUM_LIT:2>*k+<NUM_LIT:5>)*<NUM_LIT:1.> for (k,v) in iteritems(yties))<EOL>v1 = np.sum([v*k*(k-<NUM_LIT:1>) for (k, v) in iteritems(xties)], dtype=float) *np.sum([v*k*(k-<NUM_LIT:1>) for (k, v) in iteritems(yties)], dtype=float)<EOL>v1 /= <NUM_LIT>*n*(n-<NUM_LIT:1>)<EOL>if n > <NUM_LIT:2>:<EOL><INDENT>v2 = np.sum([v*k*(k-<NUM_LIT:1>)*(k-<NUM_LIT:2>) for (k,v) in iteritems(xties)],<EOL>dtype=float) *np.sum([v*k*(k-<NUM_LIT:1>)*(k-<NUM_LIT:2>) for (k,v) in iteritems(yties)],<EOL>dtype=float)<EOL>v2 /= <NUM_LIT>*n*(n-<NUM_LIT:1>)*(n-<NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>v2 = <NUM_LIT:0><EOL><DEDENT><DEDENT>else:<EOL><INDENT>v1 = v2 = <NUM_LIT:0><EOL><DEDENT>var_s /= <NUM_LIT><EOL>var_s += (v1 + v2)<EOL>z = (C-D)/np.sqrt(var_s)<EOL>prob = special.erfc(abs(z)/np.sqrt(<NUM_LIT:2>))<EOL>return (tau, prob)<EOL>

Computes Kendall's rank correlation tau on two variables *x* and *y*.

Parameters
----------
xdata : sequence
    First data list (for example, time).
ydata : sequence
    Second data list.
use_ties : {True, False}, optional
    Whether ties correction should be performed.
use_missing : {False, True}, optional
    Whether missing data should be allocated a rank of 0 (False) or the
    average rank (True)

Returns
-------
tau : float
    Kendall tau
prob : float
    Approximate 2-side p-value.


x = ma.array(x, subok=True, copy=False, ndmin=<NUM_LIT:2>)<EOL>(n,m) = x.shape<EOL>n_p = x.count(<NUM_LIT:0>)<EOL>S_szn = np.sum(msign(x[i:]-x[i]).sum(<NUM_LIT:0>) for i in range(n))<EOL>S_tot = S_szn.sum()<EOL>n_tot = x.count()<EOL>ties = count_tied_groups(x.compressed())<EOL>corr_ties = np.sum(v*k*(k-<NUM_LIT:1>) for (k,v) in iteritems(ties))<EOL>denom_tot = ma.sqrt(<NUM_LIT:1.>*n_tot*(n_tot-<NUM_LIT:1>)*(n_tot*(n_tot-<NUM_LIT:1>)-corr_ties))/<NUM_LIT><EOL>R = rankdata(x, axis=<NUM_LIT:0>, use_missing=True)<EOL>K = ma.empty((m,m), dtype=int)<EOL>covmat = ma.empty((m,m), dtype=float)<EOL>denom_szn = ma.empty(m, dtype=float)<EOL>for j in range(m):<EOL><INDENT>ties_j = count_tied_groups(x[:,j].compressed())<EOL>corr_j = np.sum(v*k*(k-<NUM_LIT:1>) for (k,v) in iteritems(ties_j))<EOL>cmb = n_p[j]*(n_p[j]-<NUM_LIT:1>)<EOL>for k in range(j,m,<NUM_LIT:1>):<EOL><INDENT>K[j,k] = np.sum(msign((x[i:,j]-x[i,j])*(x[i:,k]-x[i,k])).sum()<EOL>for i in range(n))<EOL>covmat[j,k] = (K[j,k] + <NUM_LIT:4>*(R[:,j]*R[:,k]).sum() -<EOL>n*(n_p[j]+<NUM_LIT:1>)*(n_p[k]+<NUM_LIT:1>))/<NUM_LIT><EOL>K[k,j] = K[j,k]<EOL>covmat[k,j] = covmat[j,k]<EOL><DEDENT>denom_szn[j] = ma.sqrt(cmb*(cmb-corr_j)) / <NUM_LIT><EOL><DEDENT>var_szn = covmat.diagonal()<EOL>z_szn = msign(S_szn) * (abs(S_szn)-<NUM_LIT:1>) / ma.sqrt(var_szn)<EOL>z_tot_ind = msign(S_tot) * (abs(S_tot)-<NUM_LIT:1>) / ma.sqrt(var_szn.sum())<EOL>z_tot_dep = msign(S_tot) * (abs(S_tot)-<NUM_LIT:1>) / ma.sqrt(covmat.sum())<EOL>prob_szn = special.erfc(abs(z_szn)/np.sqrt(<NUM_LIT:2>))<EOL>prob_tot_ind = special.erfc(abs(z_tot_ind)/np.sqrt(<NUM_LIT:2>))<EOL>prob_tot_dep = special.erfc(abs(z_tot_dep)/np.sqrt(<NUM_LIT:2>))<EOL>chi2_tot = (z_szn*z_szn).sum()<EOL>chi2_trd = m * z_szn.mean()**<NUM_LIT:2><EOL>output = {'<STR_LIT>': S_szn/denom_szn,<EOL>'<STR_LIT>': S_tot/denom_tot,<EOL>'<STR_LIT>': S_tot/denom_szn.sum(),<EOL>'<STR_LIT>': prob_szn,<EOL>'<STR_LIT>': prob_tot_ind,<EOL>'<STR_LIT>': prob_tot_dep,<EOL>'<STR_LIT>': chi2_tot,<EOL>'<STR_LIT>': chi2_trd,<EOL>}<EOL>return output<EOL>

Computes a multivariate Kendall's rank correlation tau, for seasonal data.

Parameters
----------
x : 2-D ndarray
    Array of seasonal data, with seasons in columns.


if len(args) == <NUM_LIT:1>:<EOL><INDENT>args = ma.array(args[<NUM_LIT:0>], copy=True)<EOL>if len(args) == <NUM_LIT:2>:<EOL><INDENT>x = args[<NUM_LIT:0>]<EOL>y = args[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>x = args[:, <NUM_LIT:0>]<EOL>y = args[:, <NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>x = ma.array(args[<NUM_LIT:0>]).flatten()<EOL>y = ma.array(args[<NUM_LIT:1>]).flatten()<EOL><DEDENT>m = ma.mask_or(ma.getmask(x), ma.getmask(y), shrink=False)<EOL>if m is not nomask:<EOL><INDENT>x = ma.array(x, mask=m)<EOL>y = ma.array(y, mask=m)<EOL>if np.any(~m):<EOL><INDENT>slope, intercept, r, prob, sterrest = stats.linregress(x.data[~m],<EOL>y.data[~m])<EOL><DEDENT>else:<EOL><INDENT>return None, None, None, None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>slope, intercept, r, prob, sterrest = stats.linregress(x.data, y.data)<EOL><DEDENT>return slope, intercept, r, prob, sterrest<EOL>

Linear regression calculation

Note that the non-masked version is used, and that this docstring is
replaced by the non-masked docstring + some info on missing data.


x = ma.asarray(x).compressed().view(ndarray)<EOL>y = ma.asarray(y).compressed().view(ndarray)<EOL>ranks = rankdata(np.concatenate([x,y]))<EOL>(nx, ny) = (len(x), len(y))<EOL>nt = nx + ny<EOL>U = ranks[:nx].sum() - nx*(nx+<NUM_LIT:1>)/<NUM_LIT><EOL>U = max(U, nx*ny - U)<EOL>u = nx*ny - U<EOL>mu = (nx*ny)/<NUM_LIT><EOL>sigsq = (nt**<NUM_LIT:3> - nt)/<NUM_LIT><EOL>ties = count_tied_groups(ranks)<EOL>sigsq -= np.sum(v*(k**<NUM_LIT:3>-k) for (k,v) in iteritems(ties))/<NUM_LIT><EOL>sigsq *= nx*ny/float(nt*(nt-<NUM_LIT:1>))<EOL>if use_continuity:<EOL><INDENT>z = (U - <NUM_LIT:1>/<NUM_LIT> - mu) / ma.sqrt(sigsq)<EOL><DEDENT>else:<EOL><INDENT>z = (U - mu) / ma.sqrt(sigsq)<EOL><DEDENT>prob = special.erfc(abs(z)/np.sqrt(<NUM_LIT:2>))<EOL>return (u, prob)<EOL>

Computes the Mann-Whitney statistic

Missing values in `x` and/or `y` are discarded.

Parameters
----------
x : sequence
    Input
y : sequence
    Input
use_continuity : {True, False}, optional
    Whether a continuity correction (1/2.) should be taken into account.

Returns
-------
u : float
    The Mann-Whitney statistics
prob : float
    Approximate p-value assuming a normal distribution.


def ks_twosamp(data1, data2, alternative="<STR_LIT>"):

(data1, data2) = (ma.asarray(data1), ma.asarray(data2))<EOL>(n1, n2) = (data1.count(), data2.count())<EOL>n = (n1*n2/float(n1+n2))<EOL>mix = ma.concatenate((data1.compressed(), data2.compressed()))<EOL>mixsort = mix.argsort(kind='<STR_LIT>')<EOL>csum = np.where(mixsort < n1, <NUM_LIT:1.>/n1, -<NUM_LIT:1.>/n2).cumsum()<EOL>if len(np.unique(mix)) < (n1+n2):<EOL><INDENT>csum = csum[np.r_[np.diff(mix[mixsort]).nonzero()[<NUM_LIT:0>],-<NUM_LIT:1>]]<EOL><DEDENT>alternative = str(alternative).lower()[<NUM_LIT:0>]<EOL>if alternative == '<STR_LIT:t>':<EOL><INDENT>d = ma.abs(csum).max()<EOL>prob = special.kolmogorov(np.sqrt(n)*d)<EOL><DEDENT>elif alternative == '<STR_LIT:l>':<EOL><INDENT>d = -csum.min()<EOL>prob = np.exp(-<NUM_LIT:2>*n*d**<NUM_LIT:2>)<EOL><DEDENT>elif alternative == '<STR_LIT:g>':<EOL><INDENT>d = csum.max()<EOL>prob = np.exp(-<NUM_LIT:2>*n*d**<NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return (d, prob)<EOL>

Computes the Kolmogorov-Smirnov test on two samples.

Missing values are discarded.

Parameters
----------
data1 : array_like
    First data set
data2 : array_like
    Second data set
alternative : {'two-sided', 'less', 'greater'}, optional
    Indicates the alternative hypothesis.  Default is 'two-sided'.

Returns
-------
d : float
    Value of the Kolmogorov Smirnov test
p : float
    Corresponding p-value.


(data1, data2) = [ma.asarray(d).compressed() for d in (data1,data2)]<EOL>return stats.ks_2samp(data1,data2)<EOL>

Computes the Kolmogorov-Smirnov statistic on 2 samples.

    Returns
    -------
    KS D-value, p-value


def threshold(a, threshmin=None, threshmax=None, newval=<NUM_LIT:0>):

a = ma.array(a, copy=True)<EOL>mask = np.zeros(a.shape, dtype=bool)<EOL>if threshmin is not None:<EOL><INDENT>mask |= (a < threshmin).filled(False)<EOL><DEDENT>if threshmax is not None:<EOL><INDENT>mask |= (a > threshmax).filled(False)<EOL><DEDENT>a[mask] = newval<EOL>return a<EOL>

Clip array to a given value.

Similar to numpy.clip(), except that values less than `threshmin` or
greater than `threshmax` are replaced by `newval`, instead of by
`threshmin` and `threshmax` respectively.

Parameters
----------
a : ndarray
    Input data
threshmin : {None, float}, optional
    Lower threshold. If None, set to the minimum value.
threshmax : {None, float}, optional
    Upper threshold. If None, set to the maximum value.
newval : {0, float}, optional
    Value outside the thresholds.

Returns
-------
threshold : ndarray
    Returns `a`, with values less then `threshmin` and values greater
    `threshmax` replaced with `newval`.


def trima(a, limits=None, inclusive=(True,True)):

a = ma.asarray(a)<EOL>a.unshare_mask()<EOL>if (limits is None) or (limits == (None, None)):<EOL><INDENT>return a<EOL><DEDENT>(lower_lim, upper_lim) = limits<EOL>(lower_in, upper_in) = inclusive<EOL>condition = False<EOL>if lower_lim is not None:<EOL><INDENT>if lower_in:<EOL><INDENT>condition |= (a < lower_lim)<EOL><DEDENT>else:<EOL><INDENT>condition |= (a <= lower_lim)<EOL><DEDENT><DEDENT>if upper_lim is not None:<EOL><INDENT>if upper_in:<EOL><INDENT>condition |= (a > upper_lim)<EOL><DEDENT>else:<EOL><INDENT>condition |= (a >= upper_lim)<EOL><DEDENT><DEDENT>a[condition.filled(True)] = masked<EOL>return a<EOL>

Trims an array by masking the data outside some given limits.

Returns a masked version of the input array.

Parameters
----------
a : array_like
    Input array.
limits : {None, tuple}, optional
    Tuple of (lower limit, upper limit) in absolute values.
    Values of the input array lower (greater) than the lower (upper) limit
    will be masked.  A limit is None indicates an open interval.
inclusive : (bool, bool) tuple, optional
    Tuple of (lower flag, upper flag), indicating whether values exactly
    equal to the lower (upper) limit are allowed.


def trimr(a, limits=None, inclusive=(True, True), axis=None):

def _trimr1D(a, low_limit, up_limit, low_inclusive, up_inclusive):<EOL><INDENT>n = a.count()<EOL>idx = a.argsort()<EOL>if low_limit:<EOL><INDENT>if low_inclusive:<EOL><INDENT>lowidx = int(low_limit*n)<EOL><DEDENT>else:<EOL><INDENT>lowidx = np.round(low_limit*n)<EOL><DEDENT>a[idx[:lowidx]] = masked<EOL><DEDENT>if up_limit is not None:<EOL><INDENT>if up_inclusive:<EOL><INDENT>upidx = n - int(n*up_limit)<EOL><DEDENT>else:<EOL><INDENT>upidx = n - np.round(n*up_limit)<EOL><DEDENT>a[idx[upidx:]] = masked<EOL><DEDENT>return a<EOL><DEDENT>a = ma.asarray(a)<EOL>a.unshare_mask()<EOL>if limits is None:<EOL><INDENT>return a<EOL><DEDENT>(lolim, uplim) = limits<EOL>errmsg = "<STR_LIT>"<EOL>if lolim is not None:<EOL><INDENT>if lolim > <NUM_LIT:1.> or lolim < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(errmsg % '<STR_LIT>' + "<STR_LIT>" % lolim)<EOL><DEDENT><DEDENT>if uplim is not None:<EOL><INDENT>if uplim > <NUM_LIT:1.> or uplim < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(errmsg % '<STR_LIT:end>' + "<STR_LIT>" % uplim)<EOL><DEDENT><DEDENT>(loinc, upinc) = inclusive<EOL>if axis is None:<EOL><INDENT>shp = a.shape<EOL>return _trimr1D(a.ravel(),lolim,uplim,loinc,upinc).reshape(shp)<EOL><DEDENT>else:<EOL><INDENT>return ma.apply_along_axis(_trimr1D, axis, a, lolim,uplim,loinc,upinc)<EOL><DEDENT>

Trims an array by masking some proportion of the data on each end.
Returns a masked version of the input array.

Parameters
----------
a : sequence
    Input array.
limits : {None, tuple}, optional
    Tuple of the percentages to cut on each side of the array, with respect
    to the number of unmasked data, as floats between 0. and 1.
    Noting n the number of unmasked data before trimming, the
    (n*limits[0])th smallest data and the (n*limits[1])th largest data are
    masked, and the total number of unmasked data after trimming is
    n*(1.-sum(limits)).  The value of one limit can be set to None to
    indicate an open interval.
inclusive : {(True,True) tuple}, optional
    Tuple of flags indicating whether the number of data being masked on
    the left (right) end should be truncated (True) or rounded (False) to
    integers.
axis : {None,int}, optional
    Axis along which to trim. If None, the whole array is trimmed, but its
    shape is maintained.


def trim(a, limits=None, inclusive=(True,True), relative=False, axis=None):

if relative:<EOL><INDENT>return trimr(a, limits=limits, inclusive=inclusive, axis=axis)<EOL><DEDENT>else:<EOL><INDENT>return trima(a, limits=limits, inclusive=inclusive)<EOL><DEDENT>

Trims an array by masking the data outside some given limits.

Returns a masked version of the input array.

%s

Examples
--------
>>> z = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10]
>>> trim(z,(3,8))
[--,--, 3, 4, 5, 6, 7, 8,--,--]
>>> trim(z,(0.1,0.2),relative=True)
[--, 2, 3, 4, 5, 6, 7, 8,--,--]


def trimboth(data, proportiontocut=<NUM_LIT>, inclusive=(True,True), axis=None):

return trimr(data, limits=(proportiontocut,proportiontocut),<EOL>inclusive=inclusive, axis=axis)<EOL>

Trims the smallest and largest data values.

Trims the `data` by masking the ``int(proportiontocut * n)`` smallest and
``int(proportiontocut * n)`` largest values of data along the given axis,
where n is the number of unmasked values before trimming.

Parameters
----------
data : ndarray
    Data to trim.
proportiontocut : float, optional
    Percentage of trimming (as a float between 0 and 1).
    If n is the number of unmasked values before trimming, the number of
    values after trimming is ``(1 - 2*proportiontocut) * n``.
    Default is 0.2.
inclusive : {(bool, bool) tuple}, optional
    Tuple indicating whether the number of data being masked on each side
    should be rounded (True) or truncated (False).
axis : int, optional
    Axis along which to perform the trimming.
    If None, the input array is first flattened.


def trimtail(data, proportiontocut=<NUM_LIT>, tail='<STR_LIT:left>', inclusive=(True,True),<EOL>axis=None):

tail = str(tail).lower()[<NUM_LIT:0>]<EOL>if tail == '<STR_LIT:l>':<EOL><INDENT>limits = (proportiontocut,None)<EOL><DEDENT>elif tail == '<STR_LIT:r>':<EOL><INDENT>limits = (None, proportiontocut)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return trimr(data, limits=limits, axis=axis, inclusive=inclusive)<EOL>

Trims the data by masking values from one tail.

Parameters
----------
data : array_like
    Data to trim.
proportiontocut : float, optional
    Percentage of trimming. If n is the number of unmasked values
    before trimming, the number of values after trimming is
    ``(1 - proportiontocut) * n``.  Default is 0.2.
tail : {'left','right'}, optional
    If 'left' the `proportiontocut` lowest values will be masked.
    If 'right' the `proportiontocut` highest values will be masked.
    Default is 'left'.
inclusive : {(bool, bool) tuple}, optional
    Tuple indicating whether the number of data being masked on each side
    should be rounded (True) or truncated (False).  Default is
    (True, True).
axis : int, optional
    Axis along which to perform the trimming.
    If None, the input array is first flattened.  Default is None.

Returns
-------
trimtail : ndarray
    Returned array of same shape as `data` with masked tail values.


def trimmed_stde(a, limits=(<NUM_LIT:0.1>,<NUM_LIT:0.1>), inclusive=(<NUM_LIT:1>,<NUM_LIT:1>), axis=None):

def _trimmed_stde_1D(a, low_limit, up_limit, low_inclusive, up_inclusive):<EOL><INDENT>"<STR_LIT>"<EOL>n = a.count()<EOL>idx = a.argsort()<EOL>if low_limit:<EOL><INDENT>if low_inclusive:<EOL><INDENT>lowidx = int(low_limit*n)<EOL><DEDENT>else:<EOL><INDENT>lowidx = np.round(low_limit*n)<EOL><DEDENT>a[idx[:lowidx]] = masked<EOL><DEDENT>if up_limit is not None:<EOL><INDENT>if up_inclusive:<EOL><INDENT>upidx = n - int(n*up_limit)<EOL><DEDENT>else:<EOL><INDENT>upidx = n - np.round(n*up_limit)<EOL><DEDENT>a[idx[upidx:]] = masked<EOL><DEDENT>a[idx[:lowidx]] = a[idx[lowidx]]<EOL>a[idx[upidx:]] = a[idx[upidx-<NUM_LIT:1>]]<EOL>winstd = a.std(ddof=<NUM_LIT:1>)<EOL>return winstd / ((<NUM_LIT:1>-low_limit-up_limit)*np.sqrt(len(a)))<EOL><DEDENT>a = ma.array(a, copy=True, subok=True)<EOL>a.unshare_mask()<EOL>if limits is None:<EOL><INDENT>return a.std(axis=axis,ddof=<NUM_LIT:1>)/ma.sqrt(a.count(axis))<EOL><DEDENT>if (not isinstance(limits,tuple)) and isinstance(limits,float):<EOL><INDENT>limits = (limits, limits)<EOL><DEDENT>(lolim, uplim) = limits<EOL>errmsg = "<STR_LIT>"<EOL>if lolim is not None:<EOL><INDENT>if lolim > <NUM_LIT:1.> or lolim < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(errmsg % '<STR_LIT>' + "<STR_LIT>" % lolim)<EOL><DEDENT><DEDENT>if uplim is not None:<EOL><INDENT>if uplim > <NUM_LIT:1.> or uplim < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(errmsg % '<STR_LIT:end>' + "<STR_LIT>" % uplim)<EOL><DEDENT><DEDENT>(loinc, upinc) = inclusive<EOL>if (axis is None):<EOL><INDENT>return _trimmed_stde_1D(a.ravel(),lolim,uplim,loinc,upinc)<EOL><DEDENT>else:<EOL><INDENT>if a.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>" % a.ndim)<EOL><DEDENT>return ma.apply_along_axis(_trimmed_stde_1D, axis, a,<EOL>lolim,uplim,loinc,upinc)<EOL><DEDENT>

Returns the standard error of the trimmed mean along the given axis.

Parameters
----------
a : sequence
    Input array
limits : {(0.1,0.1), tuple of float}, optional
    tuple (lower percentage, upper percentage) to cut  on each side of the
    array, with respect to the number of unmasked data.

    If n is the number of unmasked data before trimming, the values
    smaller than ``n * limits[0]`` and the values larger than
    ``n * `limits[1]`` are masked, and the total number of unmasked
    data after trimming is ``n * (1.-sum(limits))``.  In each case,
    the value of one limit can be set to None to indicate an open interval.
    If `limits` is None, no trimming is performed.
inclusive : {(bool, bool) tuple} optional
    Tuple indicating whether the number of data being masked on each side
    should be rounded (True) or truncated (False).
axis : int, optional
    Axis along which to trim.

Returns
-------
trimmed_stde : scalar or ndarray


def winsorize(a, limits=None, inclusive=(True, True), inplace=False,<EOL>axis=None):

def _winsorize1D(a, low_limit, up_limit, low_include, up_include):<EOL><INDENT>n = a.count()<EOL>idx = a.argsort()<EOL>if low_limit:<EOL><INDENT>if low_include:<EOL><INDENT>lowidx = int(low_limit * n)<EOL><DEDENT>else:<EOL><INDENT>lowidx = np.round(low_limit * n)<EOL><DEDENT>a[idx[:lowidx]] = a[idx[lowidx]]<EOL><DEDENT>if up_limit is not None:<EOL><INDENT>if up_include:<EOL><INDENT>upidx = n - int(n * up_limit)<EOL><DEDENT>else:<EOL><INDENT>upidx = n - np.round(n * up_limit)<EOL><DEDENT>a[idx[upidx:]] = a[idx[upidx - <NUM_LIT:1>]]<EOL><DEDENT>return a<EOL><DEDENT>a = ma.array(a, copy=np.logical_not(inplace))<EOL>if limits is None:<EOL><INDENT>return a<EOL><DEDENT>if (not isinstance(limits, tuple)) and isinstance(limits, float):<EOL><INDENT>limits = (limits, limits)<EOL><DEDENT>(lolim, uplim) = limits<EOL>errmsg = "<STR_LIT>"<EOL>if lolim is not None:<EOL><INDENT>if lolim > <NUM_LIT:1.> or lolim < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(errmsg % '<STR_LIT>' + "<STR_LIT>" % lolim)<EOL><DEDENT><DEDENT>if uplim is not None:<EOL><INDENT>if uplim > <NUM_LIT:1.> or uplim < <NUM_LIT:0>:<EOL><INDENT>raise ValueError(errmsg % '<STR_LIT:end>' + "<STR_LIT>" % uplim)<EOL><DEDENT><DEDENT>(loinc, upinc) = inclusive<EOL>if axis is None:<EOL><INDENT>shp = a.shape<EOL>return _winsorize1D(a.ravel(), lolim, uplim, loinc, upinc).reshape(shp)<EOL><DEDENT>else:<EOL><INDENT>return ma.apply_along_axis(_winsorize1D, axis, a, lolim, uplim, loinc,<EOL>upinc)<EOL><DEDENT>

Returns a Winsorized version of the input array.

    The (limits[0])th lowest values are set to the (limits[0])th percentile,
    and the (limits[1])th highest values are set to the (1 - limits[1])th
    percentile.
    Masked values are skipped.

    Parameters
    ----------
    a : sequence
        Input array.
    limits : {None, tuple of float}, optional
        Tuple of the percentages to cut on each side of the array, with respect
        to the number of unmasked data, as floats between 0. and 1.
        Noting n the number of unmasked data before trimming, the
        (n*limits[0])th smallest data and the (n*limits[1])th largest data are
        masked, and the total number of unmasked data after trimming
        is n*(1.-sum(limits)) The value of one limit can be set to None to
        indicate an open interval.
    inclusive : {(True, True) tuple}, optional
        Tuple indicating whether the number of data being masked on each side
        should be rounded (True) or truncated (False).
    inplace : {False, True}, optional
        Whether to winsorize in place (True) or to use a copy (False)
    axis : {None, int}, optional
        Axis along which to trim. If None, the whole array is trimmed, but its
        shape is maintained.

    Notes
    -----
    This function is applied to reduce the effect of possibly spurious outliers
    by limiting the extreme values.


a, axis = _chk_asarray(a, axis)<EOL>n = a.count(axis)<EOL>mm = (ma.minimum.reduce(a), ma.maximum.reduce(a))<EOL>m = a.mean(axis)<EOL>v = a.var(axis,ddof=ddof)<EOL>sk = skew(a, axis)<EOL>kurt = kurtosis(a, axis)<EOL>return n, mm, m, v, sk, kurt<EOL>

Computes several descriptive statistics of the passed array.

Parameters
----------
a : array

axis : int or None

ddof : int
    degree of freedom (default 0); note that default ddof is different
    from the same routine in stats.describe

Returns
-------
n : int
    (size of the data (discarding missing values)
mm : (int, int)
    min, max

arithmetic mean : float

unbiased variance : float

biased skewness : float

biased kurtosis : float

Examples
--------

>>> ma = np.ma.array(range(6), mask=[0, 0, 0, 1, 1, 1])
>>> describe(ma)
(array(3),
 (0, 2),
 1.0,
 1.0,
 masked_array(data = 0.0,
             mask = False,
       fill_value = 1e+20)
,
 -1.5)


def _stdemed_1D(data):<EOL><INDENT>data = np.sort(data.compressed())<EOL>n = len(data)<EOL>z = <NUM_LIT><EOL>k = int(np.round((n+<NUM_LIT:1>)/<NUM_LIT> - z * np.sqrt(n/<NUM_LIT>),<NUM_LIT:0>))<EOL>return ((data[n-k] - data[k-<NUM_LIT:1>])/(<NUM_LIT>*z))<EOL><DEDENT>data = ma.array(data, copy=False, subok=True)<EOL>if (axis is None):<EOL><INDENT>return _stdemed_1D(data)<EOL><DEDENT>else:<EOL><INDENT>if data.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % data.ndim)<EOL><DEDENT>return ma.apply_along_axis(_stdemed_1D, axis, data)<EOL><DEDENT>

Returns the McKean-Schrader estimate of the standard error of the sample
    median along the given axis. masked values are discarded.

    Parameters
    ----------
    data : ndarray
        Data to trim.
    axis : {None,int}, optional
        Axis along which to perform the trimming.
        If None, the input array is first flattened.


def mquantiles(a, prob=list([<NUM_LIT>,<NUM_LIT>,<NUM_LIT>]), alphap=<NUM_LIT>, betap=<NUM_LIT>, axis=None,<EOL>limit=()):

def _quantiles1D(data,m,p):<EOL><INDENT>x = np.sort(data.compressed())<EOL>n = len(x)<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>return ma.array(np.empty(len(p), dtype=float), mask=True)<EOL><DEDENT>elif n == <NUM_LIT:1>:<EOL><INDENT>return ma.array(np.resize(x, p.shape), mask=nomask)<EOL><DEDENT>aleph = (n*p + m)<EOL>k = np.floor(aleph.clip(<NUM_LIT:1>, n-<NUM_LIT:1>)).astype(int)<EOL>gamma = (aleph-k).clip(<NUM_LIT:0>,<NUM_LIT:1>)<EOL>return (<NUM_LIT:1.>-gamma)*x[(k-<NUM_LIT:1>).tolist()] + gamma*x[k.tolist()]<EOL><DEDENT>data = ma.array(a, copy=False)<EOL>if data.ndim > <NUM_LIT:2>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if limit:<EOL><INDENT>condition = (limit[<NUM_LIT:0>] < data) & (data < limit[<NUM_LIT:1>])<EOL>data[~condition.filled(True)] = masked<EOL><DEDENT>p = np.array(prob, copy=False, ndmin=<NUM_LIT:1>)<EOL>m = alphap + p*(<NUM_LIT:1.>-alphap-betap)<EOL>if (axis is None):<EOL><INDENT>return _quantiles1D(data, m, p)<EOL><DEDENT>return ma.apply_along_axis(_quantiles1D, axis, data, m, p)<EOL>

Computes empirical quantiles for a data array.

Samples quantile are defined by ``Q(p) = (1-gamma)*x[j] + gamma*x[j+1]``,
where ``x[j]`` is the j-th order statistic, and gamma is a function of
``j = floor(n*p + m)``, ``m = alphap + p*(1 - alphap - betap)`` and
``g = n*p + m - j``.

Reinterpreting the above equations to compare to **R** lead to the
equation: ``p(k) = (k - alphap)/(n + 1 - alphap - betap)``

Typical values of (alphap,betap) are:
    - (0,1)    : ``p(k) = k/n`` : linear interpolation of cdf
      (**R** type 4)
    - (.5,.5)  : ``p(k) = (k - 1/2.)/n`` : piecewise linear function
      (**R** type 5)
    - (0,0)    : ``p(k) = k/(n+1)`` :
      (**R** type 6)
    - (1,1)    : ``p(k) = (k-1)/(n-1)``: p(k) = mode[F(x[k])].
      (**R** type 7, **R** default)
    - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``: Then p(k) ~ median[F(x[k])].
      The resulting quantile estimates are approximately median-unbiased
      regardless of the distribution of x.
      (**R** type 8)
    - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``: Blom.
      The resulting quantile estimates are approximately unbiased
      if x is normally distributed
      (**R** type 9)
    - (.4,.4)  : approximately quantile unbiased (Cunnane)
    - (.35,.35): APL, used with PWM

Parameters
----------
a : array_like
    Input data, as a sequence or array of dimension at most 2.
prob : array_like, optional
    List of quantiles to compute.
alphap : float, optional
    Plotting positions parameter, default is 0.4.
betap : float, optional
    Plotting positions parameter, default is 0.4.
axis : int, optional
    Axis along which to perform the trimming.
    If None (default), the input array is first flattened.
limit : tuple
    Tuple of (lower, upper) values.
    Values of `a` outside this open interval are ignored.

Returns
-------
mquantiles : MaskedArray
    An array containing the calculated quantiles.

Notes
-----
This formulation is very similar to **R** except the calculation of
``m`` from ``alphap`` and ``betap``, where in **R** ``m`` is defined
with each type.

References
----------
.. [1] *R* statistical software: http://www.r-project.org/
.. [2] *R* ``quantile`` function:
        http://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html

Examples
--------
>>> from scipy.stats.mstats import mquantiles
>>> a = np.array([6., 47., 49., 15., 42., 41., 7., 39., 43., 40., 36.])
>>> mquantiles(a)
array([ 19.2,  40. ,  42.8])

Using a 2D array, specifying axis and limit.

>>> data = np.array([[   6.,    7.,    1.],
                     [  47.,   15.,    2.],
                     [  49.,   36.,    3.],
                     [  15.,   39.,    4.],
                     [  42.,   40., -999.],
                     [  41.,   41., -999.],
                     [   7., -999., -999.],
                     [  39., -999., -999.],
                     [  43., -999., -999.],
                     [  40., -999., -999.],
                     [  36., -999., -999.]])
>>> mquantiles(data, axis=0, limit=(0, 50))
array([[ 19.2 ,  14.6 ,   1.45],
       [ 40.  ,  37.5 ,   2.5 ],
       [ 42.8 ,  40.05,   3.55]])

>>> data[:, 2] = -999.
>>> mquantiles(data, axis=0, limit=(0, 50))
masked_array(data =
 [[19.2 14.6 --]
 [40.0 37.5 --]
 [42.8 40.05 --]],
             mask =
 [[False False  True]
  [False False  True]
  [False False  True]],
       fill_value = 1e+20)


def scoreatpercentile(data, per, limit=(), alphap=<NUM_LIT>, betap=<NUM_LIT>):

if (per < <NUM_LIT:0>) or (per > <NUM_LIT>):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % per)<EOL><DEDENT>return mquantiles(data, prob=[per/<NUM_LIT>], alphap=alphap, betap=betap,<EOL>limit=limit, axis=<NUM_LIT:0>).squeeze()<EOL>

Calculate the score at the given 'per' percentile of the
    sequence a.  For example, the score at per=50 is the median.

    This function is a shortcut to mquantile


def plotting_positions(data, alpha=<NUM_LIT>, beta=<NUM_LIT>):

data = ma.array(data, copy=False).reshape(<NUM_LIT:1>,-<NUM_LIT:1>)<EOL>n = data.count()<EOL>plpos = np.empty(data.size, dtype=float)<EOL>plpos[n:] = <NUM_LIT:0><EOL>plpos[data.argsort()[:n]] = ((np.arange(<NUM_LIT:1>, n+<NUM_LIT:1>) - alpha) /<EOL>(n + <NUM_LIT:1.0> - alpha - beta))<EOL>return ma.array(plpos, mask=data._mask)<EOL>

Returns plotting positions (or empirical percentile points) for the data.

Plotting positions are defined as ``(i-alpha)/(n+1-alpha-beta)``, where:
    - i is the rank order statistics
    - n is the number of unmasked values along the given axis
    - `alpha` and `beta` are two parameters.

Typical values for `alpha` and `beta` are:
    - (0,1)    : ``p(k) = k/n``, linear interpolation of cdf (R, type 4)
    - (.5,.5)  : ``p(k) = (k-1/2.)/n``, piecewise linear function
      (R, type 5)
    - (0,0)    : ``p(k) = k/(n+1)``, Weibull (R type 6)
    - (1,1)    : ``p(k) = (k-1)/(n-1)``, in this case,
      ``p(k) = mode[F(x[k])]``. That's R default (R type 7)
    - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``, then
      ``p(k) ~ median[F(x[k])]``.
      The resulting quantile estimates are approximately median-unbiased
      regardless of the distribution of x. (R type 8)
    - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``, Blom.
      The resulting quantile estimates are approximately unbiased
      if x is normally distributed (R type 9)
    - (.4,.4)  : approximately quantile unbiased (Cunnane)
    - (.35,.35): APL, used with PWM
    - (.3175, .3175): used in scipy.stats.probplot

Parameters
----------
data : array_like
    Input data, as a sequence or array of dimension at most 2.
alpha : float, optional
    Plotting positions parameter. Default is 0.4.
beta : float, optional
    Plotting positions parameter. Default is 0.4.

Returns
-------
positions : MaskedArray
    The calculated plotting positions.


data = argstoarray(*args).T<EOL>v = data.var(axis=<NUM_LIT:0>,ddof=<NUM_LIT:1>)<EOL>m = data.mean(<NUM_LIT:0>)<EOL>n = data.count(<NUM_LIT:0>).astype(float)<EOL>data -= m<EOL>data **= <NUM_LIT:2><EOL>data *= (n-<NUM_LIT>)*n<EOL>data -= <NUM_LIT:0.5>*v*(n-<NUM_LIT:1>)<EOL>data /= (n-<NUM_LIT:1.>)*(n-<NUM_LIT>)<EOL>if not ma.allclose(v,data.mean(<NUM_LIT:0>)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return data<EOL>

Computes a transform on input data (any number of columns).  Used to
test for homogeneity of variance prior to running one-way stats.  Each
array in *args is one level of a factor.  If an F_oneway() run on the
transformed data and found significant, variances are unequal.   From
Maxwell and Delaney, p.112.

Returns: transformed data for use in an ANOVA


data = ma.array(data, copy=False)<EOL>m = data.mean(axis)<EOL>sd = data.std(axis, ddof=<NUM_LIT:0>)<EOL>return m/sd<EOL>

Calculates the signal-to-noise ratio, as the ratio of the mean over
    standard deviation along the given axis.

    Parameters
    ----------
    data : sequence
        Input data
    axis : {0, int}, optional
        Axis along which to compute. If None, the computation is performed
        on a flat version of the array.


def sem(a, axis=<NUM_LIT:0>, ddof=<NUM_LIT:1>):

a, axis = _chk_asarray(a, axis)<EOL>n = a.count(axis=axis)<EOL>s = a.std(axis=axis, ddof=ddof) / ma.sqrt(n)<EOL>return s<EOL>

Calculates the standard error of the mean of the input array.

Also sometimes called standard error of measurement.

Parameters
----------
a : array_like
    An array containing the values for which the standard error is
    returned.
axis : int or None, optional.
    If axis is None, ravel `a` first. If axis is an integer, this will be
    the axis over which to operate. Defaults to 0.
ddof : int, optional
    Delta degrees-of-freedom. How many degrees of freedom to adjust
    for bias in limited samples relative to the population estimate
    of variance. Defaults to 1.

Returns
-------
s : ndarray or float
    The standard error of the mean in the sample(s), along the input axis.

Notes
-----
The default value for `ddof` changed in scipy 0.15.0 to be consistent with
`stats.sem` as well as with the most common definition used (like in the R
documentation).

Examples
--------
Find standard error along the first axis:

>>> from scipy import stats
>>> a = np.arange(20).reshape(5,4)
>>> stats.sem(a)
array([ 2.8284,  2.8284,  2.8284,  2.8284])

Find standard error across the whole array, using n degrees of freedom:

>>> stats.sem(a, axis=None, ddof=0)
1.2893796958227628


<EOL>data = argstoarray(*args)<EOL>ngroups = len(data)<EOL>ntot = data.count()<EOL>sstot = (data**<NUM_LIT:2>).sum() - (data.sum())**<NUM_LIT:2>/float(ntot)<EOL>ssbg = (data.count(-<NUM_LIT:1>) * (data.mean(-<NUM_LIT:1>)-data.mean())**<NUM_LIT:2>).sum()<EOL>sswg = sstot-ssbg<EOL>dfbg = ngroups-<NUM_LIT:1><EOL>dfwg = ntot - ngroups<EOL>msb = ssbg/float(dfbg)<EOL>msw = sswg/float(dfwg)<EOL>f = msb/msw<EOL>prob = special.fdtrc(dfbg, dfwg, f)  <EOL>return f, prob<EOL>

Performs a 1-way ANOVA, returning an F-value and probability given
any number of groups.  From Heiman, pp.394-7.

Usage: ``f_oneway(*args)``, where ``*args`` is 2 or more arrays,
                            one per treatment group.
Returns: f-value, probability


def f_value_wilks_lambda(ER, EF, dfnum, dfden, a, b):

ER = ma.array(ER, copy=False, ndmin=<NUM_LIT:2>)<EOL>EF = ma.array(EF, copy=False, ndmin=<NUM_LIT:2>)<EOL>if ma.getmask(ER).any() or ma.getmask(EF).any():<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>lmbda = np.linalg.det(EF) / np.linalg.det(ER)<EOL>q = ma.sqrt(((a-<NUM_LIT:1>)**<NUM_LIT:2>*(b-<NUM_LIT:1>)**<NUM_LIT:2> - <NUM_LIT:2>) / ((a-<NUM_LIT:1>)**<NUM_LIT:2> + (b-<NUM_LIT:1>)**<NUM_LIT:2> - <NUM_LIT:5>))<EOL>q = ma.filled(q, <NUM_LIT:1>)<EOL>n_um = (<NUM_LIT:1> - lmbda**(<NUM_LIT:1.0>/q))*(a-<NUM_LIT:1>)*(b-<NUM_LIT:1>)<EOL>d_en = lmbda**(<NUM_LIT:1.0>/q) / (n_um*q - <NUM_LIT:0.5>*(a-<NUM_LIT:1>)*(b-<NUM_LIT:1>) + <NUM_LIT:1>)<EOL>return n_um / d_en<EOL>

Calculation of Wilks lambda F-statistic for multivariate data, per
    Maxwell & Delaney p.657.


data = argstoarray(*args).astype(float)<EOL>k = len(data)<EOL>if k < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>" % k +<EOL>"<STR_LIT>")<EOL><DEDENT>ranked = ma.masked_values(rankdata(data, axis=<NUM_LIT:0>), <NUM_LIT:0>)<EOL>if ranked._mask is not nomask:<EOL><INDENT>ranked = ma.mask_cols(ranked)<EOL>ranked = ranked.compressed().reshape(k,-<NUM_LIT:1>).view(ndarray)<EOL><DEDENT>else:<EOL><INDENT>ranked = ranked._data<EOL><DEDENT>(k,n) = ranked.shape<EOL>repeats = np.array([find_repeats(_) for _ in ranked.T], dtype=object)<EOL>ties = repeats[repeats.nonzero()].reshape(-<NUM_LIT:1>,<NUM_LIT:2>)[:,-<NUM_LIT:1>].astype(int)<EOL>tie_correction = <NUM_LIT:1> - (ties**<NUM_LIT:3>-ties).sum()/float(n*(k**<NUM_LIT:3>-k))<EOL>ssbg = np.sum((ranked.sum(-<NUM_LIT:1>) - n*(k+<NUM_LIT:1>)/<NUM_LIT>)**<NUM_LIT:2>)<EOL>chisq = ssbg * <NUM_LIT>/(n*k*(k+<NUM_LIT:1>)) * <NUM_LIT:1.>/tie_correction<EOL>return chisq, stats.chisqprob(chisq,k-<NUM_LIT:1>)<EOL>

Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA.
    This function calculates the Friedman Chi-square test for repeated measures
    and returns the result, along with the associated probability value.

    Each input is considered a given group. Ideally, the number of treatments
    among each group should be equal. If this is not the case, only the first
    n treatments are taken into account, where n is the number of treatments
    of the smallest group.
    If a group has some missing values, the corresponding treatments are masked
    in the other groups.
    The test statistic is corrected for ties.

    Masked values in one group are propagated to the other groups.

    Returns: chi-square statistic, associated p-value


def hdquantiles(data, prob=list([<NUM_LIT>,<NUM_LIT>,<NUM_LIT>]), axis=None, var=False,):

def _hd_1D(data,prob,var):<EOL><INDENT>"<STR_LIT>"<EOL>xsorted = np.squeeze(np.sort(data.compressed().view(ndarray)))<EOL>n = xsorted.size<EOL>hd = np.empty((<NUM_LIT:2>,len(prob)), float_)<EOL>if n < <NUM_LIT:2>:<EOL><INDENT>hd.flat = np.nan<EOL>if var:<EOL><INDENT>return hd<EOL><DEDENT>return hd[<NUM_LIT:0>]<EOL><DEDENT>v = np.arange(n+<NUM_LIT:1>) / float(n)<EOL>betacdf = beta.cdf<EOL>for (i,p) in enumerate(prob):<EOL><INDENT>_w = betacdf(v, (n+<NUM_LIT:1>)*p, (n+<NUM_LIT:1>)*(<NUM_LIT:1>-p))<EOL>w = _w[<NUM_LIT:1>:] - _w[:-<NUM_LIT:1>]<EOL>hd_mean = np.dot(w, xsorted)<EOL>hd[<NUM_LIT:0>,i] = hd_mean<EOL>hd[<NUM_LIT:1>,i] = np.dot(w, (xsorted-hd_mean)**<NUM_LIT:2>)<EOL><DEDENT>hd[<NUM_LIT:0>, prob == <NUM_LIT:0>] = xsorted[<NUM_LIT:0>]<EOL>hd[<NUM_LIT:0>, prob == <NUM_LIT:1>] = xsorted[-<NUM_LIT:1>]<EOL>if var:<EOL><INDENT>hd[<NUM_LIT:1>, prob == <NUM_LIT:0>] = hd[<NUM_LIT:1>, prob == <NUM_LIT:1>] = np.nan<EOL>return hd<EOL><DEDENT>return hd[<NUM_LIT:0>]<EOL><DEDENT>data = ma.array(data, copy=False, dtype=float_)<EOL>p = np.array(prob, copy=False, ndmin=<NUM_LIT:1>)<EOL>if (axis is None) or (data.ndim == <NUM_LIT:1>):<EOL><INDENT>result = _hd_1D(data, p, var)<EOL><DEDENT>else:<EOL><INDENT>if data.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % data.ndim)<EOL><DEDENT>result = ma.apply_along_axis(_hd_1D, axis, data, p, var)<EOL><DEDENT>return ma.fix_invalid(result, copy=False)<EOL>

Computes quantile estimates with the Harrell-Davis method.

The quantile estimates are calculated as a weighted linear combination
of order statistics.

Parameters
----------
data : array_like
    Data array.
prob : sequence
    Sequence of quantiles to compute.
axis : int
    Axis along which to compute the quantiles. If None, use a flattened
    array.
var : boolean
    Whether to return the variance of the estimate.

Returns
-------
hdquantiles : MaskedArray
    A (p,) array of quantiles (if `var` is False), or a (2,p) array of
    quantiles and variances (if `var` is True), where ``p`` is the
    number of quantiles.


def hdmedian(data, axis=-<NUM_LIT:1>, var=False):

result = hdquantiles(data,[<NUM_LIT:0.5>], axis=axis, var=var)<EOL>return result.squeeze()<EOL>

Returns the Harrell-Davis estimate of the median along the given axis.

Parameters
----------
data : ndarray
    Data array.
axis : int
    Axis along which to compute the quantiles. If None, use a flattened
    array.
var : boolean
    Whether to return the variance of the estimate.


def hdquantiles_sd(data, prob=list([<NUM_LIT>,<NUM_LIT>,<NUM_LIT>]), axis=None):

def _hdsd_1D(data,prob):<EOL><INDENT>"<STR_LIT>"<EOL>xsorted = np.sort(data.compressed())<EOL>n = len(xsorted)<EOL>hdsd = np.empty(len(prob), float_)<EOL>if n < <NUM_LIT:2>:<EOL><INDENT>hdsd.flat = np.nan<EOL><DEDENT>vv = np.arange(n) / float(n-<NUM_LIT:1>)<EOL>betacdf = beta.cdf<EOL>for (i,p) in enumerate(prob):<EOL><INDENT>_w = betacdf(vv, (n+<NUM_LIT:1>)*p, (n+<NUM_LIT:1>)*(<NUM_LIT:1>-p))<EOL>w = _w[<NUM_LIT:1>:] - _w[:-<NUM_LIT:1>]<EOL>mx_ = np.fromiter([np.dot(w,xsorted[np.r_[list(range(<NUM_LIT:0>,k)),<EOL>list(range(k+<NUM_LIT:1>,n))].astype(int_)])<EOL>for k in range(n)], dtype=float_)<EOL>mx_var = np.array(mx_.var(), copy=False, ndmin=<NUM_LIT:1>) * n / float(n-<NUM_LIT:1>)<EOL>hdsd[i] = float(n-<NUM_LIT:1>) * np.sqrt(np.diag(mx_var).diagonal() / float(n))<EOL><DEDENT>return hdsd<EOL><DEDENT>data = ma.array(data, copy=False, dtype=float_)<EOL>p = np.array(prob, copy=False, ndmin=<NUM_LIT:1>)<EOL>if (axis is None):<EOL><INDENT>result = _hdsd_1D(data, p)<EOL><DEDENT>else:<EOL><INDENT>if data.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % data.ndim)<EOL><DEDENT>result = ma.apply_along_axis(_hdsd_1D, axis, data, p)<EOL><DEDENT>return ma.fix_invalid(result, copy=False).ravel()<EOL>

The standard error of the Harrell-Davis quantile estimates by jackknife.

Parameters
----------
data : array_like
    Data array.
prob : sequence
    Sequence of quantiles to compute.
axis : int
    Axis along which to compute the quantiles. If None, use a flattened
    array.

Returns
-------
hdquantiles_sd : MaskedArray
    Standard error of the Harrell-Davis quantile estimates.


def trimmed_mean_ci(data, limits=(<NUM_LIT>,<NUM_LIT>), inclusive=(True,True),<EOL>alpha=<NUM_LIT>, axis=None):

data = ma.array(data, copy=False)<EOL>trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis)<EOL>tmean = trimmed.mean(axis)<EOL>tstde = mstats.trimmed_stde(data,limits=limits,inclusive=inclusive,axis=axis)<EOL>df = trimmed.count(axis) - <NUM_LIT:1><EOL>tppf = t.ppf(<NUM_LIT:1>-alpha/<NUM_LIT>,df)<EOL>return np.array((tmean - tppf*tstde, tmean+tppf*tstde))<EOL>

Selected confidence interval of the trimmed mean along the given axis.

Parameters
----------
data : array_like
    Input data.
limits : {None, tuple}, optional
    None or a two item tuple.
    Tuple of the percentages to cut on each side of the array, with respect
    to the number of unmasked data, as floats between 0. and 1. If ``n``
    is the number of unmasked data before trimming, then
    (``n * limits[0]``)th smallest data and (``n * limits[1]``)th
    largest data are masked.  The total number of unmasked data after
    trimming is ``n * (1. - sum(limits))``.
    The value of one limit can be set to None to indicate an open interval.

    Defaults to (0.2, 0.2).
inclusive : (2,) tuple of boolean, optional
    If relative==False, tuple indicating whether values exactly equal to
    the absolute limits are allowed.
    If relative==True, tuple indicating whether the number of data being
    masked on each side should be rounded (True) or truncated (False).

    Defaults to (True, True).
alpha : float, optional
    Confidence level of the intervals.

    Defaults to 0.05.
axis : int, optional
    Axis along which to cut. If None, uses a flattened version of `data`.

    Defaults to None.

Returns
-------
trimmed_mean_ci : (2,) ndarray
    The lower and upper confidence intervals of the trimmed data.


def mjci(data, prob=[<NUM_LIT>,<NUM_LIT:0.5>,<NUM_LIT>], axis=None):

def _mjci_1D(data, p):<EOL><INDENT>data = np.sort(data.compressed())<EOL>n = data.size<EOL>prob = (np.array(p) * n + <NUM_LIT:0.5>).astype(int_)<EOL>betacdf = beta.cdf<EOL>mj = np.empty(len(prob), float_)<EOL>x = np.arange(<NUM_LIT:1>,n+<NUM_LIT:1>, dtype=float_) / n<EOL>y = x - <NUM_LIT:1.>/n<EOL>for (i,m) in enumerate(prob):<EOL><INDENT>(m1,m2) = (m-<NUM_LIT:1>, n-m)<EOL>W = betacdf(x,m-<NUM_LIT:1>,n-m) - betacdf(y,m-<NUM_LIT:1>,n-m)<EOL>C1 = np.dot(W,data)<EOL>C2 = np.dot(W,data**<NUM_LIT:2>)<EOL>mj[i] = np.sqrt(C2 - C1**<NUM_LIT:2>)<EOL><DEDENT>return mj<EOL><DEDENT>data = ma.array(data, copy=False)<EOL>if data.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % data.ndim)<EOL><DEDENT>p = np.array(prob, copy=False, ndmin=<NUM_LIT:1>)<EOL>if (axis is None):<EOL><INDENT>return _mjci_1D(data, p)<EOL><DEDENT>else:<EOL><INDENT>return ma.apply_along_axis(_mjci_1D, axis, data, p)<EOL><DEDENT>

Returns the Maritz-Jarrett estimators of the standard error of selected
experimental quantiles of the data.

Parameters
----------
data: ndarray
    Data array.
prob: sequence
    Sequence of quantiles to compute.
axis : int
    Axis along which to compute the quantiles. If None, use a flattened
    array.


def mquantiles_cimj(data, prob=[<NUM_LIT>,<NUM_LIT>,<NUM_LIT>], alpha=<NUM_LIT>, axis=None):

alpha = min(alpha, <NUM_LIT:1>-alpha)<EOL>z = norm.ppf(<NUM_LIT:1>-alpha/<NUM_LIT>)<EOL>xq = mstats.mquantiles(data, prob, alphap=<NUM_LIT:0>, betap=<NUM_LIT:0>, axis=axis)<EOL>smj = mjci(data, prob, axis=axis)<EOL>return (xq - z * smj, xq + z * smj)<EOL>

Computes the alpha confidence interval for the selected quantiles of the
data, with Maritz-Jarrett estimators.

Parameters
----------
data : ndarray
    Data array.
prob : sequence
    Sequence of quantiles to compute.
alpha : float
    Confidence level of the intervals.
axis : integer
    Axis along which to compute the quantiles.
    If None, use a flattened array.


def median_cihs(data, alpha=<NUM_LIT>, axis=None):

def _cihs_1D(data, alpha):<EOL><INDENT>data = np.sort(data.compressed())<EOL>n = len(data)<EOL>alpha = min(alpha, <NUM_LIT:1>-alpha)<EOL>k = int(binom._ppf(alpha/<NUM_LIT>, n, <NUM_LIT:0.5>))<EOL>gk = binom.cdf(n-k,n,<NUM_LIT:0.5>) - binom.cdf(k-<NUM_LIT:1>,n,<NUM_LIT:0.5>)<EOL>if gk < <NUM_LIT:1>-alpha:<EOL><INDENT>k -= <NUM_LIT:1><EOL>gk = binom.cdf(n-k,n,<NUM_LIT:0.5>) - binom.cdf(k-<NUM_LIT:1>,n,<NUM_LIT:0.5>)<EOL><DEDENT>gkk = binom.cdf(n-k-<NUM_LIT:1>,n,<NUM_LIT:0.5>) - binom.cdf(k,n,<NUM_LIT:0.5>)<EOL>I = (gk - <NUM_LIT:1> + alpha)/(gk - gkk)<EOL>lambd = (n-k) * I / float(k + (n-<NUM_LIT:2>*k)*I)<EOL>lims = (lambd*data[k] + (<NUM_LIT:1>-lambd)*data[k-<NUM_LIT:1>],<EOL>lambd*data[n-k-<NUM_LIT:1>] + (<NUM_LIT:1>-lambd)*data[n-k])<EOL>return lims<EOL><DEDENT>data = ma.rray(data, copy=False)<EOL>if (axis is None):<EOL><INDENT>result = _cihs_1D(data.compressed(), alpha)<EOL><DEDENT>else:<EOL><INDENT>if data.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % data.ndim)<EOL><DEDENT>result = ma.apply_along_axis(_cihs_1D, axis, data, alpha)<EOL><DEDENT>return result<EOL>

Computes the alpha-level confidence interval for the median of the data.

Uses the Hettmasperger-Sheather method.

Parameters
----------
data : array_like
    Input data. Masked values are discarded. The input should be 1D only,
    or `axis` should be set to None.
alpha : float
    Confidence level of the intervals.
axis : integer
    Axis along which to compute the quantiles. If None, use a flattened
    array.

Returns
-------
median_cihs :
    Alpha level confidence interval.


def compare_medians_ms(group_1, group_2, axis=None):

(med_1, med_2) = (ma.median(group_1,axis=axis), ma.median(group_2,axis=axis))<EOL>(std_1, std_2) = (mstats.stde_median(group_1, axis=axis),<EOL>mstats.stde_median(group_2, axis=axis))<EOL>W = np.abs(med_1 - med_2) / ma.sqrt(std_1**<NUM_LIT:2> + std_2**<NUM_LIT:2>)<EOL>return <NUM_LIT:1> - norm.cdf(W)<EOL>

Compares the medians from two independent groups along the given axis.

The comparison is performed using the McKean-Schrader estimate of the
standard error of the medians.

Parameters
----------
group_1 : array_like
    First dataset.
group_2 : array_like
    Second dataset.
axis : int, optional
    Axis along which the medians are estimated. If None, the arrays are
    flattened.  If `axis` is not None, then `group_1` and `group_2`
    should have the same shape.

Returns
-------
compare_medians_ms : {float, ndarray}
    If `axis` is None, then returns a float, otherwise returns a 1-D
    ndarray of floats with a length equal to the length of `group_1`
    along `axis`.


def _idf(data):<EOL><INDENT>x = data.compressed()<EOL>n = len(x)<EOL>if n < <NUM_LIT:3>:<EOL><INDENT>return [np.nan,np.nan]<EOL><DEDENT>(j,h) = divmod(n/<NUM_LIT> + <NUM_LIT:5>/<NUM_LIT>,<NUM_LIT:1>)<EOL>j = int(j)<EOL>qlo = (<NUM_LIT:1>-h)*x[j-<NUM_LIT:1>] + h*x[j]<EOL>k = n - j<EOL>qup = (<NUM_LIT:1>-h)*x[k] + h*x[k-<NUM_LIT:1>]<EOL>return [qlo, qup]<EOL><DEDENT>data = ma.sort(data, axis=axis).view(MaskedArray)<EOL>if (axis is None):<EOL><INDENT>return _idf(data)<EOL><DEDENT>else:<EOL><INDENT>return ma.apply_along_axis(_idf, axis, data)<EOL><DEDENT>

Returns an estimate of the lower and upper quartiles.

Uses the ideal fourths algorithm.

Parameters
----------
data : array_like
    Input array.
axis : int, optional
    Axis along which the quartiles are estimated. If None, the arrays are
    flattened.

Returns
-------
idealfourths : {list of floats, masked array}
    Returns the two internal values that divide `data` into four parts
    using the ideal fourths algorithm either along the flattened array
    (if `axis` is None) or along `axis` of `data`.


data = ma.array(data, copy=False)<EOL>if points is None:<EOL><INDENT>points = data<EOL><DEDENT>else:<EOL><INDENT>points = np.array(points, copy=False, ndmin=<NUM_LIT:1>)<EOL><DEDENT>if data.ndim != <NUM_LIT:1>:<EOL><INDENT>raise AttributeError("<STR_LIT>")<EOL><DEDENT>n = data.count()<EOL>r = idealfourths(data, axis=None)<EOL>h = <NUM_LIT> * (r[-<NUM_LIT:1>]-r[<NUM_LIT:0>]) / n**(<NUM_LIT:1.>/<NUM_LIT:5>)<EOL>nhi = (data[:,None] <= points[None,:] + h).sum(<NUM_LIT:0>)<EOL>nlo = (data[:,None] < points[None,:] - h).sum(<NUM_LIT:0>)<EOL>return (nhi-nlo) / (<NUM_LIT>*n*h)<EOL>

Evaluates Rosenblatt's shifted histogram estimators for each point
on the dataset 'data'.

Parameters
----------
data : sequence
    Input data. Masked values are ignored.
points : sequence
    Sequence of points where to evaluate Rosenblatt shifted histogram.
    If None, use the data.


<EOL>res = []<EOL>for quant, tot, good, draw in zip(k, M, n, N):<EOL><INDENT>k2 = np.arange(quant + <NUM_LIT:1>, draw + <NUM_LIT:1>)<EOL>res.append(np.sum(self._pmf(k2, tot, good, draw)))<EOL><DEDENT>return np.asarray(res)<EOL>

More precise calculation, 1 - cdf doesn't cut it.


return mtrand.randint(low, high, self._size)<EOL>

An array of *size* random integers >= ``low`` and < ``high``.

        If ``high`` is ``None``, then range is >=0  and < low


@inherit_docstring_from(rv_continuous)<EOL><INDENT>def fit(self, data, **kwds):<DEDENT>

floc = kwds.get('<STR_LIT>', None)<EOL>fscale = kwds.get('<STR_LIT>', None)<EOL>if floc is not None and fscale is not None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>data = np.asarray(data)<EOL>if floc is None:<EOL><INDENT>loc = data.mean()<EOL><DEDENT>else:<EOL><INDENT>loc = floc<EOL><DEDENT>if fscale is None:<EOL><INDENT>scale = np.sqrt(((data - loc)**<NUM_LIT:2>).mean())<EOL><DEDENT>else:<EOL><INDENT>scale = fscale<EOL><DEDENT>return loc, scale<EOL>

%(super)s
        This function (norm_gen.fit) uses explicit formulas for the maximum
        likelihood estimation of the parameters, so the `optimizer` argument
        is ignored.


@inherit_docstring_from(rv_continuous)<EOL><INDENT>def fit(self, data, *args, **kwds):<DEDENT>

<EOL>f0 = kwds.get('<STR_LIT>', None)<EOL>f1 = kwds.get('<STR_LIT>', None)<EOL>floc = kwds.get('<STR_LIT>', None)<EOL>fscale = kwds.get('<STR_LIT>', None)<EOL>if floc is None or fscale is None:<EOL><INDENT>return super(beta_gen, self).fit(data, *args, **kwds)<EOL><DEDENT>if f0 is not None and f1 is not None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>data = (ravel(data) - floc) / fscale<EOL>if np.any(data <= <NUM_LIT:0>) or np.any(data >= <NUM_LIT:1>):<EOL><INDENT>raise FitDataError("<STR_LIT>", lower=floc, upper=floc + fscale)<EOL><DEDENT>xbar = data.mean()<EOL>if f0 is not None or f1 is not None:<EOL><INDENT>if f0 is not None:<EOL><INDENT>b = f0<EOL>data = <NUM_LIT:1> - data<EOL>xbar = <NUM_LIT:1> - xbar<EOL><DEDENT>else:<EOL><INDENT>b = f1<EOL><DEDENT>a = b * xbar / (<NUM_LIT:1> - xbar)<EOL>theta, info, ier, mesg = optimize.fsolve(<EOL>_beta_mle_a, a,<EOL>args=(b, len(data), np.log(data).sum()),<EOL>full_output=True<EOL>)<EOL>if ier != <NUM_LIT:1>:<EOL><INDENT>raise FitSolverError(mesg=mesg)<EOL><DEDENT>a = theta[<NUM_LIT:0>]<EOL>if f0 is not None:<EOL><INDENT>a, b = b, a<EOL><DEDENT><DEDENT>else:<EOL><INDENT>s1 = np.log(data).sum()<EOL>s2 = np.log(<NUM_LIT:1> - data).sum()<EOL>fac = xbar * (<NUM_LIT:1> - xbar) / data.var(ddof=<NUM_LIT:0>) - <NUM_LIT:1><EOL>a = xbar * fac<EOL>b = (<NUM_LIT:1> - xbar) * fac<EOL>theta, info, ier, mesg = optimize.fsolve(<EOL>_beta_mle_ab, [a, b],<EOL>args=(len(data), s1, s2),<EOL>full_output=True<EOL>)<EOL>if ier != <NUM_LIT:1>:<EOL><INDENT>raise FitSolverError(mesg=mesg)<EOL><DEDENT>a, b = theta<EOL><DEDENT>return a, b, floc, fscale<EOL>

%(super)s
        In the special case where both `floc` and `fscale` are given, a
        `ValueError` is raised if any value `x` in `data` does not satisfy
        `floc < x < floc + fscale`.


margsums = []<EOL>ranged = list(range(a.ndim))<EOL>for k in ranged:<EOL><INDENT>marg = np.apply_over_axes(np.sum, a, [j for j in ranged if j != k])<EOL>margsums.append(marg)<EOL><DEDENT>return margsums<EOL>

Return a list of the marginal sums of the array `a`.

    Parameters
    ----------
    a : ndarray
        The array for which to compute the marginal sums.

    Returns
    -------
    margsums : list of ndarrays
        A list of length `a.ndim`.  `margsums[k]` is the result
        of summing `a` over all axes except `k`; it has the same
        number of dimensions as `a`, but the length of each axis
        except axis `k` will be 1.

    Examples
    --------
    >>> a = np.arange(12).reshape(2, 6)
    >>> a
    array([[ 0,  1,  2,  3,  4,  5],
           [ 6,  7,  8,  9, 10, 11]])
    >>> m0, m1 = margins(a)
    >>> m0
    array([[15],
           [51]])
    >>> m1
    array([[ 6,  8, 10, 12, 14, 16]])

    >>> b = np.arange(24).reshape(2,3,4)
    >>> m0, m1, m2 = margins(b)
    >>> m0
    array([[[ 66]],
           [[210]]])
    >>> m1
    array([[[ 60],
            [ 92],
            [124]]])
    >>> m2
    array([[[60, 66, 72, 78]]])


<EOL>observed = np.asarray(observed, dtype=np.float64)<EOL>margsums = margins(observed)<EOL>d = observed.ndim<EOL>expected = reduce(np.multiply, margsums) / observed.sum() ** (d - <NUM_LIT:1>)<EOL>return expected<EOL>

Compute the expected frequencies from a contingency table.

Given an n-dimensional contingency table of observed frequencies,
compute the expected frequencies for the table based on the marginal
sums under the assumption that the groups associated with each
dimension are independent.

Parameters
----------
observed : array_like
    The table of observed frequencies.  (While this function can handle
    a 1-D array, that case is trivial.  Generally `observed` is at
    least 2-D.)

Returns
-------
expected : ndarray of float64
    The expected frequencies, based on the marginal sums of the table.
    Same shape as `observed`.

Examples
--------
>>> observed = np.array([[10, 10, 20],[20, 20, 20]])
>>> expected_freq(observed)
array([[ 12.,  12.,  16.],
       [ 18.,  18.,  24.]])


def chi2_contingency(observed, correction=True, lambda_=None):

observed = np.asarray(observed)<EOL>if np.any(observed < <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if observed.size == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>expected = expected_freq(observed)<EOL>if np.any(expected == <NUM_LIT:0>):<EOL><INDENT>zeropos = list(zip(*np.where(expected == <NUM_LIT:0>)))[<NUM_LIT:0>]<EOL>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (zeropos,))<EOL><DEDENT>dof = expected.size - sum(expected.shape) + expected.ndim - <NUM_LIT:1><EOL>if dof == <NUM_LIT:0>:<EOL><INDENT>chi2 = <NUM_LIT:0.0><EOL>p = <NUM_LIT:1.0><EOL><DEDENT>else:<EOL><INDENT>if dof == <NUM_LIT:1> and correction:<EOL><INDENT>observed = observed + <NUM_LIT:0.5> * np.sign(expected - observed)<EOL><DEDENT>chi2, p = power_divergence(observed, expected,<EOL>ddof=observed.size - <NUM_LIT:1> - dof, axis=None,<EOL>lambda_=lambda_)<EOL><DEDENT>return chi2, p, dof, expected<EOL>

Chi-square test of independence of variables in a contingency table.

    This function computes the chi-square statistic and p-value for the
    hypothesis test of independence of the observed frequencies in the
    contingency table [1]_ `observed`.  The expected frequencies are computed
    based on the marginal sums under the assumption of independence; see
    `scipy.stats.contingency.expected_freq`.  The number of degrees of
    freedom is (expressed using numpy functions and attributes)::

        dof = observed.size - sum(observed.shape) + observed.ndim - 1

    Parameters
    ----------
    observed : array_like
        The contingency table. The table contains the observed frequencies
        (i.e. number of occurrences) in each category.  In the two-dimensional
        case, the table is often described as an "R x C table".
    correction : bool, optional
        If True, *and* the degrees of freedom is 1, apply Yates' correction
        for continuity.  The effect of the correction is to adjust each
        observed value by 0.5 towards the corresponding expected value.
    lambda_ : float or str, optional.
        By default, the statistic computed in this test is Pearson's
        chi-squared statistic [2]_.  `lambda_` allows a statistic from the
        Cressie-Read power divergence family [3]_ to be used instead.  See
        `power_divergence` for details.

    Returns
    -------
    chi2 : float
        The test statistic.
    p : float
        The p-value of the test
    dof : int
        Degrees of freedom
    expected : ndarray, same shape as `observed`
        The expected frequencies, based on the marginal sums of the table.

    See Also
    --------
    contingency.expected_freq
    fisher_exact
    chisquare
    power_divergence

    Notes
    -----
    An often quoted guideline for the validity of this calculation is that
    the test should be used only if the observed and expected frequency in
    each cell is at least 5.

    This is a test for the independence of different categories of a
    population. The test is only meaningful when the dimension of
    `observed` is two or more.  Applying the test to a one-dimensional
    table will always result in `expected` equal to `observed` and a
    chi-square statistic equal to 0.

    This function does not handle masked arrays, because the calculation
    does not make sense with missing values.

    Like stats.chisquare, this function computes a chi-square statistic;
    the convenience this function provides is to figure out the expected
    frequencies and degrees of freedom from the given contingency table.
    If these were already known, and if the Yates' correction was not
    required, one could use stats.chisquare.  That is, if one calls::

        chi2, p, dof, ex = chi2_contingency(obs, correction=False)

    then the following is true::

        (chi2, p) == stats.chisquare(obs.ravel(), f_exp=ex.ravel(),
                                     ddof=obs.size - 1 - dof)

    The `lambda_` argument was added in version 0.13.0 of scipy.

    References
    ----------
    .. [1] "Contingency table", http://en.wikipedia.org/wiki/Contingency_table
    .. [2] "Pearson's chi-squared test",
           http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
    .. [3] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
           Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
           pp. 440-464.

    Examples
    --------
    A two-way example (2 x 3):

    >>> obs = np.array([[10, 10, 20], [20, 20, 20]])
    >>> chi2_contingency(obs)
    (2.7777777777777777,
     0.24935220877729619,
     2,
     array([[ 12.,  12.,  16.],
            [ 18.,  18.,  24.]]))

    Perform the test using the log-likelihood ratio (i.e. the "G-test")
    instead of Pearson's chi-squared statistic.

    >>> g, p, dof, expctd = chi2_contingency(obs, lambda_="log-likelihood")
    >>> g, p
    (2.7688587616781319, 0.25046668010954165)

    A four-way example (2 x 2 x 2 x 2):

    >>> obs = np.array(
    ...     [[[[12, 17],
    ...        [11, 16]],
    ...       [[11, 12],
    ...        [15, 16]]],
    ...      [[[23, 15],
    ...        [30, 22]],
    ...       [[14, 17],
    ...        [15, 16]]]])
    >>> chi2_contingency(obs)
    (8.7584514426741897,
     0.64417725029295503,
     11,
     array([[[[ 14.15462386,  14.15462386],
              [ 16.49423111,  16.49423111]],
             [[ 11.2461395 ,  11.2461395 ],
              [ 13.10500554,  13.10500554]]],
            [[[ 19.5591166 ,  19.5591166 ],
              [ 22.79202844,  22.79202844]],
             [[ 15.54012004,  15.54012004],
              [ 18.10873492,  18.10873492]]]]))


if uses_accelerate(info) or uses_veclib(info):<EOL><INDENT>return True<EOL><DEDENT>elif uses_mkl(info) and sys.platform == "<STR_LIT>":<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Returns True if g77 ABI wrapper must be used.


wrapper_sources = []<EOL>path = os.path.abspath(os.path.dirname(__file__))<EOL>if needs_g77_abi_wrapper(info):<EOL><INDENT>wrapper_sources += [<EOL>os.path.join(path, '<STR_LIT:src>', '<STR_LIT>'),<EOL>os.path.join(path, '<STR_LIT:src>', '<STR_LIT>'),<EOL>]<EOL>if uses_accelerate(info):<EOL><INDENT>wrapper_sources += [<EOL>os.path.join(path, '<STR_LIT:src>', '<STR_LIT>'),<EOL>os.path.join(path, '<STR_LIT:src>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>elif uses_mkl(info):<EOL><INDENT>wrapper_sources += [<EOL>os.path.join(path, '<STR_LIT:src>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>" % (info,))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>wrapper_sources += [<EOL>os.path.join(path, '<STR_LIT:src>', '<STR_LIT>'),<EOL>os.path.join(path, '<STR_LIT:src>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>return wrapper_sources<EOL>

Returns file names of source files containing Fortran ABI wrapper
routines.


if uses_accelerate(info):<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>


path = os.path.abspath(os.path.dirname(__file__))<EOL>if needs_sgemv_fix(info):<EOL><INDENT>return [os.path.join(path, '<STR_LIT:src>', '<STR_LIT>')]<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT>

Returns source file needed to correct SGEMV


if subroutines is not None:<EOL><INDENT>subroutines = [x.lower() for x in subroutines]<EOL><DEDENT>def split_file(fname):<EOL><INDENT>with open(fname, '<STR_LIT:rb>') as f:<EOL><INDENT>lines = f.readlines()<EOL>subs = []<EOL>need_split_next = True<EOL>for ix, line in enumerate(lines):<EOL><INDENT>m = re.match(b'<STR_LIT>', line, re.I)<EOL>if m and line[<NUM_LIT:0>] not in b'<STR_LIT>':<EOL><INDENT>if subroutines is not None:<EOL><INDENT>subr_name = m.group(<NUM_LIT:1>).decode('<STR_LIT:ascii>').lower()<EOL>subr_wanted = (subr_name in subroutines)<EOL><DEDENT>else:<EOL><INDENT>subr_wanted = True<EOL><DEDENT>if subr_wanted or need_split_next:<EOL><INDENT>need_split_next = subr_wanted<EOL>subs.append(ix)<EOL><DEDENT><DEDENT><DEDENT>if len(subs) <= <NUM_LIT:1>:<EOL><INDENT>return [fname]<EOL><DEDENT>new_fnames = []<EOL>num_files = len(subs)<EOL>for nfile in range(num_files):<EOL><INDENT>new_fname = fname[:-<NUM_LIT:2>] + '<STR_LIT>' + str(nfile) + '<STR_LIT>'<EOL>new_fnames.append(new_fname)<EOL>if not newer(fname, new_fname):<EOL><INDENT>continue<EOL><DEDENT>with open(new_fname, '<STR_LIT:wb>') as fn:<EOL><INDENT>if nfile + <NUM_LIT:1> == num_files:<EOL><INDENT>fn.writelines(lines[subs[nfile]:])<EOL><DEDENT>else:<EOL><INDENT>fn.writelines(lines[subs[nfile]:subs[nfile+<NUM_LIT:1>]])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return new_fnames<EOL><DEDENT>exclude_pattern = re.compile('<STR_LIT>')<EOL>source_fnames = [f for f in glob.glob(os.path.join(source_dir, '<STR_LIT>'))<EOL>if not exclude_pattern.search(os.path.basename(f))]<EOL>fnames = []<EOL>for source_fname in source_fnames:<EOL><INDENT>created_files = split_file(source_fname)<EOL>if created_files is not None:<EOL><INDENT>for cfile in created_files:<EOL><INDENT>fnames.append(os.path.basename(cfile))<EOL><DEDENT><DEDENT><DEDENT>return fnames<EOL>

Split each file in `source_dir` into separate files per subroutine.

    Parameters
    ----------
    source_dir : str
        Full path to directory in which sources to be split are located.
    subroutines : list of str, optional
        Subroutines to split. (Default: all)

    Returns
    -------
    fnames : list of str
        List of file names (not including any path) that were created
        in `source_dir`.

    Notes
    -----
    This function is useful for code that can't be compiled with g77 because of
    type casting errors which do work with gfortran.

    Created files are named: ``original_name + '_subr_i' + '.f'``, with ``i``
    starting at zero and ending at ``num_subroutines_in_file - 1``.


if os.path.exists(temp_storage_dir):<EOL><INDENT>shutil.rmtree(temp_storage_dir)<EOL><DEDENT>os.mkdir(temp_storage_dir)<EOL>file_path1 = os.path.join(os.path.dirname(__file__), '<STR_LIT>')<EOL>self.file1 = self.File(open(file_path1, '<STR_LIT:rb>'), name='<STR_LIT>')<EOL>file_path2 = os.path.join(os.path.dirname(__file__), '<STR_LIT>')<EOL>self.file2 = self.File(open(file_path2, '<STR_LIT:rb>'), name='<STR_LIT>')<EOL>

Creates a pristine temp directory (or deletes and recreates if it
already exists) that the model uses as its storage directory.

Sets up two ImageFile instances for use in tests.


self.file1.close()<EOL>self.file2.close()<EOL>shutil.rmtree(temp_storage_dir)<EOL>

Removes temp directory and all its contents.


def check_dimensions(self, instance, width, height,<EOL>field_name='<STR_LIT>'):

field = getattr(instance, field_name)<EOL>if width is None and height is None:<EOL><INDENT>with self.assertRaises(ValueError):<EOL><INDENT>getattr(field, '<STR_LIT:width>')<EOL><DEDENT>with self.assertRaises(ValueError):<EOL><INDENT>getattr(field, '<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.assertEqual(field.width, width)<EOL>self.assertEqual(field.height, height)<EOL><DEDENT>width_field_name = field_name + '<STR_LIT>'<EOL>if hasattr(instance, width_field_name):<EOL><INDENT>self.assertEqual(getattr(instance, width_field_name), width)<EOL><DEDENT>height_field_name = field_name + '<STR_LIT>'<EOL>if hasattr(instance, height_field_name):<EOL><INDENT>self.assertEqual(getattr(instance, height_field_name), height)<EOL><DEDENT>

Asserts that the given width and height values match both the
field's height and width attributes and the height and width fields
(if defined) the image field is caching to.

Note, this method will check for dimension fields named by adding
"_width" or "_height" to the name of the ImageField.  So, the
models used in these tests must have their fields named
accordingly.

By default, we check the field named "mugshot", but this can be
specified by passing the field_name parameter.


def _mock_subprocess_call(*args):<EOL><INDENT>self.subprocess_args = list(*args)<EOL>if '<STR_LIT>' in os.environ:<EOL><INDENT>with open(os.environ['<STR_LIT>'], '<STR_LIT:r>') as f:<EOL><INDENT>self.pgpass = f.read().strip()  <EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.pgpass = None<EOL><DEDENT>return <NUM_LIT:0><EOL><DEDENT>self.subprocess_args = None<EOL>self.pgpass = None<EOL>with mock.patch('<STR_LIT>', new=_mock_subprocess_call):<EOL><INDENT>DatabaseClient.runshell_db(dbinfo)<EOL><DEDENT>return self.subprocess_args, self.pgpass<EOL>

That function invokes the runshell command, while mocking
subprocess.call. It returns a 2-tuple with:
- The command line list
- The content of the file pointed by environment PGPASSFILE, or None.


storage.request.session[storage.session_key] = storage.serialize_messages(messages)<EOL>if hasattr(storage, '<STR_LIT>'):<EOL><INDENT>del storage._loaded_data<EOL><DEDENT>

Sets the messages into the backend request's session and remove the
backend's loaded data cache.


storage.add(constants.INFO, '<STR_LIT>')<EOL>storage.add(<NUM_LIT>, '<STR_LIT>')<EOL>storage.add(constants.DEBUG, '<STR_LIT>', extra_tags='<STR_LIT>')<EOL>storage.add(constants.WARNING, '<STR_LIT>')<EOL>storage.add(constants.ERROR, '<STR_LIT>')<EOL>storage.add(constants.SUCCESS, '<STR_LIT>')<EOL>

Add 6 messages from different levels (including a custom one) to a storage
instance.


storage = self.storage_class(self.get_request())<EOL>storage._loaded_data = data or []<EOL>return storage<EOL>

Return the storage backend, setting its loaded data to the ``data``
argument.

This method avoids the storage ``_get`` method from getting called so
that other parts of the storage backend can be tested independent of
the message retrieval logic.


def stored_messages_count(self, storage, response):

raise NotImplementedError('<STR_LIT>')<EOL>

Return the number of messages being stored after a
``storage.update()`` call.


def set_cookie_data(storage, messages, invalid=False, encode_empty=False):

encoded_data = storage._encode(messages, encode_empty=encode_empty)<EOL>if invalid:<EOL><INDENT>encoded_data = encoded_data[<NUM_LIT:1>:]<EOL><DEDENT>storage.request.COOKIES = {CookieStorage.cookie_name: encoded_data}<EOL>if hasattr(storage, '<STR_LIT>'):<EOL><INDENT>del storage._loaded_data<EOL><DEDENT>

Set ``request.COOKIES`` with the encoded data and remove the storage
backend's loaded data cache.


<EOL>cookie = response.cookies.get(storage.cookie_name)<EOL>if not cookie or cookie['<STR_LIT>'] == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>data = storage._decode(cookie.value)<EOL>if not data:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if data[-<NUM_LIT:1>] == CookieStorage.not_finished:<EOL><INDENT>data.pop()<EOL><DEDENT>return len(data)<EOL>

Return an integer containing the number of messages stored.


return (<EOL>self.stored_cookie_messages_count(storage, response) +<EOL>self.stored_session_messages_count(storage, response)<EOL>)<EOL>

Return the storage totals from both cookie and session backends.


def custom_key_func(key, key_prefix, version):

return '<STR_LIT>' + '<STR_LIT:->'.join([key_prefix, str(version), key])<EOL>


def has_change_permission(self, request, obj=None):

return request.user.is_staff and (obj is not None) and (obj.id % <NUM_LIT:2> == <NUM_LIT:0>)<EOL>

Only allow changing objects with even id number


return self.name<EOL>

A property that simply returns the name. Used to test #24461


ct = ContentType.objects.get_for_model(Model)<EOL>return Permission.objects.get(content_type=ct, codename=perm)<EOL>

Return the permission object, for the Model


admin_form = response.context['<STR_LIT>']<EOL>fieldsets = list(admin_form)<EOL>field_lines = []<EOL>for fieldset in fieldsets:<EOL><INDENT>field_lines += list(fieldset)<EOL><DEDENT>fields = []<EOL>for field_line in field_lines:<EOL><INDENT>fields += list(field_line)<EOL><DEDENT>return fields<EOL>

Return a list of AdminFields for the AdminForm in the response.


return [f for f in self.get_admin_form_fields(response) if f.is_readonly]<EOL>

Return the readonly fields for the response's AdminForm.


def get_admin_readonly_field(self, response, field_name):

admin_readonly_fields = self.get_admin_readonly_fields(response)<EOL>for field in admin_readonly_fields:<EOL><INDENT>if field.field['<STR_LIT:name>'] == field_name:<EOL><INDENT>return field<EOL><DEDENT><DEDENT>

Return the readonly field for the given field_name.


def assertContentBefore(self, response, text1, text2, failing_msg=None):

self.assertEqual(response.status_code, <NUM_LIT:200>)<EOL>self.assertLess(<EOL>response.content.index(text1.encode()),<EOL>response.content.index(text2.encode()),<EOL>(failing_msg or '<STR_LIT>') + '<STR_LIT>' + response.content.decode(response.charset)<EOL>)<EOL>

Testing utility asserting that text1 appears before text2 in response
content.


def assert_non_localized_year(self, response, year):

self.assertNotContains(response, formats.number_format(year))<EOL>

The year is not localized with USE_THOUSAND_SEPARATOR (#15234).


action_data = {<EOL>ACTION_CHECKBOX_NAME: [<NUM_LIT:1>],<EOL>'<STR_LIT:action>': '<STR_LIT>' % level,<EOL>'<STR_LIT:index>': <NUM_LIT:0>,<EOL>}<EOL>response = self.client.post(reverse('<STR_LIT>'),<EOL>action_data, follow=True)<EOL>self.assertContains(response,<EOL>'<STR_LIT>' % (level, level),<EOL>html=True)<EOL>

Helper that sends a post to the dummy test methods and asserts that a
message with the level has appeared in the response.


parsed_url1 = urlparse(url1)<EOL>path1 = parsed_url1.path<EOL>parsed_qs1 = dict(parse_qsl(parsed_url1.query))<EOL>parsed_url2 = urlparse(url2)<EOL>path2 = parsed_url2.path<EOL>parsed_qs2 = dict(parse_qsl(parsed_url2.query))<EOL>for parsed_qs in [parsed_qs1, parsed_qs2]:<EOL><INDENT>if '<STR_LIT>' in parsed_qs:<EOL><INDENT>changelist_filters = parsed_qs['<STR_LIT>']<EOL>parsed_filters = dict(parse_qsl(changelist_filters))<EOL>parsed_qs['<STR_LIT>'] = parsed_filters<EOL><DEDENT><DEDENT>self.assertEqual(path1, path2)<EOL>self.assertEqual(parsed_qs1, parsed_qs2)<EOL>

Assert that two URLs are equal despite the ordering
of their querystring. Refs #22360.


def assertMessageHasHeaders(self, message, headers):

if isinstance(message, bytes):<EOL><INDENT>message = message_from_bytes(message)<EOL><DEDENT>msg_headers = set(message.items())<EOL>self.assertTrue(headers.issubset(msg_headers), msg='<STR_LIT>'<EOL>'<STR_LIT>' % (headers - msg_headers),)<EOL>

Asserts that the `message` has all `headers`.

message: can be an instance of an email.Message subclass or a string
         with the contents of an email message.
headers: should be a set of (header-name, header-value) tuples.


msg_bytes = django_message.message().as_bytes()<EOL>email_message = message_from_bytes(msg_bytes)<EOL>def iter_attachments():<EOL><INDENT>for i in email_message.walk():<EOL><INDENT>if i.get_content_disposition() == '<STR_LIT>':<EOL><INDENT>filename = i.get_filename()<EOL>content = i.get_payload(decode=True)<EOL>mimetype = i.get_content_type()<EOL>yield filename, content, mimetype<EOL><DEDENT><DEDENT><DEDENT>return list(iter_attachments())<EOL>

Encode the specified django.core.mail.message.EmailMessage, then decode
it using Python's email.parser module and, for each attachment of the
message, return a list of tuples with (filename, content, mimetype).


return [url for url in super().get_urls() if url.name != name]<EOL>

Remove all entries named 'name' from the ModelAdmin instance URL
patterns list


pass<EOL>


def verify_unsafe_response(self, view, check_for_vars=True,<EOL>check_for_POST_params=True):

request = self.rf.post('<STR_LIT>', self.breakfast_data)<EOL>response = view(request)<EOL>if check_for_vars:<EOL><INDENT>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL><DEDENT>if check_for_POST_params:<EOL><INDENT>for k, v in self.breakfast_data.items():<EOL><INDENT>self.assertContains(response, k, status_code=<NUM_LIT>)<EOL>self.assertContains(response, v, status_code=<NUM_LIT>)<EOL><DEDENT><DEDENT>

Asserts that potentially sensitive info are displayed in the response.


def verify_safe_response(self, view, check_for_vars=True,<EOL>check_for_POST_params=True):

request = self.rf.post('<STR_LIT>', self.breakfast_data)<EOL>response = view(request)<EOL>if check_for_vars:<EOL><INDENT>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertNotContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL><DEDENT>if check_for_POST_params:<EOL><INDENT>for k in self.breakfast_data:<EOL><INDENT>self.assertContains(response, k, status_code=<NUM_LIT>)<EOL><DEDENT>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertNotContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertNotContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL><DEDENT>

Asserts that certain sensitive info are not displayed in the response.


def verify_paranoid_response(self, view, check_for_vars=True,<EOL>check_for_POST_params=True):

request = self.rf.post('<STR_LIT>', self.breakfast_data)<EOL>response = view(request)<EOL>if check_for_vars:<EOL><INDENT>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertNotContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL>self.assertNotContains(response, '<STR_LIT>', status_code=<NUM_LIT>)<EOL><DEDENT>if check_for_POST_params:<EOL><INDENT>for k, v in self.breakfast_data.items():<EOL><INDENT>self.assertContains(response, k, status_code=<NUM_LIT>)<EOL>self.assertNotContains(response, v, status_code=<NUM_LIT>)<EOL><DEDENT><DEDENT>

Asserts that no variables or POST parameters are displayed in the response.


def verify_unsafe_email(self, view, check_for_POST_params=True):

with self.settings(ADMINS=[('<STR_LIT>', '<STR_LIT>')]):<EOL><INDENT>mail.outbox = []  <EOL>request = self.rf.post('<STR_LIT>', self.breakfast_data)<EOL>view(request)<EOL>self.assertEqual(len(mail.outbox), <NUM_LIT:1>)<EOL>email = mail.outbox[<NUM_LIT:0>]<EOL>body_plain = str(email.body)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>body_html = str(email.alternatives[<NUM_LIT:0>][<NUM_LIT:0>])<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>if check_for_POST_params:<EOL><INDENT>for k, v in self.breakfast_data.items():<EOL><INDENT>self.assertIn(k, body_plain)<EOL>self.assertIn(v, body_plain)<EOL>self.assertIn(k, body_html)<EOL>self.assertIn(v, body_html)<EOL><DEDENT><DEDENT><DEDENT>

Asserts that potentially sensitive info are displayed in the email report.


def verify_safe_email(self, view, check_for_POST_params=True):

with self.settings(ADMINS=[('<STR_LIT>', '<STR_LIT>')]):<EOL><INDENT>mail.outbox = []  <EOL>request = self.rf.post('<STR_LIT>', self.breakfast_data)<EOL>view(request)<EOL>self.assertEqual(len(mail.outbox), <NUM_LIT:1>)<EOL>email = mail.outbox[<NUM_LIT:0>]<EOL>body_plain = str(email.body)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>body_html = str(email.alternatives[<NUM_LIT:0>][<NUM_LIT:0>])<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>self.assertNotIn('<STR_LIT>', body_html)<EOL>if check_for_POST_params:<EOL><INDENT>for k in self.breakfast_data:<EOL><INDENT>self.assertIn(k, body_plain)<EOL><DEDENT>self.assertIn('<STR_LIT>', body_plain)<EOL>self.assertIn('<STR_LIT>', body_plain)<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>self.assertIn('<STR_LIT>', body_html)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>self.assertNotIn('<STR_LIT>', body_plain)<EOL>self.assertNotIn('<STR_LIT>', body_html)<EOL>self.assertNotIn('<STR_LIT>', body_html)<EOL><DEDENT><DEDENT>

Asserts that certain sensitive info are not displayed in the email report.


with self.settings(ADMINS=[('<STR_LIT>', '<STR_LIT>')]):<EOL><INDENT>mail.outbox = []  <EOL>request = self.rf.post('<STR_LIT>', self.breakfast_data)<EOL>view(request)<EOL>self.assertEqual(len(mail.outbox), <NUM_LIT:1>)<EOL>email = mail.outbox[<NUM_LIT:0>]<EOL>body = str(email.body)<EOL>self.assertNotIn('<STR_LIT>', body)<EOL>self.assertNotIn('<STR_LIT>', body)<EOL>self.assertNotIn('<STR_LIT>', body)<EOL>self.assertNotIn('<STR_LIT>', body)<EOL>for k, v in self.breakfast_data.items():<EOL><INDENT>self.assertIn(k, body)<EOL>self.assertNotIn(v, body)<EOL><DEDENT><DEDENT>

Asserts that no variables or POST parameters are displayed in the email report.


current_language = get_language()<EOL>return [code for code, name in settings.LANGUAGES if not code == current_language][<NUM_LIT:0>]<EOL>

Return language code for a language which is not activated.


return HttpResponse('<STR_LIT>')<EOL>


from django.core.management import call_command<EOL>prev_cwd = os.getcwd()<EOL>os.chdir(proj_dir)<EOL>call_command('<STR_LIT>')<EOL>call_command('<STR_LIT>')<EOL>pofile = os.path.join(proj_dir, '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>with open(pofile) as f:<EOL><INDENT>content = f.read()<EOL><DEDENT>content = re.sub(r'<STR_LIT>', '<STR_LIT>', content, flags=re.MULTILINE)<EOL>with open(pofile, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(content)<EOL><DEDENT>os.chdir(prev_cwd)<EOL>

Run makemessages and compilemessages in sampleproject.


def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):

return self._assertPoLocComment(True, po_filename, line_number, *comment_parts)<EOL>

r"""
        self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py')

        verifies that the django.po file has a gettext-style location comment of the form

        `#: dirA/dirB/foo.py:42`

        (or `#: .\dirA\dirB\foo.py:42` on Windows)

        None can be passed for the line_number argument to skip checking of
        the :42 suffix part.
        A string token can also be passed as line_number, in which case it
        will be searched in the template, and its line number will be used.
        A msgid is a suitable candidate.


def assertLocationCommentNotPresent(self, po_filename, line_number, *comment_parts):

return self._assertPoLocComment(False, po_filename, line_number, *comment_parts)<EOL>

Check the opposite of assertLocationComment()


delta = time.time() - os.stat(path).st_mtime<EOL>self.assertLess(delta, <NUM_LIT:10>, "<STR_LIT>" % path)<EOL>

Assert that file was recently modified (modification time was less than 10 seconds ago).


delta = time.time() - os.stat(path).st_mtime<EOL>self.assertGreater(delta, <NUM_LIT:10>, "<STR_LIT>" % path)<EOL>

Assert that file was not recently modified (modification time was more than 10 seconds ago).


for locale in self.LOCALES:<EOL><INDENT>os.utime(self.PO_FILE % locale, (<NUM_LIT:0>, <NUM_LIT:0>))<EOL><DEDENT>

Set access and modification times to the Unix epoch time for all the .po files.


def get_available_name(self, name, max_length=None):

parts = name.split('<STR_LIT:.>')<EOL>basename, ext = parts[<NUM_LIT:0>], parts[<NUM_LIT:1>:]<EOL>number = <NUM_LIT:2><EOL>while self.exists(name):<EOL><INDENT>name = '<STR_LIT:.>'.join([basename, str(number)] + ext)<EOL>number += <NUM_LIT:1><EOL><DEDENT>return name<EOL>

Append numbers to duplicate files rather than underscores, like Trac.


dir_to_test = storage.location<EOL>while not os.path.exists(dir_to_test):<EOL><INDENT>dir_to_test = os.path.dirname(dir_to_test)<EOL><DEDENT>try:<EOL><INDENT>return os.pathconf(dir_to_test, '<STR_LIT>')<EOL><DEDENT>except Exception:<EOL><INDENT>return <NUM_LIT:255><EOL><DEDENT>

Query filesystem for maximum filename length (e.g. AUFS has 242).


return name<EOL>

This method is important to test that Storage.save() doesn't replace
'\' with '/' (rather FileSystemStorage.save() does).


return self.prefix + self.get_valid_name(filename)<EOL>

This is the method that's important to override when using S3 so that
os.path() isn't called, which would break S3 keys.


@classmethod<EOL><INDENT>def traverse_qs(cls, obj_iter, path):<DEDENT>

ret_val = []<EOL>if hasattr(obj_iter, '<STR_LIT:all>'):<EOL><INDENT>obj_iter = obj_iter.all()<EOL><DEDENT>try:<EOL><INDENT>iter(obj_iter)<EOL><DEDENT>except TypeError:<EOL><INDENT>obj_iter = [obj_iter]<EOL><DEDENT>for obj in obj_iter:<EOL><INDENT>rel_objs = []<EOL>for part in path:<EOL><INDENT>if not part:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>related = getattr(obj, part[<NUM_LIT:0>])<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>continue<EOL><DEDENT>if related is not None:<EOL><INDENT>rel_objs.extend(cls.traverse_qs(related, [part[<NUM_LIT:1>:]]))<EOL><DEDENT><DEDENT>ret_val.append((obj, rel_objs))<EOL><DEDENT>return ret_val<EOL>

Helper method that returns a list containing a list of the objects in the
obj_iter. Then for each object in the obj_iter, the path will be
recursively travelled and the found objects are added to the return value.


def assertIsInvalidRegexp(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None):

invalid_obj = invalid_obj or model_admin<EOL>admin_obj = model_admin(model, AdminSite())<EOL>errors = admin_obj.check()<EOL>self.assertEqual(len(errors), <NUM_LIT:1>)<EOL>error = errors[<NUM_LIT:0>]<EOL>self.assertEqual(error.hint, hint)<EOL>self.assertEqual(error.obj, invalid_obj)<EOL>self.assertEqual(error.id, id)<EOL>self.assertRegex(error.msg, msg)<EOL>

Same as assertIsInvalid but treats the given msg as a regexp.


def _assert_allows(self, response, *expected_methods):

response_allows = set(response['<STR_LIT>'].split('<STR_LIT:U+002CU+0020>'))<EOL>self.assertEqual(set(expected_methods + ('<STR_LIT>',)), response_allows)<EOL>

Assert allowed HTTP methods reported in the Allow response header


return self._get_full_name()<EOL>


if model._meta.app_label == '<STR_LIT>':<EOL><INDENT>return '<STR_LIT:default>'<EOL><DEDENT>return None<EOL>

Point all read operations on auth models to 'default


if model._meta.app_label == '<STR_LIT>':<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return None<EOL>

Point all operations on auth models to 'other


def allow_relation(self, obj1, obj2, **hints):

return obj1._meta.app_label == '<STR_LIT>' or obj2._meta.app_label == '<STR_LIT>' or None<EOL>

Allow any relation if a model in Auth is involved


def allow_migrate(self, db, app_label, **hints):

if app_label == '<STR_LIT>':<EOL><INDENT>return db == '<STR_LIT>'<EOL><DEDENT>return None<EOL>

Make sure the auth app only appears on the 'other' db


self.data = <NUM_LIT><EOL>super().save(*args, **kwargs)<EOL>

A save method that modifies the data in the object.
A user-defined save() method isn't called when objects are deserialized
(#4459).


super().setUpClass()<EOL>cls._import_module_mock = YamlImportModuleMock()<EOL>importlib.import_module = cls._import_module_mock.import_module<EOL>serializers._serializers = {}<EOL>

Removes imported yaml and stubs importlib.import_module