ronantakizawa/codereview-bench huggingface dataset:
Repository: Rapptz/discord.py
File: discord/types/role.py (Python)

Code before:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from __future__ import annotations

from typing import TypedDict, Optional
from typing_extensions import NotRequired

from .snowflake import Snowflake


class Role(TypedDict):
    id: Snowflake
    name: str
    color: int
    secondary_color: NotRequired[Optional[int]]
    tertiary_color: NotRequired[Optional[int]]
    hoist: bool
    position: int
    permissions: str
    managed: bool
    mentionable: bool
    flags: int
    icon: NotRequired[Optional[str]]
    unicode_emoji: NotRequired[Optional[str]]
    tags: NotRequired[RoleTags]


class RoleTags(TypedDict, total=False):
    bot_id: Snowflake
    integration_id: Snowflake
    subscription_listing_id: Snowflake
    premium_subscriber: None
    available_for_purchase: None
    guild_connections: None


Review comment (suggestion):
It's not on the role object, it's under the `colors` key
```suggestion
    colors: RoleColours
```

RoleColours should be added as its independent type class:
```py
class RoleColours(TypedDict):
    primary_color: int
    secondary_color: Optional[int]
    tertiary_color: Optional[int]
```

Code after:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from __future__ import annotations

from typing import TypedDict, Optional
from typing_extensions import NotRequired

from .snowflake import Snowflake


class RoleColours(TypedDict):
    primary_color: int
    secondary_color: Optional[int]
    tertiary_color: Optional[int]


class Role(TypedDict):
    id: Snowflake
    name: str
    color: int
    colors: RoleColours
    hoist: bool
    position: int
    permissions: str
    managed: bool
    mentionable: bool
    flags: int
    icon: NotRequired[Optional[str]]
    unicode_emoji: NotRequired[Optional[str]]
    tags: NotRequired[RoleTags]


class RoleTags(TypedDict, total=False):
    bot_id: Snowflake
    integration_id: Snowflake
    subscription_listing_id: Snowflake
    premium_subscriber: None
    available_for_purchase: None
    guild_connections: None
Repository: Rapptz/discord.py
File: discord/flags.py (Python)

Code before:

        .. describe:: bool(b)

            Returns whether any flag is set to ``True``.

    Attributes
    ----------
    value: :class:`int`
        The raw value. You should query flags via the properties
        rather than using this raw value.
    """

    @flag_value
    def contains_explicit_media(self):
        """:class:`bool`: Returns ``True`` if the embed was flagged as sensitive content."""
        return 1 << 4

    @flag_value
    def content_inventory_entry(self):
        """:class:`bool`: Returns ``True`` if the embed is a reply to an activity card, and is no
        longer displayed.
        """
        return 1 << 5


class GuildInviteFlags(BaseFlags):
    r"""Wraps up the Discord Guild Invite flags

    .. versionadded:: 2.6

    .. container:: operations

        .. describe:: x == y

            Checks if two GuildInviteFlags are equal.

        .. describe:: x != y

            Checks if two GuildInviteFlags are not equal.

        .. describe:: x | y, x |= y

            Returns a GuildInviteFlags instance with all enabled flags from
            both x and y.

        .. describe:: x ^ y, x ^= y

            Returns a GuildInviteFlags instance with only flags enabled on
            only one of x or y, not on both.

        .. describe:: ~x

Review comment (suggestion):
```suggestion
class InviteFlags(BaseFlags):
```
kinda unnecessary imo

Code after:

        .. describe:: bool(b)

            Returns whether any flag is set to ``True``.

    Attributes
    ----------
    value: :class:`int`
        The raw value. You should query flags via the properties
        rather than using this raw value.
    """

    @flag_value
    def contains_explicit_media(self):
        """:class:`bool`: Returns ``True`` if the embed was flagged as sensitive content."""
        return 1 << 4

    @flag_value
    def content_inventory_entry(self):
        """:class:`bool`: Returns ``True`` if the embed is a reply to an activity card, and is no
        longer displayed.
        """
        return 1 << 5


class InviteFlags(BaseFlags):
    r"""Wraps up the Discord Invite flags

    .. versionadded:: 2.6

    .. container:: operations

        .. describe:: x == y

            Checks if two InviteFlags are equal.

        .. describe:: x != y

            Checks if two InviteFlags are not equal.

        .. describe:: x | y, x |= y

            Returns a InviteFlags instance with all enabled flags from
            both x and y.

        .. describe:: x ^ y, x ^= y

            Returns a InviteFlags instance with only flags enabled on
            only one of x or y, not on both.

        .. describe:: ~x
Repository: Rapptz/discord.py
File: discord/flags.py (Python)

Code before:
            Returns a GuildInviteFlags instance with all flags inverted from x.

        .. describe:: hash(x)

            Returns the flag's hash.

        .. describe:: iter(x)

            Returns an iterator of ``(name, value)`` pairs. This allows it
            to be, for example, constructed as a dict or a list of pairs.
            Note that aliases are not shown.

        .. describe:: bool(b)

            Returns whether any flag is set to ``True``.

    Attributes
    ----------
    value: :class:`int`
        The raw value. You should query flags via the properties
        rather than using this raw value.
    """

    @flag_value
    def is_guest_invite(self):
        """:class:`bool`: Returns ``True`` if this is a guest invite for a voice channel."""
        return 1 << 0


Review comment (suggestion):
```suggestion
    def guest(self):
        """:class:`bool`: Returns ``True`` if this is a guest invite for a voice channel."""
```
`is_` for flags is pretty redundant (and has been removed from other flags) and `_invite` also seems redundant to me for invite flags

Code after:
            Returns a InviteFlags instance with all flags inverted from x.

        .. describe:: hash(x)

            Returns the flag's hash.

        .. describe:: iter(x)

            Returns an iterator of ``(name, value)`` pairs. This allows it
            to be, for example, constructed as a dict or a list of pairs.
            Note that aliases are not shown.

        .. describe:: bool(b)

            Returns whether any flag is set to ``True``.

    Attributes
    ----------
    value: :class:`int`
        The raw value. You should query flags via the properties
        rather than using this raw value.
    """

    @flag_value
    def guest(self):
        """:class:`bool`: Returns ``True`` if this is a guest invite for a voice channel."""
        return 1 << 0
Repository: Rapptz/discord.py
File: discord/enums.py (Python)

Code before:
    greek = 'el'
    hindi = 'hi'
    hungarian = 'hu'
    italian = 'it'
    japanese = 'ja'
    korean = 'ko'
    latin_american_spanish = 'es-419'
    lithuanian = 'lt'
    norwegian = 'no'
    polish = 'pl'
    brazil_portuguese = 'pt-BR'
    romanian = 'ro'
    russian = 'ru'
    spain_spanish = 'es-ES'
    swedish = 'sv-SE'
    thai = 'th'
    turkish = 'tr'
    ukrainian = 'uk'
    vietnamese = 'vi'

    def __str__(self) -> str:
        return self.value

    @property
    def language_code(self) -> str:
        """Returns the locale's language code in the format of ``language-COUNTRY``.

        .. versionadded:: 2.5
        """
        return _UNICODE_LANG_MAP.get(self.value, self.value)


E = TypeVar('E', bound='Enum')


class EntityType(Enum):
    stage_instance = 1
    voice = 2
    external = 3


class EventStatus(Enum):
    scheduled = 1
    active = 2
    completed = 3
    canceled = 4

    ended = 3
    cancelled = 4



Review comment (suggestion):
```suggestion
        """:class:`str`: Returns the locale's BCP 47 language code in the format of ``language-COUNTRY``.
```

Code after:
    greek = 'el'
    hindi = 'hi'
    hungarian = 'hu'
    italian = 'it'
    japanese = 'ja'
    korean = 'ko'
    latin_american_spanish = 'es-419'
    lithuanian = 'lt'
    norwegian = 'no'
    polish = 'pl'
    brazil_portuguese = 'pt-BR'
    romanian = 'ro'
    russian = 'ru'
    spain_spanish = 'es-ES'
    swedish = 'sv-SE'
    thai = 'th'
    turkish = 'tr'
    ukrainian = 'uk'
    vietnamese = 'vi'

    def __str__(self) -> str:
        return self.value

    @property
    def language_code(self) -> str:
        """:class:`str`: Returns the locale's BCP 47 language code in the format of ``language-COUNTRY``.

        This is derived from a predefined mapping based on Discord's supported locales.
        If no mapping exists for the current locale, this returns the raw locale value as a fallback.

        .. versionadded:: 2.6
        """
        return _UNICODE_LANG_MAP.get(self.value, self.value)


E = TypeVar('E', bound='Enum')


class EntityType(Enum):
    stage_instance = 1
    voice = 2
    external = 3


class EventStatus(Enum):
    scheduled = 1
    active = 2
    completed = 3
    canceled = 4

    ended = 3
Repository: Rapptz/discord.py
File: discord/ui/item.py (Python)

Code before:
        elif 5 > value >= 0:
            self._row = value
        else:
            raise ValueError('row cannot be negative or greater than or equal to 5')

    @property
    def width(self) -> int:
        return 1

    @property
    def view(self) -> Optional[V]:
        """Optional[Union[:class:`View`, :class:`LayoutView`]]: The underlying view for this item."""
        return self._view

    @property
    def id(self) -> Optional[int]:
        """Optional[:class:`int`]: The ID of this component."""
        return self._id

    @id.setter
    def id(self, value: Optional[int]) -> None:
        self._id = value

    @property
    def parent(self) -> Optional[Item[V]]:
        """Optional[:class:`Item`]: This item's parent. If applicable. Only available on items with children.

        .. versionadded:: 2.6
        """
        return self._parent

    async def _run_checks(self, interaction: Interaction[ClientT]) -> bool:
        can_run = await self.interaction_check(interaction)

        if can_run and self._parent:
            can_run = await self._parent._run_checks(interaction)

        return can_run

    def _update_view(self, view) -> None:
        self._view = view

    def copy(self) -> Self:
        return copy.deepcopy(self)

    def _has_children(self) -> bool:
        return False

    async def callback(self, interaction: Interaction[ClientT]) -> Any:
        """|coro|


Review comment (suggestion):
```suggestion
        """Optional[:class:`Item`]: This item's parent, if applicable. Only available on items with children.
```

Code after:
        elif 5 > value >= 0:
            self._row = value
        else:
            raise ValueError('row cannot be negative or greater than or equal to 5')

    @property
    def width(self) -> int:
        return 1

    @property
    def view(self) -> Optional[V]:
        """Optional[Union[:class:`View`, :class:`LayoutView`]]: The underlying view for this item."""
        return self._view

    @property
    def id(self) -> Optional[int]:
        """Optional[:class:`int`]: The ID of this component."""
        return self._id

    @id.setter
    def id(self, value: Optional[int]) -> None:
        self._id = value

    @property
    def parent(self) -> Optional[Item[V]]:
        """Optional[:class:`Item`]: This item's parent, if applicable. Only available on items with children.

        .. versionadded:: 2.6
        """
        return self._parent

    async def _run_checks(self, interaction: Interaction[ClientT]) -> bool:
        can_run = await self.interaction_check(interaction)

        if can_run and self._parent:
            can_run = await self._parent._run_checks(interaction)

        return can_run

    def _update_view(self, view) -> None:
        self._view = view

    def copy(self) -> Self:
        return copy.deepcopy(self)

    def _has_children(self) -> bool:
        return False

    async def callback(self, interaction: Interaction[ClientT]) -> Any:
        """|coro|
Repository: Rapptz/discord.py
File: discord/errors.py (Python)

Code before:
    _ResponseType = Union[ClientResponse, Response]

    from .interactions import Interaction

__all__ = (
    'DiscordException',
    'ClientException',
    'GatewayNotFound',
    'HTTPException',
    'RateLimited',
    'Forbidden',
    'NotFound',
    'DiscordServerError',
    'InvalidData',
    'LoginFailure',
    'ConnectionClosed',
    'PrivilegedIntentsRequired',
    'InteractionResponded',
    'MissingApplicationID',
    'FFmpegError',
)

APP_ID_NOT_FOUND = (
    'Client does not have an application_id set. Either the function '
    'was called before on_ready was called or application_id was not '
    'passed to the Client constructor.'
)


class DiscordException(Exception):
    """Base exception class for discord.py

    Ideally speaking, this could be caught to handle any exceptions raised from this library.
    """

    pass


class ClientException(DiscordException):
    """Exception that's raised when an operation in the :class:`Client` fails.

    These are usually for exceptions that happened due to user input.
    """

    pass


class FFmpegError(ClientException):
    """Exception that's raised when an FFmpeg process fails."""

    pass

Review comment (suggestion):
This change should be reverted as errors.py passes CI checks on master.

Code after:
    _ResponseType = Union[ClientResponse, Response]

    from .interactions import Interaction

__all__ = (
    'DiscordException',
    'ClientException',
    'GatewayNotFound',
    'HTTPException',
    'RateLimited',
    'Forbidden',
    'NotFound',
    'DiscordServerError',
    'InvalidData',
    'LoginFailure',
    'ConnectionClosed',
    'PrivilegedIntentsRequired',
    'InteractionResponded',
    'MissingApplicationID',
    'FFmpegProcessError',
)

APP_ID_NOT_FOUND = (
    'Client does not have an application_id set. Either the function was called before on_ready '
    'was called or application_id was not passed to the Client constructor.'
)


class DiscordException(Exception):
    """Base exception class for discord.py

    Ideally speaking, this could be caught to handle any exceptions raised from this library.
    """

    pass


class ClientException(DiscordException):
    """Exception that's raised when an operation in the :class:`Client` fails.

    These are usually for exceptions that happened due to user input.
    """

    pass


class FFmpegProcessError(ClientException):
    """Exception that's raised when an FFmpeg process fails.

    .. versionadded:: 2.7
    """
Repository: Rapptz/discord.py
File: discord/errors.py (Python)

Code before:

APP_ID_NOT_FOUND = (
    'Client does not have an application_id set. Either the function was called before on_ready '
    'was called or application_id was not passed to the Client constructor.'
)


class DiscordException(Exception):
    """Base exception class for discord.py

    Ideally speaking, this could be caught to handle any exceptions raised from this library.
    """

    pass


class ClientException(DiscordException):
    """Exception that's raised when an operation in the :class:`Client` fails.

    These are usually for exceptions that happened due to user input.
    """

    pass


class FFmpegError(ClientException):
    """Exception that's raised when an FFmpeg process fails."""

    pass


class GatewayNotFound(DiscordException):
    """An exception that is raised when the gateway for Discord could not be found"""

    def __init__(self):
        message = 'The gateway to connect to discord was not found.'
        super().__init__(message)


def _flatten_error_dict(d: Dict[str, Any], key: str = '') -> Dict[str, str]:
    items: List[Tuple[str, str]] = []
    for k, v in d.items():
        new_key = key + '.' + k if key else k

        if isinstance(v, dict):
            try:
                _errors: List[Dict[str, Any]] = v['_errors']
            except KeyError:
                items.extend(_flatten_error_dict(v, new_key).items())
            else:
                items.append((new_key, ' '.join(x.get('message', '') for x in _errors)))

Review comment (suggestion):
```suggestion
class FFmpegProcessError(ClientException):
```

Code after:

APP_ID_NOT_FOUND = (
    'Client does not have an application_id set. Either the function was called before on_ready '
    'was called or application_id was not passed to the Client constructor.'
)


class DiscordException(Exception):
    """Base exception class for discord.py

    Ideally speaking, this could be caught to handle any exceptions raised from this library.
    """

    pass


class ClientException(DiscordException):
    """Exception that's raised when an operation in the :class:`Client` fails.

    These are usually for exceptions that happened due to user input.
    """

    pass


class FFmpegProcessError(ClientException):
    """Exception that's raised when an FFmpeg process fails.

    .. versionadded:: 2.7
    """

    pass


class GatewayNotFound(DiscordException):
    """An exception that is raised when the gateway for Discord could not be found"""

    def __init__(self):
        message = 'The gateway to connect to discord was not found.'
        super().__init__(message)


def _flatten_error_dict(d: Dict[str, Any], key: str = '') -> Dict[str, str]:
    items: List[Tuple[str, str]] = []
    for k, v in d.items():
        new_key = key + '.' + k if key else k

        if isinstance(v, dict):
            try:
                _errors: List[Dict[str, Any]] = v['_errors']
            except KeyError:
Repository: Rapptz/discord.py
File: discord/errors.py (Python)

Code before:
APP_ID_NOT_FOUND = (
    'Client does not have an application_id set. Either the function was called before on_ready '
    'was called or application_id was not passed to the Client constructor.'
)


class DiscordException(Exception):
    """Base exception class for discord.py

    Ideally speaking, this could be caught to handle any exceptions raised from this library.
    """

    pass


class ClientException(DiscordException):
    """Exception that's raised when an operation in the :class:`Client` fails.

    These are usually for exceptions that happened due to user input.
    """

    pass


class FFmpegError(ClientException):
    """Exception that's raised when an FFmpeg process fails."""

    pass


class GatewayNotFound(DiscordException):
    """An exception that is raised when the gateway for Discord could not be found"""

    def __init__(self):
        message = 'The gateway to connect to discord was not found.'
        super().__init__(message)


def _flatten_error_dict(d: Dict[str, Any], key: str = '') -> Dict[str, str]:
    items: List[Tuple[str, str]] = []
    for k, v in d.items():
        new_key = key + '.' + k if key else k

        if isinstance(v, dict):
            try:
                _errors: List[Dict[str, Any]] = v['_errors']
            except KeyError:
                items.extend(_flatten_error_dict(v, new_key).items())
            else:
                items.append((new_key, ' '.join(x.get('message', '') for x in _errors)))
        else:

Review comment (suggestion):
This is missing `.. versionadded:: 2.7`.

It's also missing from `api.rst` and the exception hierarchy.

Code after:
APP_ID_NOT_FOUND = (
    'Client does not have an application_id set. Either the function was called before on_ready '
    'was called or application_id was not passed to the Client constructor.'
)


class DiscordException(Exception):
    """Base exception class for discord.py

    Ideally speaking, this could be caught to handle any exceptions raised from this library.
    """

    pass


class ClientException(DiscordException):
    """Exception that's raised when an operation in the :class:`Client` fails.

    These are usually for exceptions that happened due to user input.
    """

    pass


class FFmpegProcessError(ClientException):
    """Exception that's raised when an FFmpeg process fails.

    .. versionadded:: 2.7
    """

    pass


class GatewayNotFound(DiscordException):
    """An exception that is raised when the gateway for Discord could not be found"""

    def __init__(self):
        message = 'The gateway to connect to discord was not found.'
        super().__init__(message)


def _flatten_error_dict(d: Dict[str, Any], key: str = '') -> Dict[str, str]:
    items: List[Tuple[str, str]] = []
    for k, v in d.items():
        new_key = key + '.' + k if key else k

        if isinstance(v, dict):
            try:
                _errors: List[Dict[str, Any]] = v['_errors']
            except KeyError:
                items.extend(_flatten_error_dict(v, new_key).items())