gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(
    self,
    dbid,
    dispersy_cid,
    name,
    description,
    nr_torrents,
    nr_favorite,
    nr_spam,
    modified,
):
    self.id = dbid
    self.name = name
    self.description = description
    self.cid = dispersy_cid
    self.modified = modified
    self.nr_torrents = nr_torrents
    self.nr_favorite = nr_favorite
    self.nr_spam = nr_spam


# Traceback (PackError)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: Traceback (most recent call last):
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/deprecated/community.py", line 330, in on_packet
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     self.decode_map[data[22]](source_address, data)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/community.py", line 104, in on_torrent_info_request
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     self.send_torrent_info_response(payload.infohash, peer=peer)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/community.py", line 211, in send_torrent_info_response
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     packet = self.create_message_packet(MSG_TORRENT_INFO_RESPONSE, info_response)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/pubsub.py", line 189, in create_message_packet
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     return self._ez_pack(self._prefix, message_type, [auth, dist, payload])
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/deprecated/community.py", line 100, in _ez_pack
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     packet += self.serializer.pack_multiple(format_list)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 191, in pack_multiple
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     out += self.pack(*packable)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 177, in pack
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     return self._packers[format].pack(*data)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: PackError: Could not pack item 2: ('I', None)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: error: cannot convert argument to integer

# Fixed code
def __init__(
    self,
    dbid,
    dispersy_cid,
    name,
    description,
    nr_torrents,
    nr_favorite,
    nr_spam,
    modified,
):
    self.id = dbid
    self.name = name
    self.description = description or ""
    self.cid = dispersy_cid
    self.modified = modified or -1
    self.nr_torrents = nr_torrents or 0
    self.nr_favorite = nr_favorite or 0
    self.nr_spam = nr_spam or 0
# Buggy code
def to_pack_list(self):
    data = [
        ("I", id),
        ("20s", str(self.cid)),
        ("varlenH", self.name),
        ("varlenH", self.description),
        ("I", self.nr_torrents),
        ("I", self.nr_favorite),
        ("I", self.nr_spam),
        ("I", self.modified),
    ]
    return data


# Traceback (PackError)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: Traceback (most recent call last):
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/deprecated/community.py", line 330, in on_packet
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     self.decode_map[data[22]](source_address, data)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/community.py", line 104, in on_torrent_info_request
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     self.send_torrent_info_response(payload.infohash, peer=peer)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/community.py", line 211, in send_torrent_info_response
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     packet = self.create_message_packet(MSG_TORRENT_INFO_RESPONSE, info_response)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/pubsub.py", line 189, in create_message_packet
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     return self._ez_pack(self._prefix, message_type, [auth, dist, payload])
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/deprecated/community.py", line 100, in _ez_pack
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     packet += self.serializer.pack_multiple(format_list)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 191, in pack_multiple
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     out += self.pack(*packable)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 177, in pack
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     return self._packers[format].pack(*data)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: PackError: Could not pack item 2: ('I', None)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: error: cannot convert argument to integer

# Fixed code
def to_pack_list(self):
    data = [
        ("I", id),
        ("20s", str(self.cid)),
        ("varlenH", self.name),
        ("varlenH", self.description.encode("utf-8")),
        ("I", self.nr_torrents),
        ("I", self.nr_favorite),
        ("I", self.nr_spam),
        ("I", self.modified),
    ]
    return data
# Buggy code
def from_unpack_list(
    cls,
    dbid,
    dispersy_cid,
    name,
    description,
    nr_torrents,
    nr_favorite,
    nr_spam,
    modified,
):
    return ChannelItemPayload(
        dbid,
        dispersy_cid,
        name,
        description,
        nr_torrents,
        nr_favorite,
        nr_spam,
        modified,
    )


# Traceback (PackError)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: Traceback (most recent call last):
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/deprecated/community.py", line 330, in on_packet
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     self.decode_map[data[22]](source_address, data)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/community.py", line 104, in on_torrent_info_request
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     self.send_torrent_info_response(payload.infohash, peer=peer)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/community.py", line 211, in send_torrent_info_response
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     packet = self.create_message_packet(MSG_TORRENT_INFO_RESPONSE, info_response)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/community/popularity/pubsub.py", line 189, in create_message_packet
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     return self._ez_pack(self._prefix, message_type, [auth, dist, payload])
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/deprecated/community.py", line 100, in _ez_pack
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     packet += self.serializer.pack_multiple(format_list)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 191, in pack_multiple
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     out += self.pack(*packable)
Jul 05 15:34:39 tribler-runner1 twistd[27982]:   File "/opt/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 177, in pack
Jul 05 15:34:39 tribler-runner1 twistd[27982]:     return self._packers[format].pack(*data)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: PackError: Could not pack item 2: ('I', None)
Jul 05 15:34:39 tribler-runner1 twistd[27982]: error: cannot convert argument to integer

# Fixed code
def from_unpack_list(
    cls,
    dbid,
    dispersy_cid,
    name,
    description,
    nr_torrents,
    nr_favorite,
    nr_spam,
    modified,
):
    return ChannelItemPayload(
        dbid,
        dispersy_cid,
        name.decode("utf-8"),
        description.decode("utf-8"),
        nr_torrents,
        nr_favorite,
        nr_spam,
        modified,
    )
# Buggy code
def update_download_hops(self, download, new_hops):
    """
    Update the amount of hops for a specified download. This can be done on runtime.
    """
    infohash = binascii.hexlify(download.tdef.get_infohash())
    self._logger.info("Updating the amount of hops of download %s", infohash)
    yield self.session.remove_download(download)

    # copy the old download_config and change the hop count
    dscfg = download.copy()
    dscfg.set_hops(new_hops)

    self.session.start_download_from_tdef(download.tdef, dscfg)


# Traceback (AttributeError)
ERROR   1529941365.43              rest_manager:53   (RESTRequest)  [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'TorrentDefNoMetainfo' object has no attribute 'get_name_utf8'
/usr/lib/python2.7/dist-packages/twisted/protocols/basic.py:571:dataReceived
/usr/lib/python2.7/dist-packages/twisted/web/http.py:1752:lineReceived
/usr/lib/python2.7/dist-packages/twisted/web/http.py:1845:allContentReceived
/usr/lib/python2.7/dist-packages/twisted/web/http.py:766:requestReceived
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/web/server.py:190:process
/usr/lib/python2.7/dist-packages/twisted/web/server.py:241:render
/usr/lib/python2.7/dist-packages/twisted/web/resource.py:250:render
/var/lib/tribler/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py:216:render_GET
]
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 190, in process
self.render(resrc)
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 241, in render
body = resrc.render(self)
File "/usr/lib/python2.7/dist-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/var/lib/tribler/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py", line 216, in render_GET
download_json = {"name": tdef.get_name_utf8(), "progress": state.get_progress(),
AttributeError: 'TorrentDefNoMetainfo' object has no attribute 'get_name_utf8'

# Fixed code
def update_download_hops(self, download, new_hops):
    """
    Update the amount of hops for a specified download. This can be done on runtime.
    """
    infohash = binascii.hexlify(download.tdef.get_infohash())
    self._logger.info("Updating the amount of hops of download %s", infohash)
    yield self.session.remove_download(download)

    # copy the old download_config and change the hop count
    dscfg = download.copy()
    dscfg.set_hops(new_hops)
    # If the user wants to change the hop count to 0, don't automatically bump this up to 1 anymore
    dscfg.set_safe_seeding(False)

    self.session.start_download_from_tdef(download.tdef, dscfg)
# Buggy code
def get_name_utf8(self):
    """
    Not all names are utf-8, attempt to construct it as utf-8 anyway.
    """
    out = self.get_name()
    try:
        # Try seeing if the delivered encoding is correct and we
        # can convert to utf8 without any issues.
        return out.decode(self.get_encoding()).encode("utf8").decode("utf8")
    except (LookupError, TypeError, ValueError):
        try:
            # The delivered encoding is incorrect, cast it to
            # latin1 and hope for the best (minor corruption).
            return out.decode("latin1").encode("utf8", "ignore").decode("utf8")
        except (TypeError, ValueError):
            # This is a very nasty string (e.g. u'\u266b'), remove the illegal entries.
            return out.encode("utf8", "ignore").decode("utf8")


# Traceback (AttributeError)
ERROR   1529941365.43              rest_manager:53   (RESTRequest)  [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'TorrentDefNoMetainfo' object has no attribute 'get_name_utf8'
/usr/lib/python2.7/dist-packages/twisted/protocols/basic.py:571:dataReceived
/usr/lib/python2.7/dist-packages/twisted/web/http.py:1752:lineReceived
/usr/lib/python2.7/dist-packages/twisted/web/http.py:1845:allContentReceived
/usr/lib/python2.7/dist-packages/twisted/web/http.py:766:requestReceived
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/web/server.py:190:process
/usr/lib/python2.7/dist-packages/twisted/web/server.py:241:render
/usr/lib/python2.7/dist-packages/twisted/web/resource.py:250:render
/var/lib/tribler/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py:216:render_GET
]
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 190, in process
self.render(resrc)
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 241, in render
body = resrc.render(self)
File "/usr/lib/python2.7/dist-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/var/lib/tribler/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py", line 216, in render_GET
download_json = {"name": tdef.get_name_utf8(), "progress": state.get_progress(),
AttributeError: 'TorrentDefNoMetainfo' object has no attribute 'get_name_utf8'

# Fixed code
def get_name_utf8(self):
    """
    Not all names are utf-8, attempt to construct it as utf-8 anyway.
    """
    return escape_as_utf8(self.get_name(), self.get_encoding())
# Buggy code
def get_ipv8_bootstrap_override(self):
    return self.config["ipv8"]["bootstrap_override"]


# Traceback (RuntimeError)
ERROR   1529233028.61            tribler_window:89   (root)  Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/core_manager.py", line 114, in on_received_state
raise RuntimeError(state['last_exception'])
RuntimeError: [Failure instance: Traceback: <class 'Tribler.pyipv8.ipv8.messaging.serialization.PackError'>: Could not pack item 0: ('4SH', '\x00\x00\x00\x03', u'7')
error: cannot convert argument to integer
/Library/Python/2.7/site-packages/twisted/internet/base.py:1199:run
/Library/Python/2.7/site-packages/twisted/internet/base.py:1208:mainLoop
/Library/Python/2.7/site-packages/twisted/internet/base.py:828:runUntilCurrent
/Library/Python/2.7/site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/Library/Python/2.7/site-packages/twisted/internet/defer.py:150:maybeDeferred
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8_service.py:109:on_tick
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8/peerdiscovery/discovery.py:58:take_step
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8/deprecated/community.py:327:get_new_introduction
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8/deprecated/community.py:174:bootstrap
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8/deprecated/community.py:304:walk_to
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8/deprecated/community.py:195:create_introduction_request
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8/deprecated/community.py:58:_ez_pack
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py:191:pack_multiple
/Users/martijndevos/Documents/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py:177:pack
]

# Fixed code
def get_ipv8_bootstrap_override(self):
    val = self.config["ipv8"]["bootstrap_override"]
    ip_port_tuple = (val[0], int(val[1])) if val else None
    return ip_port_tuple
# Buggy code
def play_active_item(self):
    self.window().left_menu_playlist.set_active_index(self.active_index)
    file_info = self.window().left_menu_playlist.get_file_info(self.active_index)
    file_index = file_info["index"]

    self.window().video_player_header_label.setText(
        file_info["name"] if file_info else "Unknown"
    )

    # reset video player controls
    self.mediaplayer.stop()
    self.window().video_player_play_pause_button.setIcon(self.play_icon)
    self.window().video_player_position_slider.setValue(0)

    media_filename = (
        "http://127.0.0.1:"
        + unicode(self.video_player_port)
        + "/"
        + self.active_infohash
        + "/"
        + unicode(file_index)
    )
    self.media = self.instance.media_new(media_filename)
    self.mediaplayer.set_media(self.media)
    self.media.parse()

    self.window().video_player_play_pause_button.setIcon(self.pause_icon)
    self.mediaplayer.play()

    self.window().video_player_play_pause_button.setEnabled(True)
    self.window().video_player_info_button.show()


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI/widgets/videoplayerpage.py", line 155, in on_files_list_loaded
File "TriblerGUI/widgets/videoplayerpage.py", line 178, in play_active_item
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def play_active_item(self):
    self.window().left_menu_playlist.set_active_index(self.active_index)
    file_info = self.window().left_menu_playlist.get_file_info(self.active_index)
    if file_info is None:
        return
    file_index = file_info["index"]

    self.window().video_player_header_label.setText(
        file_info["name"] if file_info else "Unknown"
    )

    # reset video player controls
    self.mediaplayer.stop()
    self.window().video_player_play_pause_button.setIcon(self.play_icon)
    self.window().video_player_position_slider.setValue(0)

    media_filename = (
        "http://127.0.0.1:"
        + unicode(self.video_player_port)
        + "/"
        + self.active_infohash
        + "/"
        + unicode(file_index)
    )
    self.media = self.instance.media_new(media_filename)
    self.mediaplayer.set_media(self.media)
    self.media.parse()

    self.window().video_player_play_pause_button.setIcon(self.pause_icon)
    self.mediaplayer.play()

    self.window().video_player_play_pause_button.setEnabled(True)
    self.window().video_player_info_button.show()
# Buggy code
def write_resource_logs(self, time_seconds):
    with open(self.resource_log_file, "a+") as output_file:
        output_file.write(
            "%s, %s, %s\n"
            % (
                time_seconds,
                self.memory_data[len(self.memory_data) - 1][1],
                self.cpu_data[len(self.cpu_data) - 1][1],
            )
        )


# Traceback (RuntimeError)
WARNING 1525734137.82                 community:1895 (DiscoveryCommunity)  drop a 889 byte packet invalid identifier [similarity-response] from {130.161.119.206:6422}
ERROR   1525734137.84            tribler_window:89   (root)  Traceback (most recent call last):
File "/home/tribler/tribler/TriblerGUI/core_manager.py", line 114, in on_received_state
raise RuntimeError(state['last_exception'])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.IndexError'>: list index out of range
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1199:run
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:1208:mainLoop
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:828:runUntilCurrent
/usr/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:150:maybeDeferred
/home/tribler/tribler/Tribler/Core/Modules/resource_monitor.py:148:check_resources
/home/tribler/tribler/Tribler/Core/Modules/resource_monitor.py:159:write_resource_logs
]

# Fixed code
def write_resource_logs(self, time_seconds):
    if not self.memory_data or not self.cpu_data:
        return
    with open(self.resource_log_file, "a+") as output_file:
        output_file.write(
            "%s, %s, %s\n"
            % (
                time_seconds,
                self.memory_data[len(self.memory_data) - 1][1],
                self.cpu_data[len(self.cpu_data) - 1][1],
            )
        )
# Buggy code
def received_token_balance(self, statistics):
    if not statistics:
        return

    statistics = statistics["statistics"]
    if "latest_block" in statistics:
        balance = (
            (
                statistics["latest_block"]["transaction"]["total_up"]
                - statistics["latest_block"]["transaction"]["total_down"]
            )
            / 1024
            / 1024
        )
        self.token_balance_label.setText("%d" % balance)
    else:
        self.token_balance_label.setText("0")


# Traceback (KeyError)
ERROR   1524667812.17            tribler_window:89   (root)  Traceback (most recent call last):
File "/home/sandip/tudelft/tribler/TriblerGUI/tribler_window.py", line 510, in received_token_balance
statistics = statistics["statistics"]
KeyError: 'statistics'

# Fixed code
def received_token_balance(self, statistics):
    if not statistics or "statistics" not in statistics:
        return

    statistics = statistics["statistics"]
    if "latest_block" in statistics:
        balance = (
            (
                statistics["latest_block"]["transaction"]["total_up"]
                - statistics["latest_block"]["transaction"]["total_down"]
            )
            / 1024
            / 1024
        )
        self.token_balance_label.setText("%d" % balance)
    else:
        self.token_balance_label.setText("0")
# Buggy code
def _stop_if_finished(self):
    if self.get_state().get_status() == DLSTATUS_SEEDING:
        mode = self.get_seeding_mode()
        if (
            mode == "never"
            or (
                mode == "ratio"
                and self.get_all_time_ratio() >= self.get_seeding_ratio()
            )
            or (mode == "time" and self.get_finished_time() >= self.get_seeding_time())
        ):
            self.stop()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 127, in on_read_data
RuntimeError: [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'LibtorrentDownloadImpl' object has no attribute 'get_all_time_ratio'
twisted/internet/base.py:1199:run
twisted/internet/base.py:1208:mainLoop
twisted/internet/base.py:828:runUntilCurrent
twisted/internet/task.py:239:__call__
--- <exception caught here> ---
twisted/internet/defer.py:150:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:577:_task_process_alerts
Tribler/Core/Libtorrent/LibtorrentMgr.py:387:process_alert
Tribler/Core/Libtorrent/__init__.py:17:invoke_func
Tribler/Core/Libtorrent/LibtorrentDownloadImpl.py:506:process_alert
Tribler/Core/Libtorrent/__init__.py:17:invoke_func
Tribler/Core/Libtorrent/LibtorrentDownloadImpl.py:644:on_torrent_finished_alert
Tribler/Core/Libtorrent/LibtorrentDownloadImpl.py:670:update_lt_status
Tribler/Core/Libtorrent/LibtorrentDownloadImpl.py:676:_stop_if_finished
]

# Fixed code
def _stop_if_finished(self):
    state = self.get_state()
    if state.get_status() == DLSTATUS_SEEDING:
        mode = self.get_seeding_mode()
        if (
            mode == "never"
            or (
                mode == "ratio"
                and state.get_seeding_ratio() >= self.get_seeding_ratio()
            )
            or (mode == "time" and state.get_seeding_time() >= self.get_seeding_time())
        ):
            self.stop()
# Buggy code
def __init__(self, session, infohash):
    DownloadBaseEndpoint.__init__(self, session)
    self.infohash = bytes(infohash.decode("hex"))
    self.putChild("torrent", DownloadExportTorrentEndpoint(session, self.infohash))


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def __init__(self, session, infohash):
    DownloadBaseEndpoint.__init__(self, session)
    self.infohash = bytes(infohash.decode("hex"))
    self.putChild("torrent", DownloadExportTorrentEndpoint(session, self.infohash))
    self.putChild("files", DownloadFilesEndpoint(session, self.infohash))
# Buggy code
def render_GET(self, request):
    """
    .. http:get:: /download/(string: infohash)/torrent

    A GET request to this endpoint returns the .torrent file associated with the specified download.

        **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/downloads/4344503b7e797ebf31582327a5baae35b11bda01/torrent

        **Example response**:

        The contents of the .torrent file.
    """
    download = self.session.get_download(self.infohash)
    if not download:
        return DownloadExportTorrentEndpoint.return_404(request)

    request.setHeader(b"content-type", "application/x-bittorrent")
    request.setHeader(
        b"Content-Disposition",
        "attachment; filename=%s.torrent" % self.infohash.encode("hex"),
    )
    return self.session.get_collected_torrent(self.infohash)


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def render_GET(self, request):
    """
    .. http:get:: /download/(string: infohash)/files

    A GET request to this endpoint returns the file information of a specific download.

        **Example request**:

            .. sourcecode:: none

                curl -X GET http://localhost:8085/downloads/4344503b7e797ebf31582327a5baae35b11bda01/files

        **Example response**:

        .. sourcecode:: javascript

            {
                "files": [{
                    "index": 1,
                    "name": "test.txt",
                    "size": 12345,
                    "included": True,
                    "progress": 0.5448
                }, ...]
            }
    """
    download = self.session.get_download(self.infohash)
    if not download:
        return DownloadExportTorrentEndpoint.return_404(request)

    return json.dumps({"files": self.get_files_info_json(download)})
# Buggy code
def received_token_balance(self, statistics):
    statistics = statistics["statistics"]
    if "latest_block" in statistics:
        balance = (
            (
                statistics["latest_block"]["transaction"]["total_up"]
                - statistics["latest_block"]["transaction"]["total_down"]
            )
            / 1024
            / 1024
        )
        self.token_balance_label.setText("%d" % balance)
    else:
        self.token_balance_label.setText("0")


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def received_token_balance(self, statistics):
    if not statistics:
        return

    statistics = statistics["statistics"]
    if "latest_block" in statistics:
        balance = (
            (
                statistics["latest_block"]["transaction"]["total_up"]
                - statistics["latest_block"]["transaction"]["total_down"]
            )
            / 1024
            / 1024
        )
        self.token_balance_label.setText("%d" % balance)
    else:
        self.token_balance_label.setText("0")
# Buggy code
def on_play_request_done(self, result):
    if not self:
        return
    self.window().left_menu_button_video_player.click()
    self.window().video_player_page.set_torrent_infohash(self.torrent_info["infohash"])
    self.window().left_menu_playlist.set_loading()


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def on_play_request_done(self, result):
    if not self:
        return
    self.window().left_menu_button_video_player.click()
    self.window().video_player_page.play_media_item(self.torrent_info["infohash"], -1)
# Buggy code
def on_play_file(self, file_info):
    self.window().left_menu_button_video_player.click()
    self.window().video_player_page.set_torrent_infohash(
        self.current_download["infohash"]
    )
    self.window().video_player_page.change_playing_index(
        file_info["index"], file_info["name"]
    )
    self.window().left_menu_playlist.set_files(self.current_download["files"])
    self.window().left_menu_playlist.set_active_index(file_info["index"])


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def on_play_file(self, file_info):
    self.window().left_menu_button_video_player.click()
    self.window().video_player_page.play_media_item(
        self.current_download["infohash"], file_info["index"]
    )
# Buggy code
def on_play_download_clicked(self):
    self.window().left_menu_button_video_player.click()
    self.window().video_player_page.set_torrent_infohash(
        self.selected_item.download_info["infohash"]
    )
    self.window().left_menu_playlist.set_loading()


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def on_play_download_clicked(self):
    self.window().left_menu_button_video_player.click()
    if (
        self.window().video_player_page.active_infohash
        != self.selected_item.download_info["infohash"]
    ):
        self.window().video_player_page.play_media_item(
            self.selected_item.download_info["infohash"], -1
        )
# Buggy code
def __init__(self, parent):
    QListWidget.__init__(self, parent)

    self.files_data = []
    self.loaded_list = False
    self.active_index = -1
    self.itemClicked.connect(self.on_item_clicked)
    self.itemDoubleClicked.connect(self.on_item_double_clicked)


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def __init__(self, parent):
    QListWidget.__init__(self, parent)

    self.files_data = []
    self.loaded_list = False
    self.loading_list = False
    self.active_index = -1
    self.infohash = None
    self.itemClicked.connect(self.on_item_clicked)
    self.itemDoubleClicked.connect(self.on_item_double_clicked)

    self.files_request_mgr = None
    self.files_request_timer = None
# Buggy code
def set_loading(self):
    self.clear()
    self.addItem("Loading...")
    self.loaded_list = False


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def set_loading(self):
    self.clear()
    self.addItem("Loading...")
    self.loaded_list = False
    self.loading_list = True
# Buggy code
def set_files(self, files):
    self.clear()
    self.files_data = []

    for file_info in files:
        if is_video_file(file_info["name"]):
            self.addItem(file_info["name"])
            self.files_data.append((file_info["index"], file_info["name"]))
    self.loaded_list = True


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def set_files(self, files):
    self.clear()
    self.files_data = []

    for file_info in files:
        if is_video_file(file_info["name"]):
            self.addItem(file_info["name"])
            self.files_data.append(file_info)
# Buggy code
def set_active_index(self, file_index):
    cur_ind = 0
    for index, _ in self.files_data:
        if index == file_index:
            self.item(cur_ind).setSelected(True)
            self.setFocus()
            break
        cur_ind += 1


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def set_active_index(self, file_index):
    cur_ind = 0
    for ind, file_info in enumerate(self.files_data):
        if ind == file_index:
            self.item(cur_ind).setSelected(True)
            self.setFocus()
            break
        cur_ind += 1
# Buggy code
def on_item_clicked(self, item):
    item_ind = self.row(item)
    if self.loaded_list:
        self.playing_item_change.emit(*self.files_data[item_ind])


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def on_item_clicked(self, item):
    item_ind = self.row(item)
    if self.loaded_list:
        self.playing_item_change.emit(item_ind)
# Buggy code
def update_with_download_info(self, download):
    if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
        self.window().left_menu_playlist.set_files(download["files"])

        # Play the video with the largest file index
        largest_file = None

        for file_info in download["files"]:
            if is_video_file(file_info["name"]) and (
                largest_file is None or file_info["size"] > largest_file["size"]
            ):
                largest_file = file_info

        if not largest_file:
            # We don't have a media file in this torrent. Reset everything and show an error
            ConfirmationDialog.show_error(
                self.window(),
                "No media files",
                "This download contains no media files.",
            )
            self.window().hide_left_menu_playlist()
            return

        self.window().left_menu_playlist.set_active_index(largest_file["index"])
        self.change_playing_index(largest_file["index"], largest_file["name"])

    self.window().video_player_info_button.popup.update(download)


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def update_with_download_info(self, download):
    self.window().video_player_info_button.popup.update(download)
# Buggy code
def change_playing_index(self, index, filename):
    self.active_index = index
    self.window().video_player_header_label.setText(filename)

    # reset video player controls
    self.mediaplayer.stop()
    self.window().video_player_play_pause_button.setIcon(self.play_icon)
    self.window().video_player_position_slider.setValue(0)

    media_filename = (
        "http://127.0.0.1:"
        + unicode(self.video_player_port)
        + "/"
        + self.active_infohash
        + "/"
        + unicode(index)
    )
    self.media = self.instance.media_new(media_filename)
    self.mediaplayer.set_media(self.media)
    self.media.parse()

    self.window().video_player_play_pause_button.setIcon(self.pause_icon)
    self.mediaplayer.play()

    self.window().video_player_play_pause_button.setEnabled(True)
    self.window().video_player_info_button.show()


# Traceback (KeyError)
ERROR   1522665876.61  tribler_window:92    Traceback (most recent call last):
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 165, in on_received_downloads
self.window().video_player_page.update_with_download_info(download)
File "/Users/martijndevos/Documents/tribler/TriblerGUI/widgets/videoplayerpage.py", line 121, in update_with_download_info
if len(download["files"]) > 0 and not self.window().left_menu_playlist.loaded_list:
KeyError: 'files'

# Fixed code
def change_playing_index(self, index):
    self.play_media_item(self.active_infohash, index)
# Buggy code
def on_export_download_request_done(self, filename, data):
    dest_path = os.path.join(self.export_dir, filename)
    try:
        torrent_file = open(dest_path, "wb")
        torrent_file.write(data)
        torrent_file.close()
    except IOError as exc:
        ConfirmationDialog.show_error(
            self.window(),
            "Error when exporting file",
            "An error occurred when exporting the torrent file: %s" % str(exc),
        )
    else:
        if self.window().tray_icon:
            self.window().tray_icon.showMessage(
                "Torrent file exported", "Torrent file exported to %s" % dest_path
            )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/quinten/Documents/tribler/TriblerGUI/widgets/downloadspage.py", line 163, in on_received_downloads
"Down: %s, Up: %s" % (format_speed(total_download), format_speed(total_upload)))
RuntimeError: wrapped C/C++ object of type QSystemTrayIcon has been deleted

# Fixed code
def on_export_download_request_done(self, filename, data):
    dest_path = os.path.join(self.export_dir, filename)
    try:
        torrent_file = open(dest_path, "wb")
        torrent_file.write(data)
        torrent_file.close()
    except IOError as exc:
        ConfirmationDialog.show_error(
            self.window(),
            "Error when exporting file",
            "An error occurred when exporting the torrent file: %s" % str(exc),
        )
    else:
        self.tray_show_message(
            "Torrent file exported", "Torrent file exported to %s" % dest_path
        )
# Buggy code
def __init__(self, config=None):
    """
    Create a new TriblerConfig instance.

    :param config: a ConfigObj instance
    :raises an InvalidConfigException if ConfigObj is invalid
    """
    self._logger = logging.getLogger(self.__class__.__name__)

    if config is None:
        file_name = os.path.join(self.get_default_state_dir(), FILENAME)
        if os.path.exists(file_name):
            config = ConfigObj(
                file_name, configspec=CONFIG_SPEC_PATH, encoding="latin_1"
            )
        else:
            config = ConfigObj(configspec=CONFIG_SPEC_PATH, encoding="latin_1")
    self.config = config
    self.validate()

    self.selected_ports = {}
    self._set_video_analyser_path()


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/quinten/Documents/tribler/TriblerGUI/tribler_window.py", line 633, in on_confirm_add_directory_dialog
self.tribler_settings['download_defaults']['saveas'], [], 0)
File "/home/quinten/Documents/tribler/TriblerGUI/tribler_window.py", line 369, in perform_start_download_request
if not is_dir_writable(destination):
File "/home/quinten/Documents/tribler/TriblerGUI/utilities.py", line 216, in is_dir_writable
if not os.path.exists(path):
File "/usr/lib/python2.7/genericpath.py", line 26, in exists
os.stat(path)
TypeError: coercing to Unicode: need string or buffer, NoneType found

# Fixed code
def __init__(self, config=None):
    """
    Create a new TriblerConfig instance.

    :param config: a ConfigObj instance
    :raises an InvalidConfigException if ConfigObj is invalid
    """
    self._logger = logging.getLogger(self.__class__.__name__)

    if config is None:
        file_name = os.path.join(self.get_default_state_dir(), FILENAME)
        if os.path.exists(file_name):
            config = ConfigObj(
                file_name, configspec=CONFIG_SPEC_PATH, encoding="latin_1"
            )
        else:
            config = ConfigObj(configspec=CONFIG_SPEC_PATH, encoding="latin_1")
    self.config = config
    self.validate()

    # set defaults downloads path
    if not self.config["download_defaults"]["saveas"]:
        self.config["download_defaults"]["saveas"] = get_default_dest_dir()
    self.selected_ports = {}
    self._set_video_analyser_path()
# Buggy code
def on_confirm_add_directory_dialog(self, action):
    if action == 0:
        for torrent_file in self.selected_torrent_files:
            escaped_uri = "file:%s" % quote_plus((torrent_file).encode("utf-8"))
            self.perform_start_download_request(
                escaped_uri,
                self.window().tribler_settings["download_defaults"][
                    "anonymity_enabled"
                ],
                self.window().tribler_settings["download_defaults"][
                    "safeseeding_enabled"
                ],
                self.tribler_settings["download_defaults"]["saveas"],
                [],
                0,
            )

    self.dialog.setParent(None)
    self.dialog = None


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/quinten/Documents/tribler/TriblerGUI/tribler_window.py", line 633, in on_confirm_add_directory_dialog
self.tribler_settings['download_defaults']['saveas'], [], 0)
File "/home/quinten/Documents/tribler/TriblerGUI/tribler_window.py", line 369, in perform_start_download_request
if not is_dir_writable(destination):
File "/home/quinten/Documents/tribler/TriblerGUI/utilities.py", line 216, in is_dir_writable
if not os.path.exists(path):
File "/usr/lib/python2.7/genericpath.py", line 26, in exists
os.stat(path)
TypeError: coercing to Unicode: need string or buffer, NoneType found

# Fixed code
def on_confirm_add_directory_dialog(self, action):
    if action == 0:
        for torrent_file in self.selected_torrent_files:
            escaped_uri = "file:%s" % pathname2url(torrent_file)
            self.perform_start_download_request(
                escaped_uri,
                self.window().tribler_settings["download_defaults"][
                    "anonymity_enabled"
                ],
                self.window().tribler_settings["download_defaults"][
                    "safeseeding_enabled"
                ],
                self.tribler_settings["download_defaults"]["saveas"],
                [],
                0,
            )

    self.dialog.setParent(None)
    self.dialog = None
# Buggy code
def __init__(self, wallet_dir):
    super(BitcoinWallet, self).__init__()

    if self.TESTNET:
        bitcoin.set_testnet()
        network.set_testnet()

    self.wallet_dir = wallet_dir
    self.wallet_file = "tbtc_wallet" if self.TESTNET else "btc_wallet"
    self.min_confirmations = 0
    self.created = False
    self.daemon = None
    keychain_pw = self.get_wallet_password()
    self.wallet_password = (
        keychain_pw if keychain_pw else None
    )  # Convert empty passwords to None
    self.storage = None
    self.wallet = None
    self.load_wallet(self.wallet_dir, self.wallet_file)


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def __init__(self, wallet_dir):
    super(BitcoinWallet, self).__init__()

    if self.TESTNET:
        bitcoin.set_testnet()
        network.set_testnet()

    self.wallet_dir = wallet_dir
    self.wallet_file = "tbtc_wallet" if self.TESTNET else "btc_wallet"
    self.min_confirmations = 0
    self.daemon = None
    self.wallet_password = None
    self.storage = None
    self.wallet = None

    self.initialize_storage(self.wallet_dir, self.wallet_file)
    if self.created:
        # If the wallet has been created already, we try to unlock it.
        self.unlock_wallet()
# Buggy code
def run_on_thread(thread_method):
    # We are running code that writes to the wallet on a separate thread.
    # This is done because ethereum does not allow writing to a wallet from a daemon thread.
    wallet_thread = Thread(target=thread_method, name="ethereum-create-wallet")
    wallet_thread.setDaemon(False)
    wallet_thread.start()
    wallet_thread.join()


# Traceback (EOFError)
Gkr-Message: secret service operation failed: The name org.freedesktop.secrets was not provided by any .service files
Exception in thread tribler-pipe-read:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 173, in <lambda>
pipe_thread = Thread(target=lambda: self.pipe_wait(parent_conn), name="tribler-pipe-read")
File "/home/bram/git/tribler/TriblerGUI/core_manager.py", line 158, in pipe_wait
cmd, arg = child_conn.recv()
EOFError

# Fixed code
def run_on_thread(thread_method):
    # We are running code that writes to the wallet on a separate thread.
    # This is done because Electrum does not allow writing to a wallet from a daemon thread.
    wallet_thread = Thread(target=thread_method, name="ethereum-create-wallet")
    wallet_thread.setDaemon(False)
    wallet_thread.start()
    wallet_thread.join()