gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, dist, *args, **kwds):
    self.args = args
    self.kwds = kwds

    # create a new instance
    self.dist = dist.__class__(**dist._updated_ctor_param())

    shapes, _, _ = self.dist._parse_args(*args, **kwds)
    self.dist._argcheck(*shapes)
    self.a, self.b = self.dist._get_support(*args, **kwds)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5917b24eb1bb> in <module>
----> 1 reciprocal(a=0.00623, b=1.01, loc=2, scale=3)

~/miniconda3/envs/scipy-dev/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py in __call__(self, *args, **kwds)
769
770     def __call__(self, *args, **kwds):
--> 771         return self.freeze(*args, **kwds)
772     __call__.__doc__ = freeze.__doc__
773

~/miniconda3/envs/scipy-dev/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py in freeze(self, *args, **kwds)
766
767         """
--> 768         return rv_frozen(self, *args, **kwds)
769
770     def __call__(self, *args, **kwds):

~/miniconda3/envs/scipy-dev/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py in __init__(self, dist, *args, **kwds)
430         shapes, _, _ = self.dist._parse_args(*args, **kwds)
431         self.dist._argcheck(*shapes)
--> 432         self.a, self.b = self.dist._get_support(*args, **kwds)
433
434     @property

TypeError: _get_support() got an unexpected keyword argument 'loc'

# Fixed code
def __init__(self, dist, *args, **kwds):
    self.args = args
    self.kwds = kwds

    # create a new instance
    self.dist = dist.__class__(**dist._updated_ctor_param())

    shapes, _, _ = self.dist._parse_args(*args, **kwds)
    self.dist._argcheck(*shapes)
    self.a, self.b = self.dist._get_support(*shapes)
# Buggy code
def fit(self, data, **kwds):
    floc = kwds.pop("floc", None)
    fscale = kwds.pop("fscale", None)

    _remove_optimizer_parameters(kwds)

    if floc is not None and fscale is not None:
        # This check is for consistency with `rv_continuous.fit`.
        # Without this check, this function would just return the
        # parameters that were given.
        raise ValueError("All parameters fixed. There is nothing to optimize.")

    data = np.asarray(data)

    if floc is None:
        loc = data.mean()
    else:
        loc = floc

    if fscale is None:
        scale = np.sqrt(((data - loc) ** 2).mean())
    else:
        scale = fscale

    return loc, scale


# Traceback (RuntimeError)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-86-fb3d43a0acaa> in <module>
13        1.5754, 2.2669, 1.6383, 1.7696, 1.9079, 1.0955, 1.5637, 2.66  ,
14        1.746 , 1.5319, 2.0958,    np.nan])
---> 15 K = stats.exponnorm.fit(x)

/anaconda3/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py in fit(self, data, *args, **kwds)
2195                                          'scale' in kwds):
2196             # get distribution specific starting locations
-> 2197             start = self._fitstart(data)
2198             args += start[Narg:-2]
2199         loc = kwds.pop('loc', start[-2])

/anaconda3/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py in _fitstart(self, data, args)
2034         if args is None:
2035             args = (1.0,)*self.numargs
-> 2036         loc, scale = self._fit_loc_scale_support(data, *args)
2037         return args + (loc, scale)
2038

/anaconda3/lib/python3.7/site-packages/scipy/stats/_distn_infrastructure.py in _fit_loc_scale_support(self, data, *args)
2287             return (data_b - b) + margin, 1
2288         else:
-> 2289             raise RuntimeError
2290
2291     def fit_loc_scale(self, data, *args):

RuntimeError:

# Fixed code
def fit(self, data, **kwds):
    floc = kwds.pop("floc", None)
    fscale = kwds.pop("fscale", None)

    _remove_optimizer_parameters(kwds)

    if floc is not None and fscale is not None:
        # This check is for consistency with `rv_continuous.fit`.
        # Without this check, this function would just return the
        # parameters that were given.
        raise ValueError("All parameters fixed. There is nothing to optimize.")

    data = np.asarray(data)

    if not np.isfinite(data).all():
        raise RuntimeError("The data contains non-finite values.")

    if floc is None:
        loc = data.mean()
    else:
        loc = floc

    if fscale is None:
        scale = np.sqrt(((data - loc) ** 2).mean())
    else:
        scale = fscale

    return loc, scale
# Buggy code
def _report_nonhermitian(M, a, b, name):
    """
    Report if `M` is not a hermitian matrix given the tolerances `a`, `b`.
    """
    from scipy.linalg import norm

    md = M - M.T.conj()

    nmd = norm(md, 1)
    tol = np.spacing(max(10**a, (10**b) * norm(M, 1)))
    if nmd > tol:
        print("matrix %s is not sufficiently Hermitian for a=%d, b=%d:" % (name, a, b))
        print("condition: %.e < %e" % (nmd, tol))


# Traceback (numpy.linalg.LinAlgError)
Traceback (most recent call last):
File "./test_lobpcg.py", line 47, in <module>
test_lobpcg(read_guess=True)
File "./test_lobpcg.py", line 39, in test_lobpcg
λ, v = lobpcg(A, X, largest=False, M=P, maxiter=100, tol=tol)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py", line 476, in lobpcg
aux = _b_orthonormalize(B, activeBlockVectorP, retInvR=True)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py", line 93, in _b_orthonormalize
gramVBV = cholesky(gramVBV)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/linalg/decomp_cholesky.py", line 91, in cholesky
check_finite=check_finite)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/linalg/decomp_cholesky.py", line 40, in _cholesky
"definite" % info)
numpy.linalg.LinAlgError: 9-th leading minor of the array is not positive definite

# Fixed code
def _report_nonhermitian(M, name):
    """
    Report if `M` is not a hermitian matrix given its type.
    """
    from scipy.linalg import norm

    md = M - M.T.conj()

    nmd = norm(md, 1)
    tol = 10 * np.finfo(M.dtype).eps
    tol = max(tol, tol * norm(M, 1))
    if nmd > tol:
        print(
            "matrix %s of the type %s is not sufficiently Hermitian:" % (name, M.dtype)
        )
        print("condition: %.e < %e" % (nmd, tol))
# Buggy code
def _applyConstraints(blockVectorV, factYBY, blockVectorBY, blockVectorY):
    """Changes blockVectorV in place."""
    gramYBV = np.dot(blockVectorBY.T.conj(), blockVectorV)
    tmp = cho_solve(factYBY, gramYBV)
    blockVectorV -= np.dot(blockVectorY, tmp)


# Traceback (numpy.linalg.LinAlgError)
Traceback (most recent call last):
File "./test_lobpcg.py", line 47, in <module>
test_lobpcg(read_guess=True)
File "./test_lobpcg.py", line 39, in test_lobpcg
λ, v = lobpcg(A, X, largest=False, M=P, maxiter=100, tol=tol)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py", line 476, in lobpcg
aux = _b_orthonormalize(B, activeBlockVectorP, retInvR=True)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py", line 93, in _b_orthonormalize
gramVBV = cholesky(gramVBV)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/linalg/decomp_cholesky.py", line 91, in cholesky
check_finite=check_finite)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/linalg/decomp_cholesky.py", line 40, in _cholesky
"definite" % info)
numpy.linalg.LinAlgError: 9-th leading minor of the array is not positive definite

# Fixed code
def _applyConstraints(blockVectorV, factYBY, blockVectorBY, blockVectorY):
    """Changes blockVectorV in place."""
    YBV = np.dot(blockVectorBY.T.conj(), blockVectorV)
    tmp = cho_solve(factYBY, YBV)
    blockVectorV -= np.dot(blockVectorY, tmp)
# Buggy code
def _b_orthonormalize(B, blockVectorV, blockVectorBV=None, retInvR=False):
    if blockVectorBV is None:
        if B is not None:
            blockVectorBV = B(blockVectorV)
        else:
            blockVectorBV = blockVectorV  # Shared data!!!
    gramVBV = np.dot(blockVectorV.T.conj(), blockVectorBV)
    gramVBV = cholesky(gramVBV)
    gramVBV = inv(gramVBV, overwrite_a=True)
    # gramVBV is now R^{-1}.
    blockVectorV = np.dot(blockVectorV, gramVBV)
    if B is not None:
        blockVectorBV = np.dot(blockVectorBV, gramVBV)
    else:
        blockVectorBV = None

    if retInvR:
        return blockVectorV, blockVectorBV, gramVBV
    else:
        return blockVectorV, blockVectorBV


# Traceback (numpy.linalg.LinAlgError)
Traceback (most recent call last):
File "./test_lobpcg.py", line 47, in <module>
test_lobpcg(read_guess=True)
File "./test_lobpcg.py", line 39, in test_lobpcg
λ, v = lobpcg(A, X, largest=False, M=P, maxiter=100, tol=tol)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py", line 476, in lobpcg
aux = _b_orthonormalize(B, activeBlockVectorP, retInvR=True)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.py", line 93, in _b_orthonormalize
gramVBV = cholesky(gramVBV)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/linalg/decomp_cholesky.py", line 91, in cholesky
check_finite=check_finite)
File "/home/mfh/.julia/python_virtualenv/lib/python3.7/site-packages/scipy/linalg/decomp_cholesky.py", line 40, in _cholesky
"definite" % info)
numpy.linalg.LinAlgError: 9-th leading minor of the array is not positive definite

# Fixed code
def _b_orthonormalize(B, blockVectorV, blockVectorBV=None, retInvR=False):
    """B-orthonormalize the given block vector using Cholesky."""
    normalization = blockVectorV.max(axis=0) + np.finfo(blockVectorV.dtype).eps
    blockVectorV = blockVectorV / normalization
    if blockVectorBV is None:
        if B is not None:
            blockVectorBV = B(blockVectorV)
        else:
            blockVectorBV = blockVectorV  # Shared data!!!
    else:
        blockVectorBV = blockVectorBV / normalization
    VBV = np.matmul(blockVectorV.T.conj(), blockVectorBV)
    try:
        # VBV is a Cholesky factor from now on...
        VBV = cholesky(VBV, overwrite_a=True)
        VBV = inv(VBV, overwrite_a=True)
        blockVectorV = np.matmul(blockVectorV, VBV)
        # blockVectorV = (cho_solve((VBV.T, True), blockVectorV.T)).T
        if B is not None:
            blockVectorBV = np.matmul(blockVectorBV, VBV)
            # blockVectorBV = (cho_solve((VBV.T, True), blockVectorBV.T)).T
        else:
            blockVectorBV = None
    except LinAlgError:
        # raise ValueError('Cholesky has failed')
        blockVectorV = None
        blockVectorBV = None
        VBV = None

    if retInvR:
        return blockVectorV, blockVectorBV, VBV, normalization
    else:
        return blockVectorV, blockVectorBV
# Buggy code
def _contains_nan(a, nan_policy="propagate"):
    policies = ["propagate", "raise", "omit"]
    if nan_policy not in policies:
        raise ValueError(
            "nan_policy must be one of {%s}" % ", ".join("'%s'" % s for s in policies)
        )
    try:
        # Calling np.sum to avoid creating a huge array into memory
        # e.g. np.isnan(a).any()
        with np.errstate(invalid="ignore"):
            contains_nan = np.isnan(np.sum(a))
    except TypeError:
        # If the check cannot be properly performed we fallback to omitting
        # nan values and raising a warning. This can happen when attempting to
        # sum things that are not numbers (e.g. as in the function `mode`).
        contains_nan = False
        nan_policy = "omit"
        warnings.warn(
            "The input array could not be properly checked for nan "
            "values. nan values will be ignored.",
            RuntimeWarning,
        )

    if contains_nan and nan_policy == "raise":
        raise ValueError("The input contains nan values")

    return (contains_nan, nan_policy)


# Traceback (TypeError)
Traceback (most recent call last):
File ".../venv/lib/python3.7/site-packages/scipy/stats/stats.py", line 442, in mode
if (NumpyVersion(np.__version__) < '1.9.0') or (a.dtype == object and np.nan in set(a)):
TypeError: unhashable type: 'numpy.ndarray'

# Fixed code
def _contains_nan(a, nan_policy="propagate"):
    policies = ["propagate", "raise", "omit"]
    if nan_policy not in policies:
        raise ValueError(
            "nan_policy must be one of {%s}" % ", ".join("'%s'" % s for s in policies)
        )
    try:
        # Calling np.sum to avoid creating a huge array into memory
        # e.g. np.isnan(a).any()
        with np.errstate(invalid="ignore"):
            contains_nan = np.isnan(np.sum(a))
    except TypeError:
        # This can happen when attempting to sum things which are not
        # numbers (e.g. as in the function `mode`). Try an alternative method:
        try:
            contains_nan = np.nan in set(a.ravel())
        except TypeError:
            # Don't know what to do. Fall back to omitting nan values and
            # issue a warning.
            contains_nan = False
            nan_policy = "omit"
            warnings.warn(
                "The input array could not be properly checked for nan "
                "values. nan values will be ignored.",
                RuntimeWarning,
            )

    if contains_nan and nan_policy == "raise":
        raise ValueError("The input contains nan values")

    return (contains_nan, nan_policy)
# Buggy code
def build_extension(self, ext):
    # When compiling with GNU compilers, use a version script to
    # hide symbols during linking.
    if self.__is_using_gnu_linker(ext):
        export_symbols = self.get_export_symbols(ext)
        text = "{global: %s; local: *; };" % (";".join(export_symbols),)

        script_fn = os.path.join(
            self.build_temp, "link-version-{}.map".format(ext.name)
        )
        with open(script_fn, "w") as f:
            f.write(text)
            ext.extra_link_args.append("-Wl,--version-script=" + script_fn)

    old_build_ext.build_extension(self, ext)


# Traceback (AttributeError)
<<Output from 'import sys, scipy, numpy; print(scipy.__version__, numpy.__version__, sys.version_info)'>>

Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: module 'scipy' has no attribute '__version__'

# Fixed code
def build_extension(self, ext):
    # When compiling with GNU compilers, use a version script to
    # hide symbols during linking.
    if self.__is_using_gnu_linker(ext):
        export_symbols = self.get_export_symbols(ext)
        text = "{global: %s; local: *; };" % (";".join(export_symbols),)

        script_fn = os.path.join(
            self.build_temp, "link-version-{}.map".format(ext.name)
        )
        with open(script_fn, "w") as f:
            f.write(text)
            # line below fixes gh-8680
            ext.extra_link_args = [
                arg for arg in ext.extra_link_args if not "version-script" in arg
            ]
            ext.extra_link_args.append("-Wl,--version-script=" + script_fn)

    old_build_ext.build_extension(self, ext)
# Buggy code
def entropy(self, *args, **kwds):
    """
    Differential entropy of the RV.

    Parameters
    ----------
    arg1, arg2, arg3,... : array_like
        The shape parameter(s) for the distribution (see docstring of the
        instance object for more information).
    loc : array_like, optional
        Location parameter (default=0).
    scale : array_like, optional  (continuous distributions only).
        Scale parameter (default=1).

    Notes
    -----
    Entropy is defined base `e`:

    >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
    >>> np.allclose(drv.entropy(), np.log(2.0))
    True

    """
    args, loc, scale = self._parse_args(*args, **kwds)
    # NB: for discrete distributions scale=1 by construction in _parse_args
    args = tuple(map(asarray, args))
    cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
    output = zeros(shape(cond0), "d")
    place(output, (1 - cond0), self.badvalue)
    goodargs = argsreduce(cond0, *args)
    place(output, cond0, self.vecentropy(*goodargs) + log(scale))
    return output


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/tos/py/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py", line 499, in entropy
return self.dist.entropy(*self.args, **self.kwds)
File "/Users/tos/py/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py", line 1119, in entropy
place(output, cond0, self.vecentropy(*goodargs) + log(scale))
ValueError: operands could not be broadcast together with shapes (4,) (2,2)

# Fixed code
def entropy(self, *args, **kwds):
    """
    Differential entropy of the RV.

    Parameters
    ----------
    arg1, arg2, arg3,... : array_like
        The shape parameter(s) for the distribution (see docstring of the
        instance object for more information).
    loc : array_like, optional
        Location parameter (default=0).
    scale : array_like, optional  (continuous distributions only).
        Scale parameter (default=1).

    Notes
    -----
    Entropy is defined base `e`:

    >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
    >>> np.allclose(drv.entropy(), np.log(2.0))
    True

    """
    args, loc, scale = self._parse_args(*args, **kwds)
    # NB: for discrete distributions scale=1 by construction in _parse_args
    loc, scale = map(asarray, (loc, scale))
    args = tuple(map(asarray, args))
    cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
    output = zeros(shape(cond0), "d")
    place(output, (1 - cond0), self.badvalue)
    goodargs = argsreduce(cond0, scale, *args)
    goodscale = goodargs[0]
    goodargs = goodargs[1:]
    place(output, cond0, self.vecentropy(*goodargs) + log(goodscale))
    return output
# Buggy code
def _field_template(field, precision):
    return {
        MMFile.FIELD_REAL: "%%.%ie\n" % precision,
        MMFile.FIELD_INTEGER: "%i\n",
        MMFile.FIELD_COMPLEX: "%%.%ie %%.%ie\n" % (precision, precision),
    }.get(field, None)


# Traceback (TypeError)
Traceback (most recent call last):
File "process_data.py", line 161, in <module>
scipy.io.mmwrite( 'matrix', matrix )
File "/usr/lib64/python3.5/site-packages/scipy/io/mmio.py", line 102, in mmwrite
MMFile().write(target, a, comment, field, precision, symmetry)
File "/usr/lib64/python3.5/site-packages/scipy/io/mmio.py", line 448, in write
self._write(stream, a, comment, field, precision,symmetry)
File "/usr/lib64/python3.5/site-packages/scipy/io/mmio.py", line 683, in _write
raise TypeError('unexpected dtype kind ' + kind)
TypeError: unexpected dtype kind u

# Fixed code
def _field_template(field, precision):
    return {
        MMFile.FIELD_REAL: "%%.%ie\n" % precision,
        MMFile.FIELD_INTEGER: "%i\n",
        MMFile.FIELD_UNSIGNED: "%u\n",
        MMFile.FIELD_COMPLEX: "%%.%ie %%.%ie\n" % (precision, precision),
    }.get(field, None)
# Buggy code
def _validate_minkowski_kwargs(X, m, n, **kwargs):
    if "w" in kwargs:
        kwargs["w"] = _convert_to_double(kwargs["w"])
    if "p" not in kwargs:
        kwargs["p"] = 2.0
    return kwargs


# Traceback (ValueError)
ValueErrorTraceback (most recent call last)
<ipython-input-10-71b743bead3a> in <module>()
----> 1 spatial_distance.pdist(arr, metric = 'minkowski', p=1, w=None, V=None, VI=None)

.../lib/python2.7/site-packages/scipy/spatial/distance.pyc in pdist(X, metric, *args, **kwargs)
1732         elif mstr.startswith("test_"):
1733             if mstr in _TEST_METRICS:
-> 1734                 dm = pdist(X, _TEST_METRICS[mstr], **kwargs)
1735             else:
1736                 raise ValueError('Unknown "Test" Distance Metric: %s' % mstr[5:])

.../venv/lib/python2.7/site-packages/scipy/spatial/distance.pyc in pdist(X, metric, *args, **kwargs)
1688         for i in xrange(0, m - 1):
1689             for j in xrange(i + 1, m):
-> 1690                 dm[k] = metric(X[i], X[j], **kwargs)
1691                 k = k + 1
1692

.../venv/lib/python2.7/site-packages/scipy/spatial/distance.pyc in minkowski(u, v, p, w)
479             root_w = np.power(w, 1/p)
480         u_v = root_w * u_v
--> 481     dist = norm(u_v, ord=p)
482     return dist
483

.../venv/lib/python2.7/site-packages/scipy/linalg/misc.pyc in norm(a, ord, axis, keepdims)
127     """
128     # Differs from numpy only in non-finite handling and the use of blas.
--> 129     a = np.asarray_chkfinite(a)
130
131     # Only use optimized norms if axis and keepdims are not specified.

.../venv/lib/python2.7/site-packages/numpy/lib/function_base.pyc in asarray_chkfinite(a, dtype, order)
1213     if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all():
1214         raise ValueError(
-> 1215             "array must not contain infs or NaNs")
1216     return a
1217

ValueError: array must not contain infs or NaNs

# Fixed code
def _validate_minkowski_kwargs(X, m, n, **kwargs):
    if "p" not in kwargs:
        kwargs["p"] = 2.0
    return kwargs
# Buggy code
def _validate_weights(w, dtype=None):
    w = _validate_vector(w, dtype=dtype)
    if np.any(w < 0):
        raise ValueError("Input weights should be all non-negative")
    return w


# Traceback (ValueError)
ValueErrorTraceback (most recent call last)
<ipython-input-10-71b743bead3a> in <module>()
----> 1 spatial_distance.pdist(arr, metric = 'minkowski', p=1, w=None, V=None, VI=None)

.../lib/python2.7/site-packages/scipy/spatial/distance.pyc in pdist(X, metric, *args, **kwargs)
1732         elif mstr.startswith("test_"):
1733             if mstr in _TEST_METRICS:
-> 1734                 dm = pdist(X, _TEST_METRICS[mstr], **kwargs)
1735             else:
1736                 raise ValueError('Unknown "Test" Distance Metric: %s' % mstr[5:])

.../venv/lib/python2.7/site-packages/scipy/spatial/distance.pyc in pdist(X, metric, *args, **kwargs)
1688         for i in xrange(0, m - 1):
1689             for j in xrange(i + 1, m):
-> 1690                 dm[k] = metric(X[i], X[j], **kwargs)
1691                 k = k + 1
1692

.../venv/lib/python2.7/site-packages/scipy/spatial/distance.pyc in minkowski(u, v, p, w)
479             root_w = np.power(w, 1/p)
480         u_v = root_w * u_v
--> 481     dist = norm(u_v, ord=p)
482     return dist
483

.../venv/lib/python2.7/site-packages/scipy/linalg/misc.pyc in norm(a, ord, axis, keepdims)
127     """
128     # Differs from numpy only in non-finite handling and the use of blas.
--> 129     a = np.asarray_chkfinite(a)
130
131     # Only use optimized norms if axis and keepdims are not specified.

.../venv/lib/python2.7/site-packages/numpy/lib/function_base.pyc in asarray_chkfinite(a, dtype, order)
1213     if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all():
1214         raise ValueError(
-> 1215             "array must not contain infs or NaNs")
1216     return a
1217

ValueError: array must not contain infs or NaNs

# Fixed code
def _validate_weights(w, dtype=np.double):
    w = _validate_vector(w, dtype=dtype)
    if np.any(w < 0):
        raise ValueError("Input weights should be all non-negative")
    return w
# Buggy code
def _cholesky(a, lower=False, overwrite_a=False, clean=True, check_finite=True):
    """Common code for cholesky() and cho_factor()."""

    if check_finite:
        a1 = asarray_chkfinite(a)
    else:
        a1 = asarray(a)
    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
        raise ValueError("expected square matrix")

    overwrite_a = overwrite_a or _datacopied(a1, a)
    (potrf,) = get_lapack_funcs(("potrf",), (a1,))
    c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)
    if info > 0:
        raise LinAlgError("%d-th leading minor not positive definite" % info)
    if info < 0:
        raise ValueError("illegal value in %d-th argument of internal potrf" % -info)
    return c, lower


# Traceback (ValueError)
Traceback (most recent call last):

File "<ipython-input-14-e4b1c49a19b3>", line 1, in <module>
cho_factor(np.array([]).reshape(0,0))

File "/Users/matthaberland/Desktop/ScipyDev/scipy/scipy/linalg/decomp_cholesky.py", line 132, in cho_factor
check_finite=check_finite)

File "/Users/matthaberland/Desktop/ScipyDev/scipy/scipy/linalg/decomp_cholesky.py", line 33, in _cholesky
% -info)

ValueError: illegal value in 4-th argument of internal potrf

# Fixed code
def _cholesky(a, lower=False, overwrite_a=False, clean=True, check_finite=True):
    """Common code for cholesky() and cho_factor()."""

    a1 = asarray_chkfinite(a) if check_finite else asarray(a)
    a1 = atleast_2d(a1)

    # Dimension check
    if a1.ndim != 2:
        raise ValueError(
            "Input array needs to be 2 dimensional but received a {}d-array.".format(
                a1.ndim
            )
        )
    # Squareness check
    if a1.shape[0] != a1.shape[1]:
        raise ValueError(
            "Input array is expected to be square but has the shape: {}.".format(
                a1.shape
            )
        )

    # Quick return for square empty array
    if a1.size == 0:
        return a1.copy(), lower

    overwrite_a = overwrite_a or _datacopied(a1, a)
    (potrf,) = get_lapack_funcs(("potrf",), (a1,))
    c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)
    if info > 0:
        raise LinAlgError(
            "%d-th leading minor of the array is not positive definite" % info
        )
    if info < 0:
        raise ValueError(
            "LAPACK reported an illegal value in {}-th argument"
            'on entry to "POTRF".'.format(-info)
        )
    return c, lower
# Buggy code
def setup_cache(self):
    if not self.enabled:
        return {}

    # create the logfile to start with
    with open(self.dump_fn, "w") as f:
        json.dump({}, f, indent=2)


# Traceback (TypeError)
=============== =============== ==================== ============= ==================
--                                       result type / solver
--------------- ---------------------------------------------------------------------
test function   success% / DE   success% / basinh.   <nfev> / DE   <nfev> / basinh.
=============== =============== ==================== ============= ==================
AMGM           failed            failed            failed          failed
=============== =============== ==================== ============= ==================

[100.00%] ·····

For parameters: 'AMGM', 'success%', 'DE'
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/asv/benchmark.py", line 773, in <module>
commands[mode](args)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/asv/benchmark.py", line 744, in main_run
skip = benchmark.do_setup()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/asv/benchmark.py", line 325, in do_setup
setup(*self._current_params)
TypeError: setup() takes 4 positional arguments but 5 were given
...

# Fixed code
def setup_cache(self):
    if not self.enabled:
        return

    # create the logfile to start with
    with open(self.dump_fn, "w") as f:
        json.dump({}, f, indent=2)
# Buggy code
def _argcheck(self, h, k):
    condlist = [
        np.logical_and(h > 0, k > 0),
        np.logical_and(h > 0, k == 0),
        np.logical_and(h > 0, k < 0),
        np.logical_and(h <= 0, k > 0),
        np.logical_and(h <= 0, k == 0),
        np.logical_and(h <= 0, k < 0),
    ]

    def f0(h, k):
        return (1.0 - h ** (-k)) / k

    def f1(h, k):
        return np.log(h)

    def f3(h, k):
        a = np.empty(np.shape(h))
        a[:] = -np.inf
        return a

    def f5(h, k):
        return 1.0 / k

    self.a = _lazyselect(condlist, [f0, f1, f0, f3, f3, f5], [h, k], default=np.nan)

    def f0(h, k):
        return 1.0 / k

    def f1(h, k):
        a = np.empty(np.shape(h))
        a[:] = np.inf
        return a

    self.b = _lazyselect(condlist, [f0, f1, f1, f0, f1, f1], [h, k], default=np.nan)
    return h == h


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/Paul/anaconda/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py", line 772, in __call__
return self.freeze(*args, **kwds)
File "/Users/Paul/anaconda/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py", line 769, in freeze
return rv_frozen(self, *args, **kwds)
File "/Users/Paul/anaconda/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py", line 438, in __init__
self.dist._argcheck(*shapes)
File "/Users/Paul/anaconda/lib/python3.6/site-packages/scipy/stats/_continuous_distns.py", line 3477, in _argcheck
default=np.nan)
File "/Users/Paul/anaconda/lib/python3.6/site-packages/scipy/_lib/_util.py", line 98, in _lazyselect
np.place(out, cond, func(*temp))
File "/Users/Paul/anaconda/lib/python3.6/site-packages/scipy/stats/_continuous_distns.py", line 3461, in f0
return (1.0 - h**(-k))/k
ValueError: Integers to negative integer powers are not allowed.

# Fixed code
def _argcheck(self, h, k):
    condlist = [
        np.logical_and(h > 0, k > 0),
        np.logical_and(h > 0, k == 0),
        np.logical_and(h > 0, k < 0),
        np.logical_and(h <= 0, k > 0),
        np.logical_and(h <= 0, k == 0),
        np.logical_and(h <= 0, k < 0),
    ]

    def f0(h, k):
        return (1.0 - float_power(h, -k)) / k

    def f1(h, k):
        return np.log(h)

    def f3(h, k):
        a = np.empty(np.shape(h))
        a[:] = -np.inf
        return a

    def f5(h, k):
        return 1.0 / k

    self.a = _lazyselect(condlist, [f0, f1, f0, f3, f3, f5], [h, k], default=np.nan)

    def f0(h, k):
        return 1.0 / k

    def f1(h, k):
        a = np.empty(np.shape(h))
        a[:] = np.inf
        return a

    self.b = _lazyselect(condlist, [f0, f1, f1, f0, f1, f1], [h, k], default=np.nan)
    return h == h
# Buggy code
def _parse_signature(self, sig):
    m = re.match(
        r"\s*(.*):\s*([fdgFDGil]*)\s*\\*\s*([fdgFDGil]*)\s*->\s*([*fdgFDGil]*)\s*$", sig
    )
    if m:
        func, inarg, outarg, ret = [x.strip() for x in m.groups()]
        if ret.count("*") > 1:
            raise ValueError("%s: Invalid signature: %r" % (self.name, sig))
        return (func, inarg, outarg, ret)
    m = re.match(r"\s*(.*):\s*([fdgFDGil]*)\s*->\s*([fdgFDGil]?)\s*$", sig)
    if m:
        func, inarg, ret = [x.strip() for x in m.groups()]
        return (func, inarg, "", ret)
    raise ValueError("%s: Invalid signature: %r" % (self.name, sig))


# Traceback (ValueError)
Traceback (most recent call last):
File "generate_ufuncs.py", line 1616, in <module>
main()
File "generate_ufuncs.py", line 1609, in main
ufuncs = Ufunc.parse_all(FUNCS)
File "generate_ufuncs.py", line 831, in parse_all
ufuncs.append(cls(m.group(1), m.group(2), m.group(3)))
File "generate_ufuncs.py", line 863, in __init__
super(Ufunc, self).__init__(name, signatures, headers)
File "generate_ufuncs.py", line 757, in __init__
self.signatures = self._parse_signatures(signatures, headers)
File "generate_ufuncs.py", line 768, in _parse_signatures
return [self._parse_signature(x) + (h,) for x, h in zip(sigs, headers)]
File "generate_ufuncs.py", line 768, in <listcomp>
return [self._parse_signature(x) + (h,) for x, h in zip(sigs, headers)]
File "generate_ufuncs.py", line 781, in _parse_signature
raise ValueError("%s: Invalid signature: %r" % (self.name, sig))
ValueError: _struve_asymp_large_z: Invalid signature: 'struve_asymp_large_z: ddi*d->d'

# Fixed code
def _parse_signature(self, sig):
    m = re.match(
        r"\s*(.*):\s*([fdgFDGil]*)\s*\*\s*([fdgFDGil]*)\s*->\s*([*fdgFDGil]*)\s*$", sig
    )
    if m:
        func, inarg, outarg, ret = [x.strip() for x in m.groups()]
        if ret.count("*") > 1:
            raise ValueError("%s: Invalid signature: %r" % (self.name, sig))
        return (func, inarg, outarg, ret)
    m = re.match(r"\s*(.*):\s*([fdgFDGil]*)\s*->\s*([fdgFDGil]?)\s*$", sig)
    if m:
        func, inarg, ret = [x.strip() for x in m.groups()]
        return (func, inarg, "", ret)
    raise ValueError("%s: Invalid signature: %r" % (self.name, sig))
# Buggy code
def __init__(
    self,
    roots,
    weights=None,
    hn=1.0,
    kn=1.0,
    wfunc=None,
    limits=None,
    monic=False,
    eval_func=None,
):
    np.poly1d.__init__(self, roots, r=1)
    equiv_weights = [weights[k] / wfunc(roots[k]) for k in range(len(roots))]
    self.__dict__["weights"] = np.array(list(zip(roots, weights, equiv_weights)))
    self.__dict__["weight_func"] = wfunc
    self.__dict__["limits"] = limits
    mu = sqrt(hn)
    if monic:
        evf = eval_func
        if evf:
            eval_func = lambda x: evf(x) / kn
        mu = mu / abs(kn)
        kn = 1.0
    self.__dict__["normcoef"] = mu
    self.__dict__["coeffs"] *= kn

    # Note: eval_func will be discarded on arithmetic
    self.__dict__["_eval_func"] = eval_func


# Traceback (TypeError)
0.17.1
63
-0.118896470865
64
0.949066574424
65
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-243-24c6fbe0b8bd> in <module>()
5 for i in range(63,200):
6     print i
----> 7     print chebyt(i)(0.2)

C:\Anaconda2\lib\site-packages\scipy\special\orthogonal.pyc in chebyt(n, monic)
1201     kn = 2**(n - 1)
1202     p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
-> 1203                     lambda x: eval_chebyt(n, x))
1204     return p
1205

C:\Anaconda2\lib\site-packages\scipy\special\orthogonal.pyc in __init__(self, roots, weights, hn, kn, wfunc, limits, monic, eval_func)
143             kn = 1.0
144         self.__dict__['normcoef'] = mu
--> 145         self.__dict__['coeffs'] *= kn
146
147         # Note: eval_func will be discarded on arithmetic

TypeError: ufunc 'multiply' output (typecode 'O') could not be coerced to provided output parameter (typecode 'd') according to the casting rule ''same_kind''

# Fixed code
def __init__(
    self,
    roots,
    weights=None,
    hn=1.0,
    kn=1.0,
    wfunc=None,
    limits=None,
    monic=False,
    eval_func=None,
):
    np.poly1d.__init__(self, roots, r=1)
    equiv_weights = [weights[k] / wfunc(roots[k]) for k in range(len(roots))]
    self.__dict__["weights"] = np.array(list(zip(roots, weights, equiv_weights)))
    self.__dict__["weight_func"] = wfunc
    self.__dict__["limits"] = limits
    mu = sqrt(hn)
    if monic:
        evf = eval_func
        if evf:
            eval_func = lambda x: evf(x) / kn
        mu = mu / abs(kn)
        kn = 1.0
    self.__dict__["normcoef"] = mu
    self.__dict__["coeffs"] *= float(kn)

    # Note: eval_func will be discarded on arithmetic
    self.__dict__["_eval_func"] = eval_func
# Buggy code
def nnlf(self, theta, x):
    # - sum (log pdf(x, theta),axis=0)
    #   where theta are the parameters (including loc and scale)
    #
    try:
        loc = theta[-2]
        scale = theta[-1]
        args = tuple(theta[:-2])
    except IndexError:
        raise ValueError("Not enough input arguments.")
    if not self._argcheck(*args) or scale <= 0:
        return inf
    x = asarray((x - loc) / scale)
    cond0 = (x <= self.a) | (x >= self.b)
    if any(cond0):
        return inf
    else:
        N = len(x)
        return self._nnlf(x, *args) + N * log(scale)


# Traceback (NameError)
import scipy
arr = scipy.random.rand(1000000)
res = scipy.zeros_like(arr)
blitz("""res = sin(2*sin(arr+1))""")

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/weave/blitz_tools.pyc
in blitz(expr, local_dict, global_dict, check_size, verbose, **kw)
32     #    of time.  It also can cause core-dumps if the sizes
of the inputs
33     #    aren't compatible.
---> 34     if check_size and not
size_check.check_expr(expr,local_dict,global_dict):
35         raise 'inputs failed to pass size check.'
36

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/weave/size_check.pyc
in check_expr(expr, local_vars, global_vars)
49         if isnumeric(val):
50             values[var] = val
---> 51     exec(expr,values)
52     try:
53         exec(expr,values)

NameError: name 'sin' is not defined
---------------------------------------------------------------------------------------------------------

# Fixed code
def nnlf(self, theta, x):
    """Return negative loglikelihood function,
    i.e., - sum (log pdf(x, theta),axis=0)
       where theta are the parameters (including loc and scale)
    """
    try:
        loc = theta[-2]
        scale = theta[-1]
        args = tuple(theta[:-2])
    except IndexError:
        raise ValueError("Not enough input arguments.")
    if not self._argcheck(*args) or scale <= 0:
        return inf
    x = asarray((x - loc) / scale)
    cond0 = (x <= self.a) | (self.b <= x)
    if any(cond0):
        # old call: return inf
        goodargs = argsreduce(1 - cond0, *((x,)))
        goodargs = tuple(goodargs + list(args))
        N = len(x)
        Nbad = sum(cond0)
        xmax = floatinfo.machar.xmax
        return self._nnlf(*goodargs) + N * log(scale) + Nbad * 100.0 * log(xmax)
    else:
        N = len(x)
        return self._nnlf(x, *args) + N * log(scale)
# Buggy code
def sum(self, axis=None):
    """Sum the matrix over the given axis.  If the axis is None, sum
    over both rows and columns, returning a scalar.
    """
    # We use multiplication by an array of ones to achieve this.
    # For some sparse matrix formats more efficient methods are
    # possible -- these should override this function.
    m, n = self.shape

    # Mimic numpy's casting.
    if np.issubdtype(self.dtype, np.float_):
        res_dtype = np.float_
    elif self.dtype.kind in "ib":
        res_dtype = np.int_
    elif self.dtype.kind == "u":
        res_dtype = np.uint
    else:
        res_dtype = self.dtype

    if axis is None:
        # sum over rows and columns
        return (self * np.asmatrix(np.ones((n, 1), dtype=res_dtype))).sum()

    if axis < 0:
        axis += 2
    if axis == 0:
        # sum over columns
        return np.asmatrix(np.ones((1, m), dtype=res_dtype)) * self
    elif axis == 1:
        # sum over rows
        return self * np.asmatrix(np.ones((n, 1), dtype=res_dtype))
    else:
        raise ValueError("axis out of bounds")


# Traceback (AssertionError)
======================================================================
FAIL: test_base.TestCSC.test_sum(<type 'numpy.uint64'>, 1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/home/rgommers/Code/scipy/scipy/sparse/tests/test_base.py", line 767, in check
assert_equal(dat.sum(axis=0).dtype, datsp.sum(axis=0).dtype)
File "/home/rgommers/.local/lib/python2.7/site-packages/numpy/testing/utils.py", line 375, in assert_equal
raise AssertionError(msg)
AssertionError:
Items are not equal:
ACTUAL: dtype('uint64')
DESIRED: dtype('uint32')

# Fixed code
def sum(self, axis=None):
    """Sum the matrix over the given axis.  If the axis is None, sum
    over both rows and columns, returning a scalar.
    """
    # We use multiplication by an array of ones to achieve this.
    # For some sparse matrix formats more efficient methods are
    # possible -- these should override this function.
    m, n = self.shape

    # Mimic numpy's casting.
    if np.issubdtype(self.dtype, np.float_):
        res_dtype = np.float_
    elif self.dtype.kind == "u" and np.can_cast(self.dtype, np.uint):
        res_dtype = np.uint
    elif np.can_cast(self.dtype, np.int_):
        res_dtype = np.int_
    else:
        res_dtype = self.dtype

    if axis is None:
        # sum over rows and columns
        return (self * np.asmatrix(np.ones((n, 1), dtype=res_dtype))).sum()

    if axis < 0:
        axis += 2
    if axis == 0:
        # sum over columns
        return np.asmatrix(np.ones((1, m), dtype=res_dtype)) * self
    elif axis == 1:
        # sum over rows
        return self * np.asmatrix(np.ones((n, 1), dtype=res_dtype))
    else:
        raise ValueError("axis out of bounds")
# Buggy code
def sum(self, axis=None):
    """Sum the matrix over the given axis.  If the axis is None, sum
    over both rows and columns, returning a scalar.
    """
    # The spmatrix base class already does axis=0 and axis=1 efficiently
    # so we only do the case axis=None here
    if axis is None:
        return self.data.sum()
    elif not hasattr(self, "blocksize") and axis in self._swap(((1, -1), (0, 2)))[0]:
        # faster than multiplication for large minor axis in CSC/CSR
        # Mimic numpy's casting.
        if np.issubdtype(self.dtype, np.float_):
            res_dtype = np.float_
        elif self.dtype.kind in "ib":
            res_dtype = np.int_
        elif self.dtype.kind == "u":
            res_dtype = np.uint
        else:
            res_dtype = self.dtype
        ret = np.zeros(len(self.indptr) - 1, dtype=res_dtype)

        major_index, value = self._minor_reduce(np.add)
        ret[major_index] = value
        ret = np.asmatrix(ret)
        if axis % 2 == 1:
            ret = ret.T
        return ret
    else:
        return spmatrix.sum(self, axis)


# Traceback (AssertionError)
======================================================================
FAIL: test_base.TestCSC.test_sum(<type 'numpy.uint64'>, 1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/home/rgommers/Code/scipy/scipy/sparse/tests/test_base.py", line 767, in check
assert_equal(dat.sum(axis=0).dtype, datsp.sum(axis=0).dtype)
File "/home/rgommers/.local/lib/python2.7/site-packages/numpy/testing/utils.py", line 375, in assert_equal
raise AssertionError(msg)
AssertionError:
Items are not equal:
ACTUAL: dtype('uint64')
DESIRED: dtype('uint32')

# Fixed code
def sum(self, axis=None):
    """Sum the matrix over the given axis.  If the axis is None, sum
    over both rows and columns, returning a scalar.
    """
    # The spmatrix base class already does axis=0 and axis=1 efficiently
    # so we only do the case axis=None here
    if axis is None:
        return self.data.sum()
    elif not hasattr(self, "blocksize") and axis in self._swap(((1, -1), (0, 2)))[0]:
        # faster than multiplication for large minor axis in CSC/CSR
        # Mimic numpy's casting.
        if np.issubdtype(self.dtype, np.float_):
            res_dtype = np.float_
        elif self.dtype.kind == "u" and np.can_cast(self.dtype, np.uint):
            res_dtype = np.uint
        elif np.can_cast(self.dtype, np.int_):
            res_dtype = np.int_
        else:
            res_dtype = self.dtype
        ret = np.zeros(len(self.indptr) - 1, dtype=res_dtype)

        major_index, value = self._minor_reduce(np.add)
        ret[major_index] = value
        ret = np.asmatrix(ret)
        if axis % 2 == 1:
            ret = ret.T
        return ret
    else:
        return spmatrix.sum(self, axis)
# Buggy code
def _chk_asarray(a, axis):
    if axis is None:
        a = np.ravel(a)
        outaxis = 0
    else:
        a = np.asarray(a)
        outaxis = axis
    return a, outaxis


# Traceback (UnboundLocalError)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-101-1fe8797e2f6f> in <module>()
----> 1 stats.mode([])

/Users/ch/miniconda/envs/sci34_dev/lib/python3.4/site-packages/scipy/stats/stats.py in mode(a, axis)
634         oldcounts = np.maximum(counts, oldcounts)
635         oldmostfreq = mostfrequent
--> 636     return mostfrequent, oldcounts
637
638

UnboundLocalError: local variable 'mostfrequent' referenced before assignment

# Fixed code
def _chk_asarray(a, axis):
    if len(np.array(a).shape) == 0:
        a = np.atleast_1d(a)

    if axis is None:
        a = np.ravel(a)
        outaxis = 0
    else:
        a = np.asarray(a)
        outaxis = axis
    return a, outaxis
# Buggy code
def _chk2_asarray(a, b, axis):
    if axis is None:
        a = np.ravel(a)
        b = np.ravel(b)
        outaxis = 0
    else:
        a = np.asarray(a)
        b = np.asarray(b)
        outaxis = axis
    return a, b, outaxis


# Traceback (UnboundLocalError)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-101-1fe8797e2f6f> in <module>()
----> 1 stats.mode([])

/Users/ch/miniconda/envs/sci34_dev/lib/python3.4/site-packages/scipy/stats/stats.py in mode(a, axis)
634         oldcounts = np.maximum(counts, oldcounts)
635         oldmostfreq = mostfrequent
--> 636     return mostfrequent, oldcounts
637
638

UnboundLocalError: local variable 'mostfrequent' referenced before assignment

# Fixed code
def _chk2_asarray(a, b, axis):
    if len(np.array(a).shape) == 0:
        a = np.atleast_1d(a)
    if len(np.array(b).shape) == 0:
        b = np.atleast_1d(b)

    if axis is None:
        a = np.ravel(a)
        b = np.ravel(b)
        outaxis = 0
    else:
        a = np.asarray(a)
        b = np.asarray(b)
        outaxis = axis
    return a, b, outaxis
# Buggy code
def _unpack_index(self, index):
    """Parse index. Always return a tuple of the form (row, col).
    Where row/col is a integer, slice, or array of integers.
    """
    # First, check if indexing with single boolean matrix.
    from .base import spmatrix  # This feels dirty but...

    if (
        isinstance(index, (spmatrix, np.ndarray))
        and (index.ndim == 2)
        and index.dtype.kind == "b"
    ):
        return index.nonzero()

    # Next, parse the tuple or object
    if isinstance(index, tuple):
        if len(index) == 2:
            row, col = index
        elif len(index) == 1:
            row, col = index[0], slice(None)
        else:
            raise IndexError("invalid number of indices")
    else:
        row, col = index, slice(None)

    # Next, check for validity, or transform the index as needed.
    row, col = self._check_boolean(row, col)
    return row, col


# Traceback (IndexError)
import numpy as np
m = np.matrix([[0,1], [2,3]])
import scipy.sparse as sp
s = sp.csr_matrix(m)
m[..., 1]
matrix([[1],
[3]])
s[..., 1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/csr.py", line 249, in __getitem__
P = extractor(row, self.shape[0])        #[[1,2],j] or [[1,2],1:2]
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/csr.py", line 209, in extractor
indices = asindices(indices)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/csr.py", line 191, in asindices
raise IndexError('invalid index')
IndexError: invalid index

# Fixed code
def _unpack_index(self, index):
    """Parse index. Always return a tuple of the form (row, col).
    Where row/col is a integer, slice, or array of integers.
    """
    # First, check if indexing with single boolean matrix.
    from .base import spmatrix  # This feels dirty but...

    if (
        isinstance(index, (spmatrix, np.ndarray))
        and (index.ndim == 2)
        and index.dtype.kind == "b"
    ):
        return index.nonzero()

    # Parse any ellipses.
    index = self._check_ellipsis(index)

    # Next, parse the tuple or object
    if isinstance(index, tuple):
        if len(index) == 2:
            row, col = index
        elif len(index) == 1:
            row, col = index[0], slice(None)
        else:
            raise IndexError("invalid number of indices")
    else:
        row, col = index, slice(None)

    # Next, check for validity, or transform the index as needed.
    row, col = self._check_boolean(row, col)
    return row, col