gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, db):
    self._batch = db._db.write_batch()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 130, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'plyvel._plyvel.IOError'>: IO error: C:\Users\Blake\AppData\Roaming\.Tribler\collected_torrents\000263.ldb: Could not create random access file.
lib\site-packages\twisted\internet\base.py:1243:run
lib\site-packages\twisted\internet\base.py:1252:mainLoop
lib\site-packages\twisted\internet\base.py:878:runUntilCurrent
lib\site-packages\twisted\internet\task.py:239:__call__
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:150:maybeDeferred
Tribler\Core\leveldbstore.py:141:flush
Tribler\Core\plyveladapter.py:25:Write
plyvel\_plyvel.pyx:599:plyvel._plyvel.WriteBatch.write (plyvel/_plyvel.cpp:9519)
plyvel\_plyvel.pyx:80:plyvel._plyvel.raise_for_status (plyvel/_plyvel.cpp:1689)
]

# Fixed code
def __init__(self, db):
    # Using transaction and sync in Windows to prevent CorruptionError
    self._batch = db._db.write_batch(transaction=True, sync=True)
# Buggy code
def on_subscription_status(self, source_address, data):
    """
    Message handler for content subscription message. Content subscription message is sent by the publisher stating
    the status of the subscription in response to subscribe or unsubscribe request.

    If the subscription message has subscribe=True, it means the subscription was successful, so the peer is added
    to the subscriber. In other case, publisher is removed if it is still present in the publishers list.
    """
    auth, _, payload = self._ez_unpack_auth(ContentSubscription, data)
    peer = self.get_peer_from_auth(auth, source_address)

    cache = self.request_cache.pop("request", payload.identifier)
    if not cache:
        return

    if payload.subscribe:
        self.publishers.add(peer)
    elif peer in self.publishers:
        self.publishers.remove(peer)


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/quinten/Documents/tribler/Tribler/pyipv8/ipv8/deprecated/community.py", line 270, in on_packet
self.decode_map[msg_id](source_address, data)
File "/home/quinten/Documents/tribler/Tribler/community/popularity/pubsub.py", line 173, in on_subscription_status
cache = self.request_cache.pop(u'request', payload.identifier)
File "/home/quinten/Documents/tribler/Tribler/pyipv8/ipv8/requestcache.py", line 135, in pop
cache = self._identifiers.pop(identifier)
KeyError: u'request:59006'

# Fixed code
def on_subscription_status(self, source_address, data):
    """
    Message handler for content subscription message. Content subscription message is sent by the publisher stating
    the status of the subscription in response to subscribe or unsubscribe request.

    If the subscription message has subscribe=True, it means the subscription was successful, so the peer is added
    to the subscriber. In other case, publisher is removed if it is still present in the publishers list.
    """
    auth, _, payload = self._ez_unpack_auth(ContentSubscription, data)
    peer = self.get_peer_from_auth(auth, source_address)

    if not self.request_cache.has("request", payload.identifier):
        return
    self.request_cache.pop("request", payload.identifier)

    if payload.subscribe:
        self.publishers.add(peer)
    elif peer in self.publishers:
        self.publishers.remove(peer)
# Buggy code
def get_info_from_handle(handle):
    # In libtorrent 0.16.18, the torrent_handle.torrent_file method is not available.
    # this method checks whether the torrent_file method is available on a given handle.
    # If not, fall back on the deprecated get_torrent_info
    try:
        if hasattr(handle, "torrent_file"):
            return handle.torrent_file()
        return handle.get_torrent_info()
    except RuntimeError as e:  # This can happen when the torrent handle is invalid.
        logger.warning("Got exception when fetching info from handle: %s", str(e))
        return None


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 130, in on_read_data
RuntimeError: [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'files'
lib\site-packages\twisted\internet\base.py:878:runUntilCurrent
Tribler\Core\Libtorrent\LibtorrentDownloadImpl.py:229:schedule_create_engine
Tribler\Core\Libtorrent\LibtorrentDownloadImpl.py:354:network_create_engine_wrapper
lib\site-packages\twisted\internet\defer.py:310:addCallbacks
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:653:_runCallbacks
Tribler\Core\Libtorrent\LibtorrentDownloadImpl.py:330:on_torrent_added
Tribler\Core\Libtorrent\__init__.py:17:invoke_func
Tribler\Core\Libtorrent\LibtorrentDownloadImpl.py:704:set_selected_files
]

# Fixed code
def get_info_from_handle(handle):
    # In libtorrent 0.16.18, the torrent_handle.torrent_file method is not available.
    # this method checks whether the torrent_file method is available on a given handle.
    # If not, fall back on the deprecated get_torrent_info
    try:
        if hasattr(handle, "torrent_file"):
            return handle.torrent_file()
        return handle.get_torrent_info()
    except AttributeError as ae:
        logger.warning("No torrent info found from handle: %s", str(ae))
        return None
    except RuntimeError as e:  # This can happen when the torrent handle is invalid.
        logger.warning("Got exception when fetching info from handle: %s", str(e))
        return None
# Buggy code
def on_error(error):
    request.setResponseCode(http.INTERNAL_SERVER_ERROR)
    request.write(json.dumps({"error": error.getErrorMessage()}))
    request.finish()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 130, in on_read_data
RuntimeError: [Failure instance: Traceback: <type 'exceptions.UnicodeDecodeError'>: 'utf8' codec can't decode byte 0x75 in position 33: could not dump:
dict[error]->str::'TCP connection timed out: 10060: \x90...\xc5\
lib\site-packages\twisted\internet\base.py:1080:connectionFailed
lib\site-packages\twisted\internet\endpoints.py:246:clientConnectionFailed
lib\site-packages\twisted\internet\defer.py:496:errback
lib\site-packages\twisted\internet\defer.py:563:_startRunCallbacks
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:649:_runCallbacks
Tribler\Core\Modules\restapi\torrentinfo_endpoint.py:93:on_lookup_error
Tribler\Core\Utilities\json_util.py:100:dumps
]

# Fixed code
def on_error(error):
    request.setResponseCode(http.INTERNAL_SERVER_ERROR)
    request.write(json.dumps({"error": unichar_string(error.getErrorMessage())}))
    request.finish()
# Buggy code
def on_lookup_error(failure):
    failure.trap(ConnectError, DNSLookupError, HttpError, ConnectionLost)
    request.setResponseCode(http.INTERNAL_SERVER_ERROR)
    request.write(json.dumps({"error": failure.getErrorMessage()}))
    self.finish_request(request)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 130, in on_read_data
RuntimeError: [Failure instance: Traceback: <type 'exceptions.UnicodeDecodeError'>: 'utf8' codec can't decode byte 0x75 in position 33: could not dump:
dict[error]->str::'TCP connection timed out: 10060: \x90...\xc5\
lib\site-packages\twisted\internet\base.py:1080:connectionFailed
lib\site-packages\twisted\internet\endpoints.py:246:clientConnectionFailed
lib\site-packages\twisted\internet\defer.py:496:errback
lib\site-packages\twisted\internet\defer.py:563:_startRunCallbacks
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:649:_runCallbacks
Tribler\Core\Modules\restapi\torrentinfo_endpoint.py:93:on_lookup_error
Tribler\Core\Utilities\json_util.py:100:dumps
]

# Fixed code
def on_lookup_error(failure):
    failure.trap(ConnectError, DNSLookupError, HttpError, ConnectionLost)
    request.setResponseCode(http.INTERNAL_SERVER_ERROR)
    request.write(json.dumps({"error": unichar_string(failure.getErrorMessage())}))
    self.finish_request(request)
# Buggy code
def get_magnet(self):
    return (
        "magnet:?xt=urn:btih:%s&dn=%s"
        % (str(self.infohash).encode("hex"), str(self.title).encode("utf8"))
    ) + (
        "&tr=%s" % (str(self.tracker_info).encode("utf8")) if self.tracker_info else ""
    )


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/home/quinten/.local/lib/python2.7/site-packages/twisted/web/server.py", line 198, in process
self.render(resrc)
File "/home/quinten/.local/lib/python2.7/site-packages/twisted/web/server.py", line 258, in render
body = resrc.render(self)
File "/home/quinten/.local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/home/quinten/Documents/tribler/Tribler/Core/Modules/restapi/torrents_endpoint.py", line 319, in render_GET
magnet = torrent_md.get_magnet()
File "/home/quinten/Documents/tribler/Tribler/Core/Modules/MetadataStore/OrmBindings/torrent_metadata.py", line 22, in get_magnet
(str(self.infohash).encode('hex'), str(self.title).encode('utf8'))) + \
UnicodeEncodeError: 'ascii' codec can't encode character u'\U0001f4a9' in position 0: ordinal not in range(128)

# Fixed code
def get_magnet(self):
    return (
        "magnet:?xt=urn:btih:%s&dn=%s" % (str(self.infohash).encode("hex"), self.title)
    ) + ("&tr=%s" % self.tracker_info if self.tracker_info else "")
# Buggy code
def update_with_torrent(self, torrent):
    self.show_torrent = True
    self.torrent_info = torrent
    self.thumbnail_widget.initialize(torrent["name"], HOME_ITEM_FONT_SIZE)
    self.main_label.setText(torrent["name"])
    self.category_label.setText(torrent["category"].lower())
    self.category_label.adjustSize()
    self.category_label.setHidden(False)
    self.setCursor(Qt.ArrowCursor)
    self.detail_label.setText("Size: " + format_size(torrent["size"]))


# Traceback (AttributeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\homepage.py", line 89, in received_popular_torrents
File "TriblerGUI\widgets\home_recommended_item.py", line 83, in update_with_torrent
AttributeError: 'NoneType' object has no attribute 'lower'

# Fixed code
def update_with_torrent(self, torrent):
    if not torrent:
        return
    self.show_torrent = True
    self.torrent_info = torrent
    self.thumbnail_widget.initialize(torrent["name"], HOME_ITEM_FONT_SIZE)
    self.main_label.setText(torrent["name"])
    self.category_label.setText(torrent["category"].lower())
    self.category_label.adjustSize()
    self.category_label.setHidden(False)
    self.setCursor(Qt.ArrowCursor)
    self.detail_label.setText("Size: " + format_size(torrent["size"]))
# Buggy code
def update_with_channel(self, channel):
    self.show_torrent = False
    self.channel_info = channel
    self.thumbnail_widget.initialize(channel["name"], HOME_ITEM_FONT_SIZE)

    self.main_label.setText(channel["name"])
    self.detail_label.setText("Updated " + pretty_date(channel["modified"]))
    self.category_label.setHidden(True)
    self.setCursor(Qt.PointingHandCursor)


# Traceback (AttributeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\homepage.py", line 89, in received_popular_torrents
File "TriblerGUI\widgets\home_recommended_item.py", line 83, in update_with_torrent
AttributeError: 'NoneType' object has no attribute 'lower'

# Fixed code
def update_with_channel(self, channel):
    if not channel:
        return
    self.show_torrent = False
    self.channel_info = channel
    self.thumbnail_widget.initialize(channel["name"], HOME_ITEM_FONT_SIZE)

    self.main_label.setText(channel["name"])
    self.detail_label.setText("Updated " + pretty_date(channel["modified"]))
    self.category_label.setHidden(True)
    self.setCursor(Qt.PointingHandCursor)
# Buggy code
def do_payout(self, mid):
    """
    Perform a payout to a given mid. First, determine the outstanding balance. Then resolve the node in the DHT.
    """
    if mid not in self.tribler_peers:
        return

    total_bytes = 0
    for balance in self.tribler_peers[mid].itervalues():
        total_bytes += balance

    def on_nodes(nodes):
        self.logger.debug("Received %d nodes for DHT lookup", len(nodes))
        if nodes:
            self.bandwidth_wallet.trustchain.sign_block(
                nodes[0],
                public_key=nodes[0].public_key.key_to_bin(),
                block_type="tribler_bandwidth",
                transaction={"up": 0, "down": total_bytes},
            )

    if total_bytes >= 1024 * 1024:  # Do at least 1MB payouts
        self.logger.info(
            "Doing direct payout to %s (%d bytes)", mid.encode("hex"), total_bytes
        )
        self.dht.connect_peer(mid).addCallback(on_nodes)

    # Remove the outstanding bytes; otherwise we will payout again
    self.tribler_peers.pop(mid, None)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 130, in on_read_data
RuntimeError: [Failure instance: Traceback (failure with no frames): <type 'exceptions.RuntimeError'>: Node Peer<{IP}:7759, iIfgmKR5QBqZeRTUTghJK4KARLY=> timeout
]

# Fixed code
def do_payout(self, mid):
    """
    Perform a payout to a given mid. First, determine the outstanding balance. Then resolve the node in the DHT.
    """
    if mid not in self.tribler_peers:
        return

    total_bytes = 0
    for balance in self.tribler_peers[mid].itervalues():
        total_bytes += balance

    def on_nodes(nodes):
        self.logger.debug("Received %d nodes for DHT lookup", len(nodes))
        if nodes:
            self.bandwidth_wallet.trustchain.sign_block(
                nodes[0],
                public_key=nodes[0].public_key.key_to_bin(),
                block_type="tribler_bandwidth",
                transaction={"up": 0, "down": total_bytes},
            )

    if total_bytes >= 1024 * 1024:  # Do at least 1MB payouts
        self.logger.info(
            "Doing direct payout to %s (%d bytes)", mid.encode("hex"), total_bytes
        )
        self.dht.connect_peer(mid).addCallbacks(on_nodes, lambda _: on_nodes([]))

    # Remove the outstanding bytes; otherwise we will payout again
    self.tribler_peers.pop(mid, None)
# Buggy code
def _on_add_failed(failure):
    failure.trap(ValueError, DuplicateTorrentFileError)
    self._logger.exception(failure.value)
    request.write(BaseChannelsEndpoint.return_500(self, request, failure.value))
    request.finish()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 130, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'twisted.web.error.SchemeNotSupported'>: Unsupported scheme: ''
lib\site-packages\twisted\internet\defer.py:567:_startRunCallbacks
lib\site-packages\twisted\internet\defer.py:653:_runCallbacks
Tribler\Core\Utilities\utilities.py:363:_on_response
Tribler\Core\Utilities\utilities.py:370:http_get
--- <exception caught here> ---
lib\site-packages\twisted\web\client.py:1633:request
lib\site-packages\twisted\web\client.py:1617:_getEndpoint
lib\site-packages\twisted\web\client.py:1497:endpointForURI
]

# Fixed code
def _on_add_failed(failure):
    failure.trap(ValueError, DuplicateTorrentFileError, SchemeNotSupported)
    self._logger.exception(failure.value)
    request.write(BaseChannelsEndpoint.return_500(self, request, failure.value))
    request.finish()
# Buggy code
def render_GET(self, request):
    """
    .. http:get:: /debug/cpu/history

    A GET request to this endpoint returns information about CPU usage history in the form of a list.

        **Example request**:

        .. sourcecode:: none

            curl -X GET http://localhost:8085/debug/cpu/history

        **Example response**:

        .. sourcecode:: javascript

            {
                "cpu_history": [{
                    "time": 1504015291214,
                    "cpu": 3.4,
                }, ...]
            }
    """
    return json.dumps(
        {"cpu_history": self.session.lm.resource_monitor.get_cpu_history_dict()}
    )


# Traceback (AttributeError)
ERROR   1538640159.18              rest_manager:53   (RESTRequest)  [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'get_cpu_history_dict'
/home/sandip/.local/lib/python2.7/site-packages/twisted/protocols/basic.py:572:dataReceived
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/http.py:2099:lineReceived
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/http.py:2190:allContentReceived
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/http.py:917:requestReceived
--- <exception caught here> ---
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/server.py:198:process
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/server.py:258:render
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/resource.py:250:render
/home/sandip/tudelft/tribler/Tribler/Core/Modules/restapi/debug_endpoint.py:311:render_GET
]
Traceback (most recent call last):
File "/home/sandip/.local/lib/python2.7/site-packages/twisted/web/server.py", line 198, in process
self.render(resrc)
File "/home/sandip/.local/lib/python2.7/site-packages/twisted/web/server.py", line 258, in render
body = resrc.render(self)
File "/home/sandip/.local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/home/sandip/tudelft/tribler/Tribler/Core/Modules/restapi/debug_endpoint.py", line 311, in render_GET
return json.dumps({"cpu_history": self.session.lm.resource_monitor.get_cpu_history_dict()})
AttributeError: 'NoneType' object has no attribute 'get_cpu_history_dict'

# Fixed code
def render_GET(self, request):
    """
    .. http:get:: /debug/cpu/history

    A GET request to this endpoint returns information about CPU usage history in the form of a list.

        **Example request**:

        .. sourcecode:: none

            curl -X GET http://localhost:8085/debug/cpu/history

        **Example response**:

        .. sourcecode:: javascript

            {
                "cpu_history": [{
                    "time": 1504015291214,
                    "cpu": 3.4,
                }, ...]
            }
    """
    history = (
        self.session.lm.resource_monitor.get_cpu_history_dict()
        if self.session.lm.resource_monitor
        else {}
    )
    return json.dumps({"cpu_history": history})
# Buggy code
def closeEvent(self, close_event):
    if self.cpu_plot_timer:
        self.cpu_plot_timer.stop()

    if self.memory_plot_timer:
        self.memory_plot_timer.stop()


# Traceback (AttributeError)
ERROR   1538640159.18              rest_manager:53   (RESTRequest)  [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'get_cpu_history_dict'
/home/sandip/.local/lib/python2.7/site-packages/twisted/protocols/basic.py:572:dataReceived
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/http.py:2099:lineReceived
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/http.py:2190:allContentReceived
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/http.py:917:requestReceived
--- <exception caught here> ---
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/server.py:198:process
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/server.py:258:render
/home/sandip/.local/lib/python2.7/site-packages/twisted/web/resource.py:250:render
/home/sandip/tudelft/tribler/Tribler/Core/Modules/restapi/debug_endpoint.py:311:render_GET
]
Traceback (most recent call last):
File "/home/sandip/.local/lib/python2.7/site-packages/twisted/web/server.py", line 198, in process
self.render(resrc)
File "/home/sandip/.local/lib/python2.7/site-packages/twisted/web/server.py", line 258, in render
body = resrc.render(self)
File "/home/sandip/.local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/home/sandip/tudelft/tribler/Tribler/Core/Modules/restapi/debug_endpoint.py", line 311, in render_GET
return json.dumps({"cpu_history": self.session.lm.resource_monitor.get_cpu_history_dict()})
AttributeError: 'NoneType' object has no attribute 'get_cpu_history_dict'

# Fixed code
def closeEvent(self, close_event):
    self.request_mgr.cancel_request()
    if self.cpu_plot_timer:
        self.cpu_plot_timer.stop()

    if self.memory_plot_timer:
        self.memory_plot_timer.stop()
# Buggy code
def render_GET(self, request):
    """
    .. http:get:: /debug/profiler

    A GET request to this endpoint returns information about the state of the profiler.
    This state is either STARTED or STOPPED.

        **Example request**:

        .. sourcecode:: none

            curl -X GET http://localhost:8085/debug/profiler

        **Example response**:

        .. sourcecode:: javascript

            {
                "state": "STARTED"
            }
    """
    return json.dumps(
        {
            "state": "STARTED"
            if self.session.lm.resource_monitor.profiler_running
            else "STOPPED"
        }
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/quinten/.local/lib/python2.7/site-packages/twisted/web/server.py", line 198, in process
self.render(resrc)
File "/home/quinten/.local/lib/python2.7/site-packages/twisted/web/server.py", line 258, in render
body = resrc.render(self)
File "/home/quinten/.local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/home/quinten/Documents/tribler/Tribler/pyipv8/ipv8/REST/overlays_endpoint.py", line 66, in render_GET
return json.dumps({"statistics": self.get_statistics()})
File "/home/quinten/Documents/tribler/Tribler/pyipv8/ipv8/REST/overlays_endpoint.py", line 53, in get_statistics
overlay.__class__.__name__: self.statistics_by_name(statistics, overlay)
File "/home/quinten/Documents/tribler/Tribler/pyipv8/ipv8/REST/overlays_endpoint.py", line 60, in statistics_by_name
mapped_name = str(message_id) + ":" + overlay.decode_map[chr(ord(message_id))].__name__
TypeError: ord() expected string of length 1, but int found

# Fixed code
def render_GET(self, request):
    """
    .. http:get:: /debug/profiler

    A GET request to this endpoint returns information about the state of the profiler.
    This state is either STARTED or STOPPED.

        **Example request**:

        .. sourcecode:: none

            curl -X GET http://localhost:8085/debug/profiler

        **Example response**:

        .. sourcecode:: javascript

            {
                "state": "STARTED"
            }
    """
    monitor_enabled = self.session.config.get_resource_monitor_enabled()
    state = (
        "STARTED"
        if (monitor_enabled and self.session.lm.resource_monitor.profiler_running)
        else "STOPPED"
    )
    return json.dumps({"state": state})
# Buggy code
def on_ipv8_community_stats(self, data):
    if not data:
        return
    self.window().communities_tree_widget.clear()
    for overlay in data["ipv8_overlay_statistics"]:
        item = QTreeWidgetItem(self.window().communities_tree_widget)
        item.setText(0, overlay["overlay_name"])
        item.setText(1, overlay["master_peer"][:6])
        item.setText(2, overlay["my_peer"][:6])
        item.setText(3, "%s" % len(overlay["peers"]))
        self.window().communities_tree_widget.addTopLevelItem(item)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 130, in on_read_data
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "run_tribler.py", line 84, in <module>

File "run_tribler.py", line 76, in start_tribler_core

File "lib\site-packages\twisted\internet\base.py", line 1243, in run

File "lib\site-packages\twisted\internet\base.py", line 1252, in mainLoop

--- <exception caught here> ---
File "lib\site-packages\twisted\internet\base.py", line 878, in runUntilCurrent

File "Tribler\dispersy\util.py", line 150, in wrapper

File "Tribler\Core\TFTP\handler.py", line 194, in _process_callbacks

File "Tribler\Core\TFTP\handler.py", line 263, in <lambda>

File "Tribler\pyipv8\ipv8\util.py", line 14, in helper

File "Tribler\pyipv8\ipv8\util.py", line 26, in blockingCallFromThread

File "Tribler\Core\RemoteTorrentHandler.py", line 600, in _on_download_successful

File "Tribler\pyipv8\ipv8\util.py", line 14, in helper

File "Tribler\pyipv8\ipv8\util.py", line 26, in blockingCallFromThread

File "Tribler\Core\RemoteTorrentHandler.py", line 167, in save_torrent

File "Tribler\Core\CacheDB\SqliteCacheDBHandler.py", line 313, in addExternalTorrent

File "Tribler\Core\CacheDB\SqliteCacheDBHandler.py", line 416, in _addTorrentToDB

File "Tribler\Core\CacheDB\SqliteCacheDBHandler.py", line 397, in _get_database_dict

File "Tribler\Core\Category\Category.py", line 70, in calculateCategory

exceptions.IndexError: list index out of range

# Fixed code
def on_ipv8_community_stats(self, data):
    if not data:
        return
    self.window().communities_tree_widget.clear()
    for overlay in data["ipv8_overlay_statistics"]:
        item = QTreeWidgetItem(self.window().communities_tree_widget)
        item.setText(0, overlay["overlay_name"])
        item.setText(1, overlay["master_peer"][-6:])
        item.setText(2, overlay["my_peer"][-6:])
        item.setText(3, "%s" % len(overlay["peers"]))
        self.window().communities_tree_widget.addTopLevelItem(item)
# Buggy code
def encode_values(values):
    return "".join([pack("!H", len(value)) + str(value) for value in values])


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/home/vader/.local/lib/python2.7/site-packages/twisted/web/server.py", line 198, in process
self.render(resrc)
File "/home/vader/.local/lib/python2.7/site-packages/twisted/web/server.py", line 258, in render
body = resrc.render(self)
File "/home/vader/.local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/tmp/triblerTribler/Core/Modules/restapi/search_endpoint.py", line 84, in render_GET
self.session.search_remote_torrents(keywords)
File "/tmp/triblerTribler/Core/Session.py", line 684, in search_remote_torrents
return self.lm.search_manager.search_for_torrents(keywords)
File "/tmp/triblerTribler/pyipv8/ipv8/util.py", line 14, in helper
return blockingCallFromThread(reactor, func, *args, **kargs)
File "/tmp/triblerTribler/pyipv8/ipv8/util.py", line 26, in blockingCallFromThread
return f(*args, **kwargs)
File "/tmp/triblerTribler/Core/Modules/search_manager.py", line 61, in search_for_torrents
self.session.lm.popularity_community.send_torrent_search_request(keywords)
File "/tmp/triblerTribler/community/popularity/community.py", line 265, in send_torrent_search_request
self.send_content_info_request(SEARCH_TORRENT_REQUEST, query)
File "/tmp/triblerTribler/community/popularity/community.py", line 228, in send_content_info_request
packet = self.create_message_packet(MSG_CONTENT_INFO_REQUEST, content_request)
File "/tmp/triblerTribler/community/popularity/pubsub.py", line 188, in create_message_packet
payload = payload if isinstance(payload, list) else payload.to_pack_list()
File "/tmp/triblerTribler/community/popularity/payload.py", line 273, in to_pack_list
('varlenH', encode_values(self.query_list)),
File "/tmp/triblerTribler/community/popularity/payload.py", line 8, in encode_values
return ''.join([pack('!H', len(value)) + str(value) for value in values])
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

# Fixed code
def encode_values(values):
    encoded_list = [value.encode("utf-8") for value in values]
    return "".join([pack("!H", len(encoded)) + encoded for encoded in encoded_list])
# Buggy code
def decode_values(values_str):
    values = []
    index = 0
    while index < len(values_str):
        length = unpack_from("!H", values_str)[0]
        index += calcsize("!H")
        values.append(values_str[index : index + length])
        index += length
    return values


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/home/vader/.local/lib/python2.7/site-packages/twisted/web/server.py", line 198, in process
self.render(resrc)
File "/home/vader/.local/lib/python2.7/site-packages/twisted/web/server.py", line 258, in render
body = resrc.render(self)
File "/home/vader/.local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/tmp/triblerTribler/Core/Modules/restapi/search_endpoint.py", line 84, in render_GET
self.session.search_remote_torrents(keywords)
File "/tmp/triblerTribler/Core/Session.py", line 684, in search_remote_torrents
return self.lm.search_manager.search_for_torrents(keywords)
File "/tmp/triblerTribler/pyipv8/ipv8/util.py", line 14, in helper
return blockingCallFromThread(reactor, func, *args, **kargs)
File "/tmp/triblerTribler/pyipv8/ipv8/util.py", line 26, in blockingCallFromThread
return f(*args, **kwargs)
File "/tmp/triblerTribler/Core/Modules/search_manager.py", line 61, in search_for_torrents
self.session.lm.popularity_community.send_torrent_search_request(keywords)
File "/tmp/triblerTribler/community/popularity/community.py", line 265, in send_torrent_search_request
self.send_content_info_request(SEARCH_TORRENT_REQUEST, query)
File "/tmp/triblerTribler/community/popularity/community.py", line 228, in send_content_info_request
packet = self.create_message_packet(MSG_CONTENT_INFO_REQUEST, content_request)
File "/tmp/triblerTribler/community/popularity/pubsub.py", line 188, in create_message_packet
payload = payload if isinstance(payload, list) else payload.to_pack_list()
File "/tmp/triblerTribler/community/popularity/payload.py", line 273, in to_pack_list
('varlenH', encode_values(self.query_list)),
File "/tmp/triblerTribler/community/popularity/payload.py", line 8, in encode_values
return ''.join([pack('!H', len(value)) + str(value) for value in values])
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

# Fixed code
def decode_values(values_str):
    values = []
    index = 0
    while index < len(values_str):
        length = unpack_from("!H", values_str[index:])[0]
        index += calcsize("!H")
        values.append(values_str[index : index + length].decode("utf-8"))
        index += length
    return values
# Buggy code
def show_new_order_dialog(self, is_ask):
    self.dialog = NewMarketOrderDialog(
        self.window().stackedWidget,
        is_ask,
        self.chosen_wallets[0],
        self.chosen_wallets[1],
    )
    self.dialog.button_clicked.connect(self.on_new_order_action)
    self.dialog.show()


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/widgets/marketpage.py", line 315, in on_create_ask_clicked
self.show_new_order_dialog(True)
File "/usr/share/tribler/TriblerGUI/widgets/marketpage.py", line 344, in show_new_order_dialog
self.dialog = NewMarketOrderDialog(self.window().stackedWidget, is_ask, self.chosen_wallets[0], self.chosen_wallets[1])
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def show_new_order_dialog(self, is_ask):
    if not self.wallets[self.chosen_wallets[0]]["created"]:
        ConfirmationDialog.show_error(
            self.window(),
            "Wallet not available",
            "%s wallet not available, please create it first." % self.chosen_wallets[0],
        )
        return
    elif not self.wallets[self.chosen_wallets[1]]["created"]:
        ConfirmationDialog.show_error(
            self.window(),
            "Wallet not available",
            "%s wallet not available, please create it first." % self.chosen_wallets[1],
        )
        return

    self.dialog = NewMarketOrderDialog(
        self.window().stackedWidget,
        is_ask,
        self.chosen_wallets[0],
        self.chosen_wallets[1],
    )
    self.dialog.button_clicked.connect(self.on_new_order_action)
    self.dialog.show()
# Buggy code
def update_subscribe_button(self, remote_response=None):
    if remote_response and "subscribed" in remote_response:
        self.channel_info["subscribed"] = remote_response["subscribed"]

    if remote_response and "votes" in remote_response:
        self.channel_info["votes"] = remote_response["votes"]

    if self.channel_info["subscribed"]:
        self.subscribe_button.setIcon(
            QIcon(QPixmap(get_image_path("subscribed_yes.png")))
        )
    else:
        self.subscribe_button.setIcon(
            QIcon(QPixmap(get_image_path("subscribed_not.png")))
        )

    self.num_subs_label.setText(str(self.channel_info["votes"]))

    self.credit_mining_button.setHidden(
        not self.window().tribler_settings["credit_mining"]["enabled"]
    )
    if (
        self.channel_info["dispersy_cid"]
        in self.window().tribler_settings["credit_mining"]["sources"]
    ):
        self.credit_mining_button.setIcon(
            QIcon(QPixmap(get_image_path("credit_mining_yes.png")))
        )
    else:
        self.credit_mining_button.setIcon(
            QIcon(QPixmap(get_image_path("credit_mining_not.png")))
        )


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\discoveredpage.py", line 47, in on_discovered_channel
File "TriblerGUI\widgets\lazyloadlist.py", line 51, in append_item
File "TriblerGUI\widgets\lazyloadlist.py", line 34, in load_item
File "TriblerGUI\widgets\channel_list_item.py", line 21, in __init__
File "TriblerGUI\widgets\subscriptionswidget.py", line 40, in initialize_with_channel
File "TriblerGUI\widgets\subscriptionswidget.py", line 56, in update_subscribe_button
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def update_subscribe_button(self, remote_response=None):
    if remote_response and "subscribed" in remote_response:
        self.channel_info["subscribed"] = remote_response["subscribed"]

    if remote_response and "votes" in remote_response:
        self.channel_info["votes"] = remote_response["votes"]

    if self.channel_info["subscribed"]:
        self.subscribe_button.setIcon(
            QIcon(QPixmap(get_image_path("subscribed_yes.png")))
        )
    else:
        self.subscribe_button.setIcon(
            QIcon(QPixmap(get_image_path("subscribed_not.png")))
        )

    self.num_subs_label.setText(str(self.channel_info["votes"]))

    if (
        self.window().tribler_settings
    ):  # It could be that the settings are not loaded yet
        self.credit_mining_button.setHidden(
            not self.window().tribler_settings["credit_mining"]["enabled"]
        )
        if (
            self.channel_info["dispersy_cid"]
            in self.window().tribler_settings["credit_mining"]["sources"]
        ):
            self.credit_mining_button.setIcon(
                QIcon(QPixmap(get_image_path("credit_mining_yes.png")))
            )
        else:
            self.credit_mining_button.setIcon(
                QIcon(QPixmap(get_image_path("credit_mining_not.png")))
            )
    else:
        self.credit_mining_button.hide()
# Buggy code
def send_request(self, data, tracker_session):
    self.tracker_sessions[tracker_session.transaction_id] = tracker_session
    self.transport.write(data, (tracker_session.ip_address, tracker_session.port))


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 127, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <class 'socket.error'>: [Errno 101] Network is unreachable
/usr/lib/python2.7/dist-packages/twisted/internet/base.py:878:runUntilCurrent
/usr/share/tribler/Tribler/Core/TorrentChecker/torrent_checker.py:152:_task_select_tracker
/usr/share/tribler/Tribler/Core/TorrentChecker/session.py:524:connect_to_tracker
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:310:addCallbacks
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:653:_runCallbacks
/usr/share/tribler/Tribler/Core/TorrentChecker/session.py:438:on_ip_address_resolved
/usr/share/tribler/Tribler/Core/TorrentChecker/session.py:541:connect
/usr/share/tribler/Tribler/Core/TorrentChecker/session.py:373:send_request
/usr/lib/python2.7/dist-packages/twisted/internet/udp.py:298:write
]

# Fixed code
def send_request(self, data, tracker_session):
    self.tracker_sessions[tracker_session.transaction_id] = tracker_session
    try:
        self.transport.write(data, (tracker_session.ip_address, tracker_session.port))
    except socket.error as exc:
        self._logger.warning(
            "Unable to write data to %s:%d - %s",
            tracker_session.ip_address,
            tracker_session.port,
            exc,
        )
# Buggy code
def check_disk_space(self):
    # Note that we have a resource monitor that monitors the disk where the state-directory resides.
    # However, since the credit mining directory can be on a different disk, we query the disk space ourselves.
    is_low = self.get_free_disk_space() < self.settings.low_disk_space
    if self.upload_mode != is_low:
        self._logger.info("Setting upload mode to %s", is_low)

        self.upload_mode = is_low

        def set_upload_mode(handle):
            handle.set_upload_mode(is_low)

        for download in self.session.get_downloads():
            if download.get_credit_mining():
                download.get_handle().addCallback(set_upload_mode)


# 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.WindowsError'>: [Error 3] The system cannot find the path specified
lib\site-packages\twisted\internet\base.py:1243:run
lib\site-packages\twisted\internet\base.py:1252:mainLoop
lib\site-packages\twisted\internet\base.py:878:runUntilCurrent
lib\site-packages\twisted\internet\task.py:239:__call__
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:150:maybeDeferred
Tribler\Core\CreditMining\CreditMiningManager.py:98:check_disk_space
Tribler\Core\CreditMining\CreditMiningManager.py:93:get_free_disk_space
lib\site-packages\psutil\__init__.py:2040:disk_usage
lib\site-packages\psutil\_pswindows.py:249:disk_usage
]

# Fixed code
def check_disk_space(self):
    if not self.check_mining_directory():
        return

    # Note that we have a resource monitor that monitors the disk where the state-directory resides.
    # However, since the credit mining directory can be on a different disk, we query the disk space ourselves.
    is_low = self.get_free_disk_space() < self.settings.low_disk_space
    if self.upload_mode != is_low:
        self._logger.info("Setting upload mode to %s", is_low)

        self.upload_mode = is_low

        def set_upload_mode(handle):
            handle.set_upload_mode(is_low)

        for download in self.session.get_downloads():
            if download.get_credit_mining():
                download.get_handle().addCallback(set_upload_mode)
# Buggy code
def __init__(self, wallet_dir):
    super(BitcoinWallet, self).__init__()

    self.network = "testnet" if self.TESTNET else "bitcoin"
    self.wallet_dir = wallet_dir
    self.min_confirmations = 0
    self.wallet = None
    self.unlocked = True
    self.db_path = os.path.join(wallet_dir, "wallets.sqlite")
    self.wallet_name = "tribler_testnet" if self.TESTNET else "tribler"

    if wallet_exists(self.wallet_name, databasefile=self.db_path):
        self.wallet = HDWallet(self.wallet_name, databasefile=self.db_path)
        self.created = True


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\core_manager.py", line 114, in on_received_state
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "lib\site-packages\twisted\internet\base.py", line 428, in fireEvent

File "lib\site-packages\twisted\internet\defer.py", line 321, in addCallback

File "lib\site-packages\twisted\internet\defer.py", line 310, in addCallbacks

File "lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks

--- <exception caught here> ---
File "lib\site-packages\twisted\internet\base.py", line 441, in _continueFiring

File "run_tribler.py", line 73, in start_tribler

File "Tribler\pyipv8\ipv8\util.py", line 14, in helper

File "Tribler\pyipv8\ipv8\util.py", line 26, in blockingCallFromThread

File "Tribler\Core\Session.py", line 487, in start

File "Tribler\Core\APIImplementation\LaunchManyCore.py", line 226, in register

File "Tribler\Core\APIImplementation\LaunchManyCore.py", line 406, in init

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "Tribler\Core\Modules\wallet\btc_wallet.py", line 4, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\__init__.py", line 20, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\encoding.py", line 30, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\main.py", line 75, in <module>

File "lib\site-packages\bitcoinlib\main.py", line 69, in initialize_lib

exceptions.WindowsError: [Error 3] Het systeem kan het opgegeven pad niet vinden: 'D:\\Program Files\\Tribler\\bitcoinlib\\data/*.*'

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

    bitcoinlib_main.initialize_lib(wallet_dir)
    from bitcoinlib.wallets import wallet_exists, HDWallet

    self.network = "testnet" if self.TESTNET else "bitcoin"
    self.wallet_dir = wallet_dir
    self.min_confirmations = 0
    self.wallet = None
    self.unlocked = True
    self.db_path = os.path.join(wallet_dir, "wallets.sqlite")
    self.wallet_name = "tribler_testnet" if self.TESTNET else "tribler"

    if wallet_exists(self.wallet_name, databasefile=self.db_path):
        self.wallet = HDWallet(self.wallet_name, databasefile=self.db_path)
        self.created = True
# Buggy code
def create_wallet(self):
    """
    Create a new bitcoin wallet.
    """
    self._logger.info("Creating wallet in %s", self.wallet_dir)
    try:
        self.wallet = HDWallet.create(
            self.wallet_name, network=self.network, databasefile=self.db_path
        )
        self.wallet.new_key("tribler_payments")
        self.wallet.new_key("tribler_change", change=1)
        self.created = True
    except WalletError as exc:
        self._logger.error("Cannot create BTC wallet!")
        return fail(Failure(exc))
    return succeed(None)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\core_manager.py", line 114, in on_received_state
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "lib\site-packages\twisted\internet\base.py", line 428, in fireEvent

File "lib\site-packages\twisted\internet\defer.py", line 321, in addCallback

File "lib\site-packages\twisted\internet\defer.py", line 310, in addCallbacks

File "lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks

--- <exception caught here> ---
File "lib\site-packages\twisted\internet\base.py", line 441, in _continueFiring

File "run_tribler.py", line 73, in start_tribler

File "Tribler\pyipv8\ipv8\util.py", line 14, in helper

File "Tribler\pyipv8\ipv8\util.py", line 26, in blockingCallFromThread

File "Tribler\Core\Session.py", line 487, in start

File "Tribler\Core\APIImplementation\LaunchManyCore.py", line 226, in register

File "Tribler\Core\APIImplementation\LaunchManyCore.py", line 406, in init

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "Tribler\Core\Modules\wallet\btc_wallet.py", line 4, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\__init__.py", line 20, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\encoding.py", line 30, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\main.py", line 75, in <module>

File "lib\site-packages\bitcoinlib\main.py", line 69, in initialize_lib

exceptions.WindowsError: [Error 3] Het systeem kan het opgegeven pad niet vinden: 'D:\\Program Files\\Tribler\\bitcoinlib\\data/*.*'

# Fixed code
def create_wallet(self):
    """
    Create a new bitcoin wallet.
    """
    from bitcoinlib.wallets import HDWallet, WalletError

    self._logger.info("Creating wallet in %s", self.wallet_dir)
    try:
        self.wallet = HDWallet.create(
            self.wallet_name, network=self.network, databasefile=self.db_path
        )
        self.wallet.new_key("tribler_payments")
        self.wallet.new_key("tribler_change", change=1)
        self.created = True
    except WalletError as exc:
        self._logger.error("Cannot create BTC wallet!")
        return fail(Failure(exc))
    return succeed(None)
# Buggy code
def __init__(self):
    QWidget.__init__(self)
    self.request_mgr = None
    self.initialized = False
    self.wallets_to_create = []
    self.wallets = None
    self.active_wallet = None
    self.dialog = None


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\core_manager.py", line 114, in on_received_state
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "lib\site-packages\twisted\internet\base.py", line 428, in fireEvent

File "lib\site-packages\twisted\internet\defer.py", line 321, in addCallback

File "lib\site-packages\twisted\internet\defer.py", line 310, in addCallbacks

File "lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks

--- <exception caught here> ---
File "lib\site-packages\twisted\internet\base.py", line 441, in _continueFiring

File "run_tribler.py", line 73, in start_tribler

File "Tribler\pyipv8\ipv8\util.py", line 14, in helper

File "Tribler\pyipv8\ipv8\util.py", line 26, in blockingCallFromThread

File "Tribler\Core\Session.py", line 487, in start

File "Tribler\Core\APIImplementation\LaunchManyCore.py", line 226, in register

File "Tribler\Core\APIImplementation\LaunchManyCore.py", line 406, in init

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "Tribler\Core\Modules\wallet\btc_wallet.py", line 4, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\__init__.py", line 20, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\encoding.py", line 30, in <module>

File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module

File "lib\site-packages\bitcoinlib\main.py", line 75, in <module>

File "lib\site-packages\bitcoinlib\main.py", line 69, in initialize_lib

exceptions.WindowsError: [Error 3] Het systeem kan het opgegeven pad niet vinden: 'D:\\Program Files\\Tribler\\bitcoinlib\\data/*.*'

# Fixed code
def __init__(self):
    QWidget.__init__(self)
    self.request_mgr = None
    self.initialized = False
    self.wallets_to_create = []
    self.wallets = None
    self.active_wallet = None
    self.dialog = None
    self.btc_module_available = False
# Buggy code
def on_torrent_finished(self, torrent_info):
    if self.tray_icon:
        self.window().tray_icon.showMessage(
            "Download finished", "Download of %s has finished." % torrent_info["name"]
        )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/tribler_window.py", line 306, in on_torrent_finished
"Download of %s has finished." % torrent_info["name"])
RuntimeError: wrapped C/C++ object of type QSystemTrayIcon has been deleted

# Fixed code
def on_torrent_finished(self, torrent_info):
    if self.tray_icon and not sip.isdeleted(self.tray_icon):
        self.window().tray_icon.showMessage(
            "Download finished", "Download of %s has finished." % torrent_info["name"]
        )