ronantakizawa/codereview-bench huggingface dataset:
Repository: ManimCommunity/manim
File: conftest.py (Python)

Code before:
# This file is automatically picked by pytest
# while running tests. So, that each test is
# run on difference temporary directories and avoiding
# errors.

from __future__ import annotations

try:
    # https://github.com/moderngl/moderngl/issues/517
    import readline  # required to prevent a segfault on Python 3.10 # noqa: F401
except ModuleNotFoundError:  # windows
    pass

import cairo
import moderngl

# If it is running Doctest the current directory
# is changed because it also tests the config module
# itself. If it's a normal test then it uses the
# tempconfig to change directories.
import pytest
from _pytest.doctest import DoctestItem

from manim import config, tempconfig


@pytest.fixture(autouse=True)
def temp_media_dir(tmpdir, monkeypatch, request):
    if isinstance(request.node, DoctestItem):
        monkeypatch.chdir(tmpdir)
        yield tmpdir
    else:
        with tempconfig({"media_dir": str(tmpdir)}):
            assert config.media_dir == str(tmpdir)
            yield tmpdir



Review comment (suggestion):
According to related issue, does not seem to be required anymore? Could you try removing it and see if tests passes? (Might need to update the `moderngl` locked version)

Code after:
# This file is automatically picked by pytest
# while running tests. So, that each test is
# run on difference temporary directories and avoiding
# errors.

from __future__ import annotations

import cairo
import moderngl

# If it is running Doctest the current directory
# is changed because it also tests the config module
# itself. If it's a normal test then it uses the
# tempconfig to change directories.
import pytest
from _pytest.doctest import DoctestItem

from manim import config, tempconfig


@pytest.fixture(autouse=True)
def temp_media_dir(tmpdir, monkeypatch, request):
    if isinstance(request.node, DoctestItem):
        monkeypatch.chdir(tmpdir)
        yield tmpdir
    else:
        with tempconfig({"media_dir": str(tmpdir)}):
            assert config.media_dir == str(tmpdir)
            yield tmpdir


def pytest_report_header(config):
    ctx = moderngl.create_standalone_context()
    info = ctx.info
    ctx.release()
    return (
        f"\nCairo Version: {cairo.cairo_version()}",
Repository: ManimCommunity/manim
File: manim/utils/docbuild/autoaliasattr_directive.py (Python)

Code before:

def smart_replace(base: str, alias: str, substitution: str) -> str:
    """Auxiliary function for substituting type aliases into a base
    string, when there are overlaps between the aliases themselves.

    Parameters
    ----------
    base
        The string in which the type aliases will be located and
        replaced.
    alias
        The substring to be substituted.
    substitution
        The string which will replace every occurrence of ``alias``.

    Returns
    -------
    str
        The new string after the alias substitution.
    """

    occurrences = []
    len_alias = len(alias)
    len_base = len(base)

    def condition(char: str):
        return not char.isalnum() and char != "_"

    start = 0
    i = 0
    while True:
        i = base.find(alias, start)
        if i == -1:
            break
        if (i == 0 or condition(base[i - 1])) and (
            i + len_alias == len_base or condition(base[i + len_alias])
        ):
            occurrences.append(i)
        start = i + len_alias

    for o in occurrences[::-1]:
        base = base[:o] + substitution + base[o + len_alias :]

    return base


def setup(app: Sphinx) -> None:
    app.add_directive("autoaliasattr", AliasAttrDocumenter)


class AliasAttrDocumenter(Directive):

Review comment (suggestion):
Let's fully type it :)

```suggestion
    def condition(char: str) -> bool:
```

Code after:

def smart_replace(base: str, alias: str, substitution: str) -> str:
    """Auxiliary function for substituting type aliases into a base
    string, when there are overlaps between the aliases themselves.

    Parameters
    ----------
    base
        The string in which the type aliases will be located and
        replaced.
    alias
        The substring to be substituted.
    substitution
        The string which will replace every occurrence of ``alias``.

    Returns
    -------
    str
        The new string after the alias substitution.
    """

    occurrences = []
    len_alias = len(alias)
    len_base = len(base)

    def condition(char: str) -> bool:
        return not char.isalnum() and char != "_"

    start = 0
    i = 0
    while True:
        i = base.find(alias, start)
        if i == -1:
            break
        if (i == 0 or condition(base[i - 1])) and (
            i + len_alias == len_base or condition(base[i + len_alias])
        ):
            occurrences.append(i)
        start = i + len_alias

    for o in occurrences[::-1]:
        base = base[:o] + substitution + base[o + len_alias :]

    return base


def setup(app: Sphinx) -> None:
    app.add_directive("autoaliasattr", AliasAttrDocumenter)


class AliasAttrDocumenter(Directive):
Repository: ManimCommunity/manim
File: tests/test_config.py (Python)

Code before:
        # check that config was modified correctly
        assert config["frame_width"] == 100
        assert config["frame_height"] == 42

        # check that no keys are missing and no new keys were added
        assert set(original.keys()) == set(config.keys())

    # check that the keys are still untouched
    assert set(original.keys()) == set(config.keys())

    # check that config is correctly restored
    for k, v in original.items():
        if isinstance(v, np.ndarray):
            np.testing.assert_allclose(config[k], v)
        else:
            assert config[k] == v


class MyScene(Scene):
    def construct(self):
        self.add(Square())
        self.add(Text("Prepare for unforeseen consequencesλ"))
        self.add(Tex(r"$\lambda$"))
        self.wait(1)


def test_transparent(config):
    """Test the 'transparent' config option."""

    config.verbosity = "ERROR"
    config.dry_run = True

    scene = MyScene()
    scene.render()
    frame = scene.renderer.get_frame()
    np.testing.assert_allclose(frame[0, 0], [0, 0, 0, 255])

    config.transparent = True

    scene = MyScene()
    scene.render()
    frame = scene.renderer.get_frame()
    np.testing.assert_allclose(frame[0, 0], [0, 0, 0, 0])


def test_background_color(config):
    """Test the 'background_color' config option."""

    config.background_color = WHITE
    config.verbosity = "ERROR"
    config.dry_run = True

Review comment (suggestion):
It is somewhat odd how differently we are treating the case of `.gif`, but that's a different discussion.

Code after:
    with tempconfig({"frame_width": 100, "frame_height": 42}):
        # check that config was modified correctly
        assert config["frame_width"] == 100
        assert config["frame_height"] == 42

        # check that no keys are missing and no new keys were added
        assert set(original.keys()) == set(config.keys())

    # check that the keys are still untouched
    assert set(original.keys()) == set(config.keys())

    # check that config is correctly restored
    for k, v in original.items():
        if isinstance(v, np.ndarray):
            np.testing.assert_allclose(config[k], v)
        else:
            assert config[k] == v


@pytest.mark.parametrize(
    ("format", "expected_file_extension"),
    [
        ("mp4", ".mp4"),
        ("webm", ".webm"),
        ("mov", ".mov"),
        ("gif", ".mp4"),
    ],
)
def test_resolve_file_extensions(config, format, expected_file_extension):
    config.format = format
    assert config.movie_file_extension == expected_file_extension


class MyScene(Scene):
    def construct(self):
        self.add(Square())
        self.add(Text("Prepare for unforeseen consequencesλ"))
        self.add(Tex(r"$\lambda$"))
        self.wait(1)


def test_transparent(config):
    """Test the 'transparent' config option."""

    config.verbosity = "ERROR"
    config.dry_run = True

    scene = MyScene()
    scene.render()
    frame = scene.renderer.get_frame()
    np.testing.assert_allclose(frame[0, 0], [0, 0, 0, 255])
Repository: ManimCommunity/manim
File: manim/animation/animation.py (Python)

Code before:
    def set_default(cls, **kwargs) -> None:
        """Sets the default values of keyword arguments.

        If this method is called without any additional keyword
        arguments, the original default values of the initialization
        method of this class are restored.

        Parameters
        ----------

        kwargs
            Passing any keyword argument will update the default
            values of the keyword arguments of the initialization
            function of this class.

        Examples
        --------

        .. manim:: ChangeDefaultAnimation

            class ChangeDefaultAnimation(Scene):
                def construct(self):
                    Rotate.set_default(run_time=2,rate_func=rate_functions.linear)
                    Indicate.set_default(color=None)

                    S = Square(color=BLUE,fill_color=BLUE,fill_opacity=0.25)
                    self.add(S)
                    self.play(Rotate(S,PI))
                    self.play(Indicate(S))

                    Rotate.set_default()
                    Indicate.set_default()

        """
        if kwargs:
            cls.__init__ = partialmethod(cls.__init__, **kwargs)
        else:
            cls.__init__ = cls._original__init__


def prepare_animation(
    anim: Animation | mobject._AnimationBuilder,
) -> Animation:
    r"""Returns either an unchanged animation, or the animation built
    from a passed animation factory.

    Examples
    --------

    ::


Review comment (suggestion):
```suggestion
                    S = Square(color=BLUE, fill_color=BLUE, fill_opacity=0.25)
```

Code after:
    def set_default(cls, **kwargs) -> None:
        """Sets the default values of keyword arguments.

        If this method is called without any additional keyword
        arguments, the original default values of the initialization
        method of this class are restored.

        Parameters
        ----------

        kwargs
            Passing any keyword argument will update the default
            values of the keyword arguments of the initialization
            function of this class.

        Examples
        --------

        .. manim:: ChangeDefaultAnimation

            class ChangeDefaultAnimation(Scene):
                def construct(self):
                    Rotate.set_default(run_time=2, rate_func=rate_functions.linear)
                    Indicate.set_default(color=None)

                    S = Square(color=BLUE, fill_color=BLUE, fill_opacity=0.25)
                    self.add(S)
                    self.play(Rotate(S, PI))
                    self.play(Indicate(S))

                    Rotate.set_default()
                    Indicate.set_default()

        """
        if kwargs:
            cls.__init__ = partialmethod(cls.__init__, **kwargs)
        else:
            cls.__init__ = cls._original__init__


def prepare_animation(
    anim: Animation | mobject._AnimationBuilder,
) -> Animation:
    r"""Returns either an unchanged animation, or the animation built
    from a passed animation factory.

    Examples
    --------

    ::
Repository: ManimCommunity/manim
File: manim/animation/animation.py (Python)

Code before:

        If this method is called without any additional keyword
        arguments, the original default values of the initialization
        method of this class are restored.

        Parameters
        ----------

        kwargs
            Passing any keyword argument will update the default
            values of the keyword arguments of the initialization
            function of this class.

        Examples
        --------

        .. manim:: ChangeDefaultAnimation

            class ChangeDefaultAnimation(Scene):
                def construct(self):
                    Rotate.set_default(run_time=2,rate_func=rate_functions.linear)
                    Indicate.set_default(color=None)

                    S = Square(color=BLUE,fill_color=BLUE,fill_opacity=0.25)
                    self.add(S)
                    self.play(Rotate(S,PI))
                    self.play(Indicate(S))

                    Rotate.set_default()
                    Indicate.set_default()

        """
        if kwargs:
            cls.__init__ = partialmethod(cls.__init__, **kwargs)
        else:
            cls.__init__ = cls._original__init__


def prepare_animation(
    anim: Animation | mobject._AnimationBuilder,
) -> Animation:
    r"""Returns either an unchanged animation, or the animation built
    from a passed animation factory.

    Examples
    --------

    ::

        >>> from manim import Square, FadeIn
        >>> s = Square()

Review comment (suggestion):
```suggestion
                    self.play(Rotate(S, PI))
```

Code after:

        If this method is called without any additional keyword
        arguments, the original default values of the initialization
        method of this class are restored.

        Parameters
        ----------

        kwargs
            Passing any keyword argument will update the default
            values of the keyword arguments of the initialization
            function of this class.

        Examples
        --------

        .. manim:: ChangeDefaultAnimation

            class ChangeDefaultAnimation(Scene):
                def construct(self):
                    Rotate.set_default(run_time=2, rate_func=rate_functions.linear)
                    Indicate.set_default(color=None)

                    S = Square(color=BLUE, fill_color=BLUE, fill_opacity=0.25)
                    self.add(S)
                    self.play(Rotate(S, PI))
                    self.play(Indicate(S))

                    Rotate.set_default()
                    Indicate.set_default()

        """
        if kwargs:
            cls.__init__ = partialmethod(cls.__init__, **kwargs)
        else:
            cls.__init__ = cls._original__init__


def prepare_animation(
    anim: Animation | mobject._AnimationBuilder,
) -> Animation:
    r"""Returns either an unchanged animation, or the animation built
    from a passed animation factory.

    Examples
    --------

    ::

        >>> from manim import Square, FadeIn
        >>> s = Square()
Repository: ManimCommunity/manim
File: manim/utils/color/DVIPSNAMES.py (Python)

Code before:
"""DVIPSNAMES Colors

This module contains colors defined in the DVIPS driver and are commonly accessed
as named colors in LaTeX via the `\\usepackage[dvipsnames]{xcolor}` package.

To use the colors from this list, access them directly from the module (which
is exposed to Manim's global name space):

.. code:: pycon

    >>> from manim import DVIPSNAMES
    >>> DVIPSNAMES.DARKORCHID
    ManimColor('#A4538A')

List of Color Constants
-----------------------

These hex values are derived from those specified in the `xcolor` package
documentation (see https://ctan.org/pkg/xcolor):

.. automanimcolormodule:: manim.utils.color.DVIPSNAMES

"""

from __future__ import annotations

from .core import ManimColor

AQUAMARINE = ManimColor("#00B5BE")

Review comment (suggestion):
Single backticks are italics in sphinx, I think inline code looks nicer ;)
```suggestion
as named colors in LaTeX via the ``\\usepackage[dvipsnames]{xcolor}`` package.
```
You also might want to use a raw docstring - add an `r` to the beginning of `"""`, and then you can get rid of the double `\\`

Code after:
r"""dvips Colors

This module contains the colors defined in the dvips driver, which are commonly accessed
as named colors in LaTeX via the ``\usepackage[dvipsnames]{xcolor}`` package.

To use the colors from this list, access them directly from the module (which
is exposed to Manim's global name space):

.. code:: pycon

    >>> from manim import DVIPSNAMES
    >>> DVIPSNAMES.DARKORCHID
    ManimColor('#A4538A')

List of Color Constants
-----------------------

These hex values are derived from those specified in the ``xcolor`` package
documentation (see https://ctan.org/pkg/xcolor):

.. automanimcolormodule:: manim.utils.color.DVIPSNAMES

"""

from __future__ import annotations

from .core import ManimColor

AQUAMARINE = ManimColor("#00B5BE")
Repository: ManimCommunity/manim
File: manim/utils/color/SVGNAMES.py (Python)

Code before:
"""SVGNAMES Colors

This module contains colors defined in the SVG 1.1 specification and are commonly
accessed as named colors in LaTeX via the `\\usepackage[svgnames]{xcolor}` package.

To use the colors from this list, access them directly from the module (which
is exposed to Manim's global name space):

.. code:: pycon

    >>> from manim import SVGNAMES
    >>> SVGNAMES.LIGHTCORAL
    ManimColor('#EF7F7F')

List of Color Constants
-----------------------

These hex values are derived from those specified in the `xcolor` package
documentation (see https://ctan.org/pkg/xcolor):

.. automanimcolormodule:: manim.utils.color.SVGNAMES

"""

from __future__ import annotations

from .core import ManimColor

ALICEBLUE = ManimColor("#EFF7FF")

Review comment (suggestion):
Same as above
```suggestion
accessed as named colors in LaTeX via the ``\\usepackage[svgnames]{xcolor}`` package.
```

Code after:
r"""SVG 1.1 Colors

This module contains the colors defined in the SVG 1.1 specification, which are commonly
accessed as named colors in LaTeX via the ``\usepackage[svgnames]{xcolor}`` package.

To use the colors from this list, access them directly from the module (which
is exposed to Manim's global name space):

.. code:: pycon

    >>> from manim import SVGNAMES
    >>> SVGNAMES.LIGHTCORAL
    ManimColor('#EF7F7F')

List of Color Constants
-----------------------

These hex values are derived from those specified in the ``xcolor`` package
documentation (see https://ctan.org/pkg/xcolor):

.. automanimcolormodule:: manim.utils.color.SVGNAMES

"""

from __future__ import annotations

from .core import ManimColor

ALICEBLUE = ManimColor("#EFF7FF")
Repository: ManimCommunity/manim
File: tests/module/mobject/geometry/test_unit_geometry.py (Python)

Code before:
from __future__ import annotations

import logging

import numpy as np

from manim import BackgroundRectangle, Circle, Sector, Square, SurroundingRectangle

logger = logging.getLogger(__name__)


def test_get_arc_center():
    np.testing.assert_array_equal(
        Sector(arc_center=[1, 2, 0]).get_arc_center(), [1, 2, 0]
    )


def test_SurroundingRectangle(manim_caplog):
    circle = Circle()
    square = Square()
    sr = SurroundingRectangle(circle, square)
    sr.set_style(fill_opacity=0.42)
    assert sr.get_fill_opacity() == 0.42


def test_BackgroundRectangle(manim_caplog):
    circle = Circle()
    square = Square()
    bg = BackgroundRectangle(circle, square)
    bg.set_style(fill_opacity=0.42)
    assert bg.get_fill_opacity() == 0.42
    bg.set_style(fill_opacity=1, hello="world")
    assert (
        "Argument {'hello': 'world'} is ignored in BackgroundRectangle.set_style."
        in manim_caplog.text
    )


def test_Square_side_length_reflets_correct_width_and_height():
    sq = Square(side_length=1).scale(3)
    assert sq.side_length == 3
    assert sq.height == 3
    assert sq.width == 3

Review comment (suggestion):
I don't think we need `manim_caplog` here, that's if you want to check the stdout of a command

```suggestion
def test_SurroundingRectangle():
```


Code after:
from __future__ import annotations

import logging

import numpy as np

from manim import BackgroundRectangle, Circle, Sector, Square, SurroundingRectangle

logger = logging.getLogger(__name__)


def test_get_arc_center():
    np.testing.assert_array_equal(
        Sector(arc_center=[1, 2, 0]).get_arc_center(), [1, 2, 0]
    )


def test_SurroundingRectangle():
    circle = Circle()
    square = Square()
    sr = SurroundingRectangle(circle, square)
    sr.set_style(fill_opacity=0.42)
    assert sr.get_fill_opacity() == 0.42


def test_BackgroundRectangle(manim_caplog):
    circle = Circle()
    square = Square()
    bg = BackgroundRectangle(circle, square)
    bg.set_style(fill_opacity=0.42)
    assert bg.get_fill_opacity() == 0.42
    bg.set_style(fill_opacity=1, hello="world")
    assert (
        "Argument {'hello': 'world'} is ignored in BackgroundRectangle.set_style."
        in manim_caplog.text
    )


def test_Square_side_length_reflets_correct_width_and_height():
    sq = Square(side_length=1).scale(3)
    assert sq.side_length == 3
    assert sq.height == 3
    assert sq.width == 3
Repository: ManimCommunity/manim
File: manim/mobject/three_d/three_dimensions.py (Python)

Code before:
        resolution: int | Sequence[int] = 24,
        **kwargs,
    ) -> None:
        super().__init__(
            start=start,
            end=end,
            thickness=thickness,
            color=color,
            resolution=resolution,
            **kwargs,
        )

        self.length = np.linalg.norm(self.vect)
        self.set_start_and_end_attrs(
            self.start,
            self.end - height * self.direction,
            **kwargs,
        )
        self.cone = Cone(
            direction=self.direction,
            base_radius=base_radius,
            height=height,
            **kwargs,
        )
        self.cone.shift(np.array(end, np.float64))
        self.end_point = VectorizedPoint(np.array(end, np.float64))
        self.add(self.end_point, self.cone)
        self.set_color(color)

    def get_end(self) -> np.ndarray:
        return self.end_point.get_center()


class Torus(Surface):
    """A torus.

    Parameters
    ----------
    major_radius
        Distance from the center of the tube to the center of the torus.
    minor_radius
        Radius of the tube.
    u_range
        The range of the ``u`` variable: ``(u_min, u_max)``.
    v_range
        The range of the ``v`` variable: ``(v_min, v_max)``.
    resolution
        The number of samples taken of the :class:`Torus`. A tuple can be
        used to define different resolutions for ``u`` and ``v`` respectively.

    Examples

Review comment (suggestion):
Maybe the following would be better to reduce copying
```suggestion
        np_end = np.asarray(end, dtype=np.float64)
        self.cone.shift(np_end)
        self.end_point = VectorizedPoint(np_end)
```

Code after:
    """

    def __init__(
        self,
        start: np.ndarray = LEFT,
        end: np.ndarray = RIGHT,
        thickness: float = 0.02,
        height: float = 0.3,
        base_radius: float = 0.08,
        color: ParsableManimColor = WHITE,
        resolution: int | Sequence[int] = 24,
        **kwargs,
    ) -> None:
        super().__init__(
            start=start,
            end=end,
            thickness=thickness,
            color=color,
            resolution=resolution,
            **kwargs,
        )

        self.length = np.linalg.norm(self.vect)
        self.set_start_and_end_attrs(
            self.start,
            self.end - height * self.direction,
            **kwargs,
        )
        self.cone = Cone(
            direction=self.direction,
            base_radius=base_radius,
            height=height,
            **kwargs,
        )
        np_end = np.asarray(end, dtype=np.float64)
        self.cone.shift(np_end)
        self.end_point = VectorizedPoint(np_end)
        self.add(self.end_point, self.cone)
        self.set_color(color)

    def get_end(self) -> np.ndarray:
        return self.end_point.get_center()


class Torus(Surface):
    """A torus.

    Parameters
    ----------
    major_radius
        Distance from the center of the tube to the center of the torus.