gurudesh/pytracebugs huggingface dataset:
# Buggy code
def onModeChanged(self, current_mode):
    log.info("onModeChanged")
    if current_mode is openshot.PLAYBACK_PLAY:
        self.parent.SetPlayheadFollow(False)
    else:
        self.parent.SetPlayheadFollow(True)


# Traceback (AttributeError)
preview_thread:INFO QThread Start Method Invoked
preview_thread:INFO initPlayer
preview_thread:INFO onModeChanged
exceptions:ERROR Unhandled Exception
Traceback (most recent call last):
File "C:\Program Files\OpenShot Video Editor\windows\preview_thread.py", line 61, in onModeChanged
self.parent.SetPlayheadFollow(True)
AttributeError: 'Cutting' object has no attribute 'SetPlayheadFollow'

# Fixed code
def onModeChanged(self, current_mode):
    log.info("onModeChanged")
    try:
        if current_mode is openshot.PLAYBACK_PLAY:
            self.parent.SetPlayheadFollow(False)
        else:
            self.parent.SetPlayheadFollow(True)
    except AttributeError:
        # Parent object doesn't need the playhead follow code
        pass
# Buggy code
def search(self, data, body):
    val = data.get(body.strip(), None)
    return val is None or (self.config_get_bool("include_empty", True) and val == "")


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/baldo/quodlibet/quodlibet/browsers/search.py", line 120, in __text_parse
self.activate()
File "/home/baldo/quodlibet/quodlibet/browsers/search.py", line 114, in activate
songs = self._get_songs()
File "/home/baldo/quodlibet/quodlibet/browsers/search.py", line 111, in _get_songs
return self._query.filter(self._library) if self._query else None
File "/home/baldo/quodlibet/quodlibet/query/_match.py", line 36, in filter
return [s for s in sequence if self.search(s)]
File "/home/baldo/quodlibet/quodlibet/query/_match.py", line 36, in <listcomp>
return [s for s in sequence if self.search(s)]
File "/home/baldo/quodlibet/quodlibet/query/_match.py", line 593, in search
return self.__valid and self.__plugin.search(data, self.__body)
File "/home/baldo/quodlibet/quodlibet/ext/query/missing.py", line 20, in search
val = data.get(body.strip(), None)
AttributeError: 'NoneType' object has no attribute 'strip'

# Fixed code
def search(self, data, body):
    val = data.get(body.strip() if body else None, None)
    return val is None or (self.config_get_bool("include_empty", True) and val == "")
# Buggy code
def plugin_songs(self, songs):
    value = -1
    while not 0 <= value <= 1:
        input_string = GetStringDialog(
            self.plugin_window,
            self.PLUGIN_NAME,
            _("Please give your desired rating on a scale from 0.0 to 1.0"),
            _("_Apply"),
            Icons.NONE,
        ).run()

        if input_string is None:
            return

        try:
            value = float(input_string)
        except ValueError:
            continue

    count = len(songs)
    if count > 1 and config.getboolean("browsers", "rating_confirm_multiple"):
        confirm_dialog = ConfirmRateMultipleDialog(self.plugin_window, count, value)
        if confirm_dialog.run() != Gtk.ResponseType.YES:
            return

    for song in songs:
        song["~#rating"] = value


# Traceback (TypeError)
TypeError: __init__() missing 1 required positional argument: 'value'
------
Traceback (most recent call last):

File "/home/phidica/Code/quodlibet/quodlibet/quodlibet/qltk/songsmenu.py", line 205, in __handle
ret = plugin.plugin_songs(songs)

File "/home/phidica/Code/quodlibet/quodlibet/quodlibet/ext/songsmenu/exact_rating.py", line 55, in plugin_songs
self.plugin_window, count, value)

TypeError: __init__() missing 1 required positional argument: 'value'

# Fixed code
def plugin_songs(self, songs):
    value = -1
    while not 0 <= value <= 1:
        input_string = GetStringDialog(
            self.plugin_window,
            self.PLUGIN_NAME,
            _("Please give your desired rating on a scale from 0.0 to 1.0"),
            _("_Apply"),
            Icons.NONE,
        ).run()

        if input_string is None:
            return

        try:
            value = float(input_string)
        except ValueError:
            continue

    count = len(songs)
    if count > 1 and config.getboolean("browsers", "rating_confirm_multiple"):
        confirm_dialog = ConfirmRateMultipleDialog(
            self.plugin_window, _("Change _Rating"), count, value
        )
        if confirm_dialog.run() != Gtk.ResponseType.YES:
            return

    for song in songs:
        song["~#rating"] = value
# Buggy code
def __pls_export(self, file_path, files):
    try:
        fhandler = open(file_path, "w")
    except IOError:
        self.__file_error(file_path)
    else:
        text = "[playlist]\n"

        for num, f in enumerate(files):
            num += 1
            text += "File%d=%s\n" % (num, f["path"])
            text += "Title%d=%s\n" % (num, f["title"])
            text += "Length%d=%s\n" % (num, f["length"])

        text += "NumberOfEntries=%d\n" % len(files)
        text += "Version=2\n"

        fhandler.write(text.encode("utf-8"))
        fhandler.close()


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/plugins/playlist.py", line 179, in __handle
ret = plugin.plugin_single_playlist(pl)
File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/ext/songsmenu/playlist.py", line 39, in plugin_single_playlist
return self.__save_playlist(playlist.songs, playlist.name)
File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/ext/songsmenu/playlist.py", line 101, in __save_playlist
self.__m3u_export(file_path, files)
File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/ext/songsmenu/playlist.py", line 147, in __m3u_export
fhandler.write(text.encode("utf-8"))
TypeError: write() argument must be str, not bytes

# Fixed code
def __pls_export(self, file_path, files):
    try:
        fhandler = open(file_path, "wb")
    except IOError:
        self.__file_error(file_path)
    else:
        text = "[playlist]\n"

        for num, f in enumerate(files):
            num += 1
            text += "File%d=%s\n" % (num, f["path"])
            text += "Title%d=%s\n" % (num, f["title"])
            text += "Length%d=%s\n" % (num, f["length"])

        text += "NumberOfEntries=%d\n" % len(files)
        text += "Version=2\n"

        fhandler.write(text.encode("utf-8"))
        fhandler.close()
# Buggy code
def __eq__(self, other):
    return self._song == other._song


# Traceback (AttributeError)
E: 21.321: errorreport.main.errorhook:
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/quodlibet/player/gstbe/player.py", line 343, in __songs_changed
if self.song and self.song in songs:
File "/usr/lib64/python2.7/site-packages/quodlibet/util/songwrapper.py", line 63, in __eq__
return self._song == other._song
AttributeError: 'FLACFile' object has no attribute '_song'

# Fixed code
def __eq__(self, other):
    if hasattr(other, "_song"):
        other = other._song
    return self._song == other
# Buggy code
def __lt__(self, other):
    return self._song < other._song


# Traceback (AttributeError)
E: 21.321: errorreport.main.errorhook:
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/quodlibet/player/gstbe/player.py", line 343, in __songs_changed
if self.song and self.song in songs:
File "/usr/lib64/python2.7/site-packages/quodlibet/util/songwrapper.py", line 63, in __eq__
return self._song == other._song
AttributeError: 'FLACFile' object has no attribute '_song'

# Fixed code
def __lt__(self, other):
    if hasattr(other, "_song"):
        other = other._song
    return self._song < other
# Buggy code
def __import(self, activator, library):
    cf = create_chooser_filter(_("Playlists"), ["*.pls", "*.m3u"])
    fns = choose_files(self, _("Import Playlist"), _("_Import"), cf)
    for filename in fns:
        if filename.endswith(".m3u"):
            playlist = parse_m3u(filename, library=library)
        elif filename.endswith(".pls"):
            playlist = parse_pls(filename, library=library)
        else:
            continue
        self.changed(playlist)
        library.add(playlist)


# Traceback (TypeError)
Traceback (most recent call last):

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/main.py", line 580, in __import
playlist = parse_m3u(filename, library=library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 70, in parse_m3u
return __create_playlist(pl_name, filename, filenames, library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 118, in __create_playlist
playlist.extend(filter(None, songs))

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 347, in extend
self._emit_changed(songs, msg="extend")

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 483, in _emit_changed
% (msg, len(songs), self))

TypeError: object of type 'filter' has no len()

# Fixed code
def __import(self, activator, library):
    cf = create_chooser_filter(_("Playlists"), ["*.pls", "*.m3u"])
    fns = choose_files(self, _("Import Playlist"), _("_Import"), cf)
    self._import_playlists(fns, library)
# Buggy code
def parse_m3u(filename, library=None):
    pl_name = _name_for(filename)

    filenames = []

    with open(filename, "rb") as h:
        for line in h:
            line = line.strip()
            if line.startswith(b"#"):
                continue
            else:
                try:
                    filenames.append(bytes2fsn(line, "utf-8"))
                except ValueError:
                    continue
    return __create_playlist(pl_name, filename, filenames, library)


# Traceback (TypeError)
Traceback (most recent call last):

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/main.py", line 580, in __import
playlist = parse_m3u(filename, library=library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 70, in parse_m3u
return __create_playlist(pl_name, filename, filenames, library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 118, in __create_playlist
playlist.extend(filter(None, songs))

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 347, in extend
self._emit_changed(songs, msg="extend")

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 483, in _emit_changed
% (msg, len(songs), self))

TypeError: object of type 'filter' has no len()

# Fixed code
def parse_m3u(filelike, pl_name, library=None):
    filenames = []
    for line in filelike:
        line = line.strip()
        if line.startswith(b"#"):
            continue
        __attempt_add(line, filenames)
    return __create_playlist(pl_name, _dir_for(filelike), filenames, library)
# Buggy code
def parse_pls(filename, library=None):
    pl_name = _name_for(filename)

    filenames = []
    with open(filename, "rb") as h:
        for line in h:
            line = line.strip()
            if not line.lower().startswith(b"file"):
                continue
            else:
                try:
                    line = line[line.index(b"=") + 1 :].strip()
                except ValueError:
                    pass
                else:
                    try:
                        filenames.append(bytes2fsn(line, "utf-8"))
                    except ValueError:
                        continue
    return __create_playlist(pl_name, filename, filenames, library)


# Traceback (TypeError)
Traceback (most recent call last):

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/main.py", line 580, in __import
playlist = parse_m3u(filename, library=library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 70, in parse_m3u
return __create_playlist(pl_name, filename, filenames, library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 118, in __create_playlist
playlist.extend(filter(None, songs))

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 347, in extend
self._emit_changed(songs, msg="extend")

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 483, in _emit_changed
% (msg, len(songs), self))

TypeError: object of type 'filter' has no len()

# Fixed code
def parse_pls(filelike, pl_name, library=None):
    filenames = []
    for line in filelike:
        line = line.strip()
        if not line.lower().startswith(b"file"):
            continue
        fn = line[line.index(b"=") + 1 :].strip()
        __attempt_add(fn, filenames)
    return __create_playlist(pl_name, _dir_for(filelike), filenames, library)
# Buggy code
def __create_playlist(name, pl_filename, files, library):
    playlist = FileBackedPlaylist.new(PLAYLISTS, name, library=library)
    songs = []
    win = WaitLoadWindow(
        None, len(files), _("Importing playlist.\n\n%(current)d/%(total)d songs added.")
    )
    win.show()
    for i, filename in enumerate(files):
        if not uri_is_valid(filename):
            # Plain filename.
            songs.append(_af_for(filename, library, pl_filename))
        else:
            try:
                filename = uri2fsn(filename)
            except ValueError:
                # Who knows! Hand it off to GStreamer.
                songs.append(formats.remote.RemoteFile(filename))
            else:
                # URI-encoded local filename.
                songs.append(_af_for(filename, library, pl_filename))
        if win.step():
            break
    win.destroy()
    playlist.extend(filter(None, songs))
    return playlist


# Traceback (TypeError)
Traceback (most recent call last):

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/main.py", line 580, in __import
playlist = parse_m3u(filename, library=library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 70, in parse_m3u
return __create_playlist(pl_name, filename, filenames, library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 118, in __create_playlist
playlist.extend(filter(None, songs))

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 347, in extend
self._emit_changed(songs, msg="extend")

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 483, in _emit_changed
% (msg, len(songs), self))

TypeError: object of type 'filter' has no len()

# Fixed code
def __create_playlist(name, source_dir, files, library):
    playlist = FileBackedPlaylist.new(PLAYLISTS, name, library=library)
    print_d("Created playlist %s" % playlist)
    songs = []
    win = WaitLoadWindow(
        None, len(files), _("Importing playlist.\n\n%(current)d/%(total)d songs added.")
    )
    win.show()
    for i, filename in enumerate(files):
        if not uri_is_valid(filename):
            # Plain filename.
            songs.append(_af_for(filename, library, source_dir))
        else:
            try:
                filename = uri2fsn(filename)
            except ValueError:
                # Who knows! Hand it off to GStreamer.
                songs.append(formats.remote.RemoteFile(filename))
            else:
                # URI-encoded local filename.
                songs.append(_af_for(filename, library, source_dir))
        if win.step():
            break
    win.destroy()
    playlist.extend(listfilter(None, songs))
    return playlist
# Buggy code
def _af_for(filename, library, pl_filename):
    full_path = os.path.join(os.path.dirname(pl_filename), filename)
    filename = os.path.realpath(full_path)
    if library:
        try:
            return library[filename]
        except KeyError:
            pass
    return formats.MusicFile(filename)


# Traceback (TypeError)
Traceback (most recent call last):

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/main.py", line 580, in __import
playlist = parse_m3u(filename, library=library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 70, in parse_m3u
return __create_playlist(pl_name, filename, filenames, library)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/browsers/playlists/util.py", line 118, in __create_playlist
playlist.extend(filter(None, songs))

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 347, in extend
self._emit_changed(songs, msg="extend")

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/util/collection.py", line 483, in _emit_changed
% (msg, len(songs), self))

TypeError: object of type 'filter' has no len()

# Fixed code
def _af_for(filename, library, pl_dir):
    full_path = os.path.join(pl_dir, filename)
    filename = os.path.realpath(full_path)

    af = None
    if library:
        af = library.get_filename(filename)
    if af is None:
        af = formats.MusicFile(filename)
    return af
# Buggy code
def draw_waveform(self, cr, width, height, elapsed_color, remaining_color):
    line_width = CONFIG.line_width
    value_count = len(self._rms_vals)
    max_value = max(self._rms_vals)
    ratio_width = value_count / float(width)
    ratio_height = max_value / float(height) * 2
    half_height = height // 2
    cr.set_line_width(line_width)

    if line_width < 2:
        # Default AA looks bad (and dimmer) for all 1px shapes.
        cr.set_antialias(1)

    position_width = self.position * width
    hw = line_width / 2.0
    # Avoiding object lookups is slightly faster
    data = self._rms_vals
    for x in range(0, width, line_width):
        fg_color = elapsed_color if x < position_width else remaining_color
        cr.set_source_rgba(*list(fg_color))

        # Basic anti-aliasing / oversampling
        u1 = max(0, int(floor((x - hw) * ratio_width)))
        u2 = min(int(ceil((x + hw) * ratio_width)), len(data))
        val = sum(data[u1:u2]) / (u2 - u1)

        # Draw single line, ensuring 1px minimum
        cr.move_to(x, half_height - val / ratio_height)
        cr.line_to(x, ceil(half_height + val / ratio_height))
        cr.stroke()


# Traceback (ValueError)
Traceback (most recent call last):

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/ext/events/waveformseekbar.py", line 258, in do_draw
self.draw_waveform(cr, width, height, elapsed_color, fg_color)

File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/ext/events/waveformseekbar.py", line 221, in draw_waveform
cr.line_to(x, ceil(half_height + val))

ValueError: cannot convert float NaN to integer

# Fixed code
def draw_waveform(self, cr, width, height, elapsed_color, remaining_color):
    line_width = CONFIG.line_width
    value_count = len(self._rms_vals)
    max_value = max(self._rms_vals)
    ratio_width = value_count / float(width)
    ratio_height = max_value / float(height) * 2
    half_height = height // 2
    cr.set_line_width(line_width)

    if line_width < 2:
        # Default AA looks bad (and dimmer) for all 1px shapes.
        cr.set_antialias(1)

    position_width = self.position * width
    hw = line_width / 2.0
    # Avoiding object lookups is slightly faster
    data = self._rms_vals
    for x in range(0, width, line_width):
        fg_color = elapsed_color if x < position_width else remaining_color
        cr.set_source_rgba(*list(fg_color))

        # Basic anti-aliasing / oversampling
        u1 = max(0, int(floor((x - hw) * ratio_width)))
        u2 = min(int(ceil((x + hw) * ratio_width)), len(data))
        val = sum(data[u1:u2]) / (ratio_height * (u2 - u1)) if u1 != u2 else 0.5

        # Draw single line, ensuring 1px minimum
        cr.move_to(x, half_height - val)
        cr.line_to(x, ceil(half_height + val))
        cr.stroke()
# Buggy code
def __init__(self, filename):
    with translate_errors():
        audio = MP4(filename)
    self["~codec"] = getattr(audio.info, "codec_description", "AAC")
    self["~#length"] = audio.info.length
    self["~#bitrate"] = int(audio.info.bitrate / 1000)

    for key, values in audio.items():
        if key in self.__tupletranslate:
            name = self.__tupletranslate[key]
            cur, total = values[0]
            if total:
                self[name] = "%d/%d" % (cur, total)
            else:
                self[name] = text_type(cur)
        elif key in self.__translate:
            name = self.__translate[key]
            if key == "tmpo":
                self[name] = "\n".join(map(text_type, values))
            elif key.startswith("----"):
                self[name] = "\n".join(map(lambda v: decode(v).strip("\x00"), values))
            else:
                self[name] = "\n".join(values)
        elif key == "covr":
            self.has_images = True
    self.sanitize(filename)


# Traceback (IndexError)
=== SYSTEM INFORMATION:
Quod Libet 3.7.1
Mutagen 1.34.1
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] linux2
Platform Linux-4.4.0-47-generic-x86_64-with-LinuxMint-18-sarah
=== STACK TRACE

Traceback (most recent call last):

File "/usr/lib/python2.7/dist-packages/quodlibet/util/copool.py", line 25, in wrap
for value in func(*args, **kwargs):

File "/usr/lib/python2.7/dist-packages/quodlibet/library/libraries.py", line 690, in rebuild
for value in self.scan(paths, exclude, cofuncid):

File "/usr/lib/python2.7/dist-packages/quodlibet/library/libraries.py", line 740, in scan
item = self.add_filename(fullfilename, False)

File "/usr/lib/python2.7/dist-packages/quodlibet/library/libraries.py", line 840, in add_filename
song = MusicFile(filename)

File "/usr/lib/python2.7/dist-packages/quodlibet/formats/_misc.py", line 118, in MusicFile
return loader(filename)

File "/usr/lib/python2.7/dist-packages/quodlibet/formats/mp4.py", line 91, in __init__
cur, total = values[0]

IndexError: list index out of range

# Fixed code
def __init__(self, filename):
    with translate_errors():
        audio = MP4(filename)
    self["~codec"] = getattr(audio.info, "codec_description", "AAC")
    self["~#length"] = audio.info.length
    self["~#bitrate"] = int(audio.info.bitrate / 1000)

    for key, values in audio.items():
        if key in self.__tupletranslate:
            if values:
                name = self.__tupletranslate[key]
                cur, total = values[0]
                if total:
                    self[name] = "%d/%d" % (cur, total)
                else:
                    self[name] = text_type(cur)
        elif key in self.__translate:
            name = self.__translate[key]
            if key == "tmpo":
                self[name] = "\n".join(map(text_type, values))
            elif key.startswith("----"):
                self[name] = "\n".join(map(lambda v: decode(v).strip("\x00"), values))
            else:
                self[name] = "\n".join(values)
        elif key == "covr":
            self.has_images = True
    self.sanitize(filename)
# Buggy code
def MusicFile(filename):
    """Returns a AudioFile instance or None"""

    loader = get_loader(filename)
    if loader is not None:
        try:
            return loader(filename)
        except AudioFileError:
            print_w("Error loading %r" % filename)
            util.print_exc()


# Traceback (IndexError)
=== SYSTEM INFORMATION:
Quod Libet 3.7.1
Mutagen 1.34.1
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] linux2
Platform Linux-4.4.0-47-generic-x86_64-with-LinuxMint-18-sarah
=== STACK TRACE

Traceback (most recent call last):

File "/usr/lib/python2.7/dist-packages/quodlibet/util/copool.py", line 25, in wrap
for value in func(*args, **kwargs):

File "/usr/lib/python2.7/dist-packages/quodlibet/library/libraries.py", line 690, in rebuild
for value in self.scan(paths, exclude, cofuncid):

File "/usr/lib/python2.7/dist-packages/quodlibet/library/libraries.py", line 740, in scan
item = self.add_filename(fullfilename, False)

File "/usr/lib/python2.7/dist-packages/quodlibet/library/libraries.py", line 840, in add_filename
song = MusicFile(filename)

File "/usr/lib/python2.7/dist-packages/quodlibet/formats/_misc.py", line 118, in MusicFile
return loader(filename)

File "/usr/lib/python2.7/dist-packages/quodlibet/formats/mp4.py", line 91, in __init__
cur, total = values[0]

IndexError: list index out of range

# Fixed code
def MusicFile(filename):
    """Returns a AudioFile instance or None"""

    loader = get_loader(filename)
    if loader is not None:
        try:
            return loader(filename)
        except AudioFileError:
            print_w("Error loading %r" % filename)
            util.print_exc()
        except:
            print_w("Error loading %r" % filename)
            raise
# Buggy code
def selection_set_songs(selection_data, songs):
    """Stores filenames of the passed songs in a Gtk.SelectionData"""

    filenames = []
    for filename in (song["~filename"] for song in songs):
        if isinstance(filename, text_type):
            # win32
            filename = filename.encode("utf-8")
        filenames.append(filename)

    type_ = Gdk.atom_intern("text/x-quodlibet-songs", True)
    selection_data.set(type_, 8, "\x00".join(filenames))


# Traceback (TypeError)
=== SYSTEM INFORMATION:
Quod Libet 3.8 (development)
Mutagen 1.35.1
Python 3.5.2+ (default, Nov 22 2016, 01:00:20)
[GCC 6.2.1 20161119] linux
Platform Linux-4.8.0-1-amd64-x86_64-with-debian-stretch-sid
=== STACK TRACE

Traceback (most recent call last):

File "/home/mice/prog/quodlibet-dev/quodlibet/quodlibet/browsers/covergrid/main.py", line 527, in __drag_data_get
qltk.selection_set_songs(sel, songs)

File "/home/mice/prog/quodlibet-dev/quodlibet/quodlibet/qltk/__init__.py", line 59, in selection_set_songs
selection_data.set(type_, 8, "\x00".join(filenames))

TypeError: sequence item 0: expected str instance, bytes found

# Fixed code
def selection_set_songs(selection_data, songs):
    """Stores filenames of the passed songs in a Gtk.SelectionData"""

    filenames = []
    for filename in (song["~filename"] for song in songs):
        filenames.append(fsn2bytes(filename, "utf-8"))
    type_ = Gdk.atom_intern("text/x-quodlibet-songs", True)
    selection_data.set(type_, 8, b"\x00".join(filenames))
# Buggy code
def selection_get_filenames(selection_data):
    """Extracts the filenames of songs set with selection_set_songs()
    from a Gtk.SelectionData.
    """

    data_type = selection_data.get_data_type()
    assert data_type.name() == "text/x-quodlibet-songs"

    items = selection_data.get_data().split("\x00")
    if sys.platform == "win32":
        return [item.decode("utf-8") for item in items]
    else:
        return items


# Traceback (TypeError)
=== SYSTEM INFORMATION:
Quod Libet 3.8 (development)
Mutagen 1.35.1
Python 3.5.2+ (default, Nov 22 2016, 01:00:20)
[GCC 6.2.1 20161119] linux
Platform Linux-4.8.0-1-amd64-x86_64-with-debian-stretch-sid
=== STACK TRACE

Traceback (most recent call last):

File "/home/mice/prog/quodlibet-dev/quodlibet/quodlibet/browsers/covergrid/main.py", line 527, in __drag_data_get
qltk.selection_set_songs(sel, songs)

File "/home/mice/prog/quodlibet-dev/quodlibet/quodlibet/qltk/__init__.py", line 59, in selection_set_songs
selection_data.set(type_, 8, "\x00".join(filenames))

TypeError: sequence item 0: expected str instance, bytes found

# Fixed code
def selection_get_filenames(selection_data):
    """Extracts the filenames of songs set with selection_set_songs()
    from a Gtk.SelectionData.
    """

    data_type = selection_data.get_data_type()
    assert data_type.name() == "text/x-quodlibet-songs"

    items = selection_data.get_data().split(b"\x00")
    return [bytes2fsn(i, "utf-8") for i in items]
# Buggy code
def __add_tag(self, activator, model, library):
    add = AddTagDialog(self, self.__songinfo.can_change(), library)

    while True:
        resp = add.run()
        if resp != Gtk.ResponseType.OK:
            break
        tag = add.get_tag()
        value = add.get_value()
        assert isinstance(value, unicode)
        if tag in massagers.tags:
            value = massagers.tags[tag].validate(value)
        if not self.__songinfo.can_change(tag):
            title = _("Invalid tag")
            msg = _(
                "Invalid tag <b>%s</b>\n\nThe files currently"
                " selected do not support editing this tag."
            ) % util.escape(tag)
            qltk.ErrorMessage(self, title, msg).run()
        else:
            self.__add_new_tag(model, tag, value)
            break

    add.destroy()


# Traceback (AssertionError)
=== SYSTEM INFORMATION:
Quod Libet 3.5.1
Mutagen 1.31
Python 2.7.10 (default, Sep  7 2015, 13:51:49)
[GCC 5.2.0] linux2
Platform Linux-4.2.5-1-ARCH-x86_64-with-glibc2.2.5

=== STACK TRACE
Traceback (most recent call last):

File "/usr/lib/python2.7/site-packages/quodlibet/qltk/edittags.py", line 693, in __add_tag
self.__add_new_tag(model, tag, value)

File "/usr/lib/python2.7/site-packages/quodlibet/qltk/edittags.py", line 654, in __add_new_tag
assert isinstance(value, unicode)

AssertionError

# Fixed code
def __add_tag(self, activator, model, library):
    add = AddTagDialog(self, self.__songinfo.can_change(), library)

    while True:
        resp = add.run()
        if resp != Gtk.ResponseType.OK:
            break
        tag = add.get_tag()
        value = add.get_value()
        assert isinstance(value, unicode)
        if tag in massagers.tags:
            value = massagers.tags[tag].validate(value)
            value = unicode(value)
        assert isinstance(value, unicode)
        if not self.__songinfo.can_change(tag):
            title = _("Invalid tag")
            msg = _(
                "Invalid tag <b>%s</b>\n\nThe files currently"
                " selected do not support editing this tag."
            ) % util.escape(tag)
            qltk.ErrorMessage(self, title, msg).run()
        else:
            self.__add_new_tag(model, tag, value)
            break

    add.destroy()
# Buggy code
def __init__(self, parent, plugin_name, count):
    title = ngettext(
        'Run the plugin "%(name)s" on %(count)d album?',
        'Run the plugin "%(name)s" on %(count)d albums?',
        count,
    ) % (plugin_name, count)

    super(ConfirmMultiAlbumInvoke, self).__init__(
        get_top_parent(parent), title, "", buttons=Gtk.ButtonsType.NONE
    )

    self.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
    delete_button = Button(_("_Run Plugin"), Gtk.STOCK_EXECUTE)
    delete_button.show()
    self.add_action_widget(delete_button, self.RESPONSE_INVOKE)
    self.set_default_response(Gtk.ResponseType.CANCEL)


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/qltk/songsmenu.py", line 182, in __on_activate
self.__handle(item, plugin, library, songs, parent)
File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/qltk/songsmenu.py", line 225, in __handle
parent, plugin.PLUGIN_NAME, total):
File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/qltk/songsmenu.py", line 80, in confirm
resp = cls(parent, plugin_name, count).run()
File "/home/nick/workspace/quodlibet/quodlibet/quodlibet/qltk/songsmenu.py", line 63, in __init__
count) % (plugin_name, count)
TypeError: format requires a mapping

# Fixed code
def __init__(self, parent, plugin_name, count):
    title = ngettext(
        'Run the plugin "%(name)s" on %(count)d album?',
        'Run the plugin "%(name)s" on %(count)d albums?',
        count,
    ) % {"name": plugin_name, "count": count}

    super(ConfirmMultiAlbumInvoke, self).__init__(
        get_top_parent(parent), title, "", buttons=Gtk.ButtonsType.NONE
    )

    self.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
    delete_button = Button(_("_Run Plugin"), Gtk.STOCK_EXECUTE)
    delete_button.show()
    self.add_action_widget(delete_button, self.RESPONSE_INVOKE)
    self.set_default_response(Gtk.ResponseType.CANCEL)
# Buggy code
def description(self):
    return "%s; Priority %d" % (self.STATES[self._state], self.priority)


# Traceback (KeyError)
0033899:DEBUG:gdbserver:GDB received query: [b'Xfer', b'threads', b'read', b'', b'0,7fb#d0']
0033899:DEBUG:gdbserver:GDB query b'threads': offset: 0, size: 2043
0033900:DEBUG:memory:range [200002d0:200002d1] is not cacheable
0033902:DEBUG:memory:range [200002d0:200002d1] is not cacheable
0033905:DEBUG:memory:range [200002d0:200002d1] is not cacheable
0033909:DEBUG:memory:range [200002d0:200002d1] is not cacheable
0033911:ERROR:gdbserver:Unhandled exception in handle_message: 75
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/pyocd/gdbserver/gdbserver.py", line 379, in handle_message
reply = handler(msg[msgStart:])
File "/usr/local/lib/python3.7/dist-packages/pyocd/gdbserver/gdbserver.py", line 853, in handle_query
resp = self.handle_query_xml(b'threads', int(data[0], 16), int(data[1].split(b'#')[0], 16))
File "/usr/local/lib/python3.7/dist-packages/pyocd/gdbserver/gdbserver.py", line 1040, in handle_query_xml
xml = self.get_threads_xml()
File "/usr/local/lib/python3.7/dist-packages/pyocd/gdbserver/gdbserver.py", line 1145, in get_threads_xml
t.text = thread.description
File "/usr/local/lib/python3.7/dist-packages/pyocd/rtos/rtx5.py", line 281, in description
return "%s; Priority %d" % (self.STATES[self._state], self.priority)
KeyError: 75

# Fixed code
def description(self):
    return "%s; Priority %d" % (
        self.STATES.get(self._state, "(Invalid)"),
        self.priority,
    )
# Buggy code
def handle_show_map(self, args):
    print(
        "Region          Start         End                 Size    Access    Blocksize"
    )
    for region in self.target.get_memory_map():
        print(
            "{:<15} {:#010x}    {:#010x}    {:#10x}    {:<9} {}".format(
                region.name,
                region.start,
                region.end,
                region.length,
                region.access,
                region.blocksize if region.is_flash else "-",
            )
        )


# Traceback (TypeError)
pyocd gdb -t stm32f401re --pack /Users/matost01/Downloads/CMSIS/STM32F4xx_DFP.2.13.0.pack
0000355:INFO:pack_target:Loading CMSIS-Pack: /Users/matost01/Downloads/CMSIS/STM32F4xx_DFP.2.13.0.pack
0000457:INFO:board:Target type is stm32f401re
0000464:WARNING:flash_algo:Not enough space for flash algorithm
0000464:ERROR:__main__:uncaught exception: unsupported operand type(s) for -: 'tuple' and 'int'
Traceback (most recent call last):
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/__main__.py", line 304, in run
self._commands[self._args.cmd]()
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/__main__.py", line 463, in do_gdbserver
**sessionOptions)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/core/helpers.py", line 196, in session_with_chosen_probe
session = Session(allProbes[0], options=options, **kwargs)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/core/session.py", line 127, in __init__
or Board(self, self._options.get('target_override', None))
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/board/board.py", line 47, in __init__
self.target = TARGET[self._target_type](session)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/pack_target.py", line 31, in _pack_target__init__
super(self.__class__, self).__init__(session, self._pack_device.memory_map)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/cmsis_pack.py", line 454, in memory_map
self._build_flash_regions()
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/cmsis_pack.py", line 386, in _build_flash_regions
length = nextStart - start
TypeError: unsupported operand type(s) for -: 'tuple' and 'int'```

# Fixed code
def handle_show_map(self, args):
    pt = prettytable.PrettyTable(
        ["Region", "Start", "End", "Size", "Access", "Sector", "Page"]
    )
    pt.align = "l"
    pt.border = False
    for region in self.target.get_memory_map():
        pt.add_row(
            [
                region.name,
                "0x%08x" % region.start,
                "0x%08x" % region.end,
                "0x%08x" % region.length,
                region.access,
                ("0x%08x" % region.sector_size) if region.is_flash else "-",
                ("0x%08x" % region.page_size) if region.is_flash else "-",
            ]
        )
    print(pt)
# Buggy code
def _finish(self):
    self.done = True
    self._file.write("\n")


# Traceback (TypeError)
pyocd gdb -t stm32f401re --pack /Users/matost01/Downloads/CMSIS/STM32F4xx_DFP.2.13.0.pack
0000355:INFO:pack_target:Loading CMSIS-Pack: /Users/matost01/Downloads/CMSIS/STM32F4xx_DFP.2.13.0.pack
0000457:INFO:board:Target type is stm32f401re
0000464:WARNING:flash_algo:Not enough space for flash algorithm
0000464:ERROR:__main__:uncaught exception: unsupported operand type(s) for -: 'tuple' and 'int'
Traceback (most recent call last):
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/__main__.py", line 304, in run
self._commands[self._args.cmd]()
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/__main__.py", line 463, in do_gdbserver
**sessionOptions)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/core/helpers.py", line 196, in session_with_chosen_probe
session = Session(allProbes[0], options=options, **kwargs)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/core/session.py", line 127, in __init__
or Board(self, self._options.get('target_override', None))
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/board/board.py", line 47, in __init__
self.target = TARGET[self._target_type](session)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/pack_target.py", line 31, in _pack_target__init__
super(self.__class__, self).__init__(session, self._pack_device.memory_map)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/cmsis_pack.py", line 454, in memory_map
self._build_flash_regions()
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/cmsis_pack.py", line 386, in _build_flash_regions
length = nextStart - start
TypeError: unsupported operand type(s) for -: 'tuple' and 'int'```

# Fixed code
def _finish(self):
    self._file.write("\n")
# Buggy code
def _finish(self):
    self.done = True
    self._file.write("]\n")
    self._file.flush()


# Traceback (TypeError)
pyocd gdb -t stm32f401re --pack /Users/matost01/Downloads/CMSIS/STM32F4xx_DFP.2.13.0.pack
0000355:INFO:pack_target:Loading CMSIS-Pack: /Users/matost01/Downloads/CMSIS/STM32F4xx_DFP.2.13.0.pack
0000457:INFO:board:Target type is stm32f401re
0000464:WARNING:flash_algo:Not enough space for flash algorithm
0000464:ERROR:__main__:uncaught exception: unsupported operand type(s) for -: 'tuple' and 'int'
Traceback (most recent call last):
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/__main__.py", line 304, in run
self._commands[self._args.cmd]()
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/__main__.py", line 463, in do_gdbserver
**sessionOptions)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/core/helpers.py", line 196, in session_with_chosen_probe
session = Session(allProbes[0], options=options, **kwargs)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/core/session.py", line 127, in __init__
or Board(self, self._options.get('target_override', None))
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/board/board.py", line 47, in __init__
self.target = TARGET[self._target_type](session)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/pack_target.py", line 31, in _pack_target__init__
super(self.__class__, self).__init__(session, self._pack_device.memory_map)
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/cmsis_pack.py", line 454, in memory_map
self._build_flash_regions()
File "/Users/matost01/mbed-studio-tools/python/lib/python2.7/site-packages/pyocd/target/pack/cmsis_pack.py", line 386, in _build_flash_regions
length = nextStart - start
TypeError: unsupported operand type(s) for -: 'tuple' and 'int'```

# Fixed code
def _finish(self):
    self._file.write("]\n")
    self._file.flush()
# Buggy code
def _process_msg(self, msg):
    data = {}
    if "x0" in msg and "x1" in msg:
        x0, x1 = msg["x0"], msg["x1"]
        if isinstance(self.plot.handles.get("xaxis"), DatetimeAxis):
            x0 = convert_timestamp(x0)
            x1 = convert_timestamp(x1)
        if self.plot.invert_xaxis:
            x0, x1 = x1, x0
        data["x_range"] = (x0, x1)
    if "y0" in msg and "y1" in msg:
        y0, y1 = msg["y0"], msg["y1"]
        if isinstance(self.plot.handles.get("yaxis"), DatetimeAxis):
            y0 = convert_timestamp(y0)
            y1 = convert_timestamp(y1)
        if self.plot.invert_yaxis:
            y0, y1 = y1, y0
        data["y_range"] = (y0, y1)
    return self._transform(data)


# Traceback (numpy.core._exceptions.UFuncTypeError)
future: <Future finished exception=UFuncTypeError(<ufunc 'true_divide'>, (dtype('<M8[ns]'), dtype('float64')))>
Traceback (most recent call last):
File "c:\users\catal\appdata\local\programs\python\python36\lib\site-packages\tornado\gen.py", line 191, in wrapper
result = func(*args, **kwargs)
File "c:\users\catal\appdata\local\programs\python\python36\lib\site-packages\holoviews\plotting\bokeh\callbacks.py", line 418, in process_on_change
self.on_msg(msg)
File "c:\users\catal\appdata\local\programs\python\python36\lib\site-packages\holoviews\plotting\bokeh\callbacks.py", line 141, in on_msg
processed_msg = self._process_msg(filtered_msg)
File "c:\users\catal\appdata\local\programs\python\python36\lib\site-packages\holoviews\plotting\bokeh\callbacks.py", line 815, in _process_msg
x0 = convert_timestamp(x0)
File "c:\users\catal\appdata\local\programs\python\python36\lib\site-packages\holoviews\plotting\bokeh\util.py", line 98, in convert_timestamp
datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)
numpy.core._exceptions.UFuncTypeError: ufunc 'true_divide' cannot use operands with types dtype('<M8[ns]') and dtype('float64')

# Fixed code
def _process_msg(self, msg):
    data = {}
    if "x0" in msg and "x1" in msg:
        x0, x1 = msg["x0"], msg["x1"]
        if isinstance(self.plot.handles.get("xaxis"), DatetimeAxis):
            if not isinstance(x0, datetime_types):
                x0 = convert_timestamp(x0)
            if not isinstance(x1, datetime_types):
                x1 = convert_timestamp(x1)
        if self.plot.invert_xaxis:
            x0, x1 = x1, x0
        data["x_range"] = (x0, x1)
    if "y0" in msg and "y1" in msg:
        y0, y1 = msg["y0"], msg["y1"]
        if isinstance(self.plot.handles.get("yaxis"), DatetimeAxis):
            if not isinstance(y0, datetime_types):
                y0 = convert_timestamp(y0)
            if not isinstance(y1, datetime_types):
                y1 = convert_timestamp(y1)
        if self.plot.invert_yaxis:
            y0, y1 = y1, y0
        data["y_range"] = (y0, y1)
    return self._transform(data)
# Buggy code
def get_data(self, element, ranges, style):
    xs = element.dimension_values(0)
    mean = element.dimension_values(1)
    neg_error = element.dimension_values(2)
    pos_idx = 3 if len(element.dimensions()) > 3 else 2
    pos_error = element.dimension_values(pos_idx)
    return (xs, mean - neg_error, mean + pos_error), style, {}


# Traceback (TypeError)
Traceback (most recent call last):

File "/usr/local/lib/python3.5/dist-packages/holoviews/plotting/mpl/element.py", line 508, in initialize_plot
handles = self.init_artists(ax, plot_data, plot_kwargs)

File "/usr/local/lib/python3.5/dist-packages/holoviews/plotting/mpl/chart.py", line 230, in init_artists
stack = fill_fn(*plot_data, **plot_kwargs)

File "/usr/local/lib/python3.5/dist-packages/matplotlib/__init__.py", line 1810, in inner
return func(ax, *args, **kwargs)

File "/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_axes.py", line 5118, in fill_between
collection = mcoll.PolyCollection(polys, **kwargs)

File "/usr/local/lib/python3.5/dist-packages/matplotlib/collections.py", line 933, in __init__
Collection.__init__(self, **kwargs)

File "/usr/local/lib/python3.5/dist-packages/matplotlib/collections.py", line 166, in __init__
self.update(kwargs)

File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 916, in update
ret = [_update_property(self, k, v) for k, v in props.items()]

File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 916, in <listcomp>
ret = [_update_property(self, k, v) for k, v in props.items()]

File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 913, in _update_property
return func(v)

File "/usr/local/lib/python3.5/dist-packages/matplotlib/collections.py", line 685, in set_facecolor
self._set_facecolor(c)

File "/usr/local/lib/python3.5/dist-packages/matplotlib/collections.py", line 668, in _set_facecolor
self._facecolors = mcolors.to_rgba_array(c, self._alpha)

File "/usr/local/lib/python3.5/dist-packages/matplotlib/colors.py", line 273, in to_rgba_array
result = np.empty((len(c), 4), float)

TypeError: object of type 'dim' has no len()

# Fixed code
def get_data(self, element, ranges, style):
    with abbreviated_exception():
        style = self._apply_transforms(element, ranges, style)
    xs = element.dimension_values(0)
    mean = element.dimension_values(1)
    neg_error = element.dimension_values(2)
    pos_idx = 3 if len(element.dimensions()) > 3 else 2
    pos_error = element.dimension_values(pos_idx)
    return (xs, mean - neg_error, mean + pos_error), style, {}
# Buggy code
def selected(self):
    index = self._selection.index
    data = [p for i, p in enumerate(self._stream.element.split()) if i in index]
    return self.element.clone(data)


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-42-14b61901e2c2> in <module>
----> 1 poly_annotator2.selected

~/projects/holoviews_annotators/holoviews/annotators.py in selected(self)
85     @property
86     def selected(self):
---> 87         selected = self.annotator.selected
88         if Store.current_backend == 'bokeh':
89             return selected.opts(clone=True, tools=['hover'])

~/projects/holoviews_annotators/holoviews/annotators.py in selected(self)
400         index = self._selection.index
401         data = [p for i, p in enumerate(self._stream.element.split()) if i in index]
--> 402         return self.element.clone(data)
403
404

AttributeError: 'PolyAnnotator' object has no attribute 'element'

# Fixed code
def selected(self):
    index = self._selection.index
    data = [p for i, p in enumerate(self._stream.element.split()) if i in index]
    return self.object.clone(data)