gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_provider_pool():
    """Returns the subliminal provider pool to be used

    :return: subliminal provider pool to be used
    :rtype: subliminal.ProviderPool
    """
    logger.debug("Creating a new ProviderPool instance")
    provider_configs = {
        "addic7ed": {
            "username": sickbeard.ADDIC7ED_USER,
            "password": sickbeard.ADDIC7ED_PASS,
        },
        "itasa": {"username": sickbeard.ITASA_USER, "password": sickbeard.ITASA_PASS},
        "legendastv": {
            "username": sickbeard.LEGENDASTV_USER,
            "password": sickbeard.LEGENDASTV_PASS,
        },
        "opensubtitles": {
            "username": sickbeard.OPENSUBTITLES_USER,
            "password": sickbeard.OPENSUBTITLES_PASS,
        },
    }
    return ProviderPool(
        providers=enabled_service_list(), provider_configs=provider_configs
    )


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def get_provider_pool():
    """Return the subliminal provider pool to be used.

    :return: subliminal provider pool to be used
    :rtype: subliminal.ProviderPool
    """
    logger.debug("Creating a new ProviderPool instance")
    provider_configs = {
        "addic7ed": {
            "username": sickbeard.ADDIC7ED_USER,
            "password": sickbeard.ADDIC7ED_PASS,
        },
        "itasa": {"username": sickbeard.ITASA_USER, "password": sickbeard.ITASA_PASS},
        "legendastv": {
            "username": sickbeard.LEGENDASTV_USER,
            "password": sickbeard.LEGENDASTV_PASS,
        },
        "opensubtitles": {
            "username": sickbeard.OPENSUBTITLES_USER,
            "password": sickbeard.OPENSUBTITLES_PASS,
        },
    }
    return ProviderPool(
        providers=enabled_service_list(), provider_configs=provider_configs
    )
# Buggy code
def compute_subtitle_path(subtitle, video_path, subtitles_dir):
    """Returns the full subtitle path that's computed by subliminal

    :param subtitle: the subtitle
    :type subtitle: subliminal.Subtitle
    :param video_path: the video path
    :type video_path: str
    :param subtitles_dir: the subtitles directory
    :type subtitles_dir: str
    :return: the computed subtitles path
    :rtype: str
    """
    subtitle_path = get_subtitle_path(
        video_path, subtitle.language if sickbeard.SUBTITLES_MULTI else None
    )
    return (
        os.path.join(subtitles_dir, os.path.split(subtitle_path)[1])
        if subtitles_dir
        else subtitle_path
    )


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def compute_subtitle_path(subtitle, video_path, subtitles_dir):
    """Return the full subtitle path that's computed by subliminal.

    :param subtitle: the subtitle
    :type subtitle: subliminal.Subtitle
    :param video_path: the video path
    :type video_path: str
    :param subtitles_dir: the subtitles directory
    :type subtitles_dir: str
    :return: the computed subtitles path
    :rtype: str
    """
    subtitle_path = get_subtitle_path(
        video_path, subtitle.language if sickbeard.SUBTITLES_MULTI else None
    )
    return (
        os.path.join(subtitles_dir, os.path.split(subtitle_path)[1])
        if subtitles_dir
        else subtitle_path
    )
# Buggy code
def merge_subtitles(existing_subtitles, new_subtitles):
    """Merges the existing and new subtitles to a single list

    Consolidates the existing_subtitles and the new_subtitles into a resulting list without repetitions. If
    SUBTITLES_MULTI is disabled and there's only one new subtitle, an `und` element is added to the returning list
    instead of using the new_subtitles.

    :param existing_subtitles: list: opensubtitles codes of the existing subtitles
    :type existing_subtitles: list of str
    :param new_subtitles: list: opensubtitles codes of the new subtitles
    :type new_subtitles: list of str
    :return: list of opensubtitles codes of the resulting subtitles
    :rtype: list of str
    """
    current_subtitles = (
        sorted({subtitle for subtitle in new_subtitles + existing_subtitles})
        if existing_subtitles
        else new_subtitles
    )

    if not sickbeard.SUBTITLES_MULTI and len(new_subtitles) == 1:
        current_subtitles.remove(new_subtitles[0])
        current_subtitles.append("und")

    return current_subtitles


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def merge_subtitles(existing_subtitles, new_subtitles):
    """Merge the existing and new subtitles to a single list.

    Consolidates the existing_subtitles and the new_subtitles into a resulting list without repetitions. If
    SUBTITLES_MULTI is disabled and there's only one new subtitle, an `und` element is added to the returning list
    instead of using the new_subtitles.

    :param existing_subtitles: list: opensubtitles codes of the existing subtitles
    :type existing_subtitles: list of str
    :param new_subtitles: list: opensubtitles codes of the new subtitles
    :type new_subtitles: list of str
    :return: list of opensubtitles codes of the resulting subtitles
    :rtype: list of str
    """
    current_subtitles = (
        sorted({subtitle for subtitle in new_subtitles + existing_subtitles})
        if existing_subtitles
        else new_subtitles
    )

    if not sickbeard.SUBTITLES_MULTI and len(new_subtitles) == 1:
        current_subtitles.remove(new_subtitles[0])
        current_subtitles.append("und")

    return current_subtitles
# Buggy code
def get_min_score():
    """Returns the min score to be used by subliminal

    Perfect match = hash - resolution (subtitle for 720p is the same as for 1080p) - video_codec - audio_codec
    Non-perfect match = series + year + season + episode

    :return: min score to be used to download subtitles
    :rtype: int
    """
    if sickbeard.SUBTITLES_PERFECT_MATCH:
        return episode_scores["hash"] - (
            episode_scores["resolution"]
            + episode_scores["video_codec"]
            + episode_scores["audio_codec"]
        )

    return (
        episode_scores["series"]
        + episode_scores["year"]
        + episode_scores["season"]
        + episode_scores["episode"]
    )


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def get_min_score():
    """Return the min score to be used by subliminal.

    Perfect match = hash - resolution (subtitle for 720p is the same as for 1080p) - video_codec - audio_codec
    Non-perfect match = series + year + season + episode

    :return: min score to be used to download subtitles
    :rtype: int
    """
    if sickbeard.SUBTITLES_PERFECT_MATCH:
        return episode_scores["hash"] - (
            episode_scores["resolution"]
            + episode_scores["video_codec"]
            + episode_scores["audio_codec"]
        )

    return (
        episode_scores["series"]
        + episode_scores["year"]
        + episode_scores["season"]
        + episode_scores["episode"]
    )
# Buggy code
def get_current_subtitles(video_path):
    """Returns a list of current subtitles for the episode.

    :param video_path: the video path
    :type video_path: str
    :return: the current subtitles (3-letter opensubtitles codes) for the specified video
    :rtype: list of str
    """
    # invalidate the cached video entry for the given path
    invalidate_video_cache(video_path)

    # get the latest video information
    video = get_video(video_path)
    if not video:
        logger.info(
            "Exception caught in subliminal.scan_video, subtitles couldn't be refreshed for %s",
            video_path,
        )
    else:
        return get_subtitles(video)


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def get_current_subtitles(video_path):
    """Return a list of current subtitles for the episode.

    :param video_path: the video path
    :type video_path: str
    :return: the current subtitles (3-letter opensubtitles codes) for the specified video
    :rtype: list of str
    """
    # invalidate the cached video entry for the given path
    invalidate_video_cache(video_path)

    # get the latest video information
    video = get_video(video_path)
    if not video:
        logger.info(
            "Exception caught in subliminal.scan_video, subtitles couldn't be refreshed for %s",
            video_path,
        )
    else:
        return get_subtitles(video)
# Buggy code
def get_subtitle_description(subtitle):
    """Returns a human readable name/description for the given subtitle (if possible)

    :param subtitle: the given subtitle
    :type subtitle: subliminal.Subtitle
    :return: name/description
    :rtype: str
    """
    desc = None
    sub_id = str(subtitle.id)
    if hasattr(subtitle, "filename") and subtitle.filename:
        desc = subtitle.filename.lower()
    elif hasattr(subtitle, "name") and subtitle.name:
        desc = subtitle.name.lower()
    if hasattr(subtitle, "release") and subtitle.release:
        desc = subtitle.release.lower()
    if hasattr(subtitle, "releases") and subtitle.releases:
        desc = str(subtitle.releases).lower()

    if not desc:
        desc = sub_id

    return sub_id + "-" + desc if desc not in sub_id else desc


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def get_subtitle_description(subtitle):
    """Return a human readable name/description for the given subtitle (if possible).

    :param subtitle: the given subtitle
    :type subtitle: subliminal.Subtitle
    :return: name/description
    :rtype: str
    """
    desc = None
    sub_id = unicode(subtitle.id)
    if hasattr(subtitle, "filename") and subtitle.filename:
        desc = subtitle.filename.lower()
    elif hasattr(subtitle, "name") and subtitle.name:
        desc = subtitle.name.lower()
    if hasattr(subtitle, "release") and subtitle.release:
        desc = subtitle.release.lower()
    if hasattr(subtitle, "releases") and subtitle.releases:
        desc = unicode(subtitle.releases).lower()

    if not desc:
        desc = sub_id

    return sub_id + "-" + desc if desc not in sub_id else desc
# Buggy code
def invalidate_video_cache(video_path):
    """Invalidates the cached subliminal.video.Video for the specified path

    :param video_path: the video path
    :type video_path: str
    """
    key = video_key.format(video_path=video_path)
    region.delete(key)
    logger.debug("Cached video information under key %s was invalidated", key)


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def invalidate_video_cache(video_path):
    """Invalidate the cached subliminal.video.Video for the specified path.

    :param video_path: the video path
    :type video_path: str
    """
    key = video_key.format(video_path=video_path)
    region.delete(key)
    logger.debug("Cached video information under key %s was invalidated", key)
# Buggy code
def get_subtitles_dir(video_path):
    """Returns the correct subtitles directory based on the user configuration.

    If the directory doesn't exist, it will be created

    :param video_path: the video path
    :type video_path: str
    :return: the subtitles directory
    :rtype: str
    """
    if not sickbeard.SUBTITLES_DIR:
        return os.path.dirname(video_path)

    if os.path.isabs(sickbeard.SUBTITLES_DIR):
        return sickbeard.SUBTITLES_DIR

    new_subtitles_path = os.path.join(
        os.path.dirname(video_path), sickbeard.SUBTITLES_DIR
    )
    if sickbeard.helpers.makeDir(new_subtitles_path):
        sickbeard.helpers.chmodAsParent(new_subtitles_path)
    else:
        logger.warning("Unable to create subtitles folder %s", new_subtitles_path)

    return new_subtitles_path


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def get_subtitles_dir(video_path):
    """Return the correct subtitles directory based on the user configuration.

    If the directory doesn't exist, it will be created

    :param video_path: the video path
    :type video_path: str
    :return: the subtitles directory
    :rtype: str
    """
    if not sickbeard.SUBTITLES_DIR:
        return os.path.dirname(video_path)

    if os.path.isabs(sickbeard.SUBTITLES_DIR):
        return _decode(sickbeard.SUBTITLES_DIR)

    new_subtitles_path = os.path.join(
        os.path.dirname(video_path), sickbeard.SUBTITLES_DIR
    )
    if sickbeard.helpers.makeDir(new_subtitles_path):
        sickbeard.helpers.chmodAsParent(new_subtitles_path)
    else:
        logger.warning("Unable to create subtitles folder %s", new_subtitles_path)

    return new_subtitles_path
# Buggy code
def get_subtitles(video):
    """Returns a sorted list of detected subtitles for the given video file.

    :param video: the video to be inspected
    :type video: subliminal.video.Video
    :return: sorted list of opensubtitles code for the given video
    :rtype: list of str
    """
    result_list = [
        l.opensubtitles
        for l in video.subtitle_languages
        if hasattr(l, "opensubtitles") and l.opensubtitles
    ]
    return sorted(result_list)


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def get_subtitles(video):
    """Return a sorted list of detected subtitles for the given video file.

    :param video: the video to be inspected
    :type video: subliminal.video.Video
    :return: sorted list of opensubtitles code for the given video
    :rtype: list of str
    """
    result_list = [
        l.opensubtitles
        for l in video.subtitle_languages
        if hasattr(l, "opensubtitles") and l.opensubtitles
    ]
    return sorted(result_list)
# Buggy code
def unpack_rar_files(dirpath):
    """Unpacks any existing rar files present in the specified dirpath

    :param dirpath: the directory path to be used
    :type dirpath: str
    """
    for root, _, files in os.walk(dirpath, topdown=False):
        rar_files = [rar_file for rar_file in files if isRarFile(rar_file)]
        if rar_files and sickbeard.UNPACK:
            video_files = [
                video_file for video_file in files if isMediaFile(video_file)
            ]
            if "_UNPACK" not in root and (
                not video_files or root == sickbeard.TV_DOWNLOAD_DIR
            ):
                logger.debug("Found rar files in post-process folder: %s", rar_files)
                result = processTV.ProcessResult()
                processTV.unRAR(root, rar_files, False, result)
        elif rar_files and not sickbeard.UNPACK:
            logger.warning("Unpack is disabled. Skipping: %s", rar_files)


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def unpack_rar_files(dirpath):
    """Unpack any existing rar files present in the specified dirpath.

    :param dirpath: the directory path to be used
    :type dirpath: str
    """
    for root, _, files in os.walk(dirpath, topdown=False):
        rar_files = [rar_file for rar_file in files if isRarFile(rar_file)]
        if rar_files and sickbeard.UNPACK:
            video_files = [
                video_file for video_file in files if isMediaFile(video_file)
            ]
            if "_UNPACK" not in root and (
                not video_files or root == sickbeard.TV_DOWNLOAD_DIR
            ):
                logger.debug("Found rar files in post-process folder: %s", rar_files)
                result = processTV.ProcessResult()
                processTV.unRAR(root, rar_files, False, result)
        elif rar_files and not sickbeard.UNPACK:
            logger.warning("Unpack is disabled. Skipping: %s", rar_files)
# Buggy code
def clear_non_release_groups(filepath):
    """Removes non release groups from the name of the given file path.

    It also renames/moves the file to the path

    :param filepath: the file path
    :type filepath: str
    :return: the new file path
    :rtype: str
    """
    try:
        # Remove non release groups from video file. Needed to match subtitles
        new_filepath = remove_non_release_groups(filepath)
        if new_filepath != filepath:
            os.rename(filepath, new_filepath)
            filepath = new_filepath
    except Exception as error:
        logger.debug(
            "Couldn't remove non release groups from video file. Error: %s", ex(error)
        )

    return filepath


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def clear_non_release_groups(filepath):
    """Remove non release groups from the name of the given file path.

    It also renames/moves the file to the path

    :param filepath: the file path
    :type filepath: str
    :return: the new file path
    :rtype: str
    """
    try:
        # Remove non release groups from video file. Needed to match subtitles
        new_filepath = remove_non_release_groups(filepath)
        if new_filepath != filepath:
            os.rename(filepath, new_filepath)
            filepath = new_filepath
    except Exception as error:
        logger.debug(
            "Couldn't remove non release groups from video file. Error: %s", ex(error)
        )

    return filepath
# Buggy code
def run_subs_pre_scripts(video_path):
    """Executes the subtitles pre-scripts for the given video path

    :param video_path: the video path
    :type video_path: str
    """
    run_subs_scripts(video_path, sickbeard.SUBTITLES_PRE_SCRIPTS, [video_path])


# Traceback (UnicodeEncodeError)
FINDSUBTITLES :: [d47493d] Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/subtitles.py", line 338, in download_best_subs
save_subtitles(video, found_subtitles, directory=subtitles_dir, single=not sickbeard.SUBTITLES_MULTI)
File "/home/home/SickRage/lib/subliminal/core.py", line 695, in save_subtitles
with io.open(subtitle_path, 'wb') as f:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xea' in position 93: ordinal not in range(128)

# Fixed code
def run_subs_pre_scripts(video_path):
    """Execute the subtitles pre-scripts for the given video path.

    :param video_path: the video path
    :type video_path: str
    """
    run_subs_scripts(video_path, sickbeard.SUBTITLES_PRE_SCRIPTS, [video_path])
# Buggy code
def __str__(self):
    """String representation.

    :return:
    :rtype: str
    """
    return str(self.fmt).format(*self.args, **self.kwargs)


# Traceback (KeyError)
FINDSUBTITLES :: [8ae9bc7] Unable to find subtitles for Mr. Robot S02E02. Error: 'type'
Traceback (most recent call last):
File "/volume1/@appstore/sickbeard-custom/var/SickBeard/sickbeard/subtitles.py", line 870, in run
episode_object.download_subtitles()
File "/volume1/@appstore/sickbeard-custom/var/SickBeard/sickbeard/tv.py", line 1759, in download_subtitles
new_subtitles = subtitles.download_subtitles(self)
File "/volume1/@appstore/sickbeard-custom/var/SickBeard/sickbeard/subtitles.py", line 327, in download_subtitles
logger.error(traceback.format_exc())
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 1456, in error
self.logger.error(msg, *args, **kwargs)
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 1185, in error
self._log(ERROR, msg, args, **kwargs)
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 1278, in _log
self.handle(record)
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 1288, in handle
self.callHandlers(record)
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 1328, in callHandlers
hdlr.handle(record)
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 751, in handle
self.emit(record)
File "/volume1/@appstore/sickbeard-custom/var/SickBeard/sickbeard/logger.py", line 135, in emit
message = self.format(record)
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 726, in format
return fmt.format(record)
File "/volume1/@appstore/sickbeard-custom/var/SickBeard/sickbeard/logger.py", line 169, in format
msg = super(CensoredFormatter, self).format(record)
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 465, in format
record.message = record.getMessage()
File "/usr/local/python/lib/python2.7/logging/__init__.py", line 325, in getMessage
msg = str(self.msg)
File "/volume1/@appstore/sickbeard-custom/var/SickBeard/sickbeard/logger.py", line 560, in __str__
return str(self.fmt).format(*self.args, **self.kwargs)
KeyError: "'type'"

# Fixed code
def __str__(self):
    """String representation.

    :return:
    :rtype: str
    """
    result = str(self.fmt)
    return (
        result.format(*self.args, **self.kwargs) if self.args or self.kwargs else result
    )
# Buggy code
def canAddTorrentRssProvider(name, url, cookies, titleTAG):
    """
    See if a Torrent provider can be added
    """
    if not name:
        return json.dumps({"error": "Invalid name specified"})

    provider_dict = dict(
        zip(
            [x.get_id() for x in sickbeard.torrentRssProviderList],
            sickbeard.torrentRssProviderList,
        )
    )

    temp_provider = TorrentRSSProvider(name, url, cookies, titleTAG)

    if temp_provider.get_id() in provider_dict:
        return json.dumps(
            {
                "error": "Exists as {name}".format(
                    name=provider_dict[temp_provider.get_id()].name
                )
            }
        )
    else:
        validate = temp_provider.validate_rss()
        if validate["result"]:
            return json.dumps({"success": temp_provider.get_id()})
        else:
            return json.dumps({"error": validate["message"]})


# Traceback (NameError)
Thread-25 :: [626c429] Failed doing web ui callback: Traceback (most recent call last):
File "C:\Users\rusty\Desktop\pymedusaSickRage\sickbeard\server\web\core\base.py", line 268, in async_call
result = function(**kwargs)
File "C:\Users\rusty\Desktop\pymedusaSickRage\sickbeard\server\web\config\providers.py", line 295, in saveProviders
new_provider = TorrentRSSProvider(cur_name, cur_url, cur_cookies, cur_title_tag)
NameError: global name 'TorrentRSSProvider' is not defined
Traceback (most recent call last):
File "C:\Users\rusty\Desktop\pymedusaSickRage\sickbeard\server\web\core\base.py", line 268, in async_call
result = function(**kwargs)
File "C:\Users\rusty\Desktop\pymedusaSickRage\sickbeard\server\web\config\providers.py", line 295, in saveProviders
new_provider = TorrentRSSProvider(cur_name, cur_url, cur_cookies, cur_title_tag)
NameError: global name 'TorrentRSSProvider' is not defined

# Fixed code
def canAddTorrentRssProvider(name, url, cookies, titleTAG):
    """
    See if a Torrent provider can be added
    """
    if not name:
        return json.dumps({"error": "Invalid name specified"})

    provider_dict = dict(
        zip(
            [x.get_id() for x in sickbeard.torrentRssProviderList],
            sickbeard.torrentRssProviderList,
        )
    )

    temp_provider = TorrentRssProvider(name, url, cookies, titleTAG)

    if temp_provider.get_id() in provider_dict:
        return json.dumps(
            {
                "error": "Exists as {name}".format(
                    name=provider_dict[temp_provider.get_id()].name
                )
            }
        )
    else:
        validate = temp_provider.validate_rss()
        if validate["result"]:
            return json.dumps({"success": temp_provider.get_id()})
        else:
            return json.dumps({"error": validate["message"]})
# Buggy code
def saveTorrentRssProvider(name, url, cookies, titleTAG):
    """
    Save a Torrent Provider
    """

    if not name or not url:
        return "0"

    provider_dict = dict(
        zip(
            [x.name for x in sickbeard.torrentRssProviderList],
            sickbeard.torrentRssProviderList,
        )
    )

    if name in provider_dict:
        provider_dict[name].name = name
        provider_dict[name].url = config.clean_url(url)
        provider_dict[name].cookies = cookies
        provider_dict[name].titleTAG = titleTAG

        return "|".join(
            [provider_dict[name].get_id(), provider_dict[name].config_string()]
        )

    else:
        new_provider = TorrentRSSProvider(name, url, cookies, titleTAG)
        sickbeard.torrentRssProviderList.append(new_provider)
        return "|".join([new_provider.get_id(), new_provider.config_string()])


# Traceback (NameError)
Thread-25 :: [626c429] Failed doing web ui callback: Traceback (most recent call last):
File "C:\Users\rusty\Desktop\pymedusaSickRage\sickbeard\server\web\core\base.py", line 268, in async_call
result = function(**kwargs)
File "C:\Users\rusty\Desktop\pymedusaSickRage\sickbeard\server\web\config\providers.py", line 295, in saveProviders
new_provider = TorrentRSSProvider(cur_name, cur_url, cur_cookies, cur_title_tag)
NameError: global name 'TorrentRSSProvider' is not defined
Traceback (most recent call last):
File "C:\Users\rusty\Desktop\pymedusaSickRage\sickbeard\server\web\core\base.py", line 268, in async_call
result = function(**kwargs)
File "C:\Users\rusty\Desktop\pymedusaSickRage\sickbeard\server\web\config\providers.py", line 295, in saveProviders
new_provider = TorrentRSSProvider(cur_name, cur_url, cur_cookies, cur_title_tag)
NameError: global name 'TorrentRSSProvider' is not defined

# Fixed code
def saveTorrentRssProvider(name, url, cookies, titleTAG):
    """
    Save a Torrent Provider
    """

    if not name or not url:
        return "0"

    provider_dict = dict(
        zip(
            [x.name for x in sickbeard.torrentRssProviderList],
            sickbeard.torrentRssProviderList,
        )
    )

    if name in provider_dict:
        provider_dict[name].name = name
        provider_dict[name].url = config.clean_url(url)
        provider_dict[name].cookies = cookies
        provider_dict[name].titleTAG = titleTAG

        return "|".join(
            [provider_dict[name].get_id(), provider_dict[name].config_string()]
        )

    else:
        new_provider = TorrentRssProvider(name, url, cookies, titleTAG)
        sickbeard.torrentRssProviderList.append(new_provider)
        return "|".join([new_provider.get_id(), new_provider.config_string()])
# Buggy code
def __init__(self):
    # Provider Init
    TorrentProvider.__init__(self, "Speedcd")

    # Credentials
    self.username = None
    self.password = None

    # Torrent Stats
    self.minseed = None
    self.minleech = None
    self.freeleech = False

    # URLs
    self.url = "https://speed.cd"
    self.urls = {
        "login": urljoin(self.url, "take.login.php"),
        "search": urljoin(self.url, "browse.php"),
    }

    # Proper Strings
    self.proper_strings = ["PROPER", "REPACK"]

    # Cache
    self.cache = tvcache.TVCache(self)


# Traceback (AttributeError)
SEARCHQUEUE-MANUAL-311937 :: [Speedcd] :: [3351698] Unknown exception while searching Speedcd. Error: "'NoneType' object has no attribute 'find'"
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/search.py", line 547, in searchProviders
forced_search, downCurQuality, manual_search, manual_search_type)
File "/home/home/SickRage/sickrage/providers/GenericProvider.py", line 149, in find_search_results
items_list += self.search(search_string, ep_obj=episode)
File "/home/home/SickRage/sickbeard/providers/speedcd.py", line 133, in search
torrent_table = html.find('div', class_='boxContent').find('table')
AttributeError: 'NoneType' object has no attribute 'find'

# Fixed code
def __init__(self):
    # Provider Init
    TorrentProvider.__init__(self, "Speedcd")

    # Credentials
    self.username = None
    self.password = None

    # Torrent Stats
    self.minseed = None
    self.minleech = None
    self.freeleech = False

    # URLs
    self.url = "https://speed.cd"
    self.urls = {
        "login": urljoin(self.url, "takelogin.php"),
        "search": urljoin(self.url, "browse.php"),
    }

    # Proper Strings
    self.proper_strings = ["PROPER", "REPACK"]

    # Cache
    self.cache = tvcache.TVCache(self)
# Buggy code
def run_subs_pre_scripts(video_path):
    """Execute the subtitles pre-scripts for the given video path.

    :param video_path: the video path
    :type video_path: str
    """
    run_subs_scripts(video_path, sickbeard.SUBTITLES_PRE_SCRIPTS, [video_path])


# Traceback (IndexError)
2016-05-14 15:28:51 INFO     FINDSUBTITLES :: [24ddc49] Running subtitle pre-script: /usr/bin/python /scripts/library-scripts/sickrage/cleanit.py
2016-05-14 15:28:51 INFO     FINDSUBTITLES :: [24ddc49] Executing command: ['/usr/bin/python', '/scripts/library-scripts/sickrage/cleanit.py', "[u'/library/series/The 100/Season 03/The 100 - S03E15 - Perverse Instantiation Part One.mkv', u'/library/series/The 100/Season 03/The 100 - S03E15 - Perverse Instantiation Part One.pt-BR.srt', u'pob', u'The 100', 3, 15, u'Perverse Instantiation (1)', 268592]"]
2016-05-14 15:28:52 DEBUG    FINDSUBTITLES :: [24ddc49] Script result: Traceback (most recent call last):
File "/scripts/library-scripts/sickrage/cleanit.py", line 21, in <module>
subtitle_path = sys.argv[2]
IndexError: list index out of range

# Fixed code
def run_subs_pre_scripts(video_path):
    """Execute the subtitles pre-scripts for the given video path.

    :param video_path: the video path
    :type video_path: str
    """
    run_subs_scripts(video_path, sickbeard.SUBTITLES_PRE_SCRIPTS, video_path)
# Buggy code
def run_subs_extra_scripts(
    video_path,
    subtitle_path,
    subtitle_language,
    show_name,
    season,
    episode,
    episode_name,
    show_indexerid,
):
    """Execute the subtitles extra-scripts for the given video path.

    :param video_path: the video path
    :type video_path: str
    :param subtitle_path: the downloaded subtitle path
    :type subtitle_path: str
    :param subtitle_language: the subtitle language
    :type subtitle_language: babelfish.Language
    :param show_name: the show name
    :type show_name: str
    :param season: the episode season number
    :type season: int
    :param episode: the episode number
    :type episode: int
    :param episode_name: the episode name
    :type episode_name: str
    :param show_indexerid: the show indexer id
    :type show_indexerid: int
    """
    run_subs_scripts(
        video_path,
        sickbeard.SUBTITLES_EXTRA_SCRIPTS,
        [
            video_path,
            subtitle_path,
            subtitle_language.opensubtitles,
            show_name,
            season,
            episode,
            episode_name,
            show_indexerid,
        ],
    )


# Traceback (IndexError)
2016-05-14 15:28:51 INFO     FINDSUBTITLES :: [24ddc49] Running subtitle pre-script: /usr/bin/python /scripts/library-scripts/sickrage/cleanit.py
2016-05-14 15:28:51 INFO     FINDSUBTITLES :: [24ddc49] Executing command: ['/usr/bin/python', '/scripts/library-scripts/sickrage/cleanit.py', "[u'/library/series/The 100/Season 03/The 100 - S03E15 - Perverse Instantiation Part One.mkv', u'/library/series/The 100/Season 03/The 100 - S03E15 - Perverse Instantiation Part One.pt-BR.srt', u'pob', u'The 100', 3, 15, u'Perverse Instantiation (1)', 268592]"]
2016-05-14 15:28:52 DEBUG    FINDSUBTITLES :: [24ddc49] Script result: Traceback (most recent call last):
File "/scripts/library-scripts/sickrage/cleanit.py", line 21, in <module>
subtitle_path = sys.argv[2]
IndexError: list index out of range

# Fixed code
def run_subs_extra_scripts(
    video_path,
    subtitle_path,
    subtitle_language,
    show_name,
    season,
    episode,
    episode_name,
    show_indexerid,
):
    """Execute the subtitles extra-scripts for the given video path.

    :param video_path: the video path
    :type video_path: str
    :param subtitle_path: the downloaded subtitle path
    :type subtitle_path: str
    :param subtitle_language: the subtitle language
    :type subtitle_language: babelfish.Language
    :param show_name: the show name
    :type show_name: str
    :param season: the episode season number
    :type season: int
    :param episode: the episode number
    :type episode: int
    :param episode_name: the episode name
    :type episode_name: str
    :param show_indexerid: the show indexer id
    :type show_indexerid: int
    """
    run_subs_scripts(
        video_path,
        sickbeard.SUBTITLES_EXTRA_SCRIPTS,
        video_path,
        subtitle_path,
        subtitle_language.opensubtitles,
        show_name,
        season,
        episode,
        episode_name,
        show_indexerid,
    )
# Buggy code
def _init(self):
    self.extractors = [
        Extractor(
            label=self.label,
            path="//div[@id='main']//table//tr",
            attrs=Attribute(
                key=None,
                multi=True,
                path={
                    self.ranktext: "./td[1]//text()",
                    "rating": "./td[2]//text()",
                    "title": "./td[3]//text()",
                    "movieID": "./td[3]//a/@href",
                    "votes": "./td[4]//text()",
                },
            ),
        )
    ]


# Traceback (KeyError)
EVENT-QUEUE :: [316d27c] Exception generated in thread EVENT-QUEUE: year
Traceback (most recent call last):
File "/usr/local/Sickrage/sickbeard/event_queue.py", line 45, in run
self.callback(event_type)
File "/usr/local/Sickrage/SickBeard.py", line 519, in shutdown
sickbeard.saveAll()  # save all shows to DB
File "/usr/local/Sickrage/sickbeard/__init__.py", line 1655, in saveAll
show.saveToDB()
File "/usr/local/Sickrage/sickbeard/tv.py", line 1171, in saveToDB
if self.imdbid and self.imdb_info['year']:
KeyError: 'year'

# Fixed code
def _init(self):
    self.extractors = [
        Extractor(
            label=self.label,
            path="//div[@id='main']//div[1]//div//table//tbody//tr",
            attrs=Attribute(
                key=None,
                multi=True,
                path={
                    self.ranktext: "./td[2]//text()",
                    "rating": "./td[3]//strong//text()",
                    "title": "./td[2]//a//text()",
                    "year": "./td[2]//span//text()",
                    "movieID": "./td[2]//a/@href",
                    "votes": "./td[3]//strong/@title",
                },
            ),
        )
    ]
# Buggy code
def postprocess_data(self, data):
    if not data or self.label not in data:
        return []
    mlist = []
    data = data[self.label]
    # Avoid duplicates.  A real fix, using XPath, is auspicabile.
    # XXX: probably this is no more needed.
    seenIDs = []
    for d in data:
        if "movieID" not in d:
            continue
        if self.ranktext not in d:
            continue
        if "title" not in d:
            continue
        theID = analyze_imdbid(d["movieID"])
        if theID is None:
            continue
        theID = str(theID)
        if theID in seenIDs:
            continue
        seenIDs.append(theID)
        minfo = analyze_title(d["title"])
        try:
            minfo[self.ranktext] = int(d[self.ranktext].replace(".", ""))
        except:
            pass
        if "votes" in d:
            try:
                minfo["votes"] = int(d["votes"].replace(",", ""))
            except:
                pass
        if "rating" in d:
            try:
                minfo["rating"] = float(d["rating"])
            except:
                pass
        mlist.append((theID, minfo))
    return mlist


# Traceback (KeyError)
EVENT-QUEUE :: [316d27c] Exception generated in thread EVENT-QUEUE: year
Traceback (most recent call last):
File "/usr/local/Sickrage/sickbeard/event_queue.py", line 45, in run
self.callback(event_type)
File "/usr/local/Sickrage/SickBeard.py", line 519, in shutdown
sickbeard.saveAll()  # save all shows to DB
File "/usr/local/Sickrage/sickbeard/__init__.py", line 1655, in saveAll
show.saveToDB()
File "/usr/local/Sickrage/sickbeard/tv.py", line 1171, in saveToDB
if self.imdbid and self.imdb_info['year']:
KeyError: 'year'

# Fixed code
def postprocess_data(self, data):
    if not data or self.label not in data:
        return []
    mlist = []
    data = data[self.label]
    # Avoid duplicates.  A real fix, using XPath, is auspicabile.
    # XXX: probably this is no more needed.
    seenIDs = []
    for d in data:
        if "movieID" not in d:
            continue
        if self.ranktext not in d:
            continue
        if "title" not in d:
            continue
        theID = analyze_imdbid(d["movieID"])
        if theID is None:
            continue
        theID = str(theID)
        if theID in seenIDs:
            continue
        seenIDs.append(theID)
        minfo = analyze_title(d["title"] + " " + d["year"])
        try:
            minfo[self.ranktext] = int(d[self.ranktext].replace(".", ""))
        except:
            pass
        if "votes" in d:
            try:
                votes = d["votes"].replace(" votes", "")
                votes = votes.split(" based on ")[1]
                minfo["votes"] = int(votes.replace(",", ""))
            except:
                pass
        if "rating" in d:
            try:
                minfo["rating"] = float(d["rating"])
            except:
                pass
        mlist.append((theID, minfo))
    return mlist
# Buggy code
def from_code(code, unknown="und"):
    """Converts an opensubtitles language code to a proper babelfish.Language object

    :param code: an opensubtitles language code to be converted
    :type code: str
    :param unknown: the code to be returned for unknown language codes
    :type unknown: str
    :return: babelfish.Language
    """
    code = code.strip()
    if code and code in language_converters["opensubtitles"].codes:
        return Language.fromopensubtitles(code)  # pylint: disable=no-member

    return Language(unknown) if unknown else None


# Traceback (TypeError)
2016-04-05 12:05:53 FINDSUBTITLES :: [a90e41d] Traceback (most recent call last):
File "/home/dariox/.sickrage/sickbeard/subtitles.py", line 325, in download_best_subs
get_subtitle_description(subtitle)), logger.DEBUG)
File "/home/dariox/.sickrage/sickbeard/subtitles.py", line 489, in get_subtitle_description
return subtitle.id + '-' + desc if desc not in subtitle.id else desc
TypeError: argument of type 'int' is not iterable

# Fixed code
def from_code(code, unknown="und"):
    """Converts an opensubtitles language code to a proper babelfish.Language object

    :param code: an opensubtitles language code to be converted
    :type code: str
    :param unknown: the code to be returned for unknown language codes
    :type unknown: str
    :return: a language object
    :rtype: babelfish.Language
    """
    code = code.strip()
    if code and code in language_converters["opensubtitles"].codes:
        return Language.fromopensubtitles(code)  # pylint: disable=no-member

    return Language(unknown) if unknown else None