ronantakizawa/codereview-bench huggingface dataset:
Repository: numpy/numpy
File: numpy/_core/numerictypes.pyi (Python)

Code before:
    "single",
    "csingle",
    "half",
    "bool_",
    "int_",
    "uint",
    "float96",
    "float128",
    "complex192",
    "complex256",
]

@type_check_only
class _TypeCodes(TypedDict):
    Character: L["c"]
    Integer: L["bhilqnp"]
    UnsignedInteger: L["BHILQNP"]
    Float: L["efdg"]
    Complex: L["FDG"]
    AllInteger: L["bBhHiIlLqQnNpP"]
    AllFloat: L["efdgFDG"]
    Datetime: L["Mm"]
    All: L["?bhilqnpBHILQNPefdgFDGSUVOMm"]

def isdtype(dtype: dtype | type, kind: DTypeLike | tuple[DTypeLike, ...]) -> py_bool: ...
def issubdtype(arg1: DTypeLike, arg2: DTypeLike | None) -> py_bool: ...

typecodes: Final[_TypeCodes] = ...
ScalarType: Final[
    tuple[
        type[int],
        type[float],
        type[complex],
        type[py_bool],
        type[bytes],
        type[str],
        type[memoryview[Any]],
        type[np.bool],
        type[csingle],
        type[cdouble],
        type[clongdouble],
        type[half],
        type[single],
        type[double],
        type[longdouble],
        type[byte],
        type[short],
        type[intc],
        type[long],
        type[longlong],
        type[timedelta64],

Review comment (suggestion):
```suggestion
def issubdtype(arg1: DTypeLike | None, arg2: DTypeLike | None) -> py_bool: ...
```

Code after:
    "single",
    "csingle",
    "half",
    "bool_",
    "int_",
    "uint",
    "float96",
    "float128",
    "complex192",
    "complex256",
]

@type_check_only
class _TypeCodes(TypedDict):
    Character: L["c"]
    Integer: L["bhilqnp"]
    UnsignedInteger: L["BHILQNP"]
    Float: L["efdg"]
    Complex: L["FDG"]
    AllInteger: L["bBhHiIlLqQnNpP"]
    AllFloat: L["efdgFDG"]
    Datetime: L["Mm"]
    All: L["?bhilqnpBHILQNPefdgFDGSUVOMm"]

def isdtype(dtype: dtype | type, kind: DTypeLike | tuple[DTypeLike, ...]) -> py_bool: ...
def issubdtype(arg1: DTypeLike | None, arg2: DTypeLike | None) -> py_bool: ...

typecodes: Final[_TypeCodes] = ...
ScalarType: Final[
    tuple[
        type[int],
        type[float],
        type[complex],
        type[py_bool],
        type[bytes],
        type[str],
        type[memoryview[Any]],
        type[np.bool],
        type[csingle],
        type[cdouble],
        type[clongdouble],
        type[half],
        type[single],
        type[double],
        type[longdouble],
        type[byte],
        type[short],
        type[intc],
        type[long],
        type[longlong],
        type[timedelta64],
Repository: numpy/numpy
File: numpy/_core/multiarray.pyi (Python)

Code before:
    def carray(self) -> bool: ...
    @property
    def contiguous(self) -> bool: ...
    @property
    def f_contiguous(self) -> bool: ...
    @property
    def farray(self) -> bool: ...
    @property
    def fnc(self) -> bool: ...
    @property
    def forc(self) -> bool: ...
    @property
    def fortran(self) -> bool: ...
    @property
    def num(self) -> int: ...
    @property
    def owndata(self) -> bool: ...
    def __getitem__(self, key: _GetItemKeys) -> bool: ...
    def __setitem__(self, key: _SetItemKeys, value: bool) -> None: ...

def nested_iters(
    op: ArrayLike | Sequence[ArrayLike],
    axes: Sequence[Sequence[SupportsIndex]],
    flags: Sequence[_NDIterFlagsKind] | None = ...,
    op_flags: Sequence[Sequence[_NDIterFlagsOp]] | None = ...,
    op_dtypes: DTypeLike | None | Sequence[DTypeLike | None] = ...,
    order: _OrderKACF = ...,
    casting: _CastingKind = ...,
    buffersize: SupportsIndex = ...,
) -> tuple[nditer, ...]: ...


Review comment (suggestion):
```suggestion
    op_dtypes: DTypeLike | Sequence[DTypeLike | None] | None = ...,
```

Code after:
    def carray(self) -> bool: ...
    @property
    def contiguous(self) -> bool: ...
    @property
    def f_contiguous(self) -> bool: ...
    @property
    def farray(self) -> bool: ...
    @property
    def fnc(self) -> bool: ...
    @property
    def forc(self) -> bool: ...
    @property
    def fortran(self) -> bool: ...
    @property
    def num(self) -> int: ...
    @property
    def owndata(self) -> bool: ...
    def __getitem__(self, key: _GetItemKeys) -> bool: ...
    def __setitem__(self, key: _SetItemKeys, value: bool) -> None: ...

def nested_iters(
    op: ArrayLike | Sequence[ArrayLike],
    axes: Sequence[Sequence[SupportsIndex]],
    flags: Sequence[_NDIterFlagsKind] | None = ...,
    op_flags: Sequence[Sequence[_NDIterFlagsOp]] | None = ...,
    op_dtypes: DTypeLike | Sequence[DTypeLike | None] | None = ...,
    order: _OrderKACF = ...,
    casting: _CastingKind = ...,
    buffersize: SupportsIndex = ...,
) -> tuple[nditer, ...]: ...
Repository: numpy/numpy
File: numpy/linalg/umath_linalg.cpp (C++)

Code before:
/* -*- c -*- */

/*
 *****************************************************************************
 **                            INCLUDES                                     **
 *****************************************************************************
 */
#define PY_SSIZE_T_CLEAN
#include <Python.h>

#include <iostream>

#define NPY_TARGET_VERSION NPY_2_1_API_VERSION
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#include "numpy/arrayobject.h"
#include "numpy/ufuncobject.h"
#include "numpy/npy_math.h"

#include "npy_config.h"

#include "npy_cblas.h"

#include <cstddef>
#include <cstdio>
#include <cassert>
#include <cmath>
#include <type_traits>
#include <utility>


static const char* umath_linalg_version_string = "0.1.5";

// global lock to serialize calls into lapack_lite
#if !HAVE_EXTERNAL_LAPACK
#if PY_VERSION_HEX < 0x30d00b3
static PyThread_type_lock lapack_lite_lock;
#else

Review comment (suggestion):
```suggestion
```
I don't think you need no iostream :).

Code after:
/* -*- c -*- */

/*
 *****************************************************************************
 **                            INCLUDES                                     **
 *****************************************************************************
 */
#define PY_SSIZE_T_CLEAN
#include <Python.h>

#define NPY_TARGET_VERSION NPY_2_1_API_VERSION
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#include "numpy/arrayobject.h"
#include "numpy/ufuncobject.h"
#include "numpy/npy_math.h"

#include "npy_config.h"

#include "npy_cblas.h"

#include <cstddef>
#include <cstdio>
#include <cassert>
#include <cmath>
#include <type_traits>
#include <utility>


static const char* umath_linalg_version_string = "0.1.5";

// global lock to serialize calls into lapack_lite
#if !HAVE_EXTERNAL_LAPACK
#if PY_VERSION_HEX < 0x30d00b3
static PyThread_type_lock lapack_lite_lock;
#else
static PyMutex lapack_lite_lock = {0};
#endif
Repository: numpy/numpy
File: numpy/linalg/umath_linalg.cpp (C++)

Code before:

static inline int
get_fp_invalid_and_clear(void)
{
    int status;
    status = npy_clear_floatstatus_barrier((char*)&status);
    return !!(status & NPY_FPE_INVALID);
}

static inline void
set_fp_invalid_or_clear(int error_occurred)
{
    if (error_occurred) {
        npy_set_floatstatus_invalid();
    }
    else {
        npy_clear_floatstatus_barrier((char*)&error_occurred);
    }
}

static inline void
report_no_memory()
{
    NPY_ALLOW_C_API_DEF
    NPY_ALLOW_C_API;
    PyErr_NoMemory();
    NPY_DISABLE_C_API;
}

/*
 *****************************************************************************
 **                      Some handy constants                               **
 *****************************************************************************
 */

#define UMATH_LINALG_MODULE_NAME "_umath_linalg"

template<typename T>
struct numeric_limits;

template<>
struct numeric_limits<float> {
static constexpr float one = 1.0f;
static constexpr float zero = 0.0f;
static constexpr float minus_one = -1.0f;
static const float ninf;
static const float nan;
};
constexpr float numeric_limits<float>::one;
constexpr float numeric_limits<float>::zero;
constexpr float numeric_limits<float>::minus_one;

Review comment (suggestion):
Let's go with this, `npy_gil_error`, got enough other places.

Code after:
get_fp_invalid_and_clear(void)
{
    int status;
    status = npy_clear_floatstatus_barrier((char*)&status);
    return !!(status & NPY_FPE_INVALID);
}

static inline void
set_fp_invalid_or_clear(int error_occurred)
{
    if (error_occurred) {
        npy_set_floatstatus_invalid();
    }
    else {
        npy_clear_floatstatus_barrier((char*)&error_occurred);
    }
}

static inline void
report_no_memory()
{
    NPY_ALLOW_C_API_DEF
    NPY_ALLOW_C_API;
    PyErr_NoMemory();
    NPY_DISABLE_C_API;
}

/*
 *****************************************************************************
 **                      Some handy constants                               **
 *****************************************************************************
 */

#define UMATH_LINALG_MODULE_NAME "_umath_linalg"

template<typename T>
struct numeric_limits;

template<>
struct numeric_limits<float> {
static constexpr float one = 1.0f;
static constexpr float zero = 0.0f;
static constexpr float minus_one = -1.0f;
static const float ninf;
static const float nan;
};
constexpr float numeric_limits<float>::one;
constexpr float numeric_limits<float>::zero;
constexpr float numeric_limits<float>::minus_one;
const float numeric_limits<float>::ninf = -NPY_INFINITYF;
const float numeric_limits<float>::nan = NPY_NANF;
Repository: numpy/numpy
File: numpy/lib/tests/test__datasource.py (Python)

Code before:

def valid_httpurl():
    return http_path + http_file


def invalid_httpurl():
    return http_fakepath + http_fakefile


def valid_baseurl():
    return http_path


def invalid_baseurl():
    return http_fakepath


def valid_httpfile():
    return http_file


def invalid_httpfile():
    return http_fakefile


@pytest.mark.thread_unsafe(reason="mkdtemp thread-unsafe")
class TestDataSourceOpen:
    def setup_method(self):
        self.tmpdir = mkdtemp()
        self.ds = datasource.DataSource(self.tmpdir)

    def teardown_method(self):
        rmtree(self.tmpdir)
        del self.ds

    def test_ValidHTTP(self):
        fh = self.ds.open(valid_httpurl())
        assert_(fh)
        fh.close()

    def test_InvalidHTTP(self):
        url = invalid_httpurl()
        assert_raises(OSError, self.ds.open, url)
        try:
            self.ds.open(url)
        except OSError as e:
            # Regression test for bug fixed in r4342.
            assert_(e.errno is None)

    def test_InvalidHTTPCacheURLError(self):
        assert_raises(URLError, self.ds._cache, invalid_httpurl())

Review comment (suggestion):
`mkdtemp` could be make thread safe here by adding the thread id as a prefix/suffix. However, since all tests use `self.ds`, that's global state which makes it harder to make the tests thread safe. Should probably give that as the reason.

Also, if `datasource.DataSource` is not thread safe, that should probably be documented.

Code after:

def valid_httpurl():
    return http_path + http_file


def invalid_httpurl():
    return http_fakepath + http_fakefile


def valid_baseurl():
    return http_path


def invalid_baseurl():
    return http_fakepath


def valid_httpfile():
    return http_file


def invalid_httpfile():
    return http_fakefile


@pytest.mark.thread_unsafe(reason="mkdtemp thread-unsafe")
class TestDataSourceOpen:
    def test_ValidHTTP(self, tmp_path):
        ds = datasource.DataSource(tmp_path)
        fh = ds.open(valid_httpurl())
        assert_(fh)
        fh.close()

    def test_InvalidHTTP(self, tmp_path):
        ds = datasource.DataSource(tmp_path)
        url = invalid_httpurl()
        assert_raises(OSError, ds.open, url)
        try:
            ds.open(url)
        except OSError as e:
            # Regression test for bug fixed in r4342.
            assert_(e.errno is None)

    def test_InvalidHTTPCacheURLError(self, tmp_path):
        ds = datasource.DataSource(tmp_path)
        assert_raises(URLError, ds._cache, invalid_httpurl())

    def test_ValidFile(self, tmp_path):
        ds = datasource.DataSource(tmp_path)
        local_file = valid_textfile(tmp_path)
        fh = ds.open(local_file)
Repository: numpy/numpy
File: numpy/matrixlib/tests/test_matrix_linalg.py (Python)

Code before:

class TestEigvalsMatrix(EigvalsCases, MatrixTestCase):
    pass


class TestEigMatrix(EigCases, MatrixTestCase):
    pass


class TestSVDMatrix(SVDCases, MatrixTestCase):
    pass


class TestCondMatrix(CondCases, MatrixTestCase):
    pass


class TestPinvMatrix(PinvCases, MatrixTestCase):
    pass


class TestDetMatrix(DetCases, MatrixTestCase):
    pass


@pytest.mark.thread_unsafe(reason="residuals not calculated properly for square tests")
class TestLstsqMatrix(LstsqCases, MatrixTestCase):
    pass


class _TestNorm2DMatrix(_TestNorm2D):
    array = np.matrix


class TestNormDoubleMatrix(_TestNorm2DMatrix, _TestNormDoubleBase):
    pass


class TestNormSingleMatrix(_TestNorm2DMatrix, _TestNormSingleBase):
    pass


class TestNormInt64Matrix(_TestNorm2DMatrix, _TestNormInt64Base):
    pass


class TestQRMatrix(_TestQR):
    array = np.matrix


Review comment (bug):
This looks like a real bug maybe? We probably need to dive a bit deeper. Certainly warrants an issue.

Code after:

class TestEigvalsMatrix(EigvalsCases, MatrixTestCase):
    pass


class TestEigMatrix(EigCases, MatrixTestCase):
    pass


class TestSVDMatrix(SVDCases, MatrixTestCase):
    pass


class TestCondMatrix(CondCases, MatrixTestCase):
    pass


class TestPinvMatrix(PinvCases, MatrixTestCase):
    pass


class TestDetMatrix(DetCases, MatrixTestCase):
    pass


@pytest.mark.thread_unsafe(
    reason="residuals not calculated properly for square tests (gh-29851)"
)
class TestLstsqMatrix(LstsqCases, MatrixTestCase):
    pass


class _TestNorm2DMatrix(_TestNorm2D):
    array = np.matrix


class TestNormDoubleMatrix(_TestNorm2DMatrix, _TestNormDoubleBase):
    pass


class TestNormSingleMatrix(_TestNorm2DMatrix, _TestNormSingleBase):
    pass


class TestNormInt64Matrix(_TestNorm2DMatrix, _TestNormInt64Base):
    pass


class TestQRMatrix(_TestQR):
    array = np.matrix
Repository: numpy/numpy
File: numpy/_core/tests/test_finfo.py (Python)

Code before:
                      iexp=8)


@pytest.fixture
def float64_ma():
    """Machine arithmetic parameters for float64."""
    f64 = ntypes.float64
    return MachArLike(f64,
                      machep=-52,
                      negep=-53,
                      minexp=-1022,
                      maxexp=1024,
                      nmant=52,
                      iexp=11)


@pytest.mark.parametrize("dtype,ma_fixture", [
    (np.half, "float16_ma"),
    (np.float32, "float32_ma"),
    (np.float64, "float64_ma"),
])
@pytest.mark.parametrize("prop", [
    'machep', 'negep', 'minexp', 'maxexp', 'nmant', 'iexp',
    'eps', 'epsneg', 'precision', 'resolution'
])
@pytest.mark.thread_unsafe(reason="request.getfixturevalue thread-unsafe?")
def test_finfo_properties(dtype, ma_fixture, prop, request):
    """Test that finfo properties match expected machine arithmetic values."""
    ma = request.getfixturevalue(ma_fixture)
    finfo = np.finfo(dtype)

    actual = getattr(finfo, prop)
    expected = getattr(ma, prop)

    assert actual == expected, (
        f"finfo({dtype}) property '{prop}' mismatch: "
        f"expected {expected}, got {actual}"
    )


Review comment (suggestion):
Maybe phrase this as "Complex fixture setup is thread-unsafe" and link to https://github.com/pytest-dev/pytest/issues/13768.

Code after:
                      iexp=8)


@pytest.fixture
def float64_ma():
    """Machine arithmetic parameters for float64."""
    f64 = ntypes.float64
    return MachArLike(f64,
                      machep=-52,
                      negep=-53,
                      minexp=-1022,
                      maxexp=1024,
                      nmant=52,
                      iexp=11)


@pytest.mark.parametrize("dtype,ma_fixture", [
    (np.half, "float16_ma"),
    (np.float32, "float32_ma"),
    (np.float64, "float64_ma"),
])
@pytest.mark.parametrize("prop", [
    'machep', 'negep', 'minexp', 'maxexp', 'nmant', 'iexp',
    'eps', 'epsneg', 'precision', 'resolution'
])
@pytest.mark.thread_unsafe(
    reason="complex fixture setup is thread-unsafe (pytest-dev/pytest#13768.)"
)
def test_finfo_properties(dtype, ma_fixture, prop, request):
    """Test that finfo properties match expected machine arithmetic values."""
    ma = request.getfixturevalue(ma_fixture)
    finfo = np.finfo(dtype)

    actual = getattr(finfo, prop)
    expected = getattr(ma, prop)

    assert actual == expected, (
        f"finfo({dtype}) property '{prop}' mismatch: "
        f"expected {expected}, got {actual}"
    )
Repository: numpy/numpy
File: numpy/_core/tests/test_multiarray.py (Python)

Code before:
        a = np.array(np.pi)
        assert_equal(f'{a:0.3g}', '3.14')
        assert_equal(f'{a[()]:0.3g}', '3.14')

    def test_1d_no_format(self):
        a = np.array([np.pi])
        assert_equal(f'{a}', str(a))

    def test_1d_format(self):
        # until gh-5543, ensure that the behaviour matches what it used to be
        a = np.array([np.pi])
        assert_raises(TypeError, '{:30}'.format, a)


from numpy.testing import IS_PYPY


class TestCTypes:

    def test_ctypes_is_available(self):
        test_arr = np.array([[1, 2, 3], [4, 5, 6]])

        assert_equal(ctypes, test_arr.ctypes._ctypes)
        assert_equal(tuple(test_arr.ctypes.shape), (2, 3))

    @pytest.mark.thread_unsafe(reason="modifies global state")
    def test_ctypes_is_not_available(self):
        from numpy._core import _internal
        _internal.ctypes = None
        try:
            test_arr = np.array([[1, 2, 3], [4, 5, 6]])

            assert_(isinstance(test_arr.ctypes._ctypes,
                               _internal._missing_ctypes))
            assert_equal(tuple(test_arr.ctypes.shape), (2, 3))
        finally:
            _internal.ctypes = ctypes

    def _make_readonly(x):
        x.flags.writeable = False
        return x

    @pytest.mark.parametrize('arr', [
        np.array([1, 2, 3]),
        np.array([['one', 'two'], ['three', 'four']]),
        np.array((1, 2), dtype='i4,i4'),
        np.zeros((2,), dtype=np.dtype({
                "formats": ['<i4', '<i4'],
                "names": ['a', 'b'],
                "offsets": [0, 2],
                "itemsize": 6

Review comment (suggestion):
```suggestion
    @pytest.mark.thread_unsafe(reason="modifies global module state")
```

Code after:
        assert_(a)

    def test_all_null_bstring_array_is_falsey(self):
        a = np.array(['spam'], dtype=str)
        a[0] = '\0\0\0\0'
        assert_(not a)

    def test_null_inside_bstring_array_is_truthy(self):
        a = np.array(['spam'], dtype=str)
        a[0] = ' \0 \0'
        assert_(a)


class TestUnicodeEncoding:
    """
    Tests for encoding related bugs, such as UCS2 vs UCS4, round-tripping
    issues, etc
    """
    def test_round_trip(self):
        """ Tests that GETITEM, SETITEM, and PyArray_Scalar roundtrip """
        # gh-15363
        arr = np.zeros(shape=(), dtype="U1")
        for i in range(1, sys.maxunicode + 1):
            expected = chr(i)
            arr[()] = expected
            assert arr[()] == expected
            assert arr.item() == expected

    def test_assign_scalar(self):
        # gh-3258
        l = np.array(['aa', 'bb'])
        l[:] = np.str_('cc')
        assert_equal(l, ['cc', 'cc'])

    def test_fill_scalar(self):
        # gh-7227
        l = np.array(['aa', 'bb'])
        l.fill(np.str_('cc'))
        assert_equal(l, ['cc', 'cc'])


class TestUnicodeArrayNonzero:

    def test_empty_ustring_array_is_falsey(self):
        assert_(not np.array([''], dtype=np.str_))

    def test_whitespace_ustring_array_is_truthy(self):
        a = np.array(['eggs'], dtype=np.str_)
        a[0] = '  \0\0'
        assert_(a)
Repository: numpy/numpy
File: numpy/_core/tests/test_multithreading.py (Python)

Code before:
import concurrent.futures
import threading

import pytest

import numpy as np
from numpy._core import _rational_tests
from numpy._core.tests.test_stringdtype import random_unicode_string_list
from numpy.testing import IS_64BIT, IS_WASM
from numpy.testing._private.utils import run_threaded

if IS_WASM:
    pytest.skip(allow_module_level=True, reason="no threading support in wasm")

pytestmark = pytest.mark.thread_unsafe(reason="multithreading on parallel threads")

def test_parallel_randomstate_creation():
    # if the coercion cache is enabled and not thread-safe, creating
    # RandomState instances simultaneously leads to a data race
    def func(seed):
        np.random.RandomState(seed)

    run_threaded(func, 500, pass_count=True)


def test_parallel_ufunc_execution():
    # if the loop data cache or dispatch cache are not thread-safe
    # computing ufuncs simultaneously in multiple threads leads
    # to a data race that causes crashes or spurious exceptions
    def func():
        arr = np.random.random((25,))
        np.isnan(arr)

    run_threaded(func, 500)

    # see gh-26690
    NUM_THREADS = 50

    a = np.ones(1000)


Review comment (suggestion):
```suggestion
pytestmark = pytest.mark.thread_unsafe(reason="Tests in this module are already explicitly multi-threaded")
```

Code after:
import concurrent.futures
import threading

import pytest

import numpy as np
from numpy._core import _rational_tests
from numpy._core.tests.test_stringdtype import random_unicode_string_list
from numpy.testing import IS_64BIT, IS_WASM
from numpy.testing._private.utils import run_threaded

if IS_WASM:
    pytest.skip(allow_module_level=True, reason="no threading support in wasm")

pytestmark = pytest.mark.thread_unsafe(
    reason="tests in this module are already explicitly multi-threaded"
)

def test_parallel_randomstate_creation():
    # if the coercion cache is enabled and not thread-safe, creating
    # RandomState instances simultaneously leads to a data race
    def func(seed):
        np.random.RandomState(seed)

    run_threaded(func, 500, pass_count=True)


def test_parallel_ufunc_execution():
    # if the loop data cache or dispatch cache are not thread-safe
    # computing ufuncs simultaneously in multiple threads leads
    # to a data race that causes crashes or spurious exceptions
    def func():
        arr = np.random.random((25,))
        np.isnan(arr)

    run_threaded(func, 500)

    # see gh-26690
    NUM_THREADS = 50