gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _get_rel_path(self):
    """Return the relative path to the file if possible, else the parent dir.

    :return: relative path to file or parent dir to file
    :rtype: text_type
    """
    if app.TV_DOWNLOAD_DIR:
        rel_path = os.path.relpath(self.file_path, app.TV_DOWNLOAD_DIR)
        # check if we really found the relative path
        if not rel_path.startswith(".."):
            return rel_path

    parent_name = os.path.basename(os.path.dirname(self.file_path))
    # return self.file_path once this bug is fixed: goo.gl/U4XNoP
    return os.path.join(parent_name, self.file_name)


# Traceback (ValueError)
2016-11-16 09:38:36 DEBUG    Thread-33 :: [32ca6ae] 314334: Renaming/moving episode from the base path F:\TV\SHOWS\Chappelle's Show\Season 03\Chappelle's.Show.dvdrip.S03E03.mkv to F:\TV\SHOWS\Chappelle's Show\Season 03\Chappelle's Show - S03E03 - Los
t Episode 3 (SD.DVD)
2016-11-16 09:38:36 ERROR    Thread-33 :: [32ca6ae] Exception generated: path is on drive F:, start on drive D:
Traceback (most recent call last):
File "C:\SickRageMedusa\**********\server\web\core\base.py", line 271, in async_call
result = function(**kwargs)
File "C:\SickRageMedusa\**********\server\web\home\handler.py", line 1891, in doRename
root_ep_obj.rename()
File "C:\SickRageMedusa\**********\tv.py", line 3191, in rename
related_files = post_processor.PostProcessor(self.location).list_associated_files(
File "C:\SickRageMedusa\**********\post_processor.py", line 69, in __init__
self.rel_path = self._get_rel_path()
File "C:\SickRageMedusa\**********\post_processor.py", line 109, in _get_rel_path
rel_path = os.path.relpath(self.file_path, app.TV_DOWNLOAD_DIR)
File "C:\SickRageMedusa\**********\init\filesystem.py", line 85, in <lambda>
return lambda *args, **kwargs: handle_output(f(*[handle_arg(arg) for arg in args], **{k: handle_arg(arg) for k, arg in kwargs.items()}))
File "C:\Python27\lib\ntpath.py", line 529, in relpath
% (path_prefix, start_prefix))
ValueError: path is on drive F:, start on drive D:

# Fixed code
def _get_rel_path(self):
    """Return the relative path to the file if possible, else the parent dir.

    :return: relative path to file or parent dir to file
    :rtype: text_type
    """
    if app.TV_DOWNLOAD_DIR:
        try:
            rel_path = os.path.relpath(self.file_path, app.TV_DOWNLOAD_DIR)
            # check if we really found the relative path
            if not rel_path.startswith(".."):
                return rel_path
        except ValueError:
            pass

    self._log(
        "Couldn't get the relative path, using the parent folder instead", logger.DEBUG
    )
    parent_name = os.path.basename(os.path.dirname(self.file_path))
    # return self.file_path once this bug is fixed: goo.gl/U4XNoP
    return os.path.join(parent_name, self.file_name)
# Buggy code
def _varargs(*args):
    """Encode var arguments to utf-8."""
    return [_handle_input(arg) for arg in args]


# Traceback (TypeError)
2016-11-01 03:00:02 ERROR    SHOWUPDATER :: [e372494] Exception generated in thread SHOWUPDATER: cafile must be None or a byte string
Traceback (most recent call last):
File "/media/sdq1/home/**********/.sickrage/medusa/scheduler.py", line 103, in run
self.action.run(self.force)
File "/media/sdq1/home/**********/.sickrage/medusa/show_updater.py", line 68, in run
t = app.indexerApi(indexer).indexer(**indexer_api_params)
File "/media/sdq1/home/**********/.sickrage/medusa/indexers/indexer_api.py", line 34, in indexer
return indexerConfig[self.indexer_id]['module'](*args, **kwargs)
File "/media/sdq1/home/**********/.sickrage/medusa/indexers/tvdbv2/tvdbv2_api.py", line 66, in __init__
access_token = auth_api.login_post(authentication_string)
File "/media/sdq1/home/**********/.sickrage/lib/tvdbapiv2/apis/authentication_api.py", line 124, in login_post
callback=params.get('callback'))
File "/media/sdq1/home/**********/.sickrage/lib/tvdbapiv2/api_client.py", line 324, in call_api
response_type, auth_settings, callback)
File "/media/sdq1/home/**********/.sickrage/lib/tvdbapiv2/api_client.py", line 150, in __call_api
post_params=post_params, body=body)
File "/media/sdq1/home/**********/.sickrage/lib/tvdbapiv2/api_client.py", line 360, in request
body=body)
File "/media/sdq1/home/**********/.sickrage/lib/tvdbapiv2/rest.py", line 208, in POST
body=body)
File "/media/sdq1/home/**********/.sickrage/lib/tvdbapiv2/rest.py", line 143, in request
headers=headers)
File "/media/sdq1/home/**********/.sickrage/lib/requests/packages/urllib3/request.py", line 73, in request
**urlopen_kw)
File "/media/sdq1/home/**********/.sickrage/lib/requests/packages/urllib3/request.py", line 151, in request_encode_body
return self.urlopen(method, url, **extra_kw)
File "/media/sdq1/home/**********/.sickrage/lib/requests/packages/urllib3/poolmanager.py", line 165, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "/media/sdq1/home/**********/.sickrage/lib/requests/packages/urllib3/connectionpool.py", line 578, in urlopen
chunked=chunked)
File "/media/sdq1/home/**********/.sickrage/lib/requests/packages/urllib3/connectionpool.py", line 351, in _make_request
self._validate_conn(conn)
File "/media/sdq1/home/**********/.sickrage/lib/requests/packages/urllib3/connectionpool.py", line 814, in _validate_conn
conn.connect()
File "/media/sdq1/home/**********/.sickrage/lib/requests/packages/urllib3/connection.py", line 289, in connect
ssl_version=resolved_ssl_version)
File "/media/sdq1/home/**********/.sickrage/lib/requests/packages/urllib3/contrib/pyopenssl.py", line 328, in ssl_wrap_socket
ctx.load_verify_locations(ca_certs, ca_cert_dir)
File "/usr/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 303, in load_verify_locations
raise TypeError("cafile must be None or a byte string")
TypeError: cafile must be None or a byte string

# Fixed code
def _varargs(*args):
    """Encode var arguments to utf-8 or fs encoding."""
    return [_handle_input(arg) for arg in args]
# Buggy code
def canonical_name(obj, fmt="{key}:{value}", separator="|", ignore_list=frozenset()):
    """Create a canonical name from a release name or a guessed dictionary.

    :param obj:
    :type obj: str or dict
    :param fmt:
    :type fmt: str or unicode
    :param separator:
    :type separator: str or unicode
    :param ignore_list:
    :type ignore_list: set
    :return:
    :rtype: str
    """
    guess = obj if isinstance(obj, dict) else guessit.guessit(obj)
    return str(
        separator.join(
            [
                fmt.format(key=k, value=v)
                for k, v in guess.items()
                if k not in ignore_list
            ]
        )
    )


# Traceback (UnicodeEncodeError)
PASTE LOGS HERE

2016-09-20 20:58:51 ERROR    SEARCHQUEUE-MANUAL-296065 :: [Torrentz2] :: [161bce5] Unknown exception while searching Torrentz2. Error: u'charmap : title: \xd0\u0161\xd0\xbe\xd0\xbd\xd0\xb5\xd1\u2020 \xd0\xb4\xd0\xb5\xd1\u201a\xd1\ufffd\xd1\u201a\xd0\xb2\xd0\xb0, season: 1, format: WEB-DL, screen_size: 1080p, release_group: NewStudio, type: episode, absolute_episode: [], quality: Unknown, episode: [] : error 7 : error 12 : character maps to '
Traceback (most recent call last):
File "C:\SickRageMedusa\**********\search\core.py", line 553, in searchProviders
downCurQuality, manual_search, manual_search_type)
File "C:\SickRageMedusa\**********\providers\GenericProvider.py", line 212, in find_search_results
parse_result = NameParser(parse_method=('normal', 'anime')[show.is_anime]).parse(title)
File "C:\SickRageMedusa\**********\name_parser\parser.py", line 234, in parse
self.assert_supported(result)
File "C:\SickRageMedusa\**********\name_parser\parser.py", line 251, in assert_supported
'Parser result: {result}'.format(result=result))
File "C:\SickRageMedusa\**********\name_parser\parser.py", line 360, in __str__
return helpers.canonical_name(obj, fmt='{key}: {value}', separator=', ')
File "C:\SickRageMedusa\**********\helpers.py", line 1634, in canonical_name
return str(separator.join([fmt.format(key=k, value=v) for k, v in guess.items() if k not in ignore_list]))
File "C:\Python27\lib\encodings\cp1252.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 7-11: character maps to

# Fixed code
def canonical_name(obj, fmt="{key}:{value}", separator="|", ignore_list=frozenset()):
    """Create a canonical name from a release name or a guessed dictionary.

    The return value is always unicode.

    :param obj:
    :type obj: str or dict
    :param fmt:
    :type fmt: str or unicode
    :param separator:
    :type separator: str or unicode
    :param ignore_list:
    :type ignore_list: set
    :return:
    :rtype: text_type
    """
    guess = obj if isinstance(obj, dict) else guessit.guessit(obj)
    return text_type(
        text_type(separator).join(
            [
                text_type(fmt).format(key=unicodify(k), value=unicodify(v))
                for k, v in guess.items()
                if k not in ignore_list
            ]
        )
    )
# Buggy code
def _execute(self, query, args=None, fetchall=False, fetchone=False):
    """
    Executes DB query

    :param query: Query to execute
    :param args: Arguments in query
    :param fetchall: Boolean to indicate all results must be fetched
    :param fetchone: Boolean to indicate one result must be fetched (to walk results for instance)
    :return: query results
    """
    try:
        if not args:
            sql_results = self.connection.cursor().execute(query)
        else:
            sql_results = self.connection.cursor().execute(query, args)
        if fetchall:
            return sql_results.fetchall()
        elif fetchone:
            return sql_results.fetchone()
        else:
            return sql_results
    except Exception:
        raise


# Traceback (OperationalError)
SEARCHQUEUE-BACKLOG-250793 :: [BeyondHD] :: [881d122] DB error: database or disk is full
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/db.py", line 254, in action
sql_results = self._execute(query, args, fetchall=fetchall, fetchone=fetchone)
File "/home/home/SickRage/sickbeard/db.py", line 108, in _execute
sql_results = self.connection.cursor().execute(query, args)
OperationalError: database or disk is full

# Fixed code
def _execute(self, query, args=None, fetchall=False, fetchone=False):
    """
    Executes DB query

    :param query: Query to execute
    :param args: Arguments in query
    :param fetchall: Boolean to indicate all results must be fetched
    :param fetchone: Boolean to indicate one result must be fetched (to walk results for instance)
    :return: query results
    """
    try:
        if not args:
            sql_results = self.connection.cursor().execute(query)
        else:
            sql_results = self.connection.cursor().execute(query, args)
        if fetchall:
            return sql_results.fetchall()
        elif fetchone:
            return sql_results.fetchone()
        else:
            return sql_results
    except sqlite3.OperationalError as e:
        # This errors user should be able to fix it.
        if (
            "unable to open database file" in e.args[0]
            or "database is locked" in e.args[0]
            or "database or disk is full" in e.args[0]
        ):
            logger.log("DB error: {0!r}".format(e), logger.WARNING)
        else:
            logger.log("DB error: {0!r}".format(e), logger.ERROR)
            raise
    except Exception as e:
        logger.log("DB error: {0!r}".format(e), logger.ERROR)
        raise
# Buggy code
def clean(self):
    """
    Calls git clean to remove all untracked files. Returns a bool depending
    on the call's success.
    """
    _, _, exit_status = self._run_git(self._git_path, 'clean -df ""')  # @UnusedVariable
    if exit_status == 0:
        return True


# Traceback (ValueError)
2016-09-09 01:16:34 WARNING  FINDSUBTITLES :: [fd8acdd] Unexpected error in provider 'legendastv', discarding it
Traceback (most recent call last):
File "/usr/local/sickbeard-custom/var/SickBeard/lib/subliminal/core.py", line 171, in download_subtitle
self[subtitle.provider_name].download_subtitle(subtitle)
File "/usr/local/sickbeard-custom/var/SickBeard/lib/subliminal/providers/legendastv.py", line 448, in download_subtitle
subtitle.content = fix_line_ending(subtitle.archive.content.read(subtitle.name))
File "/usr/local/sickbeard-custom/var/SickBeard/lib/rarfile/__init__.py", line 657, in read
File "/usr/local/sickbeard-custom/var/SickBeard/lib/rarfile/__init__.py", line 642, in open
File "/usr/local/sickbeard-custom/var/SickBeard/lib/rarfile/__init__.py", line 1189, in _open_unrar
ValueError: Cannot use unrar directly on memory buffer

# Fixed code
def clean(self):
    """Call git clean to remove all untracked files.

    It only affects source folders (sickbeard, sickrage) and the lib folder,
    to prevent deleting untracked user data not known by .gitignore

    :return:
    :rtype: bool
    """
    for folder in ("lib", "sickbeard", "sickrage"):
        _, _, exit_status = self._run_git(
            self._git_path, "clean -d -f {0}".format(folder)
        )
        if exit_status != 0:
            return False

    return True
# Buggy code
def refine(video, tv_episode=None, **kwargs):
    """Refine a video by using TVEpisode information.

    :param video: the video to refine.
    :type video: Episode
    :param tv_episode: the TVEpisode to be used.
    :type tv_episode: sickbeard.tv.TVEpisode
    :param kwargs:
    """
    if video.series_tvdb_id and video.tvdb_id:
        logger.debug("No need to refine with TVEpisode")
        return

    if not tv_episode:
        logger.debug("No TVEpisode to be used to refine")
        return

    if not isinstance(video, Episode):
        logger.debug(
            "Video {name} is not an episode. Skipping refiner...", name=video.name
        )
        return

    if tv_episode.show:
        logger.debug("Refining using TVShow information.")
        series, year, country = series_re.match(tv_episode.show.name).groups()
        enrich({"series": series, "year": int(year) if year else None}, video)
        enrich(SHOW_MAPPING, video, tv_episode.show)

    logger.debug("Refining using TVEpisode information.")
    enrich(EPISODE_MAPPING, video, tv_episode)
    enrich({"release_group": tv_episode.release_group}, video, overwrite=False)
    guess = Quality.to_guessit(tv_episode.status)
    enrich(
        {"resolution": guess["screen_size"], "format": guess["format"]},
        video,
        overwrite=False,
    )


# Traceback (KeyError)
2016-09-05 17:55:06 WARNING  FINDSUBTITLES :: [3824246] Failed to refine video
Traceback (most recent call last):
File "/home/**********/.sickrage/lib/subliminal/core.py", line 543, in refine
refiner_manager[refiner].plugin(video, **kwargs)
File "/home/**********/.sickrage/sickbeard/refiners/tvepisode.py", line 62, in refine
enrich({'resolution': guess['screen_size'], 'format': guess['format']}, video, overwrite=False)
KeyError: u'screen_size'

# Fixed code
def refine(video, tv_episode=None, **kwargs):
    """Refine a video by using TVEpisode information.

    :param video: the video to refine.
    :type video: Episode
    :param tv_episode: the TVEpisode to be used.
    :type tv_episode: sickbeard.tv.TVEpisode
    :param kwargs:
    """
    if video.series_tvdb_id and video.tvdb_id:
        logger.debug("No need to refine with TVEpisode")
        return

    if not tv_episode:
        logger.debug("No TVEpisode to be used to refine")
        return

    if not isinstance(video, Episode):
        logger.debug(
            "Video {name} is not an episode. Skipping refiner...", name=video.name
        )
        return

    if tv_episode.show:
        logger.debug("Refining using TVShow information.")
        series, year, country = series_re.match(tv_episode.show.name).groups()
        enrich({"series": series, "year": int(year) if year else None}, video)
        enrich(SHOW_MAPPING, video, tv_episode.show)

    logger.debug("Refining using TVEpisode information.")
    enrich(EPISODE_MAPPING, video, tv_episode)
    enrich({"release_group": tv_episode.release_group}, video, overwrite=False)
    guess = Quality.to_guessit(tv_episode.status)
    enrich(
        {"resolution": guess.get("screen_size"), "format": guess.get("format")},
        video,
        overwrite=False,
    )
# Buggy code
def from_guessit(guess):
    """

    :param guess: guessit dict
    :type guess: dict
    :return: quality
    :rtype: int
    """
    screen_size = guess.get("screen_size")
    fmt = guess.get("format")

    if not screen_size:
        return Quality.UNKNOWN

    format_map = Quality.guessit_map.get(screen_size)
    if not format_map:
        return Quality.UNKNOWN

    if isinstance(format_map, int):
        return format_map

    if not fmt:
        return Quality.UNKNOWN

    quality = format_map.get(fmt)
    return quality if quality is not None else Quality.UNKNOWN


# Traceback (TypeError)
SHOWQUEUE-ADD :: [ba2d949] Error searching dir for episodes: unhashable type: 'list'
Traceback (most recent call last):
File "/opt/sickrage/sickbeard/show_queue.py", line 512, in run
self.show.load_episodes_from_dir()
File "/opt/sickrage/sickbeard/tv.py", line 606, in load_episodes_from_dir
parse_result = NameParser(show=self, try_indexers=True).parse(ep_file_name)
File "/opt/sickrage/sickbeard/name_parser/parser.py", line 235, in parse
result = self._parse_string(name)
File "/opt/sickrage/sickbeard/name_parser/parser.py", line 78, in _parse_string
result.quality = common.Quality.from_guessit(guess)
File "/opt/sickrage/sickbeard/common.py", line 650, in from_guessit
quality = format_map.get(fmt)
TypeError: unhashable type: 'list'

# Fixed code
def from_guessit(guess):
    """

    :param guess: guessit dict
    :type guess: dict
    :return: quality
    :rtype: int
    """
    screen_size = guess.get("screen_size")
    fmt = guess.get("format")

    if not screen_size or isinstance(screen_size, list):
        return Quality.UNKNOWN

    format_map = Quality.guessit_map.get(screen_size)
    if not format_map:
        return Quality.UNKNOWN

    if isinstance(format_map, int):
        return format_map

    if not fmt or isinstance(fmt, list):
        return Quality.UNKNOWN

    quality = format_map.get(fmt)
    return quality if quality is not None else Quality.UNKNOWN
# Buggy code
def to_guessit(status):
    """Return a guessit dict containing 'screen_size and format' from a Quality (composite status)

    :param status: a quality composite status
    :type status: int
    :return: dict {'screen_size': <screen_size>, 'format': <format>}
    :rtype: dict (str, str)
    """
    _, quality = Quality.splitCompositeStatus(status)
    result = {
        "screen_size": Quality.to_guessit_screen_size(quality),
        "format": Quality.to_guessit_format(quality),
    }
    return result


# Traceback (TypeError)
SHOWQUEUE-ADD :: [ba2d949] Error searching dir for episodes: unhashable type: 'list'
Traceback (most recent call last):
File "/opt/sickrage/sickbeard/show_queue.py", line 512, in run
self.show.load_episodes_from_dir()
File "/opt/sickrage/sickbeard/tv.py", line 606, in load_episodes_from_dir
parse_result = NameParser(show=self, try_indexers=True).parse(ep_file_name)
File "/opt/sickrage/sickbeard/name_parser/parser.py", line 235, in parse
result = self._parse_string(name)
File "/opt/sickrage/sickbeard/name_parser/parser.py", line 78, in _parse_string
result.quality = common.Quality.from_guessit(guess)
File "/opt/sickrage/sickbeard/common.py", line 650, in from_guessit
quality = format_map.get(fmt)
TypeError: unhashable type: 'list'

# Fixed code
def to_guessit(status):
    """Return a guessit dict containing 'screen_size and format' from a Quality (composite status)

    :param status: a quality composite status
    :type status: int
    :return: dict {'screen_size': <screen_size>, 'format': <format>}
    :rtype: dict (str, str)
    """
    _, quality = Quality.splitCompositeStatus(status)
    screen_size = Quality.to_guessit_screen_size(quality)
    fmt = Quality.to_guessit_format(quality)
    result = dict()
    if screen_size:
        result["screen_size"] = screen_size
    if fmt:
        result["format"] = fmt

    return result
# Buggy code
def to_guessit_format(quality):
    """Return a guessit format from a Quality

    :param quality: the quality
    :type quality: int
    :return: guessit format
    :rtype: str
    """
    for q in Quality.to_guessit_format_list:
        if quality & q:
            return Quality.combinedQualityStrings.get(q)


# Traceback (TypeError)
SHOWQUEUE-ADD :: [ba2d949] Error searching dir for episodes: unhashable type: 'list'
Traceback (most recent call last):
File "/opt/sickrage/sickbeard/show_queue.py", line 512, in run
self.show.load_episodes_from_dir()
File "/opt/sickrage/sickbeard/tv.py", line 606, in load_episodes_from_dir
parse_result = NameParser(show=self, try_indexers=True).parse(ep_file_name)
File "/opt/sickrage/sickbeard/name_parser/parser.py", line 235, in parse
result = self._parse_string(name)
File "/opt/sickrage/sickbeard/name_parser/parser.py", line 78, in _parse_string
result.quality = common.Quality.from_guessit(guess)
File "/opt/sickrage/sickbeard/common.py", line 650, in from_guessit
quality = format_map.get(fmt)
TypeError: unhashable type: 'list'

# Fixed code
def to_guessit_format(quality):
    """Return a guessit format from a Quality

    :param quality: the quality
    :type quality: int
    :return: guessit format
    :rtype: str
    """
    for q in Quality.to_guessit_format_list:
        if quality & q:
            key = q & (
                512 - 1
            )  # 4k formats are bigger than 384 and are not part of ANY* bit set
            return Quality.combinedQualityStrings.get(key)
# Buggy code
def __getattr__(self, name):
    """Wrapper that delegates to the actual logger.

    :param name:
    :type name: str
    :return:
    """
    if name not in ADAPTER_MEMBERS:
        return getattr(self.logger, name)

    return getattr(self, name)


# Traceback (TypeError)
FINDPROPERS :: [b152c03] Exception generated in thread FINDPROPERS: _log() got an unexpected keyword argument 'name'
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/scheduler.py", line 106, in run
self.action.run(self.force)
File "/home/home/SickRage/sickbeard/properFinder.py", line 66, in run
propers = self._get_proper_results()
File "/home/home/SickRage/sickbeard/properFinder.py", line 181, in _get_proper_results
parse_result = NameParser().parse(cur_proper.name)
File "/home/home/SickRage/sickbeard/name_parser/parser.py", line 235, in parse
result = self._parse_string(name)
File "/home/home/SickRage/sickbeard/name_parser/parser.py", line 121, in _parse_string
air_date=result.air_date, name=show.name)
File "/usr/lib/python2.7/logging/__init__.py", line 1164, in warning
self._log(WARNING, msg, args, **kwargs)
TypeError: _log() got an unexpected keyword argument 'name'

# Fixed code
def __getattr__(self, name):
    """Wrapper that delegates to the actual logger.

    :param name:
    :type name: str
    :return:
    """
    if name not in ADAPTER_MEMBERS:
        return getattr(self.logger, name)

    return getattr(self, ADAPTER_MEMBERS[name])
# Buggy code
def copyFile(src_file, dest_file):
    """Copy a file from source to destination.

    :param src_file: Path of source file
    :type src_file: str
    :param dest_file: Path of destination file
    :type dest_file: str
    """
    try:
        from shutil import SpecialFileError, Error
    except ImportError:
        from shutil import Error

        SpecialFileError = Error

    try:
        ek(shutil.copyfile, src_file, dest_file)
    except (SpecialFileError, Error) as error:
        logger.warning("{error}", error=error)
    except Exception as error:
        logger.error("{error}", error=error)
    else:
        try:
            ek(shutil.copymode, src_file, dest_file)
        except OSError:
            pass


# Traceback (OSError)
POSTPROCESSER :: [3ed34a2] [Errno 28] No space left on device: '/media/extssd/Shows/Lip Sync Battle/Season 02/Lip.Sync.Battle.S02E12.Clark.Gregg.vs.Hayley.Atwell.720p.HDTV.x264-ALTEREGO.mkv'
Traceback (most recent call last):
File "/home/home/SickRage/sickbeard/helpers.py", line 371, in copyFile
ek(shutil.copyfile, srcFile, destFile)
File "/home/home/SickRage/sickrage/helper/encoding.py", line 40, in ek
result = function(*[ss(x) if isinstance(x, (str, unicode)) else x for x in args], **kwargs)
File "/home/home/SickRage/lib/shutil_custom/__init__.py", line 42, in copyfile_custom
fout = os.open(dst, WRITE_FLAGS)
OSError: [Errno 28] No space left on device: '/media/extssd/Shows/Lip Sync Battle/Season 02/Lip.Sync.Battle.S02E12.Clark.Gregg.vs.Hayley.Atwell.720p.HDTV.x264-ALTEREGO.mkv'

# Fixed code
def copyFile(src_file, dest_file):
    """Copy a file from source to destination.

    :param src_file: Path of source file
    :type src_file: str
    :param dest_file: Path of destination file
    :type dest_file: str
    """
    try:
        from shutil import SpecialFileError, Error
    except ImportError:
        from shutil import Error

        SpecialFileError = Error

    try:
        ek(shutil.copyfile, src_file, dest_file)
    except (SpecialFileError, Error) as error:
        logger.warning("{error}", error=error)
    except OSError as error:
        if "No space left on device" in error:
            logger.warning("{error}", error=error)
        else:
            logger.error("{error}", error=error)
    else:
        try:
            ek(shutil.copymode, src_file, dest_file)
        except OSError:
            pass
# Buggy code
def __init__(self, *args, **kwargs):
    super(ErrorLogs, self).__init__(*args, **kwargs)


# Traceback (TypeError)
Thread-14 :: [55af592] Failed doing webui callback: Traceback (most recent call last):
File "/app/sickrage/sickbeard/webserve.py", line 276, in async_call
result = function(**kwargs)
TypeError: viewlog() got an unexpected keyword argument 'limit'

# Fixed code
def __init__(self, *args, **kwargs):
    """Default constructor."""
    super(ErrorLogs, self).__init__(*args, **kwargs)
# Buggy code
def index(self, level=logger.ERROR):
    try:
        level = int(level)
    except Exception:
        level = logger.ERROR

    t = PageTemplate(rh=self, filename="errorlogs.mako")
    return t.render(
        header="Logs &amp; Errors",
        title="Logs &amp; Errors",
        topmenu="system",
        submenu=self.ErrorLogsMenu(level),
        logLevel=level,
        controller="errorlogs",
        action="index",
    )


# Traceback (TypeError)
Thread-14 :: [55af592] Failed doing webui callback: Traceback (most recent call last):
File "/app/sickrage/sickbeard/webserve.py", line 276, in async_call
result = function(**kwargs)
TypeError: viewlog() got an unexpected keyword argument 'limit'

# Fixed code
def index(self, level=logger.ERROR, **kwargs):
    """Default index page."""
    try:
        level = int(level)
    except (TypeError, ValueError):
        level = logger.ERROR

    t = PageTemplate(rh=self, filename="errorlogs.mako")
    return t.render(
        header="Logs &amp; Errors",
        title="Logs &amp; Errors",
        topmenu="system",
        submenu=self._create_menu(level),
        logLevel=level,
        controller="errorlogs",
        action="index",
    )
# Buggy code
def clearerrors(self, level=logger.ERROR):
    if int(level) == logger.WARNING:
        classes.WarningViewer.clear()
    else:
        classes.ErrorViewer.clear()

    return self.redirect("/errorlogs/viewlog/")


# Traceback (TypeError)
Thread-14 :: [55af592] Failed doing webui callback: Traceback (most recent call last):
File "/app/sickrage/sickbeard/webserve.py", line 276, in async_call
result = function(**kwargs)
TypeError: viewlog() got an unexpected keyword argument 'limit'

# Fixed code
def clearerrors(self, level=logger.ERROR):
    """Clear the errors or warnings."""
    if int(level) == logger.WARNING:
        classes.WarningViewer.clear()
    else:
        classes.ErrorViewer.clear()

    return self.redirect("/errorlogs/viewlog/")
# Buggy code
def submit_errors(self):
    submitter_result, issue_id = logger.submit_errors()
    logger.log(submitter_result, (logger.INFO, logger.WARNING)[issue_id is None])
    submitter_notification = (
        ui.notifications.error if issue_id is None else ui.notifications.message
    )
    submitter_notification(submitter_result)

    return self.redirect("/errorlogs/")


# Traceback (TypeError)
Thread-14 :: [55af592] Failed doing webui callback: Traceback (most recent call last):
File "/app/sickrage/sickbeard/webserve.py", line 276, in async_call
result = function(**kwargs)
TypeError: viewlog() got an unexpected keyword argument 'limit'

# Fixed code
def submit_errors(self):
    """Create an issue in medusa issue tracker."""
    submitter_result, issue_id = logger.submit_errors()
    logger.log(submitter_result, (logger.INFO, logger.WARNING)[issue_id is None])
    submitter_notification = (
        ui.notifications.error if issue_id is None else ui.notifications.message
    )
    submitter_notification(submitter_result)

    return self.redirect("/errorlogs/")
# Buggy code
def recursive_glob(treeroot, pattern):
    results = []
    for base, _, files in ek(os.walk, treeroot.encode(sickbeard.SYS_ENCODING)):
        goodfiles = fnmatch.filter(files, pattern)
        results.extend(ek(os.path.join, base, f) for f in goodfiles)
    return results


# 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 recursive_glob(treeroot, pattern):
    results = []
    for base, _, files in os.walk(treeroot):
        goodfiles = fnmatch.filter(files, pattern)
        results.extend(ek(os.path.join, base, f) for f in goodfiles)
    return results
# Buggy code
def enabled_service_list():
    """Returns an ordered list of enabled and valid subliminal provider names

    :return: list of provider names
    :rtype: list of str
    """
    return [service["name"] for service in sorted_service_list() if service["enabled"]]


# 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 enabled_service_list():
    """Return an ordered list of enabled and valid subliminal provider names.

    :return: list of provider names
    :rtype: list of str
    """
    return [service["name"] for service in sorted_service_list() if service["enabled"]]
# Buggy code
def wanted_languages():
    """Returns the wanted language codes

    :return: set of wanted subtitles (opensubtitles codes)
    :rtype: frozenset
    """
    return frozenset(sickbeard.SUBTITLES_LANGUAGES).intersection(subtitle_code_filter())


# 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 wanted_languages():
    """Return the wanted language codes.

    :return: set of wanted subtitles (opensubtitles codes)
    :rtype: frozenset
    """
    return frozenset(sickbeard.SUBTITLES_LANGUAGES).intersection(subtitle_code_filter())
# Buggy code
def get_needed_languages(subtitles):
    """Given the existing subtitles, returns a set of the needed subtitles

    :param subtitles: the existing subtitles (opensubtitles codes)
    :type subtitles: list of str
    :return: the needed subtitles
    :rtype: set of babelfish.Language
    """
    if not sickbeard.SUBTITLES_MULTI:
        return (
            set()
            if "und" in subtitles
            else {from_code(language) for language in wanted_languages()}
        )
    return {
        from_code(language) for language in wanted_languages().difference(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 get_needed_languages(subtitles):
    """Given the existing subtitles, returns a set of the needed subtitles.

    :param subtitles: the existing subtitles (opensubtitles codes)
    :type subtitles: list of str
    :return: the needed subtitles
    :rtype: set of babelfish.Language
    """
    if not sickbeard.SUBTITLES_MULTI:
        return (
            set()
            if "und" in subtitles
            else {from_code(language) for language in wanted_languages()}
        )
    return {
        from_code(language) for language in wanted_languages().difference(subtitles)
    }
# Buggy code
def subtitle_code_filter():
    """Returns a set of all 3-letter code languages of opensubtitles

    :return: all 3-letter language codes
    :rtype: set of str
    """
    return {
        code for code in language_converters["opensubtitles"].codes if len(code) == 3
    }


# 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 subtitle_code_filter():
    """Return a set of all 3-letter code languages of opensubtitles.

    :return: all 3-letter language codes
    :rtype: set of str
    """
    return {
        code for code in language_converters["opensubtitles"].codes if len(code) == 3
    }
# Buggy code
def needs_subtitles(subtitles):
    """Given the existing subtitles and wanted languages, returns True if subtitles are still needed

    :param subtitles: the existing subtitles
    :type subtitles: set of str
    :return: True if subtitles are needed
    :rtype: bool
    """
    wanted = wanted_languages()
    if not wanted:
        return False

    if isinstance(subtitles, basestring):
        subtitles = {
            subtitle.strip() for subtitle in subtitles.split(",") if subtitle.strip()
        }

    if sickbeard.SUBTITLES_MULTI:
        return wanted.difference(subtitles)

    return "und" not in 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 needs_subtitles(subtitles):
    """Given the existing subtitles and wanted languages, returns True if subtitles are still needed.

    :param subtitles: the existing subtitles
    :type subtitles: set of str
    :return: True if subtitles are needed
    :rtype: bool
    """
    wanted = wanted_languages()
    if not wanted:
        return False

    if isinstance(subtitles, basestring):
        subtitles = {
            subtitle.strip() for subtitle in subtitles.split(",") if subtitle.strip()
        }

    if sickbeard.SUBTITLES_MULTI:
        return wanted.difference(subtitles)

    return "und" not in subtitles
# 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: 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


# 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 from_code(code, unknown="und"):
    """Convert 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
# Buggy code
def from_ietf_code(code, unknown="und"):
    """Converts an IETF code to a proper babelfish.Language object

    :param code: an IETF language code
    :type code: str
    :param unknown: the code to be returned for unknown language codes
    :type unknown: str
    :return: a language object
    :rtype: babelfish.Language
    """
    try:
        return Language.fromietf(code)
    except ValueError:
        return Language(unknown) if unknown else None


# 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 from_ietf_code(code, unknown="und"):
    """Convert an IETF code to a proper babelfish.Language object.

    :param code: an IETF language code
    :type code: str
    :param unknown: the code to be returned for unknown language codes
    :type unknown: str
    :return: a language object
    :rtype: babelfish.Language
    """
    try:
        return Language.fromietf(code)
    except ValueError:
        return Language(unknown) if unknown else None
# Buggy code
def name_from_code(code):
    """Returns the language name for the given language code

    :param code: the opensubtitles language code
    :type code: str
    :return: the language name
    :rtype: str
    """
    return from_code(code).name


# 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 name_from_code(code):
    """Return the language name for the given language code.

    :param code: the opensubtitles language code
    :type code: str
    :return: the language name
    :rtype: str
    """
    return from_code(code).name
# Buggy code
def code_from_code(code):
    """Converts an opensubtitles code to a 3-letter opensubtitles code

    :param code: an opensubtitles language code
    :type code: str
    :return: a 3-letter opensubtitles language code
    :rtype: str
    """

    return from_code(code).opensubtitles


# 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 code_from_code(code):
    """Convert an opensubtitles code to a 3-letter opensubtitles code.

    :param code: an opensubtitles language code
    :type code: str
    :return: a 3-letter opensubtitles language code
    :rtype: str
    """
    return from_code(code).opensubtitles