ronantakizawa/codereview-bench huggingface dataset:
Repository: sympy/sympy
File: sympy/vector/vector.py (Python)

Code before:
        return self._system

    def _sympystr(self, printer):
        return self._name

    def _sympyrepr(self, printer):
        index, system = self._id
        return printer._print(system) + '.' + system._vector_names[index]

    @property
    def free_symbols(self):
        return {self}

    def _eval_conjugate(self):
        return self


class VectorAdd(BasisDependentAdd, Vector):
    """
    Class to denote sum of Vector instances.
    """

    def __new__(cls, *args, **options):
        for arg in args:
            if not isinstance(arg, Vector):
                raise TypeError("VectorAdd expects all arguments to be Vector instances")
        obj = BasisDependentAdd.__new__(cls, *args, **options)
        return obj

    def _sympystr(self, printer):
        ret_str = ''
        items = list(self.separate().items())
        items.sort(key=lambda x: x[0].__str__())
        for system, vect in items:
            base_vects = system.base_vectors()
            for x in base_vects:
                if x in vect.components:
                    temp_vect = self.components[x] * x
                    ret_str += printer._print(temp_vect) + " + "
        return ret_str[:-3]


class VectorMul(BasisDependentMul, Vector):
    """
    Class to denote products of scalars and BaseVectors.
    """

    def __new__(cls, *args, **options):
        obj = BasisDependentMul.__new__(cls, *args, **options)
        return obj


Review comment (suggestion):
Not sure if this is really necessary because `BasisDependentAdd.__new__` is already doing these checks.

Code after:
        return self._system

    def _sympystr(self, printer):
        return self._name

    def _sympyrepr(self, printer):
        index, system = self._id
        return printer._print(system) + '.' + system._vector_names[index]

    @property
    def free_symbols(self):
        return {self}

    def _eval_conjugate(self):
        return self


class VectorAdd(BasisDependentAdd, Vector):
    """
    Class to denote sum of Vector instances.
    """

    def __new__(cls, *args, **options):
        obj = BasisDependentAdd.__new__(cls, *args, **options)
        return obj

    def _sympystr(self, printer):
        ret_str = ''
        items = list(self.separate().items())
        items.sort(key=lambda x: x[0].__str__())
        for system, vect in items:
            base_vects = system.base_vectors()
            for x in base_vects:
                if x in vect.components:
                    temp_vect = self.components[x] * x
                    ret_str += printer._print(temp_vect) + " + "
        return ret_str[:-3]


class VectorMul(BasisDependentMul, Vector):
    """
    Class to denote products of scalars and BaseVectors.
    """

    def __new__(cls, *args, **options):
        obj = BasisDependentMul.__new__(cls, *args, **options)
        return obj

    @property
    def base_vector(self):
        """ The BaseVector involved in the product. """
Repository: sympy/sympy
File: sympy/matrices/inverse.py (Python)

Code before:
    d    = M.det(method='berkowitz')
    zero = d.equals(0)

    if zero is None: # if equals() can't decide, will rref be able to?
        ok   = M.rref(simplify=True)[0]
        zero = any(iszerofunc(ok[j, j]) for j in range(ok.rows))

    if zero:
        raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")

    return d

def _inv_ADJ(M, iszerofunc=_iszero):
    """Calculates the inverse using the adjugate matrix and a determinant.

    See Also
    ========

    inv
    inverse_GE
    inverse_LU
    inverse_CH
    inverse_LDL
    """

    d = M.det()

    return M.adjugate() / d

def _inv_GE(M, iszerofunc=_iszero):
    """Calculates the inverse using Gaussian elimination.

    See Also
    ========

    inv
    inverse_ADJ
    inverse_LU
    inverse_CH
    inverse_LDL
    """

    from .dense import Matrix

    if not M.is_square:
        raise NonSquareMatrixError("A Matrix must be square to invert.")

    big = Matrix.hstack(M.as_mutable(), Matrix.eye(M.rows))
    red = big.rref(iszerofunc=iszerofunc, simplify=True)[0]

    return M._new(red[:, big.rows:])

Review comment (suggestion):
This should check if `d` is zero using the iszerofunc.

Code after:
    d    = M.det(method='berkowitz')
    zero = d.equals(0)

    if zero is None: # if equals() can't decide, will rref be able to?
        ok   = M.rref(simplify=True)[0]
        zero = any(iszerofunc(ok[j, j]) for j in range(ok.rows))

    if zero:
        raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")

    return d

def _inv_ADJ(M, iszerofunc=_iszero):
    """Calculates the inverse using the adjugate matrix and a determinant.

    See Also
    ========

    inv
    inverse_GE
    inverse_LU
    inverse_CH
    inverse_LDL
    """

    d = M.det()

    if iszerofunc(d):
        raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")

    return M.adjugate() / d

def _inv_GE(M, iszerofunc=_iszero):
    """Calculates the inverse using Gaussian elimination.

    See Also
    ========

    inv
    inverse_ADJ
    inverse_LU
    inverse_CH
    inverse_LDL
    """

    from .dense import Matrix

    if not M.is_square:
        raise NonSquareMatrixError("A Matrix must be square to invert.")

    big = Matrix.hstack(M.as_mutable(), Matrix.eye(M.rows))
Repository: sympy/sympy
File: sympy/integrals/tests/test_integrals.py (Python)

Code before:
    f1 = Piecewise( *p ).subs( {t:t1} )
    f2 = Piecewise( *p ).subs( {t:t2} )
    f3 = Piecewise( *p ).subs( {t:t3} )

    I2 = integrate(f2 * integrate(f3, (t3, 0, t2)), (t2, 0, t1))
    assert I2 == Piecewise((a1**2*t1**2/2, t1 < 0),
        (a1**2*Min(1, t1)**2/2
        - a2**2*Min(1, t1)**2/2
        + a2**2*Min(2, t1)**2/2
        - a3**2*Min(2, t1)**2/2
        + a3**2*Min(3, t1)**2/2
        - (a1*a2 - a2**2)*Min(1, t1)
        + (a1*a2 - a2**2)*Min(2, t1)
        - (a1*a3 + a2*a3 - 2*a3**2)*Min(2, t1)
        + (a1*a3 + a2*a3 - 2*a3**2)*Min(3, t1), t1 <= Min(3, t1)
        ),
        (nan, True))

    assert integrate(f1 * I2, (t1, 0, 3)) == a1**3/6 + a1**2*a2/2 \
        + a1**2*a3/2 + a1*a2**2/2 + a1*a2*a3 + a1*a3**2/2 + a2**3/6 + a2**2*a3/2 + a2*a3**2/2 + a3**3/6

    assert integrate( Piecewise( (2,t2<1) , (nan , True)) , (t2,0,t1) ) == \
        Piecewise((2*t1, t1 < 0), (2*Min(1, t1), t1 <= Min(1, t1)), (nan, True))



def test_issue_15566():
    a, m, s = symbols('a m s', real=True)
    t = symbols('t')

    expr = (S(1) / sqrt(2 * pi * s**2)) * (t + m) * exp(-t**2 / (2 * s**2))
    result = integrate(expr, (t, a - m, oo))

    assert isinstance(result, Piecewise)

    assert result.has(erf)


Review comment (suggestion):
There are three consecutive blank lines here. According to the PEP 8 style guide and the conventions followed in this file, there should be only two blank lines between top-level function definitions. Remove one blank line.
```suggestion

```

Code after:
    f1 = Piecewise( *p ).subs( {t:t1} )
    f2 = Piecewise( *p ).subs( {t:t2} )
    f3 = Piecewise( *p ).subs( {t:t3} )

    I2 = integrate(f2 * integrate(f3, (t3, 0, t2)), (t2, 0, t1))
    assert I2 == Piecewise((a1**2*t1**2/2, t1 < 0),
        (a1**2*Min(1, t1)**2/2
        - a2**2*Min(1, t1)**2/2
        + a2**2*Min(2, t1)**2/2
        - a3**2*Min(2, t1)**2/2
        + a3**2*Min(3, t1)**2/2
        - (a1*a2 - a2**2)*Min(1, t1)
        + (a1*a2 - a2**2)*Min(2, t1)
        - (a1*a3 + a2*a3 - 2*a3**2)*Min(2, t1)
        + (a1*a3 + a2*a3 - 2*a3**2)*Min(3, t1), t1 <= Min(3, t1)
        ),
        (nan, True))

    assert integrate(f1 * I2, (t1, 0, 3)) == a1**3/6 + a1**2*a2/2 \
        + a1**2*a3/2 + a1*a2**2/2 + a1*a2*a3 + a1*a3**2/2 + a2**3/6 + a2**2*a3/2 + a2*a3**2/2 + a3**3/6

    assert integrate( Piecewise( (2,t2<1) , (nan , True)) , (t2,0,t1) ) == \
        Piecewise((2*t1, t1 < 0), (2*Min(1, t1), t1 <= Min(1, t1)), (nan, True))


def test_issue_15566():
    a, m, s = symbols('a m s', real=True)
    t = symbols('t')

    expr = (S(1) / sqrt(2 * pi * s**2)) * (t + m) * exp(-t**2 / (2 * s**2))
    result = integrate(expr, (t, a - m, oo))

    assert isinstance(result, Piecewise)

    assert result.has(erf)
Repository: sympy/sympy
File: sympy/integrals/tests/test_integrals.py (Python)

Code before:
        + a2**2*Min(2, t1)**2/2
        - a3**2*Min(2, t1)**2/2
        + a3**2*Min(3, t1)**2/2
        - (a1*a2 - a2**2)*Min(1, t1)
        + (a1*a2 - a2**2)*Min(2, t1)
        - (a1*a3 + a2*a3 - 2*a3**2)*Min(2, t1)
        + (a1*a3 + a2*a3 - 2*a3**2)*Min(3, t1), t1 <= Min(3, t1)
        ),
        (nan, True))

    assert integrate(f1 * I2, (t1, 0, 3)) == a1**3/6 + a1**2*a2/2 \
        + a1**2*a3/2 + a1*a2**2/2 + a1*a2*a3 + a1*a3**2/2 + a2**3/6 + a2**2*a3/2 + a2*a3**2/2 + a3**3/6

    assert integrate( Piecewise( (2,t2<1) , (nan , True)) , (t2,0,t1) ) == \
        Piecewise((2*t1, t1 < 0), (2*Min(1, t1), t1 <= Min(1, t1)), (nan, True))



def test_issue_15566():
    a, m, s = symbols('a m s', real=True)
    t = symbols('t')

    expr = (S(1) / sqrt(2 * pi * s**2)) * (t + m) * exp(-t**2 / (2 * s**2))
    result = integrate(expr, (t, a - m, oo))

    assert isinstance(result, Piecewise)

    assert result.has(erf)


Review comment (suggestion):
This line contains trailing whitespace. Remove the trailing spaces to comply with PEP 8 style guidelines.
```suggestion

```

Code after:
        + a2**2*Min(2, t1)**2/2
        - a3**2*Min(2, t1)**2/2
        + a3**2*Min(3, t1)**2/2
        - (a1*a2 - a2**2)*Min(1, t1)
        + (a1*a2 - a2**2)*Min(2, t1)
        - (a1*a3 + a2*a3 - 2*a3**2)*Min(2, t1)
        + (a1*a3 + a2*a3 - 2*a3**2)*Min(3, t1), t1 <= Min(3, t1)
        ),
        (nan, True))

    assert integrate(f1 * I2, (t1, 0, 3)) == a1**3/6 + a1**2*a2/2 \
        + a1**2*a3/2 + a1*a2**2/2 + a1*a2*a3 + a1*a3**2/2 + a2**3/6 + a2**2*a3/2 + a2*a3**2/2 + a3**3/6

    assert integrate( Piecewise( (2,t2<1) , (nan , True)) , (t2,0,t1) ) == \
        Piecewise((2*t1, t1 < 0), (2*Min(1, t1), t1 <= Min(1, t1)), (nan, True))


def test_issue_15566():
    a, m, s = symbols('a m s', real=True)
    t = symbols('t')

    expr = (S(1) / sqrt(2 * pi * s**2)) * (t + m) * exp(-t**2 / (2 * s**2))
    result = integrate(expr, (t, a - m, oo))

    assert isinstance(result, Piecewise)

    assert result.has(erf)
Repository: sympy/sympy
File: sympy/core/tests/test_evalf.py (Python)

Code before:
    # is a real number.
    zeta = Symbol('zeta')
    a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), [-1, -1, 0, 0], alias=zeta)
    z = a5.evalf()
    assert isinstance(z, Float)
    assert not hasattr(z, '_mpc_')
    assert hasattr(z, '_mpf_')


def test_issue_20733():
    expr = 1/((x - 9)*(x - 8)*(x - 7)*(x - 4)**2*(x - 3)**3*(x - 2))
    assert str(expr.evalf(1, subs={x:1})) == '-4.e-5'
    assert str(expr.evalf(2, subs={x:1})) == '-4.1e-5'
    assert str(expr.evalf(11, subs={x:1})) == '-4.1335978836e-5'
    assert str(expr.evalf(20, subs={x:1})) == '-0.000041335978835978835979'

    expr = Mul(*((x - i) for i in range(2, 1000)))
    assert srepr(expr.evalf(2, subs={x: 1})) == "Float('4.0271e+2561', precision=10)"
    assert srepr(expr.evalf(10, subs={x: 1})) == "Float('4.02790050126e+2561', precision=37)"
    assert srepr(expr.evalf(53, subs={x: 1})) == "Float('4.0279005012722099453824067459760158730668154575647110393e+2561', precision=179)"


def test_issue_28280():
    # This test demonstrates why `evalf_log` needs to specially handle
    # arguments close to 1.If the argument is evaluated directly
    # as `1 + 10**-10` at default precision,it loses the small
    # term and becomes exactly 1. This results in `log(1) -> 0`
    # causing `x > 20` to incorrectly evaluate to False.
    x = 20 + log(1 + S(10)**-10)
    assert x > 20
    y = 20 + log(1 + S(10)**-9)
    assert y > 20

Review comment (suggestion):
Missing space after comma. Should be "precision, it" instead of "precision,it".
```suggestion
    # as `1 + 10**-10` at default precision, it loses the small
```

Code after:
    # is a real number.
    zeta = Symbol('zeta')
    a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), [-1, -1, 0, 0], alias=zeta)
    z = a5.evalf()
    assert isinstance(z, Float)
    assert not hasattr(z, '_mpc_')
    assert hasattr(z, '_mpf_')


def test_issue_20733():
    expr = 1/((x - 9)*(x - 8)*(x - 7)*(x - 4)**2*(x - 3)**3*(x - 2))
    assert str(expr.evalf(1, subs={x:1})) == '-4.e-5'
    assert str(expr.evalf(2, subs={x:1})) == '-4.1e-5'
    assert str(expr.evalf(11, subs={x:1})) == '-4.1335978836e-5'
    assert str(expr.evalf(20, subs={x:1})) == '-0.000041335978835978835979'

    expr = Mul(*((x - i) for i in range(2, 1000)))
    assert srepr(expr.evalf(2, subs={x: 1})) == "Float('4.0271e+2561', precision=10)"
    assert srepr(expr.evalf(10, subs={x: 1})) == "Float('4.02790050126e+2561', precision=37)"
    assert srepr(expr.evalf(53, subs={x: 1})) == "Float('4.0279005012722099453824067459760158730668154575647110393e+2561', precision=179)"


def test_issue_28280():
    # This test demonstrates why `evalf_log` needs to specially handle
    # arguments close to 1.If the argument is evaluated directly
    # as `1 + 10**-10` at default precision,it loses the small
    # term and becomes exactly 1. This results in `log(1) -> 0`
    # causing `x > 20` to incorrectly evaluate to False.
    x = 20 + log(1 + S(10)**-10)
    assert x > 20
    y = 20 + log(1 + S(10)**-9)
    assert y > 20
Repository: sympy/sympy
File: sympy/ntheory/digits.py (Python)

Code before:
from collections import defaultdict
from typing import SupportsIndex

from sympy.utilities.iterables import multiset, is_palindromic as _palindromic
from sympy.utilities.misc import as_int


def digits(n: SupportsIndex, b: int = 10, digits: int | None = None) -> list[int]:
    """
    Return a list of the digits of ``n`` in base ``b``. The first
    element in the list is ``b`` (or ``-b`` if ``n`` is negative).

    Examples
    ========

    >>> from sympy.ntheory.digits import digits
    >>> digits(35)
    [10, 3, 5]

    If the number is negative, the negative sign will be placed on the
    base (which is the first element in the returned list):

    >>> digits(-35)
    [-10, 3, 5]

    Bases other than 10 (and greater than 1) can be selected with ``b``:

    >>> digits(27, b=2)
    [2, 1, 1, 0, 1, 1]

    Use the ``digits`` keyword if a certain number of digits is desired:

    >>> digits(35, digits=4)

Review comment (suggestion):
The parameter `b` should be `SupportsIndex` as well. Same goes for the other functions.

I think `digits` is fine as `int | None` though.

Code after:
from __future__ import annotations

from collections import defaultdict
from typing import SupportsIndex

from sympy.utilities.iterables import multiset, is_palindromic as _palindromic
from sympy.utilities.misc import as_int


def digits(n: SupportsIndex, b: SupportsIndex = 10, digits: int | None = None) -> list[int]:
    """
    Return a list of the digits of ``n`` in base ``b``. The first
    element in the list is ``b`` (or ``-b`` if ``n`` is negative).

    Examples
    ========

    >>> from sympy.ntheory.digits import digits
    >>> digits(35)
    [10, 3, 5]

    If the number is negative, the negative sign will be placed on the
    base (which is the first element in the returned list):

    >>> digits(-35)
    [-10, 3, 5]

    Bases other than 10 (and greater than 1) can be selected with ``b``:

    >>> digits(27, b=2)
    [2, 1, 1, 0, 1, 1]

    Use the ``digits`` keyword if a certain number of digits is desired:
Repository: sympy/sympy
File: sympy/ntheory/generate.py (Python)

Code before:

        ValueError
            If ``ith <= 0``.
            If ``n`` or ``ith`` is not an integer.

        Notes
        =====

        Potential primes are located at 6*j +/- 1. This
        property is used during searching.

        >>> from sympy import nextprime
        >>> [(i, nextprime(i)) for i in range(10, 15)]
        [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
        >>> nextprime(2, ith=2) # the 2nd prime after 2
        5

        See Also
        ========

        prevprime : Return the largest prime smaller than n
        primerange : Generate all primes in a given range

    """
    n_int = int(as_int(n))
    i = int(as_int(ith))
    if i <= 0:
        raise ValueError("ith should be positive")
    if n_int < 2:
        n_int = 2
        i -= 1
    if n_int <= sieve._list[-2]:
        l, _ = sieve.search(n_int)
        if l + i - 1 < len(sieve._list):
            return sieve._list[l + i - 1]
        n_int = sieve._list[-1]
        i += l - len(sieve._list)
    nn = 6*(n_int//6)
    if nn == n_int:
        n_int += 1
        if isprime(n_int):
            i -= 1
            if not i:
                return n_int
        n_int += 4
    elif n_int - nn == 5:
        n_int += 2
        if isprime(n_int):
            i -= 1
            if not i:
                return n_int

Review comment (suggestion):
I think a better way of handling this is to have two separate functions here:
```python
def nextprime(n: SupportsIndex, ith: SupportsIndex = 1) -> int:
    """ Return the ith prime greater than n.
    """
    return _nextprime(as_int(n), as_int(ith))


def _nextprime(n: int, ith: int) -> int:
    ...
```
Then in internal code we can call the `_nextprime` function and not bother with the `as_int` conversion. It also means we don't have to change the variable names throughout all of the code.

Code after:

def nextprime(n: SupportsIndex, ith: SupportsIndex = 1) -> int:
    """ Return the ith prime greater than n.

        Parameters
        ==========

        n : integer
        ith : positive integer

        Returns
        =======

        int : Return the ith prime greater than n

        Raises
        ======

        ValueError
            If ``ith <= 0``.
            If ``n`` or ``ith`` is not an integer.

        Notes
        =====

        Potential primes are located at 6*j +/- 1. This
        property is used during searching.

        >>> from sympy import nextprime
        >>> [(i, nextprime(i)) for i in range(10, 15)]
        [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
        >>> nextprime(2, ith=2) # the 2nd prime after 2
        5

        See Also
        ========

        prevprime : Return the largest prime smaller than n
        primerange : Generate all primes in a given range

    """
    return _nextprime(as_int(n), as_int(ith))

def _nextprime(n: int, ith: int = 1) -> int:
    """ Internal implementation of nextprime. """
    i = ith
    if i <= 0:
        raise ValueError("ith should be positive")
    if n < 2:
        n = 2
        i -= 1
Repository: sympy/sympy
File: sympy/ntheory/primetest.py (Python)

Code before:
    #if n < 3071837692357849:
    #    return mr(n, [2, 75088, 642735, 203659041, 3613982119])
    #if n < 18446744073709551616:
    #    return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])

    # Step 3: BPSW.
    #
    #  Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
    #     44.0s   old isprime using 46 bases
    #      5.3s   strong BPSW + one random base
    #      4.3s   extra strong BPSW + one random base
    #      4.1s   strong BPSW
    #      3.2s   extra strong BPSW

    # Classic BPSW from page 1401 of the paper.  See alternate ideas below.
    return is_strong_bpsw_prp(n)

    # Using extra strong test, which is somewhat faster
    #return mr(n, [2]) and is_extra_strong_lucas_prp(n)

    # Add a random M-R base
    #import random
    #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)


def is_gaussian_prime(num: Any) -> bool:
    r"""Test if num is a Gaussian prime number.

    References
    ==========

    .. [1] https://oeis.org/wiki/Gaussian_primes
    """

    num = sympify(num)
    a, b = num.as_real_imag()
    a = as_int(a, strict=False)
    b = as_int(b, strict=False)
    if a == 0:
        b = abs(b)
        return isprime(b) and b % 4 == 3
    elif b == 0:
        a = abs(a)
        return isprime(a) and a % 4 == 3
    return isprime(a**2 + b**2)


Review comment (suggestion):
This should use a more specific type than Any. We should only use Any if no other type can be used.

Code after:
    #if n < 105936894253:
    #    return mr(n, [2, 1005905886, 1340600841])
    #if n < 31858317218647:
    #    return mr(n, [2, 642735, 553174392, 3046413974])
    #if n < 3071837692357849:
    #    return mr(n, [2, 75088, 642735, 203659041, 3613982119])
    #if n < 18446744073709551616:
    #    return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])

    # Step 3: BPSW.
    #
    #  Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
    #     44.0s   old isprime using 46 bases
    #      5.3s   strong BPSW + one random base
    #      4.3s   extra strong BPSW + one random base
    #      4.1s   strong BPSW
    #      3.2s   extra strong BPSW

    # Classic BPSW from page 1401 of the paper.  See alternate ideas below.
    return is_strong_bpsw_prp(n)

    # Using extra strong test, which is somewhat faster
    #return mr(n, [2]) and is_extra_strong_lucas_prp(n)

    # Add a random M-R base
    #import random
    #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)


def is_gaussian_prime(num: Expr | complex) -> bool:
    r"""Test if num is a Gaussian prime number.

    References
    ==========

    .. [1] https://oeis.org/wiki/Gaussian_primes
    """

    num = sympify(num)
    _a, _b = num.as_real_imag()
    a = as_int(_a, strict=False)
    b = as_int(_b, strict=False)
    if a == 0:
        b = abs(b)
        return isprime(b) and b % 4 == 3
    elif b == 0:
        a = abs(a)
        return isprime(a) and a % 4 == 3
    return isprime(a**2 + b**2)