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

Code before:
This script generates contributor and pull request lists for release
changelogs using Github v3 protocol. Use requires an authentication token in
order to have sufficient bandwidth, you can get one following the directions at
`<https://help.github.com/articles/creating-an-access-token-for-command-line-use/>_
Don't add any scope, as the default is read access to public information. The
token may be stored in an environment variable as you only get one chance to
see it.

Usage::

    $ ./scripts/dev_changelog.py <token> <revision range> <output_file>

The output is utf8 rst.

Dependencies
------------

- gitpython
- pygithub

Examples
--------

From the bash command line with $GITHUB token::

    $ ./scripts/dev_changelog.py $GITHUB v0.3.0..HEAD -t v0.4.0 -o 0.4.0-changelog.rst

Note
----

This script was taken from Numpy under the terms of BSD-3-Clause license.
"""

import datetime
import re
import sys
from collections import defaultdict
from textwrap import dedent, indent
from pathlib import Path
import git
from tqdm import tqdm
from git import Repo
from github import Github


this_repo = Repo(str(Path(__file__).resolve().parent.parent))


def get_authors_and_reviewers(revision_range, github_repo, pr_nums):
    pat = r"^.*\t(.*)$"
    lst_release, cur_release = [r.strip() for r in revision_range.split("..")]

Review comment (suggestion):
I like this! I can update the GitHub Wiki accordingly.

One thing I'll add is that `..HEAD` portion of `v0.3.0..HEAD` seems unnecessary with this. I think the revision_range logic can be modified

Code after:
This script generates contributor and pull request lists for release
changelogs using Github v3 protocol. Use requires an authentication token in
order to have sufficient bandwidth, you can get one following the directions at
`<https://help.github.com/articles/creating-an-access-token-for-command-line-use/>_
Don't add any scope, as the default is read access to public information. The
token may be stored in an environment variable as you only get one chance to
see it.

Usage::

    $ ./scripts/dev_changelog.py [OPTIONS] TOKEN PRIOR TAG [ADDITIONAL]...

The output is utf8 rst.

Dependencies
------------

- gitpython
- pygithub

Examples
--------

From a bash command line with $GITHUB environment variable as the GitHub token::

    $ ./scripts/dev_changelog.py $GITHUB v0.3.0 v0.4.0

This would generate 0.4.0-changelog.rst file and place it automatically under
docs/source/changelog/.

As another example, you may also run include PRs that have been excluded by
providing a space separated list of ticket numbers after TAG::

    $ ./scripts/dev_changelog.py $GITHUB v0.3.0 v0.4.0 1911 1234 1492 ...


Note
----

This script was taken from Numpy under the terms of BSD-3-Clause license.
"""

import datetime
import re
import click

from manim.constants import EPILOG, CONTEXT_SETTINGS
from collections import defaultdict
from textwrap import dedent, indent
from pathlib import Path
from tqdm import tqdm
Repository: ManimCommunity/manim
File: manim/__main__.py (Python)

Code before:
import requests
from click_default_group import DefaultGroup
from . import __version__, console
from .constants import EPILOG
from .constants import CONTEXT_SETTINGS
from .cli.cfg.commands import cfg
from .cli.plugins.commands import plugins
from .cli.render.commands import render


def exit_early(ctx, param, value):
    if value:
        sys.exit()


latest = requests.get(
    "https://api.github.com/repos/ManimCommunity/manim/releases/latest"
)
latest_tag = latest.json()["tag_name"]
curr_version = "v" + __version__

if latest_tag == curr_version:
    console.print(f"Manim Community [green]{curr_version}[/green] (latest)\n")
else:
    console.print(f"Manim Community [red]{curr_version}[/red] (outdated)")
    console.print(f"Update available: [green]{latest_tag}[/green]\n")


@click.group(
    cls=DefaultGroup,
    default="render",
    no_args_is_help=True,
    context_settings=CONTEXT_SETTINGS,
    help="Animation engine for explanatory math videos",
    epilog=EPILOG,
)
@click.option(
    "--version",
    is_flag=True,
    help="Show version and exit.",
    callback=exit_early,
    is_eager=True,
    expose_value=False,
)
@click.pass_context
def main(ctx):
    """The entry point for manim."""
    pass


main.add_command(cfg)

Review comment (suggestion):
I would like to be printed or the request being made only at the end of the animation and it should be disabled using config files or cli options.

It would be helpful for the bot we have on discord as it can save time waiting for a request.

Code after:
import click
from click_default_group import DefaultGroup

from . import __version__, console
from .cli.cfg.commands import cfg
from .cli.plugins.commands import plugins
from .cli.render.commands import render
from .constants import CONTEXT_SETTINGS, EPILOG


def exit_early(ctx, param, value):
    if value:
        sys.exit()


console.print(f"Manim Community [green]v{__version__}[/green]\n")


@click.group(
    cls=DefaultGroup,
    default="render",
    no_args_is_help=True,
    context_settings=CONTEXT_SETTINGS,
    help="Animation engine for explanatory math videos",
    epilog=EPILOG,
)
@click.option(
    "--version",
    is_flag=True,
    help="Show version and exit.",
    callback=exit_early,
    is_eager=True,
    expose_value=False,
)
@click.pass_context
def main(ctx):
    """The entry point for manim."""
    pass


main.add_command(cfg)
main.add_command(plugins)
main.add_command(render)

if __name__ == "__main__":
    main()
Repository: ManimCommunity/manim
File: manim/cli/render/global_options.py (Python)

Code before:
    option(
        "--custom_folders",
        is_flag=True,
        help="Use the folders defined in the [custom_folders] section of the "
        "config file to define the output folder structure.",
    ),
    option(
        "--disable_caching",
        is_flag=True,
        help="Disable the use of the cache (still generates cache files).",
    ),
    option("--flush_cache", is_flag=True, help="Remove cached partial movie files."),
    option("--tex_template", help="Specify a custom TeX template file."),
    option(
        "-v",
        "--verbosity",
        type=click.Choice(
            ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
            case_sensitive=False,
        ),
        help="Verbosity of CLI output. Changes ffmpeg log level unless 5+.",
    ),
    option(
        "--notify_outdated_version",
        is_flag=True,
        help="Display warnings for outdated installation",
    ),
)


Review comment (suggestion):
```suggestion
        help="Display warnings for outdated installation.",
```

Code after:
        "--custom_folders",
        is_flag=True,
        help="Use the folders defined in the [custom_folders] section of the "
        "config file to define the output folder structure.",
    ),
    option(
        "--disable_caching",
        is_flag=True,
        help="Disable the use of the cache (still generates cache files).",
    ),
    option("--flush_cache", is_flag=True, help="Remove cached partial movie files."),
    option("--tex_template", help="Specify a custom TeX template file."),
    option(
        "-v",
        "--verbosity",
        type=click.Choice(
            ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
            case_sensitive=False,
        ),
        help="Verbosity of CLI output. Changes ffmpeg log level unless 5+.",
    ),
    option(
        "--notify_outdated_version/--silent",
        is_flag=True,
        default=None,
        help="Display warnings for outdated installation.",
    ),
)
Repository: ManimCommunity/manim
File: manim/cli/render/commands.py (Python)

Code before:
            )
            console.print_exception()
    else:
        for SceneClass in scene_classes_from_file(file):
            try:
                scene = SceneClass()
                scene.render()
            except Exception:
                console.print_exception()

    if nov or args["notify_outdated_version"]:
        manim = requests.get("https://pypi.org/pypi/manim/json")
        releases = manim.json()["releases"].keys()
        latest = max(releases)

        if latest != __version__:
            console.print(
                f"[yellow]WARNING: You are running on an outdated version of manim[/yellow]"
            )
            console.print(f"Installed version: [red]v{__version__}[/red]")
            console.print(f"Latest version: [green]v{latest}[/green]")
            console.print(
                f"[yellow]To disable this warning, go to [white]manim/_config/default.cfg[/white] and set [red]notify_outdated_version[/red] to [/yellow]False"
            )
        else:
            console.print(f"[green]You are using the latest version of manim[/green]")

    return args


Review comment (suggestion):
No need to inform users they're up to date. Especially because this isn't always true... they would be running the latest released version (e.g. v0.5.0 for now), but the latest is actually whatever is on master
```suggestion
```

Code after:
            console.print_exception()
    else:
        for SceneClass in scene_classes_from_file(file):
            try:
                scene = SceneClass()
                scene.render()
            except Exception:
                console.print_exception()

    if config.notify_outdated_version:
        manim_info_url = "https://pypi.org/pypi/manim/json"
        warn_prompt = "Cannot check if latest release of manim is installed"
        req_info = {}

        try:
            req_info = requests.get(manim_info_url)
            req_info.raise_for_status()
        except requests.exceptions.HTTPError:
            logger.debug(f"HTTP Error: {warn_prompt}")
        except requests.exceptions.ConnectionError:
            logger.debug(f"Connection Error: {warn_prompt}")
        except requests.exceptions.Timeout:
            logger.debug(f"Timed Out: {warn_prompt}")
        except Exception:
            logger.debug(f"Something went wrong: {warn_prompt}")

        try:
            stable = req_info.json()["info"]["version"]

            if stable != __version__:
                console.print(
                    f"You are using manim version [red]v{__version__}[/red], but version [green]v{stable}[/green] is available."
                )
                console.print(
                    "You should consider upgrading via [yellow]pip install -U manim[/yellow]"
                )
        except json.JSONDecodeError:
            logger.debug(warn_prompt)
            logger.debug(f"Error decoding JSON from {manim_info_url}")

    return args
Repository: ManimCommunity/manim
File: manim/cli/render/commands.py (Python)

Code before:
            console.print_exception()
    else:
        for SceneClass in scene_classes_from_file(file):
            try:
                scene = SceneClass()
                scene.render()
            except Exception:
                console.print_exception()

    if nov or args["notify_outdated_version"]:
        manim = requests.get("https://pypi.org/pypi/manim/json")
        releases = manim.json()["releases"].keys()
        latest = max(releases)

        if latest != __version__:
            console.print(
                "[yellow]WARNING: You are running on an outdated version of manim[/yellow]"
            )
            console.print(f"Installed version: [red]v{__version__}[/red]")
            console.print(f"Latest version: [green]v{latest}[/green]")
            console.print(
                "[yellow]To disable this warning, go to config and set [red]notify_outdated_version[/red] to [/yellow]False"
            )
            console.print(
                "https://docs.manim.community/en/latest/tutorials/configuration.html"
            )

    return args


Review comment (suggestion):
latest != most recently released
```suggestion
```

Code after:
    else:
        for SceneClass in scene_classes_from_file(file):
            try:
                scene = SceneClass()
                scene.render()
            except Exception:
                console.print_exception()

    if config.notify_outdated_version:
        manim_info_url = "https://pypi.org/pypi/manim/json"
        warn_prompt = "Cannot check if latest release of manim is installed"
        req_info = {}

        try:
            req_info = requests.get(manim_info_url)
            req_info.raise_for_status()
        except requests.exceptions.HTTPError:
            logger.debug(f"HTTP Error: {warn_prompt}")
        except requests.exceptions.ConnectionError:
            logger.debug(f"Connection Error: {warn_prompt}")
        except requests.exceptions.Timeout:
            logger.debug(f"Timed Out: {warn_prompt}")
        except Exception:
            logger.debug(f"Something went wrong: {warn_prompt}")

        try:
            stable = req_info.json()["info"]["version"]

            if stable != __version__:
                console.print(
                    f"You are using manim version [red]v{__version__}[/red], but version [green]v{stable}[/green] is available."
                )
                console.print(
                    "You should consider upgrading via [yellow]pip install -U manim[/yellow]"
                )
        except json.JSONDecodeError:
            logger.debug(warn_prompt)
            logger.debug(f"Error decoding JSON from {manim_info_url}")

    return args
Repository: ManimCommunity/manim
File: manim/cli/render/commands.py (Python)

Code before:

    if config.notify_outdated_version:
        manim_info_url = "https://pypi.org/pypi/manim/json"
        warn_prompt = "Cannot check if latest release of manim is installed"
        req_info = {}

        try:
            req_info = requests.get(manim_info_url, timeout=3)
            req_info.raise_for_status()
        except requests.exceptions.HTTPError:
            logger.warning(f"HTTP Error: {warn_prompt}")
            raise SystemExit
        except requests.exceptions.ConnectionError:
            logger.warning(f"Connection Error: {warn_prompt}")
            raise SystemExit
        except requests.exceptions.Timeout:
            logger.warning(f"Timed Out: {warn_prompt}")
            raise SystemExit
        except Exception:
            logger.warning(f"Something went wrong: {warn_prompt}")
            raise SystemExit

        try:
            releases = req_info.json()["releases"].keys()

            if max(releases) != __version__:
                console.print(
                    f"You are using manim version [red]v{__version__}[/red], but version [green]v{max(releases)}[/green] is available."
                )
                console.print(
                    "You should consider upgrading via [yellow]pip install -U manim[/yellow]"
                )
        except json.JSONDecodeError:
            logger.warning(warn_prompt)
            logger.warning(f"Error decoding JSON from {manim_info_url}")
            raise SystemExit

    return args


Review comment (suggestion):
looking at https://pypi.org/pypi/manim/json it seems it is better to directly pick version from info rather than doing this

```suggestion
        try:
            releases = req_info.json()["info"]["version"]

            if releases != __version__:
```

Code after:

    if config.notify_outdated_version:
        manim_info_url = "https://pypi.org/pypi/manim/json"
        warn_prompt = "Cannot check if latest release of manim is installed"
        req_info = {}

        try:
            req_info = requests.get(manim_info_url)
            req_info.raise_for_status()
        except requests.exceptions.HTTPError:
            logger.debug(f"HTTP Error: {warn_prompt}")
        except requests.exceptions.ConnectionError:
            logger.debug(f"Connection Error: {warn_prompt}")
        except requests.exceptions.Timeout:
            logger.debug(f"Timed Out: {warn_prompt}")
        except Exception:
            logger.debug(f"Something went wrong: {warn_prompt}")

        try:
            stable = req_info.json()["info"]["version"]

            if stable != __version__:
                console.print(
                    f"You are using manim version [red]v{__version__}[/red], but version [green]v{stable}[/green] is available."
                )
                console.print(
                    "You should consider upgrading via [yellow]pip install -U manim[/yellow]"
                )
        except json.JSONDecodeError:
            logger.debug(warn_prompt)
            logger.debug(f"Error decoding JSON from {manim_info_url}")

    return args
Repository: ManimCommunity/manim
File: manim/utils/color.py (Python)

Code before:

import random
from enum import Enum

import numpy as np
from colour import Color

from ..utils.bezier import interpolate
from ..utils.simple_functions import clip_in_place
from ..utils.space_ops import normalize


class Colors(Enum):
    """A list of pre-defined colors.

    Examples
    --------

    .. manim:: ColorExample
        :save_last_frame:

        from manim.utils.color import Colors
        class ColorExample(Scene):
            def construct(self):
                cols= Colors._member_names_
                s= VGroup(*[Line(DOWN, UP, stroke_width=15).set_color(Colors[cols[i]].value) for i in range(0,len(cols))])
                s.arrange_submobjects(buff=0.2)
                self.add(s)

    The preferred way of using these colors is

    .. code-block:: python

        >>> import manim.utils.color as C
        >>> C.WHITE
        '#FFFFFF'

    Note this way uses the name of the colors in UPPERCASE.

    Alternatively, you can also import this Enum directly and use its members
    directly, through the use of :code:`color.value`.  Note this way uses the
    name of the colors in lowercase.

    .. code-block:: python

        >>> from manim.utils.color import Colors
        >>> Colors.white.value
        '#FFFFFF'

    """


Review comment (suggestion):
```suggestion
                cols = Colors._member_names_
                s = VGroup(*[Line(DOWN, UP, stroke_width=15).set_color(Colors[cols[i]].value) for i in range(0, len(cols))])
```

Code after:

import random
from enum import Enum

import numpy as np
from colour import Color

from ..utils.bezier import interpolate
from ..utils.simple_functions import clip_in_place
from ..utils.space_ops import normalize


class Colors(Enum):
    """A list of pre-defined colors.

    Examples
    --------

    .. manim:: ColorExample
        :save_last_frame:

        from manim.utils.color import Colors
        class ColorExample(Scene):
            def construct(self):
                cols = Colors._member_names_
                s = VGroup(*[Line(DOWN, UP, stroke_width=15).set_color(Colors[cols[i]].value) for i in range(0, len(cols))])
                s.arrange_submobjects(buff=0.2)
                self.add(s)

    The preferred way of using these colors is

    .. code-block:: python

        >>> import manim.utils.color as C
        >>> C.WHITE
        '#FFFFFF'

    Note this way uses the name of the colors in UPPERCASE.

    Alternatively, you can also import this Enum directly and use its members
    directly, through the use of :code:`color.value`.  Note this way uses the
    name of the colors in lowercase.

    .. code-block:: python

        >>> from manim.utils.color import Colors
        >>> Colors.white.value
        '#FFFFFF'

    """
Repository: ManimCommunity/manim
File: manim/renderer/cairo_renderer.py (Python)

Code before:
        the number of animations that were played correspond to
        the number of animations that need to be played, and
        raises an EndSceneEarlyException if they don't correspond.
        """
        if config["save_last_frame"]:
            self.skip_animations = True
        if config["from_animation_number"]:
            if self.num_plays < config["from_animation_number"]:
                self.skip_animations = True
        if config["upto_animation_number"]:
            if self.num_plays > config["upto_animation_number"]:
                self.skip_animations = True
                raise EndSceneEarlyException()

    def scene_finished(self, scene):
        # If no animations in scene, display the image instead
        if self.num_plays != 0:
            self.file_writer.finish()
        elif config["preview"] or config["show_in_file_browser"]:
            config["save_last_frame"] = True
            config["write_to_movie"] = False
            logger.warning("No animations found in the scene. Showing an image instead")
        elif not (config["save_last_frame"] or config["save_pngs"]):
            logger.warning(
                "No animations found in the scene. Use -s flag to produce an image"
            )
        if config["save_last_frame"]:
            self.update_frame(scene, ignore_skipping=False)
            self.file_writer.save_final_image(self.camera.get_image())


Review comment (suggestion):
```suggestion
        if self.num_plays:
            self.file_writer.finish()
        else:
            config.save_last_frame = True
            config.write_to_movie = False
            self.update_frame(scene, ignore_skipping=False)
            self.file_writer.save_final_image(self.camera.get_image()
```

Code after:
        the number of animations that were played correspond to
        the number of animations that need to be played, and
        raises an EndSceneEarlyException if they don't correspond.
        """
        if config["save_last_frame"]:
            self.skip_animations = True
        if config["from_animation_number"]:
            if self.num_plays < config["from_animation_number"]:
                self.skip_animations = True
        if config["upto_animation_number"]:
            if self.num_plays > config["upto_animation_number"]:
                self.skip_animations = True
                raise EndSceneEarlyException()

    def scene_finished(self, scene):
        # If no animations in scene, render an image instead
        if self.num_plays:
            self.file_writer.finish()
        elif config.write_to_movie:
            config.save_last_frame = True
            config.write_to_movie = False
        else:
            self.update_frame(scene)

        if config["save_last_frame"]:
            self.update_frame(scene)
            self.file_writer.save_final_image(self.camera.get_image())