ronantakizawa/codereview-bench huggingface dataset:
Repository: matplotlib/matplotlib
File: lib/matplotlib/tests/test_patheffects.py (Python)

Code before:
import platform

import numpy as np
from matplotlib.testing.decorators import image_comparison, check_figures_equal
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
from matplotlib.path import Path
import matplotlib.patches as patches
from matplotlib.backend_bases import RendererBase
from matplotlib.patheffects import PathEffectRenderer


@image_comparison(['patheffect1'], remove_text=True)
def test_patheffect1():
    ax1 = plt.subplot()
    ax1.imshow([[1, 2], [2, 3]])
    txt = ax1.annotate("test", (1., 1.), (0., 0),
                       arrowprops=dict(arrowstyle="->",
                                       connectionstyle="angle3", lw=2),
                       size=20, ha="center",
                       path_effects=[path_effects.withStroke(linewidth=3,
                                                             foreground="w")])
    txt.arrow_patch.set_path_effects([path_effects.Stroke(linewidth=5,
                                                          foreground="w"),
                                      path_effects.Normal()])

    pe = [path_effects.withStroke(linewidth=3, foreground="w")]
    ax1.grid(True, linestyle="-", path_effects=pe)


@image_comparison(['patheffect2'], remove_text=True, style='mpl20',

Review comment (suggestion):
This belongs in the third block, with first-party imports:
```suggestion
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison, check_figures_equal
```

Code after:
import platform

import numpy as np

from matplotlib.testing.decorators import image_comparison, check_figures_equal
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
from matplotlib.path import Path
import matplotlib.patches as patches
from matplotlib.backend_bases import RendererBase
from matplotlib.patheffects import PathEffectRenderer


@image_comparison(['patheffect1'], remove_text=True)
def test_patheffect1():
    ax1 = plt.subplot()
    ax1.imshow([[1, 2], [2, 3]])
    txt = ax1.annotate("test", (1., 1.), (0., 0),
                       arrowprops=dict(arrowstyle="->",
                                       connectionstyle="angle3", lw=2),
                       size=20, ha="center",
                       path_effects=[path_effects.withStroke(linewidth=3,
                                                             foreground="w")])
    txt.arrow_patch.set_path_effects([path_effects.Stroke(linewidth=5,
                                                          foreground="w"),
                                      path_effects.Normal()])

    pe = [path_effects.withStroke(linewidth=3, foreground="w")]
    ax1.grid(True, linestyle="-", path_effects=pe)
Repository: matplotlib/matplotlib
File: galleries/examples/text_labels_and_annotations/demo_annotation_box.py (Python)

Code before:
"""
======================
Artists as annotations
======================

`.AnnotationBbox` creates an annotation using an `.OffsetBox` object, which is a class
of container artists for positioning an artist relative to a parent artist. This allows
for annotations that are texts, images, and arbitrary artists.  `.AnnotationBbox` also
provides more fine-grained control than `.Axes.annotate`.
"""

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.cbook import get_sample_data
from matplotlib.offsetbox import (AnnotationBbox, DrawingArea, OffsetImage,
                                  TextArea)
from matplotlib.patches import Annulus, Circle

# %%%%
# Text
# ====
#
# `.AnnotationBbox` supports positioning annotations relative to data, Artists, and
# callables, as described in :ref:`annotations`. The  `.TextArea` is used to create a
# textbox that is not explicitly attached to an axes.
#
fig, ax = plt.subplots()

# Define a 1st position to annotate (display it with a marker)
xy = (0.5, 0.7)
ax.plot(xy[0], xy[1], ".r")

# Annotate the 1st position with a text box ('Test 1')

Review comment (suggestion):
Not sure whether my description is exactly correct, but I suggest to first state what you can achieve and only in the second step explain the technical background. I'd also push the discussion of `.Axes.annotate` down into the "Text" section.

```suggestion
`.AnnotationBbox` allows to use arbitrary Artists as annotations, including geometric shapes or images.

Technically, it accepts any `.OffsetBox` subclass, which is a container that supports positioning an artist relative to a parent artist.
```

Code after:
"""
======================
Artists as annotations
======================

`.AnnotationBbox` facilitates using arbitrary artists as annotations, i.e. data at
position *xy* is annotated by a box containing an artist at position *xybox*. The
coordinate systems for these points are set via the *xycoords* and *boxcoords*
parameters, respectively; see the *xycoords* and *textcoords* parameters of
`.Axes.annotate` for a full listing of supported coordinate systems.
The box containing the artist is a subclass of `.OffsetBox`, which is a container
artist for positioning an artist relative to a parent artist.
"""
from pathlib import Path

import PIL

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import get_data_path
from matplotlib.offsetbox import AnnotationBbox, DrawingArea, OffsetImage, TextArea
from matplotlib.patches import Annulus, Circle, ConnectionPatch

# %%%%
# Text
# ====
#
# `.AnnotationBbox` supports positioning annotations relative to data, Artists, and
# callables, as described in :ref:`annotations`. The  `.TextArea` is used to create a
# textbox that is not explicitly attached to an axes, which allows it to be used for
# annotating figure objects. When annotating an axes element (such as a plot) with text,
# use `.Axes.annotate` because it will create the text artist for you.
Repository: matplotlib/matplotlib
File: galleries/examples/text_labels_and_annotations/demo_annotation_box.py (Python)

Code before:

imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, xy,
                    xybox=(120., -80.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.5,
                    arrowprops=dict(
                        arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=3")
                    )

ax.add_artist(ab)

# Fix the display limits to see everything
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

plt.show()

# %%%%
# Arbitrary Artists
# ================
# `.DrawingArea` artists position arbitrary artists relative to their parent artists.

fig, ax = plt.subplots()
# Define a position to annotate (don't display with a marker)
xy = [0.3, 0.55]

# Annotate the position with a circle and annulus
da = DrawingArea(30, 30, 0, 0)
p = Circle((10, 10), 10, color='C0')
da.add_artist(p)
q = Annulus((20, 20), 10, 5, color='C1')
da.add_artist(q)


# Use the drawing area as an annotation
ab = AnnotationBbox(da, xy,
                    xybox=(.75, xy[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
                    box_alignment=(0.2, 0.5),
                    arrowprops=dict(arrowstyle="->"),
                    bboxprops=dict(alpha=0.5))

ax.add_artist(ab)
plt.show()
#

Review comment (suggestion):
```suggestion
# =================
# You can place a `.DrawingArea` inside the `.AnnoationBbox`. Then you can place mutliple
# and arbitrary artists inside the `.DrawingArea`.
```

Code after:
                    xybox=(-50., 50.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.3,
                    arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)

# Annotate the position with an image from file (a Grace Hopper portrait)
img_fp = Path(get_data_path(), "sample_data", "grace_hopper.jpg")
with PIL.Image.open(img_fp) as arr_img:
    imagebox = OffsetImage(arr_img, zoom=0.2)

imagebox.image.axes = ax

# place the image SE of xy
ab = AnnotationBbox(imagebox, xy=xy,
                    xybox=(120., -80.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.5,
                    arrowprops=dict(
                        arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=3")
                    )

ax.add_artist(ab)

# Fix the display limits to see everything
ax.set(xlim=(0, 1), ylim=(0, 1))

plt.show()

# %%%%
# Arbitrary Artists
# =================
#
# Multiple and arbitrary artists can be placed inside a `.DrawingArea`.

# make this the thumbnail image
# sphinx_gallery_thumbnail_number = 3
fig, ax = plt.subplots()

# Define a position to annotate
xy = (0.05, 0.5)
ax.scatter(*xy, s=500, marker='X')

# Annotate the position with a circle and annulus
da = DrawingArea(120, 120)
p = Circle((30, 30), 25, color='C0')
da.add_artist(p)
q = Annulus((65, 65), 50, 5, color='C1')
Repository: matplotlib/matplotlib
File: galleries/examples/text_labels_and_annotations/demo_annotation_box.py (Python)

Code before:
                    arrowprops=dict(
                        arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=3")
                    )

ax.add_artist(ab)

# Fix the display limits to see everything
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

plt.show()

# %%%%
# Arbitrary Artists
# =================
#
# Multiple and arbitrary artists can be placed inside a `.DrawingArea`.


fig, ax = plt.subplots()
# Define a position to annotate (don't display with a marker)
xy = [0.3, 0.55]

# Annotate the position with a circle and annulus
da = DrawingArea(30, 30, 0, 0)
p = Circle((10, 10), 10, color='C0')
da.add_artist(p)
q = Annulus((20, 20), 10, 5, color='C1')
da.add_artist(q)


# Use the drawing area as an annotation
ab = AnnotationBbox(da, xy,
                    xybox=(.75, xy[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
                    box_alignment=(0.2, 0.5),
                    arrowprops=dict(arrowstyle="->"),
                    bboxprops=dict(alpha=0.5))

ax.add_artist(ab)
plt.show()
#

# %%
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:

Review comment (suggestion):
```suggestion
da = DrawingArea(30, 30)
```
Leave out defaults

Code after:
    imagebox = OffsetImage(arr_img, zoom=0.2)

imagebox.image.axes = ax

# place the image SE of xy
ab = AnnotationBbox(imagebox, xy=xy,
                    xybox=(120., -80.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.5,
                    arrowprops=dict(
                        arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=3")
                    )

ax.add_artist(ab)

# Fix the display limits to see everything
ax.set(xlim=(0, 1), ylim=(0, 1))

plt.show()

# %%%%
# Arbitrary Artists
# =================
#
# Multiple and arbitrary artists can be placed inside a `.DrawingArea`.

# make this the thumbnail image
# sphinx_gallery_thumbnail_number = 3
fig, ax = plt.subplots()

# Define a position to annotate
xy = (0.05, 0.5)
ax.scatter(*xy, s=500, marker='X')

# Annotate the position with a circle and annulus
da = DrawingArea(120, 120)
p = Circle((30, 30), 25, color='C0')
da.add_artist(p)
q = Annulus((65, 65), 50, 5, color='C1')
da.add_artist(q)


# Use the drawing area as an annotation
ab = AnnotationBbox(da, xy=xy,
                    xybox=(.55, xy[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
                    box_alignment=(0, 0.5),
                    arrowprops=dict(arrowstyle="->"),
Repository: matplotlib/matplotlib
File: galleries/examples/text_labels_and_annotations/demo_annotation_box.py (Python)

Code before:
"""
======================
Artists as annotations
======================

`.AnnotationBbox` facilitates using arbitrary artists as annotations, i.e. data at
position *xy* is annotated by a box containing an artist at position *xybox*. The
coordinate systems for these point are set via the *xycoords* and *boxcoords*
parameters, respectively; see the *xycoords* and *textcoords* parameters of
`.Axes.annotate` for a full listing of supported coordinate systems.
The box containing the artist is a subclass of `.OffsetBox`, which is a container
artist for positioning an artist relative to a parent artist.
"""
from pathlib import Path

import PIL

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import get_data_path
from matplotlib.offsetbox import AnnotationBbox, DrawingArea, OffsetImage, TextArea
from matplotlib.patches import Annulus, Circle, ConnectionPatch

# %%%%
# Text
# ====
#
# `.AnnotationBbox` supports positioning annotations relative to data, Artists, and
# callables, as described in :ref:`annotations`. The  `.TextArea` is used to create a
# textbox that is not explicitly attached to an axes, which allows it to be used for
# annotating figure objects. When annotating an axes element (such as a plot) with text,
# use `.Axes.annotate` because it will create the text artist for you.

Review comment (suggestion):
```suggestion
coordinate systems for these points are set via the *xycoords* and *boxcoords*
```

Code after:
"""
======================
Artists as annotations
======================

`.AnnotationBbox` facilitates using arbitrary artists as annotations, i.e. data at
position *xy* is annotated by a box containing an artist at position *xybox*. The
coordinate systems for these points are set via the *xycoords* and *boxcoords*
parameters, respectively; see the *xycoords* and *textcoords* parameters of
`.Axes.annotate` for a full listing of supported coordinate systems.
The box containing the artist is a subclass of `.OffsetBox`, which is a container
artist for positioning an artist relative to a parent artist.
"""
from pathlib import Path

import PIL

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import get_data_path
from matplotlib.offsetbox import AnnotationBbox, DrawingArea, OffsetImage, TextArea
from matplotlib.patches import Annulus, Circle, ConnectionPatch

# %%%%
# Text
# ====
#
# `.AnnotationBbox` supports positioning annotations relative to data, Artists, and
# callables, as described in :ref:`annotations`. The  `.TextArea` is used to create a
# textbox that is not explicitly attached to an axes, which allows it to be used for
# annotating figure objects. When annotating an axes element (such as a plot) with text,
# use `.Axes.annotate` because it will create the text artist for you.
Repository: matplotlib/matplotlib
File: lib/matplotlib/legend.pyi (Python)

Code before:
from matplotlib.axes import Axes
from matplotlib.artist import Artist
from matplotlib.backend_bases import MouseEvent
from matplotlib.figure import Figure
from matplotlib.font_manager import FontProperties
from matplotlib.legend_handler import HandlerBase
from matplotlib.lines import Line2D
from matplotlib.offsetbox import (
    DraggableOffsetBox,
)
from matplotlib.patches import FancyBboxPatch, Patch, Rectangle
from matplotlib.text import Text
from matplotlib.transforms import (
    BboxBase,
    Transform,
)


import pathlib
from collections.abc import Iterable
from typing import Any, Literal, overload
from .typing import ColorType, LegendLocType

class DraggableLegend(DraggableOffsetBox):
    legend: Legend
    def __init__(
        self, legend: Legend, use_blit: bool = ..., update: Literal["loc", "bbox"] = ...
    ) -> None: ...
    def finalize_offset(self) -> None: ...

class Legend(Artist):
    codes: dict[str, int]
    zorder: float
    prop: FontProperties
    texts: list[Text]
    legend_handles: list[Artist | None]
    numpoints: int
    markerscale: float
    scatterpoints: int
    borderpad: float
    labelspacing: float
    handlelength: float
    handleheight: float
    handletextpad: float
    borderaxespad: float
    columnspacing: float
    shadow: bool

Review comment (suggestion):
This line is technically first-party and should be grouped with the others (though the rest of these of this block are stdlib and belong first, also.)

Code after:
from matplotlib.axes import Axes
from matplotlib.artist import Artist
from matplotlib.backend_bases import MouseEvent
from matplotlib.figure import Figure
from matplotlib.font_manager import FontProperties
from matplotlib.legend_handler import HandlerBase
from matplotlib.lines import Line2D
from matplotlib.offsetbox import (
    DraggableOffsetBox,
)
from matplotlib.patches import FancyBboxPatch, Patch, Rectangle
from matplotlib.text import Text
from matplotlib.transforms import (
    BboxBase,
    Transform,
)
from matplotlib.typing import ColorType, LegendLocType


import pathlib
from collections.abc import Iterable
from typing import Any, Literal, overload


class DraggableLegend(DraggableOffsetBox):
    legend: Legend
    def __init__(
        self, legend: Legend, use_blit: bool = ..., update: Literal["loc", "bbox"] = ...
    ) -> None: ...
    def finalize_offset(self) -> None: ...

class Legend(Artist):
    codes: dict[str, int]
    zorder: float
    prop: FontProperties
    texts: list[Text]
    legend_handles: list[Artist | None]
    numpoints: int
    markerscale: float
    scatterpoints: int
    borderpad: float
    labelspacing: float
    handlelength: float
    handleheight: float
    handletextpad: float
    borderaxespad: float
    columnspacing: float
Repository: matplotlib/matplotlib
File: src/ft2font.cpp (C++)

Code before:

int FT2Font::get_kerning(FT_UInt left, FT_UInt right, FT_Kerning_Mode mode)
{
    if (!FT_HAS_KERNING(face)) {
        return 0;
    }

    FT_Vector delta;
    if (!FT_Get_Kerning(face, left, right, mode, &delta)) {
        return (int)(delta.x) / (hinting_factor << kerning_factor);
    } else {
        return 0;
    }
}

void FT2Font::set_kerning_factor(int factor)
{
    kerning_factor = factor;
    for (auto & fallback : fallbacks) {
        fallback->set_kerning_factor(factor);
    }
}

void FT2Font::set_text(
    std::u32string_view text, double angle, FT_Int32 flags,
    std::optional<std::vector<std::string>> features, // TODO: Apply features with libraqm.
    std::vector<double> &xys)
{
    FT_Matrix matrix; /* transformation matrix */

    angle = angle * (2 * M_PI / 360.0);

    // this computes width and height in subpixels so we have to multiply by 64
    double cosangle = cos(angle) * 0x10000L;
    double sinangle = sin(angle) * 0x10000L;

    matrix.xx = (FT_Fixed)cosangle;
    matrix.xy = (FT_Fixed)-sinangle;
    matrix.yx = (FT_Fixed)sinangle;
    matrix.yy = (FT_Fixed)cosangle;

    clear();

    bbox.xMin = bbox.yMin = 32000;
    bbox.xMax = bbox.yMax = -32000;

    FT_UInt previous = 0;
    FT2Font *previous_ft_object = nullptr;

    for (auto codepoint : text) {
        FT_UInt glyph_index = 0;

Review comment (suggestion):
Same question, is the TODO intended to have been resolved here? (This one I think more explicitly looks like it requires the actual libraqm changes, but checking)

Code after:
        fallback->set_size(ptsize, dpi);
    }
}

void FT2Font::set_charmap(int i)
{
    if (i >= face->num_charmaps) {
        throw std::runtime_error("i exceeds the available number of char maps");
    }
    FT_CHECK(FT_Set_Charmap, face, face->charmaps[i]);
}

void FT2Font::select_charmap(unsigned long i)
{
    FT_CHECK(FT_Select_Charmap, face, (FT_Encoding)i);
}

int FT2Font::get_kerning(FT_UInt left, FT_UInt right, FT_Kerning_Mode mode)
{
    if (!FT_HAS_KERNING(face)) {
        return 0;
    }

    FT_Vector delta;
    if (!FT_Get_Kerning(face, left, right, mode, &delta)) {
        return (int)(delta.x) / (hinting_factor << kerning_factor);
    } else {
        return 0;
    }
}

void FT2Font::set_kerning_factor(int factor)
{
    kerning_factor = factor;
    for (auto & fallback : fallbacks) {
        fallback->set_kerning_factor(factor);
    }
}

std::vector<raqm_glyph_t> FT2Font::layout(
    std::u32string_view text, FT_Int32 flags,
    std::optional<std::vector<std::string>> features, LanguageType languages,
    std::set<FT_String*>& glyph_seen_fonts)
{
    clear();

    auto rq = raqm_create();
    if (!rq) {
        throw std::runtime_error("failed to compute text layout");
    }
    [[maybe_unused]] auto const& rq_cleanup =
Repository: matplotlib/matplotlib
File: lib/matplotlib/_mathtext.py (Python)

Code before:
"""
Implementation details for :mod:`.mathtext`.
"""

from __future__ import annotations

import abc
import copy
import enum
import functools
import logging
import os
import re
import types
import unicodedata
import string
import typing as T
from typing import NamedTuple

import numpy as np
from pyparsing import (
    Empty, Forward, Literal, NotAny, one_of, OneOrMore, Optional,
    ParseBaseException, ParseException, ParseExpression, ParseFatalException,
    ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore,
    pyparsing_common, Group, nested_expr)

import matplotlib as mpl
from . import cbook
from ._mathtext_data import (
    latex_to_bakoma, stix_glyph_fixes, stix_virtual_fonts, tex2uni)
from .font_manager import FontProperties, findfont, get_font
from .ft2font import FT2Font, FT2Image, Kerning, LoadFlags


if T.TYPE_CHECKING:
    from collections.abc import Iterable
    from .ft2font import Glyph

ParserElement.enable_packrat()
_log = logging.getLogger("matplotlib.mathtext")


##############################################################################
# FONTS


def get_unicode_index(symbol: str) -> int:  # Publicly exported.
    r"""
    Return the integer index (from the Unicode table) of *symbol*.


Review comment (suggestion):
This is almost sorted, so let's fix that.
```suggestion
    Empty, Forward, Group, Literal, NotAny, OneOrMore, Optional,
    ParseBaseException, ParseException, ParseExpression, ParseFatalException,
    ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore,
    nested_expr, one_of, pyparsing_common)
```

Code after:
"""
Implementation details for :mod:`.mathtext`.
"""

from __future__ import annotations

import abc
import copy
import enum
import functools
import logging
import os
import re
import types
import unicodedata
import string
import typing as T
from typing import NamedTuple

import numpy as np
from pyparsing import (
    Empty, Forward, Literal, Group, NotAny, OneOrMore, Optional,
    ParseBaseException, ParseException, ParseExpression, ParseFatalException,
    ParserElement, ParseResults, QuotedString, Regex, StringEnd, ZeroOrMore,
    pyparsing_common, nested_expr, one_of)

import matplotlib as mpl
from . import cbook
from ._mathtext_data import (
    latex_to_bakoma, stix_glyph_fixes, stix_virtual_fonts, tex2uni)
from .font_manager import FontProperties, findfont, get_font
from .ft2font import FT2Font, FT2Image, Kerning, LoadFlags


if T.TYPE_CHECKING:
    from collections.abc import Iterable
    from .ft2font import Glyph

ParserElement.enable_packrat()
_log = logging.getLogger("matplotlib.mathtext")


##############################################################################
# FONTS


def get_unicode_index(symbol: str) -> int:  # Publicly exported.
    r"""
    Return the integer index (from the Unicode table) of *symbol*.