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:
    import readline  # required to prevent a segfault on Python 3.10
except ModuleNotFoundError:  # windows
    pass

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 (bug):
A link to the open issue is better https://github.com/moderngl/moderngl/issues/517
```suggestion
    # https://github.com/moderngl/moderngl/issues/517
    import readline  # required to prevent a segfault on Python 3.10
```

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

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

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
Repository: ManimCommunity/manim
File: manim/utils/testing/_frames_testers.py (Python)

Code before:
from __future__ import annotations

import contextlib
import warnings
from pathlib import Path

import numpy as np

from manim import logger

from ._show_diff import show_diff_helper


FRAME_ABSOLUTE_TOLERANCE = 1.01
FRAME_NUMBER_MISMATCH_TOLERANCE = 1e-5


class _FramesTester:
    def __init__(self, file_path: Path, show_diff=False) -> None:
        self._file_path = file_path
        self._show_diff = show_diff
        self._frames: np.ndarray
        self._number_frames: int = 0
        self._frames_compared = 0

    @contextlib.contextmanager
    def testing(self):
        with np.load(self._file_path) as data:
            self._frames = data["frame_data"]
            # For backward compatibility, when the control data contains only one frame (<= v0.8.0)
            if len(self._frames.shape) != 4:
                self._frames = np.expand_dims(self._frames, axis=0)
            logger.debug(self._frames.shape)
            self._number_frames = np.ma.size(self._frames, axis=0)
            yield
            assert self._frames_compared == self._number_frames, (
                f"The scene tested contained {self._frames_compared} frames, "
                f"when there are {self._number_frames} control frames for this test."
            )


Review comment (suggestion):
```suggestion
FRAME_MISMATCH_RATIO_TOLERANCE = 1e-5
```

Ok, I'm **_really_** nitpicking, it should be 

Code after:
from __future__ import annotations

import contextlib
import warnings
from pathlib import Path

import numpy as np

from manim import logger

from ._show_diff import show_diff_helper

FRAME_ABSOLUTE_TOLERANCE = 1.01
FRAME_MISMATCH_RATIO_TOLERANCE = 1e-5


class _FramesTester:
    def __init__(self, file_path: Path, show_diff=False) -> None:
        self._file_path = file_path
        self._show_diff = show_diff
        self._frames: np.ndarray
        self._number_frames: int = 0
        self._frames_compared = 0

    @contextlib.contextmanager
    def testing(self):
        with np.load(self._file_path) as data:
            self._frames = data["frame_data"]
            # For backward compatibility, when the control data contains only one frame (<= v0.8.0)
            if len(self._frames.shape) != 4:
                self._frames = np.expand_dims(self._frames, axis=0)
            logger.debug(self._frames.shape)
            self._number_frames = np.ma.size(self._frames, axis=0)
            yield
            assert self._frames_compared == self._number_frames, (
                f"The scene tested contained {self._frames_compared} frames, "
                f"when there are {self._number_frames} control frames for this test."
            )

    def check_frame(self, frame_number: int, frame: np.ndarray):
Repository: ManimCommunity/manim
File: tests/test_graphical_units/test_geometry.py (Python)

Code before:
        LEFT,
        RIGHT,
        tip_shape_start=ArrowCircleTip,
        tip_shape_end=ArrowSquareFilledTip,
    )
    scene.add(arrow, double_arrow)


@frames_comparison
def test_LabeledLine(scene):
    line = LabeledLine(
        label="0.5",
        label_position=0.8,
        font_size=20,
        label_color=WHITE,
        label_frame=True,
        start=LEFT + DOWN,
        end=RIGHT + UP,
    )
    scene.add(line)


@frames_comparison
def test_LabeledArrow(scene):
    l_arrow = LabeledArrow(
        "0.5", start=LEFT * 3, end=RIGHT * 3 + UP * 2, label_position=0.5
    )
    scene.add(l_arrow)


Review comment (suggestion):
Because of the default parameter change, the test data either has to be regenerated, or font_size has to be passed:
```suggestion
        "0.5", start=LEFT * 3, end=RIGHT * 3 + UP * 2, label_position=0.5, font_size=15
```

Code after:
        LEFT,
        RIGHT,
        tip_shape_start=ArrowCircleTip,
        tip_shape_end=ArrowSquareFilledTip,
    )
    scene.add(arrow, double_arrow)


@frames_comparison
def test_LabeledLine(scene):
    line = LabeledLine(
        label="0.5",
        label_position=0.8,
        font_size=20,
        label_color=WHITE,
        label_frame=True,
        start=LEFT + DOWN,
        end=RIGHT + UP,
    )
    scene.add(line)


@frames_comparison
def test_LabeledArrow(scene):
    l_arrow = LabeledArrow(
        "0.5", start=LEFT * 3, end=RIGHT * 3 + UP * 2, label_position=0.5, font_size=15
    )
    scene.add(l_arrow)
Repository: ManimCommunity/manim
File: manim/cli/render/global_options.py (Python)

Code before:
        is_flag=True,
        help="Expand the window to its maximum possible size.",
        default=None,
    ),
    option(
        "--enable_wireframe",
        is_flag=True,
        help="Enable wireframe debugging mode in opengl.",
        default=None,
    ),
    option(
        "--force_window",
        is_flag=True,
        help="Force window to open when using the opengl renderer, intended for debugging as it may impact performance",
        default=False,
    ),
    option(
        "--dry_run",
        is_flag=True,
        help="Renders animations without outputting image or video files and disables the window",
        default=False,
    ),
    option(
        "--no_latex_cleanup",
        is_flag=True,
        help="Deletes .aux, .dvi, and .log files produced by Tex and MathTex.",
        default=False,
    ),
)


Review comment (suggestion):
```suggestion
        help="Prevents deletion of .aux, .dvi, and .log files produced by Tex and MathTex.",
```

Code after:
        is_flag=True,
        help="Expand the window to its maximum possible size.",
        default=None,
    ),
    option(
        "--enable_wireframe",
        is_flag=True,
        help="Enable wireframe debugging mode in opengl.",
        default=None,
    ),
    option(
        "--force_window",
        is_flag=True,
        help="Force window to open when using the opengl renderer, intended for debugging as it may impact performance",
        default=False,
    ),
    option(
        "--dry_run",
        is_flag=True,
        help="Renders animations without outputting image or video files and disables the window",
        default=False,
    ),
    option(
        "--no_latex_cleanup",
        is_flag=True,
        help="Prevents deletion of .aux, .dvi, and .log files produced by Tex and MathTex.",
        default=False,
    ),
)
Repository: ManimCommunity/manim
File: manim/animation/updaters/mobject_update_utils.py (Python)

Code before:
                        sine,
                        alpha=alpha.get_value(),
                        color=YELLOW,
                        length=4)
                )
                self.add(ax, sine, point, tangent)
                self.play(alpha.animate.set_value(1), rate_func=linear, run_time=2)
    """
    mob = func()
    mob.add_updater(lambda _: mob.become(func()))
    return mob


def always_shift(
    mobject: Mobject, direction: np.ndarray[np.float64] = RIGHT, rate: float = 0.1
) -> Mobject:
    """Shift the mobject by `rate*direction` every second

    Parameters
    ----------
    mobject
        The mobject to shift
    direction
        The direction to shift
    rate
        Amount of direction to be covered in one second

    Examples
    --------

    .. manim:: ShiftingSquare

        class ShiftingSquare(Scene):
            def construct(self):
                sq = Square().set_fill(opacity=1)
                tri = Triangle()
                VGroup(sq, tri).arrange(LEFT)

                # always shift square one unit to the right
                # even if there is an animation going on
                always_shift(sq, RIGHT, rate=5)

                self.add(sq)
                self.play(tri.animate.set_fill(opacity=1))
    """

    def normalize(v):
        norm = np.linalg.norm(v)
        if norm == 0:
            return v
        return v / norm

Review comment (suggestion):
```suggestion
        Length in Manim units which the mobject travels in one
        second along the specified direction.
```

Code after:
                        color=BLUE
                    )
                )
                tangent = always_redraw(
                    lambda: TangentLine(
                        sine,
                        alpha=alpha.get_value(),
                        color=YELLOW,
                        length=4
                    )
                )
                self.add(ax, sine, point, tangent)
                self.play(alpha.animate.set_value(1), rate_func=linear, run_time=2)
    """
    mob = func()
    mob.add_updater(lambda _: mob.become(func()))
    return mob


def always_shift(
    mobject: Mobject, direction: np.ndarray[np.float64] = RIGHT, rate: float = 0.1
) -> Mobject:
    """A mobject which is continuously shifted along some direction
    at a certain rate.

    Parameters
    ----------
    mobject
        The mobject to shift.
    direction
        The direction to shift. The vector is normalized, the specified magnitude
        is not relevant.
    rate
        Length in Manim units which the mobject travels in one
        second along the specified direction.

    Examples
    --------

    .. manim:: ShiftingSquare

        class ShiftingSquare(Scene):
            def construct(self):
                sq = Square().set_fill(opacity=1)
                tri = Triangle()
                VGroup(sq, tri).arrange(LEFT)

                # construct a square which is continuously
                # shifted to the right
                always_shift(sq, RIGHT, rate=5)
Repository: ManimCommunity/manim
File: manim/animation/updaters/mobject_update_utils.py (Python)

Code before:
    mobject: Mobject, direction: np.ndarray[np.float64] = RIGHT, rate: float = 0.1
) -> Mobject:
    """Shift the mobject by `rate*direction` every second

    Parameters
    ----------
    mobject
        The mobject to shift
    direction
        The direction to shift
    rate
        Amount of direction to be covered in one second

    Examples
    --------

    .. manim:: ShiftingSquare

        class ShiftingSquare(Scene):
            def construct(self):
                sq = Square().set_fill(opacity=1)
                tri = Triangle()
                VGroup(sq, tri).arrange(LEFT)

                # always shift square one unit to the right
                # even if there is an animation going on
                always_shift(sq, RIGHT, rate=5)

                self.add(sq)
                self.play(tri.animate.set_fill(opacity=1))
    """

    def normalize(v):
        norm = np.linalg.norm(v)
        if norm == 0:
            return v
        return v / norm

    mobject.add_updater(lambda m, dt: m.shift(dt * rate * normalize(direction)))
    return mobject


def always_rotate(mobject: Mobject, rate: float = 20 * DEGREES, **kwargs) -> Mobject:
    """Rotate the mobject by `rate` every second

    Parameters
    ----------
    mobject
        The mobject to rotate

    Examples

Review comment (suggestion):
```suggestion
                # construct a square which is continuously
                # shifted to the right
```

Code after:
    mob = func()
    mob.add_updater(lambda _: mob.become(func()))
    return mob


def always_shift(
    mobject: Mobject, direction: np.ndarray[np.float64] = RIGHT, rate: float = 0.1
) -> Mobject:
    """A mobject which is continuously shifted along some direction
    at a certain rate.

    Parameters
    ----------
    mobject
        The mobject to shift.
    direction
        The direction to shift. The vector is normalized, the specified magnitude
        is not relevant.
    rate
        Length in Manim units which the mobject travels in one
        second along the specified direction.

    Examples
    --------

    .. manim:: ShiftingSquare

        class ShiftingSquare(Scene):
            def construct(self):
                sq = Square().set_fill(opacity=1)
                tri = Triangle()
                VGroup(sq, tri).arrange(LEFT)

                # construct a square which is continuously
                # shifted to the right
                always_shift(sq, RIGHT, rate=5)

                self.add(sq)
                self.play(tri.animate.set_fill(opacity=1))
    """
    mobject.add_updater(lambda m, dt: m.shift(dt * rate * normalize(direction)))
    return mobject


def always_rotate(mobject: Mobject, rate: float = 20 * DEGREES, **kwargs) -> Mobject:
    """A mobject which is continuously rotated at a certain rate.

    Parameters
    ----------
    mobject
        The mobject to be rotated.
Repository: ManimCommunity/manim
File: tests/module/mobject/test_image.py (Python)

Code before:
import numpy as np
import pytest

from manim import ImageMobject


@pytest.mark.parametrize("dtype", (np.uint8, np.uint16))
def test_invert_image(dtype):
    array = (255 * np.random.rand(10, 10, 4)).astype(dtype)
    image = ImageMobject(array, pixel_array_dtype=dtype, invert=True)
    assert image.pixel_array.dtype == dtype

    array[:, :, :3] = np.iinfo(dtype).max - array[:, :, :3]
    assert np.allclose(array, image.pixel_array)


Review comment (suggestion):
```suggestion
@pytest.mark.parametrize("dtype", [np.uint8, np.uint16])
```

In order to make pre-commit happy.

Code after:
import numpy as np
import pytest

from manim import ImageMobject


@pytest.mark.parametrize("dtype", [np.uint8, np.uint16])
def test_invert_image(dtype):
    array = (255 * np.random.rand(10, 10, 4)).astype(dtype)
    image = ImageMobject(array, pixel_array_dtype=dtype, invert=True)
    assert image.pixel_array.dtype == dtype

    array[:, :, :3] = np.iinfo(dtype).max - array[:, :, :3]
    assert np.allclose(array, image.pixel_array)
Repository: ManimCommunity/manim
File: manim/utils/tex.py (Python)

Code before:
"""Utilities for processing LaTeX templates."""

from __future__ import annotations

__all__ = [
    "TexTemplate",
]

import copy
import re
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

from typing_extensions import Self

from manim.typing import StrPath

_DEFAULT_PREAMBLE = r"""\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}"""

_BEGIN_DOCUMENT = r"\begin{document}"
_END_DOCUMENT = r"\end{document}"


@dataclass(eq=True)
class TexTemplate:
    """TeX templates are used to create ``Tex`` and ``MathTex`` objects."""

    _body: str = field(default="", init=False)
    """A custom body, can be set from a file."""

    tex_compiler: str = "latex"
    """The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``."""

    output_format: str = ".dvi"
    """The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``."""

    documentclass: str = r"\documentclass[preview]{standalone}"
    r"""The command defining the documentclass, e.g. ``\documentclass[preview]{standalone}``."""


Review comment (suggestion):
```suggestion
if TYPE_CHECKING:
    from typing_extensions import Self
    from manim.typing import StrPath
```

Code after:
"""Utilities for processing LaTeX templates."""

from __future__ import annotations

__all__ = [
    "TexTemplate",
]

import copy
import re
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from typing_extensions import Self

    from manim.typing import StrPath

_DEFAULT_PREAMBLE = r"""\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}"""

_BEGIN_DOCUMENT = r"\begin{document}"
_END_DOCUMENT = r"\end{document}"


@dataclass(eq=True)
class TexTemplate:
    """TeX templates are used to create ``Tex`` and ``MathTex`` objects."""

    _body: str = field(default="", init=False)
    """A custom body, can be set from a file."""

    tex_compiler: str = "latex"
    """The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``."""

    output_format: str = ".dvi"
    """The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``."""

    documentclass: str = r"\documentclass[preview]{standalone}"
    r"""The command defining the documentclass, e.g. ``\documentclass[preview]{standalone}``."""
Repository: ManimCommunity/manim
File: manim/utils/tex.py (Python)

Code before:
"""Utilities for processing LaTeX templates."""

from __future__ import annotations

__all__ = [
    "TexTemplate",
]

import copy
import re
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

from typing_extensions import Self

from manim.typing import StrPath

_DEFAULT_PREAMBLE = r"""\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}"""

_BEGIN_DOCUMENT = r"\begin{document}"
_END_DOCUMENT = r"\end{document}"


@dataclass(eq=True)
class TexTemplate:
    """TeX templates are used to create ``Tex`` and ``MathTex`` objects."""

    _body: str = field(default="", init=False)
    """A custom body, can be set from a file."""

    tex_compiler: str = "latex"
    """The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``."""

    output_format: str = ".dvi"
    """The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``."""

Review comment (suggestion):
```suggestion
from typing import Any, TYPE_CHECKING
```

Code after:
"""Utilities for processing LaTeX templates."""

from __future__ import annotations

__all__ = [
    "TexTemplate",
]

import copy
import re
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from typing_extensions import Self

    from manim.typing import StrPath

_DEFAULT_PREAMBLE = r"""\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}"""

_BEGIN_DOCUMENT = r"\begin{document}"
_END_DOCUMENT = r"\end{document}"


@dataclass(eq=True)
class TexTemplate:
    """TeX templates are used to create ``Tex`` and ``MathTex`` objects."""

    _body: str = field(default="", init=False)
    """A custom body, can be set from a file."""

    tex_compiler: str = "latex"
    """The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``."""

    output_format: str = ".dvi"
Repository: ManimCommunity/manim
File: manim/plugins/__init__.py (Python)

Code before:
from __future__ import annotations

from .. import config, logger
from .plugins_flags import get_plugins, list_plugins

__all__ = [
    "get_plugins",
    "list_plugins",
]

requested_plugins: set[str] = set(config["plugins"])
missing_plugins = requested_plugins - set(get_plugins().keys())


if missing_plugins:
    logger.warning("Missing Plugins: %s", missing_plugins)


Review comment (suggestion):
```suggestion
from manim._config import config, logger
```
I believe MrDiver and Chopan were trying to move away from these kinds of imports. 


Code after:
from __future__ import annotations

from manim import config, logger

from .plugins_flags import get_plugins, list_plugins

__all__ = [
    "get_plugins",
    "list_plugins",
]

requested_plugins: set[str] = set(config["plugins"])
missing_plugins = requested_plugins - set(get_plugins().keys())


if missing_plugins:
    logger.warning("Missing Plugins: %s", missing_plugins)
Repository: ManimCommunity/manim
File: manim/animation/creation.py (Python)

Code before:
    "Write",
    "Unwrite",
    "ShowPartial",
    "ShowIncreasingSubsets",
    "SpiralIn",
    "AddTextLetterByLetter",
    "RemoveTextLetterByLetter",
    "ShowSubmobjectsOneByOne",
    "AddTextWordByWord",
    "AddTextLetterByLetterWithCursor",
    "RemoveTextLetterByLetterWithCursor",
]


import itertools as it
from typing import TYPE_CHECKING, Callable, Iterable, Sequence

import numpy as np

if TYPE_CHECKING:
    from manim.mobject.text.text_mobject import Text

from manim.constants import RIGHT
from manim.mobject.opengl.opengl_surface import OpenGLSurface
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject
from manim.scene.scene import Scene
from manim.utils.color import ManimColor

from .. import config
from ..animation.animation import Animation
from ..animation.composition import Succession
from ..constants import TAU
from ..mobject.mobject import Group, Mobject
from ..mobject.types.vectorized_mobject import VMobject
from ..utils.bezier import integer_interpolate
from ..utils.rate_functions import double_smooth, linear


class ShowPartial(Animation):
    """Abstract class for Animations that show the VMobject partially.

    Raises
    ------
    :class:`TypeError`
        If ``mobject`` is not an instance of :class:`~.VMobject`.

    See Also
    --------
    :class:`Create`, :class:`~.ShowPassingFlash`

    """

Review comment (suggestion):
This should be moved under the `if TYPE_CHECKING` gate, unless I missed where `Scene` is explicitly used in the code.

Code after:
    "Write",
    "Unwrite",
    "ShowPartial",
    "ShowIncreasingSubsets",
    "SpiralIn",
    "AddTextLetterByLetter",
    "RemoveTextLetterByLetter",
    "ShowSubmobjectsOneByOne",
    "AddTextWordByWord",
    "TypeWithCursor",
    "UntypeWithCursor",
]


import itertools as it
from typing import TYPE_CHECKING, Callable, Iterable, Sequence

import numpy as np

if TYPE_CHECKING:
    from manim.mobject.text.text_mobject import Text
    from manim.scene.scene import Scene

from manim.constants import RIGHT, TAU
from manim.mobject.opengl.opengl_surface import OpenGLSurface
from manim.mobject.opengl.opengl_vectorized_mobject import OpenGLVMobject
from manim.utils.color import ManimColor

from .. import config
from ..animation.animation import Animation
from ..animation.composition import Succession
from ..mobject.mobject import Group, Mobject
from ..mobject.types.vectorized_mobject import VMobject
from ..utils.bezier import integer_interpolate
from ..utils.rate_functions import double_smooth, linear


class ShowPartial(Animation):
    """Abstract class for Animations that show the VMobject partially.

    Raises
    ------
    :class:`TypeError`
        If ``mobject`` is not an instance of :class:`~.VMobject`.

    See Also
    --------
    :class:`Create`, :class:`~.ShowPassingFlash`

    """