ronantakizawa/codereview-bench huggingface dataset:
Repository: matplotlib/matplotlib
File: lib/matplotlib/font_manager.pyi (Python)

Code before:
from collections.abc import Iterable
from dataclasses import dataclass
from numbers import Number
import os
from pathlib import Path
from typing import Any, Literal

from matplotlib._afm import AFM
from matplotlib import ft2font

font_scalings: dict[str | None, float]
stretch_dict: dict[str, int]
weight_dict: dict[str, int]
font_family_aliases: set[str]
MSFolders: str
MSFontDirectories: list[str]
MSUserFontDirectories: list[str]
X11FontDirectories: list[str]
OSXFontDirectories: list[str]

def _normalize_weight(weight: str | Number) -> Number: ...
def get_fontext_synonyms(fontext: str) -> list[str]: ...
def list_fonts(directory: str, extensions: Iterable[str]) -> list[str]: ...
def win32FontDirectory() -> str: ...
def _get_fontconfig_fonts() -> list[Path]: ...
def findSystemFonts(
    fontpaths: Iterable[str | os.PathLike | Path] | None = ..., fontext: str = ...
) -> list[str]: ...
@dataclass
class FontEntry:
    fname: str = ...
    name: str = ...
    style: str = ...
    variant: str = ...
    weight: str | int = ...
    stretch: str = ...
    size: str = ...
    def _repr_html_(self) -> str: ...
    def _repr_png_(self) -> bytes: ...

def ttfFontProperty(font: ft2font.FT2Font) -> FontEntry: ...
def afmFontProperty(fontpath: str, font: AFM) -> FontEntry: ...

class FontProperties:
    def __init__(
        self,

Review comment (suggestion):
Typical font weights are multiples of 100. Can / should this be any Number or can we specialize to int?

```suggestion
def _normalize_weight(weight: str | int) -> int: ...
```

If we want a general Number, there should be a test case for it.

Code after:
from collections.abc import Iterable
from dataclasses import dataclass
from numbers import Integral
import os
from pathlib import Path
from typing import Any, Literal

from matplotlib._afm import AFM
from matplotlib import ft2font

font_scalings: dict[str | None, float]
stretch_dict: dict[str, int]
weight_dict: dict[str, int]
font_family_aliases: set[str]
MSFolders: str
MSFontDirectories: list[str]
MSUserFontDirectories: list[str]
X11FontDirectories: list[str]
OSXFontDirectories: list[str]

def _normalize_weight(weight: str | Integral) -> Integral: ...
def get_fontext_synonyms(fontext: str) -> list[str]: ...
def list_fonts(directory: str, extensions: Iterable[str]) -> list[str]: ...
def win32FontDirectory() -> str: ...
def _get_fontconfig_fonts() -> list[Path]: ...
def findSystemFonts(
    fontpaths: Iterable[str | os.PathLike | Path] | None = ..., fontext: str = ...
) -> list[str]: ...
@dataclass
class FontEntry:
    fname: str = ...
    name: str = ...
    style: str = ...
    variant: str = ...
    weight: str | int = ...
    stretch: str = ...
    size: str = ...
    def _repr_html_(self) -> str: ...
    def _repr_png_(self) -> bytes: ...

def ttfFontProperty(font: ft2font.FT2Font) -> FontEntry: ...
def afmFontProperty(fontpath: str, font: AFM) -> FontEntry: ...

class FontProperties:
    def __init__(
        self,
Repository: matplotlib/matplotlib
File: lib/matplotlib/pyplot.py (Python)

Code before:
def get_figlabels() -> list[Any]:
    """Return a list of existing figure labels."""
    managers = _pylab_helpers.Gcf.get_all_fig_managers()
    managers.sort(key=lambda m: m.num)
    return [m.canvas.figure.get_label() for m in managers]


def get_current_fig_manager() -> FigureManagerBase | None:
    """
    Return the figure manager of the current figure.

    The figure manager is a container for the actual backend-depended window
    that displays the figure on screen.

    If no current figure exists, a new one is created, and its figure
    manager is returned.

    Returns
    -------
    `.FigureManagerBase` or backend-dependent subclass thereof
    """
    return gcf().canvas.manager


@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect)
def connect(s: EventType, func: Callable[[Event], Any]) -> int:
    return gcf().canvas.mpl_connect(s, func)


@_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect)
def disconnect(cid: int) -> None:
    gcf().canvas.mpl_disconnect(cid)


def close(fig: None | int | str | Figure | Literal["all"] = None) -> None:
    """
    Close a figure window, and unregister it from pyplot.

    Parameters
    ----------
    fig : None or int or str or `.Figure`
        The figure to close. There are a number of ways to specify this:

        - *None*: the current figure
        - `.Figure`: the given `.Figure` instance
        - ``int``: a figure number
        - ``str``: a figure name
        - 'all': all figures

    Notes
    -----

Review comment (suggestion):
I think you should be able to add `overload`s above this with the individual event types.

Code after:
    return (
        _pylab_helpers.Gcf.has_fignum(num)
        if isinstance(num, int)
        else num in get_figlabels()
    )


def get_fignums() -> list[int]:
    """Return a list of existing figure numbers."""
    return sorted(_pylab_helpers.Gcf.figs)


def get_figlabels() -> list[Any]:
    """Return a list of existing figure labels."""
    managers = _pylab_helpers.Gcf.get_all_fig_managers()
    managers.sort(key=lambda m: m.num)
    return [m.canvas.figure.get_label() for m in managers]


def get_current_fig_manager() -> FigureManagerBase | None:
    """
    Return the figure manager of the current figure.

    The figure manager is a container for the actual backend-depended window
    that displays the figure on screen.

    If no current figure exists, a new one is created, and its figure
    manager is returned.

    Returns
    -------
    `.FigureManagerBase` or backend-dependent subclass thereof
    """
    return gcf().canvas.manager


@overload
def connect(s: MouseEventType, func: Callable[[MouseEvent], Any]) -> int: ...


@overload
def connect(s: KeyEventType, func: Callable[[KeyEvent], Any]) -> int: ...


@overload
def connect(s: PickEventType, func: Callable[[PickEvent], Any]) -> int: ...


@overload
def connect(s: ResizeEventType, func: Callable[[ResizeEvent], Any]) -> int: ...
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_offsetbox.py (Python)

Code before:

    # Case 1: Establish a baseline with float value
    text_float = AnchoredText("float", loc='lower left', borderpad=5)
    ax.add_artist(text_float)

    # Case 2: Test that a symmetric tuple gives the exact same result.
    text_tuple_equal = AnchoredText("tuple", loc='lower left', borderpad=(5, 5))
    ax.add_artist(text_tuple_equal)

    # Case 3: Test that an asymmetric tuple with larger values works as expected.
    text_tuple_asym = AnchoredText("tuple_asym", loc='lower left', borderpad=(10, 4))
    ax.add_artist(text_tuple_asym)

    # Draw the canvas to calculate final positions
    fig.canvas.draw()

    pos_float = text_float.get_window_extent()
    pos_tuple_equal = text_tuple_equal.get_window_extent()
    pos_tuple_asym = text_tuple_asym.get_window_extent()

    # Assertion 1: Prove that borderpad=5 is identical to borderpad=(5, 5).
    assert pos_tuple_equal.x0 == pos_float.x0
    assert pos_tuple_equal.y0 == pos_float.y0

    # Assertion 2: Prove that the larger, asymmetric padding moved the box
    # further from the origin than the baseline.
    assert pos_tuple_asym.x0 > pos_float.x0
    assert pos_tuple_asym.y0 < pos_float.y0


Review comment (suggestion):
```suggestion
    # Assertion 2: Prove that the asymmetric padding moved the box
    # further from the origin than the baseline in the x-direction and less far in the y-direction.
```

Code after:

    # Case 1: Establish a baseline with float value
    text_float = AnchoredText("float", loc='lower left', borderpad=5)
    ax.add_artist(text_float)

    # Case 2: Test that a symmetric tuple gives the exact same result.
    text_tuple_equal = AnchoredText("tuple", loc='lower left', borderpad=(5, 5))
    ax.add_artist(text_tuple_equal)

    # Case 3: Test that an asymmetric tuple with different values works as expected.
    text_tuple_asym = AnchoredText("tuple_asym", loc='lower left', borderpad=(10, 4))
    ax.add_artist(text_tuple_asym)

    # Draw the canvas to calculate final positions
    fig.canvas.draw()

    pos_float = text_float.get_window_extent()
    pos_tuple_equal = text_tuple_equal.get_window_extent()
    pos_tuple_asym = text_tuple_asym.get_window_extent()

    # Assertion 1: Prove that borderpad=5 is identical to borderpad=(5, 5).
    assert pos_tuple_equal.x0 == pos_float.x0
    assert pos_tuple_equal.y0 == pos_float.y0

    # Assertion 2: Prove that the asymmetric padding moved the box
    # further from the origin than the baseline in the x-direction and less far
    # in the y-direction.
    assert pos_tuple_asym.x0 > pos_float.x0
    assert pos_tuple_asym.y0 < pos_float.y0
Repository: matplotlib/matplotlib
File: lib/matplotlib/widgets.pyi (Python)

Code before:
class Button(AxesWidget):
    label: Text
    color: ColorType
    hovercolor: ColorType
    def __init__(
        self,
        ax: Axes,
        label: str,
        image: ArrayLike | PIL.Image.Image | None = ...,
        color: ColorType = ...,
        hovercolor: ColorType = ...,
        *,
        useblit: bool = ...
    ) -> None: ...
    def on_clicked(self, func: Callable[[Event], Any]) -> int: ...
    def disconnect(self, cid: int) -> None: ...

class SliderBase(AxesWidget):
    orientation: Literal["horizontal", "vertical"]
    closedmin: bool
    closedmax: bool
    valmin: float
    valmax: float
    valstep: float | ArrayLike | None
    drag_active: bool
    valfmt: str | Callable[[float], str]
    def __init__(
        self,
        ax: Axes,
        orientation: Literal["horizontal", "vertical"],
        closedmin: bool,
        closedmax: bool,
        valmin: float,
        valmax: float,
        valfmt: str | Callable[[float], str],
        dragging: Slider | None,
        valstep: float | ArrayLike | None,
    ) -> None: ...
    def disconnect(self, cid: int) -> None: ...
    def reset(self) -> None: ...

class Slider(SliderBase):
    slidermin: Slider | None
    slidermax: Slider | None
    val: float
    valinit: float
    track: Rectangle
    poly: Polygon
    hline: Line2D
    vline: Line2D
    label: Text

Review comment (suggestion):
I think we missed None here, but it can happen ...
```suggestion
    valfmt: str | Callable[[float], str] | None
```

Code after:
class Button(AxesWidget):
    label: Text
    color: ColorType
    hovercolor: ColorType
    def __init__(
        self,
        ax: Axes,
        label: str,
        image: ArrayLike | PIL.Image.Image | None = ...,
        color: ColorType = ...,
        hovercolor: ColorType = ...,
        *,
        useblit: bool = ...
    ) -> None: ...
    def on_clicked(self, func: Callable[[Event], Any]) -> int: ...
    def disconnect(self, cid: int) -> None: ...

class SliderBase(AxesWidget):
    orientation: Literal["horizontal", "vertical"]
    closedmin: bool
    closedmax: bool
    valmin: float
    valmax: float
    valstep: float | ArrayLike | None
    drag_active: bool
    valfmt: str | Callable[[float], str] | None
    def __init__(
        self,
        ax: Axes,
        orientation: Literal["horizontal", "vertical"],
        closedmin: bool,
        closedmax: bool,
        valmin: float,
        valmax: float,
        valfmt: str | Callable[[float], str] | None,
        dragging: Slider | None,
        valstep: float | ArrayLike | None,
    ) -> None: ...
    def disconnect(self, cid: int) -> None: ...
    def reset(self) -> None: ...

class Slider(SliderBase):
    slidermin: Slider | None
    slidermax: Slider | None
    val: float
    valinit: float
    track: Rectangle
    poly: Polygon
    hline: Line2D
    vline: Line2D
    label: Text
Repository: matplotlib/matplotlib
File: lib/matplotlib/widgets.pyi (Python)

Code before:
        color: ColorType = ...,
        hovercolor: ColorType = ...,
        *,
        useblit: bool = ...
    ) -> None: ...
    def on_clicked(self, func: Callable[[Event], Any]) -> int: ...
    def disconnect(self, cid: int) -> None: ...

class SliderBase(AxesWidget):
    orientation: Literal["horizontal", "vertical"]
    closedmin: bool
    closedmax: bool
    valmin: float
    valmax: float
    valstep: float | ArrayLike | None
    drag_active: bool
    valfmt: str | Callable[[float], str]
    def __init__(
        self,
        ax: Axes,
        orientation: Literal["horizontal", "vertical"],
        closedmin: bool,
        closedmax: bool,
        valmin: float,
        valmax: float,
        valfmt: str | Callable[[float], str],
        dragging: Slider | None,
        valstep: float | ArrayLike | None,
    ) -> None: ...
    def disconnect(self, cid: int) -> None: ...
    def reset(self) -> None: ...

class Slider(SliderBase):
    slidermin: Slider | None
    slidermax: Slider | None
    val: float
    valinit: float
    track: Rectangle
    poly: Polygon
    hline: Line2D
    vline: Line2D
    label: Text
    valtext: Text
    def __init__(
        self,
        ax: Axes,
        label: str,
        valmin: float,
        valmax: float,
        *,
        valinit: float = ...,

Review comment (suggestion):
Same here
```suggestion
        valfmt: str | Callable[[float], str] | None,
```

Code after:
        color: ColorType = ...,
        hovercolor: ColorType = ...,
        *,
        useblit: bool = ...
    ) -> None: ...
    def on_clicked(self, func: Callable[[Event], Any]) -> int: ...
    def disconnect(self, cid: int) -> None: ...

class SliderBase(AxesWidget):
    orientation: Literal["horizontal", "vertical"]
    closedmin: bool
    closedmax: bool
    valmin: float
    valmax: float
    valstep: float | ArrayLike | None
    drag_active: bool
    valfmt: str | Callable[[float], str] | None
    def __init__(
        self,
        ax: Axes,
        orientation: Literal["horizontal", "vertical"],
        closedmin: bool,
        closedmax: bool,
        valmin: float,
        valmax: float,
        valfmt: str | Callable[[float], str] | None,
        dragging: Slider | None,
        valstep: float | ArrayLike | None,
    ) -> None: ...
    def disconnect(self, cid: int) -> None: ...
    def reset(self) -> None: ...

class Slider(SliderBase):
    slidermin: Slider | None
    slidermax: Slider | None
    val: float
    valinit: float
    track: Rectangle
    poly: Polygon
    hline: Line2D
    vline: Line2D
    label: Text
    valtext: Text
    def __init__(
        self,
        ax: Axes,
        label: str,
        valmin: float,
        valmax: float,
        *,
        valinit: float = ...,
Repository: matplotlib/matplotlib
File: lib/matplotlib/backends/backend_agg.py (Python)

Code before:

    def print_avif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
        self._print_pil(filename_or_obj, "avif", pil_kwargs, metadata)

    (print_gif.__doc__,
     print_jpg.__doc__,
     print_tif.__doc__,
     print_webp.__doc__,
     print_avif.__doc__) = map(
        """
        Write the figure to a {} file.

        Parameters
        ----------
        filename_or_obj : str or path-like or file-like
            The file to write to.
        pil_kwargs : dict, optional
            Additional keyword arguments that are passed to
            `PIL.Image.Image.save` when saving the figure.
        """.format, ["GIF", "JPEG", "TIFF", "WebP", "AVIF"])


@_Backend.export
class _BackendAgg(_Backend):
    backend_version = 'v2.2'
    FigureCanvas = FigureCanvasAgg
    FigureManager = FigureManagerBase


Review comment (suggestion):
Not directly related, but while at it, let's clarify this:

```suggestion
        metadata : None
            Unused for pillow-based writers. All supported options
            can be passed via *pil_kwargs*.
        pil_kwargs : dict, optional
```

Code after:
        self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata)

    def print_avif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
        if not features.check("avif"):
            raise RuntimeError(
                "The installed pillow version does not support avif. Full "
                "avif support has been added in pillow 11.3."
            )
        self._print_pil(filename_or_obj, "avif", pil_kwargs, metadata)

    (print_gif.__doc__,
     print_jpg.__doc__,
     print_tif.__doc__,
     print_webp.__doc__,
     print_avif.__doc__) = map(
        """
        Write the figure to a {} file.

        Parameters
        ----------
        filename_or_obj : str or path-like or file-like
            The file to write to.
        metadata : None
            Unused for pillow-based writers. All supported options
            can be passed via *pil_kwargs*.
        pil_kwargs : dict, optional
            Additional keyword arguments that are passed to
            `PIL.Image.Image.save` when saving the figure.
        """.format, ["GIF", "JPEG", "TIFF", "WebP", "AVIF"])


@_Backend.export
class _BackendAgg(_Backend):
    backend_version = 'v2.2'
    FigureCanvas = FigureCanvasAgg
    FigureManager = FigureManagerBase
Repository: matplotlib/matplotlib
File: lib/mpl_toolkits/mplot3d/tests/test_axes3d.py (Python)

Code before:
        poly = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float)
        c = art3d.Poly3DCollection([poly], shade=True)


def test_ndarray_color_kwargs_value_error():
    # smoke test
    # ensures ndarray can be passed to color in kwargs for 3d projection plot
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(1, 0, 0, color=np.array([0, 0, 0, 1]))
    fig.canvas.draw()


def test_line3dcollection_autolim_ragged():
    """Test Line3DCollection with autolim=True and lines of different lengths."""
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')

    # Create lines with different numbers of points (ragged arrays)
    edges = [
        [(0, 0, 0), (1, 1, 1), (2, 2, 2)],  # 3 points
        [(0, 1, 0), (1, 2, 1)],             # 2 points
        [(1, 0, 1), (2, 1, 2), (3, 2, 3), (4, 3, 4)]  # 4 points
    ]

    # This should not raise an exception with the fix
    collections = ax.add_collection3d(art3d.Line3DCollection(edges), autolim=True)

    # Check that limits were computed correctly with margins
    # The limits should include all points with default margins
    assert np.allclose(ax.get_xlim3d(), (-0.08333333333333333, 4.083333333333333))
    assert np.allclose(ax.get_ylim3d(), (-0.0625, 3.0625))
    assert np.allclose(ax.get_zlim3d(), (-0.08333333333333333, 4.083333333333333))

    plt.close(fig)


Review comment (suggestion):
"with the fix" won't make much sense in a few month.
```suggestion
    # This should not raise an exception.
```

Code after:
        poly = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float)
        c = art3d.Poly3DCollection([poly], shade=True)


def test_ndarray_color_kwargs_value_error():
    # smoke test
    # ensures ndarray can be passed to color in kwargs for 3d projection plot
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(1, 0, 0, color=np.array([0, 0, 0, 1]))
    fig.canvas.draw()


def test_line3dcollection_autolim_ragged():
    """Test Line3DCollection with autolim=True and lines of different lengths."""
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')

    # Create lines with different numbers of points (ragged arrays)
    edges = [
        [(0, 0, 0), (1, 1, 1), (2, 2, 2)],  # 3 points
        [(0, 1, 0), (1, 2, 1)],             # 2 points
        [(1, 0, 1), (2, 1, 2), (3, 2, 3), (4, 3, 4)]  # 4 points
    ]

    # This should not raise an exception.
    collections = ax.add_collection3d(art3d.Line3DCollection(edges), autolim=True)

    # Check that limits were computed correctly with margins
    # The limits should include all points with default margins
    assert np.allclose(ax.get_xlim3d(), (-0.08333333333333333, 4.083333333333333))
    assert np.allclose(ax.get_ylim3d(), (-0.0625, 3.0625))
    assert np.allclose(ax.get_zlim3d(), (-0.08333333333333333, 4.083333333333333))
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_contour.py (Python)

Code before:
    for result in [cs.allsegs, cs.allkinds]:
        assert len(result) == 2
        assert len(result[0]) == 5
        assert len(result[1]) == 4


@image_comparison(baseline_images=['contour_rasterization'],
                  extensions=['pdf'], style='mpl20', savefig_kwarg={'dpi': 25})
def test_contourf_rasterize():
    fig, ax = plt.subplots()
    data = [[0, 1], [1, 0]]
    circle = mpatches.Circle([0.5, 0.5], 0.5, transform=ax.transAxes)
    cs = ax.contourf(data, clip_path=circle, rasterized=True)
    assert cs._rasterized


@check_figures_equal(extensions=["png"])
def test_contour_aliases(fig_test, fig_ref):
    data = np.arange(100).reshape((10, 10)) ** 2
    fig_test.add_subplot().contour(data, linestyle=":")
    fig_ref.add_subplot().contour(data, linestyles="dotted")


def test_contour_singular_color():
    with pytest.raises(TypeError):
        plt.figure().add_subplot().contour([[0]], color="r")


Review comment (bug):
The TypeError is coming from the wrong place, the first argument rather than the second.  To fix, use
`plt.figure().add_subplot().contour([[0, 1], [2, 3]], color="r")`.

Code after:
    for result in [cs.allsegs, cs.allkinds]:
        assert len(result) == 2
        assert len(result[0]) == 5
        assert len(result[1]) == 4


@image_comparison(baseline_images=['contour_rasterization'],
                  extensions=['pdf'], style='mpl20', savefig_kwarg={'dpi': 25})
def test_contourf_rasterize():
    fig, ax = plt.subplots()
    data = [[0, 1], [1, 0]]
    circle = mpatches.Circle([0.5, 0.5], 0.5, transform=ax.transAxes)
    cs = ax.contourf(data, clip_path=circle, rasterized=True)
    assert cs._rasterized


@check_figures_equal(extensions=["png"])
def test_contour_aliases(fig_test, fig_ref):
    data = np.arange(100).reshape((10, 10)) ** 2
    fig_test.add_subplot().contour(data, linestyle=":")
    fig_ref.add_subplot().contour(data, linestyles="dotted")


def test_contour_singular_color():
    with pytest.raises(TypeError):
        plt.figure().add_subplot().contour([[0, 1], [2, 3]], color="r")