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

Code before:
        positive_space_ratio=0.5,
        **kwargs
    ):
        self.dash_length = dash_length
        self.dash_spacing = (dash_spacing,)
        self.positive_space_ratio = positive_space_ratio
        Line.__init__(self, *args, **kwargs)
        dashes = DashedVMobject(
            self,
            num_dashes=self.calculate_num_dashes(),
            positive_space_ratio=positive_space_ratio,
        )
        self.clear_points()
        self.add(*dashes)

    def calculate_num_dashes(self):
        """Returns the number of dashes in the dashed line.

        Examples
        --------
        ::

            >>> DashedLine().calculate_num_dashes()
            20

        :class:`int`
        """

        try:
            full_length = self.dash_length / self.positive_space_ratio
            return int(np.ceil(self.get_length() / full_length))
        except ZeroDivisionError:
            return 1

    def calculate_positive_space_ratio(self):
        return fdiv(self.dash_length, self.dash_length + self.dash_spacing)

    def get_start(self):
        """Returns the start point of the line.

        Examples
        --------
        ::

            >>> DashedLine().get_start()
            array([-1.,  0.,  0.])

        :class:`numpy.ndarray`
        """

        if len(self.submobjects) > 0:

Review comment (suggestion):
Personally, I would remove the return type from the docstring, and rather add a type hint to the method header: `def calculate_num_dashes(self) -> int:`.

```suggestion
```

Code after:
        positive_space_ratio=0.5,
        **kwargs
    ):
        self.dash_length = dash_length
        self.dash_spacing = (dash_spacing,)
        self.positive_space_ratio = positive_space_ratio
        Line.__init__(self, *args, **kwargs)
        dashes = DashedVMobject(
            self,
            num_dashes=self.calculate_num_dashes(),
            positive_space_ratio=positive_space_ratio,
        )
        self.clear_points()
        self.add(*dashes)

    def calculate_num_dashes(self) -> int:
        """Returns the number of dashes in the dashed line.

        Examples
        --------
        ::

            >>> DashedLine().calculate_num_dashes()
            20
        """

        try:
            full_length = self.dash_length / self.positive_space_ratio
            return int(np.ceil(self.get_length() / full_length))
        except ZeroDivisionError:
            return 1

    def calculate_positive_space_ratio(self):
        return fdiv(self.dash_length, self.dash_length + self.dash_spacing)

    def get_start(self) -> np.ndarray:
        """Returns the start point of the line.

        Examples
        --------
        ::

            >>> DashedLine().get_start()
            array([-1.,  0.,  0.])
        """

        if len(self.submobjects) > 0:
            return self.submobjects[0].get_start()
        else:
            return Line.get_start(self)
Repository: ManimCommunity/manim
File: manim/mobject/geometry.py (Python)

Code before:
        ::

            >>> DashedLine().get_first_handle()
            array([-0.98333333,  0.        ,  0.        ])

        :class:`numpy.ndarray`
        """
        return self.submobjects[0].points[1]

    def get_last_handle(self):
        """Returns the point of the last handle.

        Examples
        --------
        ::

            >>> DashedLine().get_last_handle()
            array([0.98205128, 0.        , 0.        ])

        :class:`numpy.ndarray`
        """
        return self.submobjects[-1].points[-2]


class TangentLine(Line):
    """Constructs a line tangent to a VMobject at a specific point.

    Parameters
    ----------
    vmob : :class:`~.VMobject`
        The VMobject on which the tangent line is drawn.
    alpha : :class:`float`
        How far along the shape that the line will be constructed. range: 0-1.
    length : :class:`float`, optional
        Length of the tangent line.
    d_alpha: :class:`float`, optional
        The `dx` value
    kwargs : Any
        Additional arguments to be passed to :class:`Line`

    Examples
    --------

    .. manim:: TangentLineExample
        :save_last_frame:

        class TangentLineExample(Scene):
            def construct(self):
                circle = Circle(radius=2)
                line_1 = TangentLine(circle, alpha=0.0, length=4, color=BLUE_D) # right
                line_2 = TangentLine(circle, alpha=0.4, length=4, color=GREEN) # top left

Review comment (suggestion):
```suggestion
    """Constructs a line tangent to a :class:`~.VMobject` at a specific point.
```

Code after:
        return self.submobjects[0].points[1]

    def get_last_handle(self) -> np.ndarray:
        """Returns the point of the last handle.

        Examples
        --------
        ::

            >>> DashedLine().get_last_handle()
            array([0.98205128, 0.        , 0.        ])
        """

        return self.submobjects[-1].points[-2]


class TangentLine(Line):
    """Constructs a line tangent to a :class:`~.VMobject` at a specific point.

    Parameters
    ----------
    vmob : :class:`~.VMobject`
        The VMobject on which the tangent line is drawn.
    alpha : :class:`float`
        How far along the shape that the line will be constructed. range: 0-1.
    length : :class:`float`, optional
        Length of the tangent line.
    d_alpha: :class:`float`, optional
        The ``dx`` value
    kwargs : Any
        Additional arguments to be passed to :class:`Line`

    Examples
    --------

    .. manim:: TangentLineExample
        :save_last_frame:

        class TangentLineExample(Scene):
            def construct(self):
                circle = Circle(radius=2)
                line_1 = TangentLine(circle, alpha=0.0, length=4, color=BLUE_D) # right
                line_2 = TangentLine(circle, alpha=0.4, length=4, color=GREEN) # top left
                self.add(circle, line_1, line_2)

    See Also
    --------
    :meth:`~.VMobject.point_from_proportion`
    """

    def __init__(self, vmob, alpha, length=1, d_alpha=1e-6, **kwargs):
Repository: ManimCommunity/manim
File: manim/mobject/geometry.py (Python)

Code before:
        p0, p1, p2 = self.tip.get_start_anchors()[:3]
        return normalize(np.cross(p2 - p1, p1 - p0))

    def reset_normal_vector(self):
        """Resets the normal of a vector"""
        self.normal_vector = self.get_normal_vector()
        return self

    def get_default_tip_length(self):
        """Returns the default tip_length of the arrow.

        Examples
        --------

        ::

            >>> Arrow().get_default_tip_length()
            0.35

        :class:`float`
        """
        max_ratio = self.max_tip_length_to_length_ratio
        return min(self.tip_length, max_ratio * self.get_length())

    def set_stroke_width_from_length(self):
        """Used internally. Sets stroke width based on length"""
        max_ratio = self.max_stroke_width_to_length_ratio
        self.set_stroke(
            width=min(self.initial_stroke_width, max_ratio * self.get_length()),
            family=False,
        )
        return self


class Vector(Arrow):
    """A vector specialized for use in graphs.

    Parameters
    ----------
    direction : Union[:class:`list`, :class:`numpy.ndarray`]
        The direction of the arrow.
    buff : :class:`float`
         The distance of the vector from its endpoints.
    kwargs : Any
        Additional arguments to be passed to :class:`Arrow`

    Examples
    --------

    .. manim:: VectorExample
        :save_last_frame:

Review comment (suggestion):
```suggestion
        """Used internally. Sets stroke width based on length."""
```

Code after:
        """Returns the default tip_length of the arrow.

        Examples
        --------

        ::

            >>> Arrow().get_default_tip_length()
            0.35
        """

        max_ratio = self.max_tip_length_to_length_ratio
        return min(self.tip_length, max_ratio * self.get_length())

    def set_stroke_width_from_length(self):
        """Used internally. Sets stroke width based on length."""
        max_ratio = self.max_stroke_width_to_length_ratio
        self.set_stroke(
            width=min(self.initial_stroke_width, max_ratio * self.get_length()),
            family=False,
        )
        return self


class Vector(Arrow):
    """A vector specialized for use in graphs.

    Parameters
    ----------
    direction : Union[:class:`list`, :class:`numpy.ndarray`]
        The direction of the arrow.
    buff : :class:`float`
         The distance of the vector from its endpoints.
    kwargs : Any
        Additional arguments to be passed to :class:`Arrow`

    Examples
    --------

    .. manim:: VectorExample
        :save_last_frame:

        class VectorExample(Scene):
            def construct(self):
                plane = NumberPlane()
                vector_1 = Vector([1,2])
                vector_2 = Vector([-5,-2])
                self.add(plane, vector_1, vector_2)
    """

    def __init__(self, direction=RIGHT, buff=0, **kwargs):
Repository: ManimCommunity/manim
File: manim/plugins/import_plugins.py (Python)

Code before:
    plugins_requested.remove("")
for plugin in pkg_resources.iter_entry_points("manim.plugins"):
    if plugin.name not in plugins_requested:
        continue
    loaded_plugin = plugin.load()
    if isinstance(loaded_plugin, types.ModuleType):
        # it is a module so it can't be called
        # see if __all__ is defined
        # if it is defined use that to load all the modules necessary
        # essentially this would be similar to `from plugin import *``
        # if not just import the module with the plugin name
        if hasattr(loaded_plugin, "__all__"):
            for thing in loaded_plugin.__all__:
                exec(f"{thing}=loaded_plugin.{thing}")
                __all__.append(thing)
        else:
            exec(f"{plugin.name}=loaded_plugin")
            __all__.append(plugin.name)
    elif isinstance(loaded_plugin, types.FunctionType):
        # call the function first
        # it will return a list of modules to add globally
        # finally add it
        lists = loaded_plugin()
        for x in lists:
            exec(f"{x.__name__}=x")
            __all__.append(x.__name__)
    plugins_requested.remove(plugin.name)
else:
    if plugins_requested != []:
        logger.warning("Missing Plugins: %s", plugins_requested)


Review comment (suggestion):
Renaming `l` to `x` is not a particularly great improvement.

```suggestion
        for lst in lists:
            exec(f"{lst.__name__}=lst")
            __all__.append(lst.__name__)
```

Code after:
    plugins_requested.remove("")
for plugin in pkg_resources.iter_entry_points("manim.plugins"):
    if plugin.name not in plugins_requested:
        continue
    loaded_plugin = plugin.load()
    if isinstance(loaded_plugin, types.ModuleType):
        # it is a module so it can't be called
        # see if __all__ is defined
        # if it is defined use that to load all the modules necessary
        # essentially this would be similar to `from plugin import *``
        # if not just import the module with the plugin name
        if hasattr(loaded_plugin, "__all__"):
            for thing in loaded_plugin.__all__:
                exec(f"{thing}=loaded_plugin.{thing}")
                __all__.append(thing)
        else:
            exec(f"{plugin.name}=loaded_plugin")
            __all__.append(plugin.name)
    elif isinstance(loaded_plugin, types.FunctionType):
        # call the function first
        # it will return a list of modules to add globally
        # finally add it
        lists = loaded_plugin()
        for lst in lists:
            exec(f"{lst.__name__}=lst")
            __all__.append(lst.__name__)
    plugins_requested.remove(plugin.name)
else:
    if plugins_requested != []:
        logger.warning("Missing Plugins: %s", plugins_requested)
Repository: ManimCommunity/manim
File: manim/utils/iterables.py (Python)

Code before:
    return np.resize(nparray, (length, *nparray.shape[1:]))


def resize_preserving_order(nparray, length):
    if len(nparray) == 0:
        return np.zeros((length, *nparray.shape[1:]))
    if len(nparray) == length:
        return nparray
    indices = np.arange(length) * len(nparray) // length
    return nparray[indices]


def resize_with_interpolation(nparray, length):
    if len(nparray) == length:
        return nparray
    cont_indices = np.linspace(0, len(nparray) - 1, length)
    return np.array(
        [
            (1 - a) * nparray[lh] + a * nparray[rh]
            for ci in cont_indices
            for lh, rh, a in [(int(ci), int(np.ceil(ci)), ci % 1)]
        ]
    )


def remove_list_redundancies(i):
    """
    Used instead of list(set(l)) to maintain order
    Keeps the last occurrence of each element
    """
    reversed_result = []
    used = set()
    for x in reversed(i):
        if x not in used:
            reversed_result.append(x)
            used.add(x)
    reversed_result.reverse()
    return reversed_result


def list_update(l1, l2):
    """
    Used instead of list(set(l1).update(l2)) to maintain order,
    making sure duplicates are removed from l1, not l2.
    """
    return [e for e in l1 if e not in l2] + list(l2)


def list_difference_update(l1, l2):
    return [e for e in l1 if e not in l2]


Review comment (suggestion):
```suggestion
def remove_list_redundancies(lst):
```

Code after:
    return np.resize(nparray, (length, *nparray.shape[1:]))


def resize_preserving_order(nparray, length):
    if len(nparray) == 0:
        return np.zeros((length, *nparray.shape[1:]))
    if len(nparray) == length:
        return nparray
    indices = np.arange(length) * len(nparray) // length
    return nparray[indices]


def resize_with_interpolation(nparray, length):
    if len(nparray) == length:
        return nparray
    cont_indices = np.linspace(0, len(nparray) - 1, length)
    return np.array(
        [
            (1 - a) * nparray[lh] + a * nparray[rh]
            for ci in cont_indices
            for lh, rh, a in [(int(ci), int(np.ceil(ci)), ci % 1)]
        ]
    )


def remove_list_redundancies(lst):
    """
    Used instead of list(set(l)) to maintain order
    Keeps the last occurrence of each element
    """
    reversed_result = []
    used = set()
    for x in reversed(lst):
        if x not in used:
            reversed_result.append(x)
            used.add(x)
    reversed_result.reverse()
    return reversed_result


def list_update(l1, l2):
    """
    Used instead of list(set(l1).update(l2)) to maintain order,
    making sure duplicates are removed from l1, not l2.
    """
    return [e for e in l1 if e not in l2] + list(l2)


def list_difference_update(l1, l2):
    return [e for e in l1 if e not in l2]
Repository: ManimCommunity/manim
File: manim/utils/iterables.py (Python)

Code before:
    length = max(len(list_1), len(list_2))
    return (
        [list_1[(n * len(list_1)) // length] for n in range(length)],
        [list_2[(n * len(list_2)) // length] for n in range(length)],
    )


def make_even_by_cycling(iterable_1, iterable_2):
    length = max(len(iterable_1), len(iterable_2))
    cycle1 = it.cycle(iterable_1)
    cycle2 = it.cycle(iterable_2)
    return (
        [next(cycle1) for x in range(length)],
        [next(cycle2) for x in range(length)],
    )


def remove_nones(sequence):
    return [x for x in sequence if x]


# Note this is redundant with it.chain


def concatenate_lists(*list_of_lists):
    return [item for i in list_of_lists for item in i]


Review comment (suggestion):
```suggestion
    return [item for lst in list_of_lists for item in lst]
```

Code after:
    length = max(len(list_1), len(list_2))
    return (
        [list_1[(n * len(list_1)) // length] for n in range(length)],
        [list_2[(n * len(list_2)) // length] for n in range(length)],
    )


def make_even_by_cycling(iterable_1, iterable_2):
    length = max(len(iterable_1), len(iterable_2))
    cycle1 = it.cycle(iterable_1)
    cycle2 = it.cycle(iterable_2)
    return (
        [next(cycle1) for x in range(length)],
        [next(cycle2) for x in range(length)],
    )


def remove_nones(sequence):
    return [x for x in sequence if x]


# Note this is redundant with it.chain


def concatenate_lists(*list_of_lists):
    return [item for lst in list_of_lists for item in lst]
Repository: ManimCommunity/manim
File: tests/test_graphical_units/test_opengl.py (Python)

Code before:
import pytest

from manim import *
from manim.opengl import *
from ..utils.testing_utils import get_scenes_to_test
from ..utils.GraphicalUnitTester import GraphicalUnitTester

with tempconfig({"use_opengl_renderer": True}):

    class CircleTest(Scene):
        def construct(self):
            circle = OpenGLCircle().set_color(RED)
            self.add(circle)
            self.wait()


MODULE_NAME = "opengl"


@pytest.mark.parametrize("scene_to_test", get_scenes_to_test(__name__), indirect=False)
def test_scene(scene_to_test, tmpdir, show_diff):
    with tempconfig({"use_opengl_renderer": True}):
        # allow 1/255 RGB value differences with opengl tests because of differences across platforms
        GraphicalUnitTester(scene_to_test[1], MODULE_NAME, tmpdir, rgb_atol=1.01).test(
            show_diff=show_diff
        )


Review comment (suggestion):
If I had to guess, I'd think that this context here is actually not necessary. It *should* be enough to set the `use_opengl_renderer` flag only for `test_scene` below.

Code after:
import pytest

from manim import *
from manim.opengl import *
from ..utils.testing_utils import get_scenes_to_test
from ..utils.GraphicalUnitTester import GraphicalUnitTester


class CircleTest(Scene):
    def construct(self):
        circle = OpenGLCircle().set_color(RED)
        self.add(circle)
        self.wait()


MODULE_NAME = "opengl"


@pytest.mark.parametrize("scene_to_test", get_scenes_to_test(__name__), indirect=False)
def test_scene(scene_to_test, tmpdir, show_diff):
    with tempconfig({"use_opengl_renderer": True}):
        # allow 1/255 RGB value differences with opengl tests because of differences across platforms
        GraphicalUnitTester(scene_to_test[1], MODULE_NAME, tmpdir, rgb_atol=1.01).test(
            show_diff=show_diff
        )
Repository: ManimCommunity/manim
File: tests/assert_utils.py (Python)

Code before:
import typing
from os import PathLike
from pathlib import Path
from pprint import pformat


def assert_file_exists(filepath: typing.Union[str, PathLike]) -> None:
    """Assert if filepath points to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath.

    This is mostly to have better assert message than using a raw assert os.path.isfile(filepath).

    Parameters
    ----------
    filepath : typing.Union[str, PathLike]
        Filepath to check.

    Raises
    ------
    AssertionError
        If filepath does not point to a file (if the file does not exist or it's a dir).
    """
    path = Path(filepath)
    if not path.is_file():
        message = f"{path.absolute()} is not a file. Other elements in the parent directory are \n{pformat([path.name for path in list(path.parent.iterdir())])}"
        raise AssertionError(message)


Review comment (suggestion):
you don't need to specify types in docstring if you did in typing.
```suggestion
    filepath
```

Code after:
import typing
from os import PathLike
from pathlib import Path
from pprint import pformat


def assert_file_exists(filepath: typing.Union[str, PathLike]) -> None:
    """Assert if filepath points to an existing file. Print all the elements (files and dir) of the parent dir of the given filepath.

    This is mostly to have better assert message than using a raw assert os.path.isfile(filepath).

    Parameters
    ----------
    filepath
        Filepath to check.

    Raises
    ------
    AssertionError
        If filepath does not point to a file (if the file does not exist or it's a dir).
    """
    path = Path(filepath)
    if not path.is_file():
        message = f"{path.absolute()} is not a file. Other elements in the parent directory are \n{pformat([path.name for path in list(path.parent.iterdir())])}"
        raise AssertionError(message)
Repository: ManimCommunity/manim
File: manim/animation/animation.py (Python)

Code before:
    def get_run_time(self) -> float:
        return self.run_time

    def set_rate_func(
        self, rate_func: typing.Callable[[float, float], np.ndarray]
    ) -> "Animation":
        self.rate_func = rate_func
        return self

    def get_rate_func(self) -> typing.Callable[[float, float], np.ndarray]:
        return self.rate_func

    def set_name(self, name: str) -> "Animation":
        self.name = name
        return self

    def is_remover(self) -> bool:
        return self.remover

    def is_dummy(self) -> bool:
        return animation_is_dummy(self)


def animation_is_dummy(anim: Union["Animation", "mobject._AnimationBuilder"]) -> bool:
    return True if anim.mobject is None else False


def prepare_animation(
    anim: Union["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()
        >>> prepare_animation(FadeIn(s))
        FadeIn(Square)

    ::

        >>> prepare_animation(s.animate.scale(2).rotate(42))
        _MethodAnimation(Square)

    ::

        >>> prepare_animation(42)

Review comment (suggestion):
```suggestion
    def is_dummy(self) -> bool:
        return self.mobject is None
```

Code after:
    def get_run_time(self) -> float:
        return self.run_time

    def set_rate_func(
        self, rate_func: typing.Callable[[float, float], np.ndarray]
    ) -> "Animation":
        self.rate_func = rate_func
        return self

    def get_rate_func(self) -> typing.Callable[[float, float], np.ndarray]:
        return self.rate_func

    def set_name(self, name: str) -> "Animation":
        self.name = name
        return self

    def is_remover(self) -> bool:
        return self.remover

    def is_dummy(self) -> bool:
        return self.mobject is None


def prepare_animation(
    anim: Union["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()
        >>> prepare_animation(FadeIn(s))
        FadeIn(Square)

    ::

        >>> prepare_animation(s.animate.scale(2).rotate(42))
        _MethodAnimation(Square)

    ::

        >>> prepare_animation(42)
        Traceback (most recent call last):
        ...
        TypeError: Object 42 cannot be converted to an animation