ronantakizawa/codereview-bench huggingface dataset:
Repository: TheAlgorithms/Python
File: maths/perfect_number.py (Python)

Code before:
    Traceback (most recent call last):
      ...
    ValueError: number must be an integer
    >>> perfect("Hello")
    Traceback (most recent call last):
      ...
    ValueError: number must be an integer
    """
    if not isinstance(number, int):
        raise ValueError("number must be an integer")
    if number <= 0:
        return False
    return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number


if __name__ == "__main__":
    from doctest import testmod

    testmod()
    print("Program to check whether a number is a Perfect number or not...")
    try:
        number = int(input("Enter a positive integer: ").strip())
    except ValueError:
        msg = "number must be an integer"
        print(msg)
        raise ValueError(msg)

    print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")


Review comment (bug):
```suggestion
        msg = "number must be an integer"
        raise ValueError(msg)
```
Nothing wrong with your changes, but the original code prints the error message before raising an error, and outputting the message twice is unnecessary.

Code after:
    Traceback (most recent call last):
      ...
    ValueError: number must be an integer
    >>> perfect("Hello")
    Traceback (most recent call last):
      ...
    ValueError: number must be an integer
    """
    if not isinstance(number, int):
        raise ValueError("number must be an integer")
    if number <= 0:
        return False
    return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number


if __name__ == "__main__":
    from doctest import testmod

    testmod()
    print("Program to check whether a number is a Perfect number or not...")
    try:
        number = int(input("Enter a positive integer: ").strip())
    except ValueError:
        msg = "number must be an integer"
        raise ValueError(msg)

    print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
Repository: TheAlgorithms/Python
File: computer_vision/intensity_based_segmentation.py (Python)

Code before:
# Source: "https://www.ijcse.com/docs/IJCSE11-02-03-117.pdf"

# Importing necessary libraries
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt


def segment_image(image: np.ndarray, thresholds: list[int]) -> np.ndarray:
    """
    Performs image segmentation based on intensity thresholds.

    Args:
        image (np.ndarray): Input grayscale image as a 2D array.
        thresholds (list[int]): Intensity thresholds to define segments.

    Returns:
        np.ndarray: A labeled 2D array where each region corresponds to a threshold range.

    Example:
        >>> img = np.array([[80, 120, 180], [40, 90, 150], [20, 60, 100]])
        >>> segment_image(img, [50, 100, 150])
        array([[1, 2, 3],
               [0, 1, 2],
               [0, 1, 1]])
    """
    # Initialize segmented array with zeros
    segmented = np.zeros_like(image, dtype=np.int32)

    # Assign labels based on thresholds
    for i, threshold in enumerate(thresholds):

Review comment (suggestion):
```suggestion
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
```

Code after:
# Source: "https://www.ijcse.com/docs/IJCSE11-02-03-117.pdf"

# Importing necessary libraries
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image


def segment_image(image: np.ndarray, thresholds: list[int]) -> np.ndarray:
    """
    Performs image segmentation based on intensity thresholds.

    Args:
        image: Input grayscale image as a 2D array.
        thresholds: Intensity thresholds to define segments.

    Returns:
        A labeled 2D array where each region corresponds to a threshold range.

    Example:
        >>> img = np.array([[80, 120, 180], [40, 90, 150], [20, 60, 100]])
        >>> segment_image(img, [50, 100, 150])
        array([[1, 2, 3],
               [0, 1, 2],
               [0, 1, 1]], dtype=int32)
    """
    # Initialize segmented array with zeros
    segmented = np.zeros_like(image, dtype=np.int32)

    # Assign labels based on thresholds
    for i, threshold in enumerate(thresholds):
Repository: TheAlgorithms/Python
File: web_programming/current_stock_price.py (Python)

Code before:
Get the HTML code of finance yahoo and select the current qsp-price
Current AAPL stock price is   228.43
Current AMZN stock price is   201.85
Current IBM  stock price is   210.30
Current GOOG stock price is   177.86
Current MSFT stock price is   414.82
Current ORCL stock price is   188.87
"""


def stock_price(symbol: str = "AAPL") -> str:
    """
    >>> stock_price("EEEE")
    '- '
    >>> isinstance(float(stock_price("GOOG")),float)
    True
    """
    url = f"https://finance.yahoo.com/quote/{symbol}?p={symbol}"
    yahoo_finance_source = requests.get(
        url, headers={"USER-AGENT": "Mozilla/5.0"}, timeout=10
    ).text
    soup = BeautifulSoup(yahoo_finance_source, "html.parser")

    if specific_fin_streamer_tag := soup.find("span", {"data-testid": "qsp-price"}):
        text = specific_fin_streamer_tag.get_text()
        return text
    return "No <fin-streamer> tag with the specified data-testid attribute found."


# Search for the symbol at https://finance.yahoo.com/lookup
if __name__ == "__main__":
    from doctest import testmod

    testmod()

    for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
        print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")


Review comment (suggestion):
```suggestion
        return specific_fin_streamer_tag.get_text()
```

Code after:
Get the HTML code of finance yahoo and select the current qsp-price
Current AAPL stock price is   228.43
Current AMZN stock price is   201.85
Current IBM  stock price is   210.30
Current GOOG stock price is   177.86
Current MSFT stock price is   414.82
Current ORCL stock price is   188.87
"""


def stock_price(symbol: str = "AAPL") -> str:
    """
    >>> stock_price("EEEE")
    '- '
    >>> isinstance(float(stock_price("GOOG")),float)
    True
    """
    url = f"https://finance.yahoo.com/quote/{symbol}?p={symbol}"
    yahoo_finance_source = requests.get(
        url, headers={"USER-AGENT": "Mozilla/5.0"}, timeout=10
    ).text
    soup = BeautifulSoup(yahoo_finance_source, "html.parser")

    if specific_fin_streamer_tag := soup.find("span", {"data-testid": "qsp-price"}):
        return specific_fin_streamer_tag.get_text()
    return "No <fin-streamer> tag with the specified data-testid attribute found."


# Search for the symbol at https://finance.yahoo.com/lookup
if __name__ == "__main__":
    from doctest import testmod

    testmod()

    for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split():
        print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")
Repository: TheAlgorithms/Python
File: data_structures/hashing/hash_map.py (Python)

Code before:
        """
        Get next index.

        Implements linear open addressing.
        >>> HashMap(5)._get_next_ind(3)
        4
        >>> HashMap(5)._get_next_ind(5)
        1
        >>> HashMap(5)._get_next_ind(6)
        2
        >>> HashMap(5)._get_next_ind(9)
        0
        """
        return (ind + 1) % len(self._buckets)

    def _try_set(self, ind: int, key: KEY, val: VAL) -> bool:
        """
        Try to add value to the bucket.

        If bucket is empty or key is the same, does insert and return True.

        If bucket has another key that means that we need to check next bucket.
        """
        stored = self._buckets[ind]
        if not stored:
            # A falsy item means that is None (bucket never used) or _deleted.
            self._buckets[ind] = _Item(key, val)
            self._len += 1
            return True
        elif stored.key == key:
            stored.val = val
            return True
        else:
            return False

    def _is_full(self) -> bool:
        """
        Return true if we have reached safe capacity.

        So we need to increase the number of buckets to avoid collisions.

        >>> hm = HashMap(2)
        >>> hm._add_item(1, 10)
        >>> hm._add_item(2, 20)
        >>> hm._is_full()
        True
        >>> HashMap(2)._is_full()
        False
        """
        limit = len(self._buckets) * self._capacity_factor
        return len(self) >= int(limit)

Review comment (suggestion):
```suggestion
            # A falsy item means that bucket was never used (None) or was deleted (_deleted).
```

Code after:
        """
        Get next index.

        Implements linear open addressing.
        >>> HashMap(5)._get_next_ind(3)
        4
        >>> HashMap(5)._get_next_ind(5)
        1
        >>> HashMap(5)._get_next_ind(6)
        2
        >>> HashMap(5)._get_next_ind(9)
        0
        """
        return (ind + 1) % len(self._buckets)

    def _try_set(self, ind: int, key: KEY, val: VAL) -> bool:
        """
        Try to add value to the bucket.

        If bucket is empty or key is the same, does insert and return True.

        If bucket has another key that means that we need to check next bucket.
        """
        stored = self._buckets[ind]
        if not stored:
            # A falsy item means that bucket was never used (None)
            # or was deleted (_deleted).
            self._buckets[ind] = _Item(key, val)
            self._len += 1
            return True
        elif stored.key == key:
            stored.val = val
            return True
        else:
            return False

    def _is_full(self) -> bool:
        """
        Return true if we have reached safe capacity.

        So we need to increase the number of buckets to avoid collisions.

        >>> hm = HashMap(2)
        >>> hm._add_item(1, 10)
        >>> hm._add_item(2, 20)
        >>> hm._is_full()
        True
        >>> HashMap(2)._is_full()
        False
        """
        limit = len(self._buckets) * self._capacity_factor
Repository: TheAlgorithms/Python
File: web_programming/covid_stats_via_xpath.py (Python)

Code before:
#     "lxml",
# ]
# ///

from typing import NamedTuple

import httpx
from lxml import html


class CovidData(NamedTuple):
    cases: str
    deaths: str
    recovered: str


def covid_stats(
    url: str = (
        "https://web.archive.org/web/20250825095350/"
        "https://www.worldometers.info/coronavirus/"
    ),
) -> CovidData:
    xpath_str = '//div[@class = "maincounter-number"]/span/text()'
    try:
        response = httpx.get(url, timeout=10)
        response.raise_for_status()
    except httpx.TimeoutException:
        print(
            "Request timed out. Please check your network connection "
            "or try again later."
        )
        return CovidData("N/A", "N/A", "N/A")
    except httpx.HTTPStatusError as e:
        print(f"HTTP error occurred: {e}")
        return CovidData("N/A", "N/A", "N/A")
    data = html.fromstring(response.content).xpath(xpath_str)
    if len(data) != 3:
        print("Unexpected data format. The page structure may have changed.")
        return CovidData("N/A", "N/A", "N/A")
    return CovidData(*data)


if __name__ == "__main__":
    fmt = (
        "Total COVID-19 cases in the world: {}\n"
        "Total deaths due to COVID-19 in the world: {}\n"
        "Total COVID-19 patients recovered in the world: {}"
    )
    print(fmt.format(*covid_stats()))


Review comment (suggestion):
```suggestion
        response = httpx.get(url, timeout=10).raise_for_status()
```

Code after:
#     "lxml",
# ]
# ///

from typing import NamedTuple

import httpx
from lxml import html


class CovidData(NamedTuple):
    cases: str
    deaths: str
    recovered: str


def covid_stats(
    url: str = (
        "https://web.archive.org/web/20250825095350/"
        "https://www.worldometers.info/coronavirus/"
    ),
) -> CovidData:
    xpath_str = '//div[@class = "maincounter-number"]/span/text()'
    try:
        response = httpx.get(url, timeout=10).raise_for_status()
    except httpx.TimeoutException:
        print(
            "Request timed out. Please check your network connection "
            "or try again later."
        )
        return CovidData("N/A", "N/A", "N/A")
    except httpx.HTTPStatusError as e:
        print(f"HTTP error occurred: {e}")
        return CovidData("N/A", "N/A", "N/A")
    data = html.fromstring(response.content).xpath(xpath_str)
    if len(data) != 3:
        print("Unexpected data format. The page structure may have changed.")
        data = "N/A", "N/A", "N/A"
    return CovidData(*data)


if __name__ == "__main__":
    fmt = (
        "Total COVID-19 cases in the world: {}\n"
        "Total deaths due to COVID-19 in the world: {}\n"
        "Total COVID-19 patients recovered in the world: {}"
    )
    print(fmt.format(*covid_stats()))
Repository: TheAlgorithms/Python
File: web_programming/covid_stats_via_xpath.py (Python)

Code before:
    recovered: str


def covid_stats(
    url: str = (
        "https://web.archive.org/web/20250825095350/"
        "https://www.worldometers.info/coronavirus/"
    ),
) -> CovidData:
    xpath_str = '//div[@class = "maincounter-number"]/span/text()'
    try:
        response = httpx.get(url, timeout=10)
        response.raise_for_status()
    except httpx.TimeoutException:
        print(
            "Request timed out. Please check your network connection "
            "or try again later."
        )
        return CovidData("N/A", "N/A", "N/A")
    except httpx.HTTPStatusError as e:
        print(f"HTTP error occurred: {e}")
        return CovidData("N/A", "N/A", "N/A")
    data = html.fromstring(response.content).xpath(xpath_str)
    if len(data) != 3:
        print("Unexpected data format. The page structure may have changed.")
        return CovidData("N/A", "N/A", "N/A")
    return CovidData(*data)


if __name__ == "__main__":
    fmt = (
        "Total COVID-19 cases in the world: {}\n"
        "Total deaths due to COVID-19 in the world: {}\n"
        "Total COVID-19 patients recovered in the world: {}"
    )
    print(fmt.format(*covid_stats()))


Review comment (suggestion):
```suggestion
        data = "N/A", "N/A", "N/A"
```

Code after:
    recovered: str


def covid_stats(
    url: str = (
        "https://web.archive.org/web/20250825095350/"
        "https://www.worldometers.info/coronavirus/"
    ),
) -> CovidData:
    xpath_str = '//div[@class = "maincounter-number"]/span/text()'
    try:
        response = httpx.get(url, timeout=10).raise_for_status()
    except httpx.TimeoutException:
        print(
            "Request timed out. Please check your network connection "
            "or try again later."
        )
        return CovidData("N/A", "N/A", "N/A")
    except httpx.HTTPStatusError as e:
        print(f"HTTP error occurred: {e}")
        return CovidData("N/A", "N/A", "N/A")
    data = html.fromstring(response.content).xpath(xpath_str)
    if len(data) != 3:
        print("Unexpected data format. The page structure may have changed.")
        data = "N/A", "N/A", "N/A"
    return CovidData(*data)


if __name__ == "__main__":
    fmt = (
        "Total COVID-19 cases in the world: {}\n"
        "Total deaths due to COVID-19 in the world: {}\n"
        "Total COVID-19 patients recovered in the world: {}"
    )
    print(fmt.format(*covid_stats()))
Repository: TheAlgorithms/Python
File: machine_learning/t_stochastic_neighbour_embedding.py (Python)

Code before:
import doctest
import numpy as np
from numpy import ndarray
from sklearn.datasets import load_iris


def collect_dataset() -> tuple[ndarray, ndarray]:
    """
    Load the Iris dataset and return features and labels.

    Returns:
        tuple[ndarray, ndarray]: Feature matrix and target labels.

    Example:
        >>> features, targets = collect_dataset()
        >>> features.shape
        (150, 4)
        >>> targets.shape
        (150,)
    """
    iris_dataset = load_iris()
    return np.array(iris_dataset.data), np.array(iris_dataset.target)


def compute_pairwise_affinities(data_matrix: ndarray, sigma: float = 1.0) -> ndarray:
    """
    Compute high-dimensional affinities (P matrix) using a Gaussian kernel.

    Args:
        data_matrix: Input data of shape (n_samples, n_features).
        sigma: Gaussian kernel bandwidth.

    Returns:
        ndarray: Symmetrized probability matrix.

    Example:
        >>> x = np.array([[0.0, 0.0], [1.0, 0.0]])
        >>> probabilities = compute_pairwise_affinities(x)
        >>> float(round(probabilities[0, 1], 3))

Review comment (suggestion):
We don't need this line.
```suggestion
```
Repeat below.

Code after:
"""
t-distributed stochastic neighbor embedding (t-SNE)

For more details, see:
https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding
"""

import doctest

import numpy as np
from numpy import ndarray
from sklearn.datasets import load_iris


def collect_dataset() -> tuple[ndarray, ndarray]:
    """
    Load the Iris dataset and return features and labels.

    Returns:
        tuple[ndarray, ndarray]: Feature matrix and target labels.

    >>> features, targets = collect_dataset()
    >>> features.shape
    (150, 4)
    >>> targets.shape
    (150,)
    """
    iris_dataset = load_iris()
    return np.array(iris_dataset.data), np.array(iris_dataset.target)


def compute_pairwise_affinities(data_matrix: ndarray, sigma: float = 1.0) -> ndarray:
    """
    Compute high-dimensional affinities (P matrix) using a Gaussian kernel.

    Args:
        data_matrix: Input data of shape (n_samples, n_features).
        sigma: Gaussian kernel bandwidth.
Repository: TheAlgorithms/Python
File: machine_learning/t_stochastic_neighbour_embedding.py (Python)

Code before:
import doctest

import numpy as np
from numpy import ndarray
from sklearn.datasets import load_iris


def collect_dataset() -> tuple[ndarray, ndarray]:
    """
    Load the Iris dataset and return features and labels.

    Returns:
        tuple[ndarray, ndarray]: Feature matrix and target labels.

        >>> features, targets = collect_dataset()
        >>> features.shape
        (150, 4)
        >>> targets.shape
        (150,)
    """
    iris_dataset = load_iris()
    return np.array(iris_dataset.data), np.array(iris_dataset.target)


def compute_pairwise_affinities(data_matrix: ndarray, sigma: float = 1.0) -> ndarray:
    """
    Compute high-dimensional affinities (P matrix) using a Gaussian kernel.

    Args:
        data_matrix: Input data of shape (n_samples, n_features).
        sigma: Gaussian kernel bandwidth.

    Returns:
        ndarray: Symmetrized probability matrix.

    Example:
        >>> x = np.array([[0.0, 0.0], [1.0, 0.0]])
        >>> probabilities = compute_pairwise_affinities(x)
        >>> float(round(probabilities[0, 1], 3))
        0.25
    """
    n_samples = data_matrix.shape[0]
    squared_sum = np.sum(np.square(data_matrix), axis=1)
    squared_distance = np.add(

Review comment (suggestion):
```suggestion
    >>> features, targets = collect_dataset()
    >>> features.shape
    (150, 4)
    >>> targets.shape
    (150,)
```

Code after:
"""
t-distributed stochastic neighbor embedding (t-SNE)

For more details, see:
https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding
"""

import doctest

import numpy as np
from numpy import ndarray
from sklearn.datasets import load_iris


def collect_dataset() -> tuple[ndarray, ndarray]:
    """
    Load the Iris dataset and return features and labels.

    Returns:
        tuple[ndarray, ndarray]: Feature matrix and target labels.

    >>> features, targets = collect_dataset()
    >>> features.shape
    (150, 4)
    >>> targets.shape
    (150,)
    """
    iris_dataset = load_iris()
    return np.array(iris_dataset.data), np.array(iris_dataset.target)


def compute_pairwise_affinities(data_matrix: ndarray, sigma: float = 1.0) -> ndarray:
    """
    Compute high-dimensional affinities (P matrix) using a Gaussian kernel.

    Args:
        data_matrix: Input data of shape (n_samples, n_features).
        sigma: Gaussian kernel bandwidth.

    Returns:
        ndarray: Symmetrized probability matrix.

    >>> x = np.array([[0.0, 0.0], [1.0, 0.0]])
    >>> probabilities = compute_pairwise_affinities(x)
Repository: TheAlgorithms/Python
File: machine_learning/t_stochastic_neighbour_embedding.py (Python)

Code before:
"""
t-SNE (t-distributed Stochastic Neighbor Embedding) implementation.

For more details, see:
https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding
"""

import doctest

import numpy as np
from numpy import ndarray
from sklearn.datasets import load_iris


def collect_dataset() -> tuple[ndarray, ndarray]:
    """
    Load the Iris dataset and return features and labels.

    Returns:
        tuple[ndarray, ndarray]: Feature matrix and target labels.

    >>> features, targets = collect_dataset()
    >>> features.shape
    (150, 4)
    >>> targets.shape
    (150,)
    """

Review comment (suggestion):
```suggestion
t-distributed stochastic neighbor embedding (t-SNE)
```

Code after:
"""
t-distributed stochastic neighbor embedding (t-SNE)

For more details, see:
https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding
"""

import doctest

import numpy as np
from numpy import ndarray
from sklearn.datasets import load_iris


def collect_dataset() -> tuple[ndarray, ndarray]:
    """
    Load the Iris dataset and return features and labels.

    Returns:
        tuple[ndarray, ndarray]: Feature matrix and target labels.

    >>> features, targets = collect_dataset()
    >>> features.shape
    (150, 4)
    >>> targets.shape
    (150,)
    """
Repository: VinciGit00/Scrapegraph-ai
File: scrapegraphai/nodes/fetch_screen_node.py (Python)

Code before:
        screenshots = []

        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.goto(self.url)

            viewport_height = page.viewport_size["height"]

            screenshot_counter = 1

            screenshot_data_list = []

            def capture_screenshot(scroll_position, counter):
                page.evaluate(f"window.scrollTo(0, {scroll_position});")
                screenshot_data = page.screenshot()
                screenshot_data_list.append(screenshot_data)

            capture_screenshot(0, screenshot_counter)
            screenshot_counter += 1
            capture_screenshot(viewport_height, screenshot_counter)

            browser.close()

        for screenshot_data in screenshot_data_list:
            screenshots.append(screenshot_data)

        state["link"] = self.url
        state['screenshots'] = screenshots

        return state


Review comment (refactor):
why having duplicate data structures `screenshots` and `screenshot_data_list`?

keep only one of the two, and drop the other

Code after:
        self.logger.info(f"--- Executing {self.node_name} Node ---")

        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.goto(self.url)

            viewport_height = page.viewport_size["height"]

            screenshot_counter = 1

            screenshot_data_list = []

            def capture_screenshot(scroll_position, counter):
                page.evaluate(f"window.scrollTo(0, {scroll_position});")
                screenshot_data = page.screenshot()
                screenshot_data_list.append(screenshot_data)

            capture_screenshot(0, screenshot_counter)
            screenshot_counter += 1
            capture_screenshot(viewport_height, screenshot_counter)

            browser.close()

        state["link"] = self.url
        state['screenshots'] = screenshot_data_list

        return state