gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_status(self):
    """Returns the status of the torrent.
    @return DLSTATUS_*"""
    if not self.lt_status:
        return (
            (
                DLSTATUS_CIRCUITS
                if not self.download.session.tunnel_community
                or self.download.session.tunnel_community.get_candidates(
                    PEER_FLAG_EXIT_ANY
                )
                else DLSTATUS_EXIT_NODES
            )
            if self.download.config.get_hops() > 0
            else DLSTATUS_WAITING4HASHCHECK
        )
    elif self.get_error():
        return DLSTATUS_STOPPED_ON_ERROR
    return (
        DLSTATUS_MAP[self.lt_status.state]
        if not self.lt_status.paused
        else DLSTATUS_STOPPED
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def get_status(self):
    """Returns the status of the torrent.
    @return DLSTATUS_*"""
    if not self.lt_status:
        return (
            (
                DLSTATUS_CIRCUITS
                if not self.download.session.tunnel_community
                or self.download.session.tunnel_community.get_candidates(
                    PEER_FLAG_EXIT_BT
                )
                else DLSTATUS_EXIT_NODES
            )
            if self.download.config.get_hops() > 0
            else DLSTATUS_WAITING4HASHCHECK
        )
    elif self.get_error():
        return DLSTATUS_STOPPED_ON_ERROR
    return (
        DLSTATUS_MAP[self.lt_status.state]
        if not self.lt_status.paused
        else DLSTATUS_STOPPED
    )
# Buggy code
def __init__(self, *args, **kwargs):
    self.metadata_store = kwargs.pop("metadata_store")
    self.torrent_checker = kwargs.pop("torrent_checker", None)

    super(PopularityCommunity, self).__init__(*args, **kwargs)

    self.decode_map.update({chr(MSG_TORRENTS_HEALTH): self.on_torrents_health})

    self.logger.info(
        "Popularity Community initialized (peer mid %s)", hexlify(self.my_peer.mid)
    )
    self.register_task(
        "publish", self.gossip_torrents_health, interval=PUBLISH_INTERVAL
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def __init__(self, *args, **kwargs):
    self.metadata_store = kwargs.pop("metadata_store")
    self.torrent_checker = kwargs.pop("torrent_checker", None)

    super(PopularityCommunity, self).__init__(*args, **kwargs)

    self.decode_map[MSG_TORRENTS_HEALTH] = self.on_torrents_health

    self.logger.info(
        "Popularity Community initialized (peer mid %s)", hexlify(self.my_peer.mid)
    )
    self.register_task(
        "publish", self.gossip_torrents_health, interval=PUBLISH_INTERVAL
    )
# Buggy code
def from_half_block(cls, block, circuit_id):
    return BalanceResponsePayload(
        circuit_id,
        block.public_key,
        block.sequence_number,
        block.link_public_key,
        block.link_sequence_number,
        block.previous_hash,
        block.signature,
        block.type,
        block._transaction,
        block.timestamp,
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def from_half_block(cls, block, circuit_id):
    return cls(
        circuit_id,
        block.public_key,
        block.sequence_number,
        block.link_public_key,
        block.link_sequence_number,
        block.previous_hash,
        block.signature,
        block.type,
        block._transaction,
        block.timestamp,
    )
# Buggy code
def from_unpack_list(cls, *args):
    return BalanceResponsePayload(*args)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def from_unpack_list(cls, *args):
    return cls(*args)
# Buggy code
def __init__(self, circuit_id):
    super(BalanceRequestPayload, self).__init__()
    self._circuit_id = circuit_id


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def __init__(
    self,
    circuit_id,
    public_key,
    sequence_number,
    link_public_key,
    link_sequence_number,
    previous_hash,
    signature,
    block_type,
    transaction,
    timestamp,
):
    super(BalanceResponsePayload, self).__init__(
        public_key,
        sequence_number,
        link_public_key,
        link_sequence_number,
        previous_hash,
        signature,
        block_type,
        transaction,
        timestamp,
    )
    self.circuit_id = circuit_id
# Buggy code
def to_pack_list(self):
    data = [("I", self.circuit_id)]

    return data


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def to_pack_list(self):
    data = super(BalanceResponsePayload, self).to_pack_list()
    data.insert(0, ("I", self.circuit_id))
    return data
# Buggy code
def from_unpack_list(cls, circuit_id):
    return BalanceRequestPayload(circuit_id)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def from_unpack_list(cls, *args):
    return cls(*args)
# Buggy code
def cache_exitnodes_to_disk(self):
    """
    Wite a copy of the exit_candidates to the file self.exitnode_cache.

    :returns: None
    """
    exit_nodes = Network()
    for peer in self.get_candidates(PEER_FLAG_EXIT_ANY):
        exit_nodes.add_verified_peer(peer)
    self.logger.debug("Writing exit nodes to cache: %s", self.exitnode_cache)
    with open(self.exitnode_cache, "wb") as cache:
        cache.write(exit_nodes.snapshot())


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def cache_exitnodes_to_disk(self):
    """
    Wite a copy of the exit_candidates to the file self.exitnode_cache.

    :returns: None
    """
    exit_nodes = Network()
    for peer in self.get_candidates(PEER_FLAG_EXIT_BT):
        exit_nodes.add_verified_peer(peer)
    self.logger.debug("Writing exit nodes to cache: %s", self.exitnode_cache)
    with open(self.exitnode_cache, "wb") as cache:
        cache.write(exit_nodes.snapshot())
# Buggy code
def on_balance_request_cell(self, source_address, data, _):
    payload = self._ez_unpack_noauth(BalanceRequestPayload, data, global_time=False)

    if self.request_cache.has("create", payload.circuit_id):
        request = self.request_cache.get("create", payload.circuit_id)
        forwarding_relay = RelayRoute(request.from_circuit_id, request.peer)
        self.send_cell(
            forwarding_relay.peer,
            "relay-balance-request",
            BalanceRequestPayload(forwarding_relay.circuit_id),
        )
    elif self.request_cache.has("retry", payload.circuit_id):
        self.on_balance_request(payload)
    else:
        self.logger.warning(
            "Circuit creation cache for id %s not found!", payload.circuit_id
        )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def on_balance_request_cell(self, source_address, payload, _):
    if self.request_cache.has("create", payload.circuit_id):
        request = self.request_cache.get("create", payload.circuit_id)
        forwarding_relay = RelayRoute(request.from_circuit_id, request.peer)
        self.send_cell(
            forwarding_relay.peer,
            RelayBalanceRequestPayload(forwarding_relay.circuit_id),
        )
    elif self.request_cache.has("retry", payload.circuit_id):
        self.on_balance_request(payload)
    else:
        self.logger.warning(
            "Circuit creation cache for id %s not found!", payload.circuit_id
        )
# Buggy code
def on_relay_balance_request_cell(self, source_address, data, _):
    payload = self._ez_unpack_noauth(BalanceRequestPayload, data, global_time=False)
    self.on_balance_request(payload)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def on_relay_balance_request_cell(self, source_address, payload, _):
    self.on_balance_request(payload)
# Buggy code
def on_balance_response_cell(self, source_address, data, _):
    payload = self._ez_unpack_noauth(BalanceResponsePayload, data, global_time=False)
    block = TriblerBandwidthBlock.from_payload(payload, self.serializer)
    if not block.transaction:
        self.on_token_balance(payload.circuit_id, 0)
    else:
        self.on_token_balance(
            payload.circuit_id,
            block.transaction[b"total_up"] - block.transaction[b"total_down"],
        )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def on_balance_response_cell(self, source_address, payload, _):
    block = TriblerBandwidthBlock.from_payload(payload, self.serializer)
    if not block.transaction:
        self.on_token_balance(payload.circuit_id, 0)
    else:
        self.on_token_balance(
            payload.circuit_id,
            block.transaction[b"total_up"] - block.transaction[b"total_down"],
        )
# Buggy code
def on_relay_balance_response_cell(self, source_address, data, _):
    payload = self._ez_unpack_noauth(BalanceResponsePayload, data, global_time=False)
    block = TriblerBandwidthBlock.from_payload(payload, self.serializer)

    # At this point, we don't have the circuit ID of the follow-up hop. We have to iterate over the items in the
    # request cache and find the link to the next hop.
    for cache in self.request_cache._identifiers.values():
        if (
            isinstance(cache, CreateRequestCache)
            and cache.from_circuit_id == payload.circuit_id
        ):
            self.send_cell(
                cache.to_peer,
                "balance-response",
                BalanceResponsePayload.from_half_block(block, cache.to_circuit_id),
            )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 81, in _run
File "ipv8\messaging\anonymization\tunnel.py", line 149, in on_ip_address
asyncio.exceptions.CancelledError

--CONTEXT--
{'message': 'Exception in callback TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\\messaging\\anonymization\\tunnel.py:147', 'exception': CancelledError(), 'handle': <Handle TunnelExitSocket.sendto.<locals>.on_ip_address(<Task cancell...unnel.py:171>>) at ipv8\messaging\anonymization\tunnel.py:147>}

# Fixed code
def on_relay_balance_response_cell(self, source_address, payload, _):
    block = TriblerBandwidthBlock.from_payload(payload, self.serializer)

    # At this point, we don't have the circuit ID of the follow-up hop. We have to iterate over the items in the
    # request cache and find the link to the next hop.
    for cache in self.request_cache._identifiers.values():
        if (
            isinstance(cache, CreateRequestCache)
            and cache.from_circuit_id == payload.circuit_id
        ):
            self.send_cell(
                cache.to_peer,
                BalanceResponsePayload.from_half_block(block, cache.to_circuit_id),
            )
# Buggy code
def on_pc_add_unknown_torrent(self, peer, infohash):
    query = {"infohash": hexlify(infohash)}
    self.send_remote_select(peer, **query)


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
Traceback (most recent call last):
File "tribler_gui/event_request_manager.py", line 138, in <lambda>
File "tribler_gui/event_request_manager.py", line 80, in on_error
tribler_gui.event_request_manager.CoreConnectTimeoutError: Could not connect with the Tribler Core within 60 seconds
[PID:2608] 2020-10-23 14:44:34,910 - ERROR <taskmanager:135> RemoteQueryCommunity.done_cb(): Task resulted in error: get_entries_query() got an unexpected keyword argument 'infohash'
Traceback (most recent call last):
File "ipv8/taskmanager.py", line 131, in done_cb
File "tribler_core/modules/metadata_store/community/remote_query_community.py", line 124, in on_remote_select
File "tribler_core/modules/metadata_store/orm_bindings/metadata_node.py", line 140, in get_entries_threaded
File "concurrent/futures/thread.py", line 57, in run
File "tribler_core/modules/metadata_store/orm_bindings/metadata_node.py", line 135, in _get_results
File "<string>", line 2, in get_entries
File "pony/orm/core.py", line 528, in new_func
File "tribler_core/modules/metadata_store/orm_bindings/metadata_node.py", line 150, in get_entries
TypeError: get_entries_query() got an unexpected keyword argument 'infohash'

# Fixed code
def on_pc_add_unknown_torrent(self, peer, infohash):
    if not self.enable_resolve_unknown_torrents_feature:
        return
    query = {"infohash": hexlify(infohash)}
    self.send_remote_select(peer, **query)
# Buggy code
async def check_new_version_api(self, version_check_url):
    try:
        async with ClientSession(raise_for_status=True) as session:
            response = await session.get(version_check_url)
            response_dict = await response.json(content_type=None)
    except (ServerConnectionError, ClientConnectionError) as e:
        self._logger.error("Error when performing version check request: %s", e)
        return False
    except ClientResponseError as e:
        self._logger.warning(
            "Got response code %s when performing version check request", e.status
        )
        return False
    except ContentTypeError:
        self._logger.warning("Response was not in JSON format")
        return False

    try:
        version = response_dict["name"][1:]
        if LooseVersion(version) > LooseVersion(version_id):
            self.session.notifier.notify(NTFY.TRIBLER_NEW_VERSION, version)
    except ValueError as ve:
        raise ValueError("Failed to parse Tribler version response.\nError:%s" % ve)
    return True


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError:
--LONG TEXT--
Traceback (most recent call last):
File "src\tribler-core\tribler_core\modules\versioncheck_manager.py", line 45, in check_new_version_api
File "lib\site-packages\aiohttp\client.py", line 582, in _request
File "lib\site-packages\aiohttp\helpers.py", line 596, in __exit__
asyncio.exceptions.TimeoutError
--CONTEXT--
{'message': 'Task exception was never retrieved', 'exception': TimeoutError(), 'future': <Task finished name='Task-208843' coro=<VersionCheckManager.check_new_version_api() done, defined at src\tribler-core\tribler_core\modules\versioncheck_manager.py:42> exception=TimeoutError()>}

# Fixed code
async def check_new_version_api(self, version_check_url):
    try:
        async with ClientSession(raise_for_status=True) as session:
            response = await session.get(version_check_url)
            response_dict = await response.json(content_type=None)
    except (ServerConnectionError, ClientConnectionError) as e:
        self._logger.error("Error when performing version check request: %s", e)
        return False
    except ClientResponseError as e:
        self._logger.warning(
            "Got response code %s when performing version check request", e.status
        )
        return False
    except ContentTypeError:
        self._logger.warning("Response was not in JSON format")
        return False
    except asyncio.TimeoutError:
        self._logger.warning(
            "Checking for new version failed for %s", version_check_url
        )

    try:
        version = response_dict["name"][1:]
        if LooseVersion(version) > LooseVersion(version_id):
            self.session.notifier.notify(NTFY.TRIBLER_NEW_VERSION, version)
    except ValueError as ve:
        raise ValueError("Failed to parse Tribler version response.\nError:%s" % ve)
    return True
# Buggy code
def _put_health_entries_in_db():
    with db_session:
        for infohash, seeders, leechers, last_check in all_torrents:
            torrent_state = self.metadata_store.TorrentState.get(infohash=infohash)
            if torrent_state and last_check > torrent_state.last_check:
                # Replace current information
                torrent_state.seeders = seeders
                torrent_state.leechers = leechers
                torrent_state.last_check = last_check
            elif not torrent_state:
                _ = self.metadata_store.TorrentState(
                    infohash=infohash,
                    seeders=seeders,
                    leechers=leechers,
                    last_check=last_check,
                )

    self.metadata_store.disconnect_thread()


# Traceback (pony.orm.core.TransactionIntegrityError)
[PID:9376] 2020-07-21 05:31:34,949 - ERROR <taskmanager:135> PopularityCommunity.done_cb(): Task resulted in error: Object TorrentState[new:9635] cannot be stored in the database. IntegrityError: UNIQUE constraint failed: TorrentState.infohash

Traceback (most recent call last):

File "ipv8\taskmanager.py", line 131, in done_cb

File "src\tribler-core\tribler_core\modules\popularity\popularity_community.py", line 84, in on_torrents_health

File "lib\concurrent\futures\thread.py", line 57, in run

File "src\tribler-core\tribler_core\modules\popularity\popularity_community.py", line 73, in _put_health_entries_in_db

File "lib\site-packages\pony\orm\core.py", line 4001, in get

File "lib\site-packages\pony\orm\core.py", line 4104, in _find_one_

File "lib\site-packages\pony\orm\core.py", line 4163, in _find_in_db_

File "lib\site-packages\pony\orm\core.py", line 942, in _exec_sql

File "lib\site-packages\pony\orm\core.py", line 1810, in prepare_connection_for_query_execution

File "lib\site-packages\pony\orm\core.py", line 1896, in flush

File "lib\site-packages\pony\orm\core.py", line 5420, in _save_

File "lib\site-packages\pony\orm\core.py", line 5262, in _save_created_

File "lib\site-packages\pony\utils\utils.py", line 106, in throw

pony.orm.core.TransactionIntegrityError: Object TorrentState[new:9635] cannot be stored in the database. IntegrityError: UNIQUE constraint failed: TorrentState.infohash

# Fixed code
def _put_health_entries_in_db():
    with db_session(immediate=True):
        for infohash, seeders, leechers, last_check in all_torrents:
            torrent_state = self.metadata_store.TorrentState.get(infohash=infohash)
            if torrent_state and last_check > torrent_state.last_check:
                # Replace current information
                torrent_state.seeders = seeders
                torrent_state.leechers = leechers
                torrent_state.last_check = last_check
            elif not torrent_state:
                _ = self.metadata_store.TorrentState(
                    infohash=infohash,
                    seeders=seeders,
                    leechers=leechers,
                    last_check=last_check,
                )

    self.metadata_store.disconnect_thread()
# Buggy code
def set_session_settings(self, lt_session, new_settings):
    """
    Apply/set new sessions in a libtorrent session.
    :param lt_session: The libtorrent session to apply the settings to.
    :param new_settings: The new settings to apply.
    """

    # Keeping a copy of the settings because subsequent calls to get_settings are likely to fail
    # when libtorrent will try to decode peer_fingerprint to unicode.
    if lt_session not in self.ltsettings:
        self.ltsettings[lt_session] = lt_session.get_settings()
    self.ltsettings[lt_session].update(new_settings)

    if hasattr(lt_session, "apply_settings"):
        lt_session.apply_settings(new_settings)
    else:
        lt_session.set_settings(new_settings)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 114, in on_read_data
RuntimeError: Python int too large to convert to C long
--LONG TEXT--
Traceback (most recent call last):
File "src\run_tribler.py", line 95, in start_tribler
File "src\tribler-core\tribler_core\session.py", line 452, in start
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 95, in initialize
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 245, in get_session
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 230, in create_session
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 565, in set_session_settings
OverflowError: Python int too large to convert to C long
--CONTEXT--
{'message': 'Task exception was never retrieved', 'exception': OverflowError('Python int too large to convert to C long'), 'future': <Task finished coro=<start_tribler_core.<locals>.start_tribler() done, defined at src\run_tribler.py:64> exception=OverflowError('Python int too large to convert to C long')>}

# Fixed code
def set_session_settings(self, lt_session, new_settings):
    """
    Apply/set new sessions in a libtorrent session.
    :param lt_session: The libtorrent session to apply the settings to.
    :param new_settings: The new settings to apply.
    """

    # Keeping a copy of the settings because subsequent calls to get_settings are likely to fail
    # when libtorrent will try to decode peer_fingerprint to unicode.
    if lt_session not in self.ltsettings:
        self.ltsettings[lt_session] = lt_session.get_settings()
    self.ltsettings[lt_session].update(new_settings)

    try:
        if hasattr(lt_session, "apply_settings"):
            lt_session.apply_settings(new_settings)
        else:
            lt_session.set_settings(new_settings)
    except OverflowError:
        raise OverflowError(
            "Overflow error when setting libtorrent sessions with settings: %s"
            % new_settings
        )
# Buggy code
def on_balance_request_cell(self, source_address, data, _):
    payload = self._ez_unpack_noauth(BalanceRequestPayload, data, global_time=False)

    if self.request_cache.has("create", payload.circuit_id):
        request = self.request_cache.get("create", payload.circuit_id)
        forwarding_relay = RelayRoute(request.from_circuit_id, request.peer)
        self.send_cell(
            forwarding_relay.peer,
            "relay-balance-request",
            BalanceRequestPayload(forwarding_relay.circuit_id),
        )
    elif self.request_cache.has("retry", payload.circuit_id):
        self.on_balance_request(payload)
    else:
        self.logger.warning(
            "Circuit creation cache for id %s not found!", payload.circuit_id
        )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 112, in on_read_data
RuntimeError: bytes must be in range(0, 256)
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 88, in _run
File "lib\asyncio\selector_events.py", line 965, in _read_ready
File "src\tribler-core\tribler_core\modules\tunnel\socks5\udp_connection.py", line 51, in datagram_received
File "src\tribler-core\tribler_core\modules\tunnel\community\dispatcher.py", line 91, in on_socks5_udp_data
File "ipv8\messaging\anonymization\community.py", line 485, in send_data
File "ipv8\messaging\anonymization\community.py", line 471, in send_cell
File "ipv8\messaging\anonymization\payload.py", line 77, in to_bin
File "ipv8\messaging\anonymization\payload.py", line 32, in encode_address
File "ipv8\util.py", line 24, in cast_to_bin
ValueError: bytes must be in range(0, 256)

--CONTEXT--
{'message': 'Exception in callback _SelectorDatagramTransport._read_ready()', 'exception': ValueError('bytes must be in range(0, 256)'), 'handle': <Handle _SelectorDatagramTransport._read_ready()>}

# Fixed code
def on_balance_request_cell(self, source_address, data, _):
    payload = self._ez_unpack_noauth(BalanceRequestPayload, data, global_time=False)

    if self.request_cache.has("create", payload.circuit_id):
        request = self.request_cache.get("create", payload.circuit_id)
        forwarding_relay = RelayRoute(request.from_circuit_id, request.peer)
        self.send_cell(
            forwarding_relay.peer,
            "relay-balance-request",
            BalanceRequestPayload(forwarding_relay.circuit_id),
        )
    elif self.request_cache.has("retry", payload.circuit_id):
        self.on_balance_request(payload)
    else:
        self.logger.warning(
            "Circuit creation cache for id %s not found!", payload.circuit_id
        )
# Buggy code
def on_relay_balance_response_cell(self, source_address, data, _):
    payload = self._ez_unpack_noauth(BalanceResponsePayload, data, global_time=False)
    block = TriblerBandwidthBlock.from_payload(payload, self.serializer)

    # At this point, we don't have the circuit ID of the follow-up hop. We have to iterate over the items in the
    # request cache and find the link to the next hop.
    for cache in self.request_cache._identifiers.values():
        if (
            isinstance(cache, CreateRequestCache)
            and cache.from_circuit_id == payload.circuit_id
        ):
            self.send_cell(
                cache.to_peer,
                "balance-response",
                BalanceResponsePayload.from_half_block(block, cache.to_circuit_id),
            )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 112, in on_read_data
RuntimeError: bytes must be in range(0, 256)
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 88, in _run
File "lib\asyncio\selector_events.py", line 965, in _read_ready
File "src\tribler-core\tribler_core\modules\tunnel\socks5\udp_connection.py", line 51, in datagram_received
File "src\tribler-core\tribler_core\modules\tunnel\community\dispatcher.py", line 91, in on_socks5_udp_data
File "ipv8\messaging\anonymization\community.py", line 485, in send_data
File "ipv8\messaging\anonymization\community.py", line 471, in send_cell
File "ipv8\messaging\anonymization\payload.py", line 77, in to_bin
File "ipv8\messaging\anonymization\payload.py", line 32, in encode_address
File "ipv8\util.py", line 24, in cast_to_bin
ValueError: bytes must be in range(0, 256)

--CONTEXT--
{'message': 'Exception in callback _SelectorDatagramTransport._read_ready()', 'exception': ValueError('bytes must be in range(0, 256)'), 'handle': <Handle _SelectorDatagramTransport._read_ready()>}

# Fixed code
def on_relay_balance_response_cell(self, source_address, data, _):
    payload = self._ez_unpack_noauth(BalanceResponsePayload, data, global_time=False)
    block = TriblerBandwidthBlock.from_payload(payload, self.serializer)

    # At this point, we don't have the circuit ID of the follow-up hop. We have to iterate over the items in the
    # request cache and find the link to the next hop.
    for cache in self.request_cache._identifiers.values():
        if (
            isinstance(cache, CreateRequestCache)
            and cache.from_circuit_id == payload.circuit_id
        ):
            self.send_cell(
                cache.to_peer,
                "balance-response",
                BalanceResponsePayload.from_half_block(block, cache.to_circuit_id),
            )
# Buggy code
def get_valid_next_tracker_for_auto_check(self):
    tracker_url = self.get_next_tracker_for_auto_check()
    while tracker_url and not is_valid_url(tracker_url):
        self.remove_tracker(tracker_url)
        tracker_url = self.get_next_tracker_for_auto_check()
    return tracker_url


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 112, in on_read_data
RuntimeError: 'NoneType' object has no attribute 'get_next_tracker_for_auto_check'
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 88, in _run
File "ipv8\taskmanager.py", line 123, in done_cb
File "ipv8\taskmanager.py", line 17, in interval_runner
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 90, in check_random_tracker
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 177, in get_valid_next_tracker_for_auto_check
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 184, in get_next_tracker_for_auto_check
AttributeError: 'NoneType' object has no attribute 'get_next_tracker_for_auto_check'
--CONTEXT--
{'message': 'Exception in callback TaskManager.register_task.<locals>.done_cb(<Task finishe...auto_check\'")>) at ipv8\\taskmanager.py:120', 'exception': AttributeError("'NoneType' object has no attribute 'get_next_tracker_for_auto_check'"), 'handle': <Handle TaskManager.register_task.<locals>.done_cb(<Task finishe...auto_check'")>) at ipv8\taskmanager.py:120>}

# Fixed code
def get_valid_next_tracker_for_auto_check(self):
    tracker = self.get_next_tracker_for_auto_check()
    while tracker and not is_valid_url(tracker.url):
        self.remove_tracker(tracker.url)
        tracker = self.get_next_tracker_for_auto_check()
    return tracker
# Buggy code
def update_tracker_info(self, tracker_url, value):
    self.tribler_session.tracker_manager.update_tracker_info(tracker_url, value)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 112, in on_read_data
RuntimeError: 'NoneType' object has no attribute 'get_next_tracker_for_auto_check'
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 88, in _run
File "ipv8\taskmanager.py", line 123, in done_cb
File "ipv8\taskmanager.py", line 17, in interval_runner
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 90, in check_random_tracker
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 177, in get_valid_next_tracker_for_auto_check
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 184, in get_next_tracker_for_auto_check
AttributeError: 'NoneType' object has no attribute 'get_next_tracker_for_auto_check'
--CONTEXT--
{'message': 'Exception in callback TaskManager.register_task.<locals>.done_cb(<Task finishe...auto_check\'")>) at ipv8\\taskmanager.py:120', 'exception': AttributeError("'NoneType' object has no attribute 'get_next_tracker_for_auto_check'"), 'handle': <Handle TaskManager.register_task.<locals>.done_cb(<Task finishe...auto_check'")>) at ipv8\taskmanager.py:120>}

# Fixed code
def update_tracker_info(self, tracker_url, is_successful):
    self.tribler_session.tracker_manager.update_tracker_info(tracker_url, is_successful)
# Buggy code
def get_next_tracker_for_auto_check(self):
    """
    Gets the next tracker for automatic tracker-checking.
    :return: The next tracker for automatic tracker-checking.
    """
    tracker = (
        self.tracker_store.select(
            lambda g: str(g.url)
            and g.alive
            and g.last_check + TRACKER_RETRY_INTERVAL <= int(time.time())
            and str(g.url) not in self.blacklist
        )
        .order_by(self.tracker_store.last_check)
        .limit(1)
    )

    if not tracker:
        return None
    return tracker[0].url


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 112, in on_read_data
RuntimeError: 'NoneType' object has no attribute 'get_next_tracker_for_auto_check'
--LONG TEXT--
Traceback (most recent call last):
File "lib\asyncio\events.py", line 88, in _run
File "ipv8\taskmanager.py", line 123, in done_cb
File "ipv8\taskmanager.py", line 17, in interval_runner
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 90, in check_random_tracker
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 177, in get_valid_next_tracker_for_auto_check
File "src\tribler-core\tribler_core\modules\torrent_checker\torrent_checker.py", line 184, in get_next_tracker_for_auto_check
AttributeError: 'NoneType' object has no attribute 'get_next_tracker_for_auto_check'
--CONTEXT--
{'message': 'Exception in callback TaskManager.register_task.<locals>.done_cb(<Task finishe...auto_check\'")>) at ipv8\\taskmanager.py:120', 'exception': AttributeError("'NoneType' object has no attribute 'get_next_tracker_for_auto_check'"), 'handle': <Handle TaskManager.register_task.<locals>.done_cb(<Task finishe...auto_check'")>) at ipv8\taskmanager.py:120>}

# Fixed code
def get_next_tracker_for_auto_check(self):
    """
    Gets the next tracker for automatic tracker-checking.
    :return: The next tracker for automatic tracker-checking.
    """
    tracker = (
        self.tracker_store.select(
            lambda g: str(g.url)
            and g.alive
            and g.last_check + TRACKER_RETRY_INTERVAL <= int(time.time())
            and str(g.url) not in self.blacklist
        )
        .order_by(self.tracker_store.last_check)
        .limit(1)
    )

    if not tracker:
        return None
    return tracker[0]
# Buggy code
def on_core_read_ready(self):
    raw_output = bytes(self.core_process.readAll())
    if b"Traceback" in raw_output:
        self.core_traceback = raw_output.decode()
    print(raw_output.decode().strip())


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\core_manager.py", line 48, in on_core_read_ready
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 108: invalid continuation byte

# Fixed code
def on_core_read_ready(self):
    raw_output = bytes(self.core_process.readAll())
    decoded_output = raw_output.decode(errors="replace")
    if b"Traceback" in raw_output:
        self.core_traceback = decoded_output
    print(decoded_output.strip())
# Buggy code
def evict_timed_out_requests(self):
    t = time()
    for req in self.requests_in_flight:
        if t - req.time > self.request_timeout_interval:
            req.cancel_request()


# Traceback (AttributeError)
[PID:44363] 2020-06-12 17:46:47,261 - ERROR <tribler_window:107> root.on_exception(): Traceback (most recent call last):
File "tribler_gui/widgets/downloadspage.py", line 148, in load_downloads
File "tribler_gui/tribler_request_manager.py", line 178, in __init__
File "tribler_gui/tribler_request_manager.py", line 100, in add_request
File "tribler_gui/tribler_request_manager.py", line 95, in evict_timed_out_requests
AttributeError: 'int' object has no attribute 'time'

ERROR:Executor:********** TRIBLER CRASHED **********
ERROR:Executor:Tribler crashed after uptime of 3090.547427892685 sec!

# Fixed code
def evict_timed_out_requests(self):
    t = time()
    for req in list(self.requests_in_flight.items()):
        if t - req.time > self.request_timeout_interval:
            req.cancel_request()
# Buggy code
def clear(self):
    for req_id, req in list(self.requests_in_flight.items()):
        req.cancel_request()


# Traceback (AttributeError)
[PID:44363] 2020-06-12 17:46:47,261 - ERROR <tribler_window:107> root.on_exception(): Traceback (most recent call last):
File "tribler_gui/widgets/downloadspage.py", line 148, in load_downloads
File "tribler_gui/tribler_request_manager.py", line 178, in __init__
File "tribler_gui/tribler_request_manager.py", line 100, in add_request
File "tribler_gui/tribler_request_manager.py", line 95, in evict_timed_out_requests
AttributeError: 'int' object has no attribute 'time'

ERROR:Executor:********** TRIBLER CRASHED **********
ERROR:Executor:Tribler crashed after uptime of 3090.547427892685 sec!

# Fixed code
def clear(self):
    for req in list(self.requests_in_flight.values()):
        req.cancel_request()
# Buggy code
def evict_timed_out_requests(self):
    t = time()
    for req in list(self.requests_in_flight.items()):
        if t - req.time > self.request_timeout_interval:
            req.cancel_request()


# Traceback (AttributeError)
[PID:44363] 2020-06-12 17:46:47,261 - ERROR <tribler_window:107> root.on_exception(): Traceback (most recent call last):
File "tribler_gui/widgets/downloadspage.py", line 148, in load_downloads
File "tribler_gui/tribler_request_manager.py", line 178, in __init__
File "tribler_gui/tribler_request_manager.py", line 100, in add_request
File "tribler_gui/tribler_request_manager.py", line 95, in evict_timed_out_requests
AttributeError: 'int' object has no attribute 'time'

ERROR:Executor:********** TRIBLER CRASHED **********
ERROR:Executor:Tribler crashed after uptime of 3090.547427892685 sec!

# Fixed code
def evict_timed_out_requests(self):
    t = time()
    for req in list(self.requests_in_flight.values()):
        if t - req.time > self.request_timeout_interval:
            req.cancel_request()
# Buggy code
def update_subscribe_button(self, remote_response=None):
    if remote_response and "subscribed" in remote_response:
        self.contents_widget.model.channel_info["subscribed"] = remote_response[
            "subscribed"
        ]

    color = (
        "#FE6D01"
        if int(self.contents_widget.model.channel_info["subscribed"])
        else "#fff"
    )
    self.subscribe_button.setStyleSheet("border:none; color: %s" % color)
    self.subscribe_button.setText(
        format_votes(self.contents_widget.model.channel_info["votes"])
    )

    # Disable channel control buttons for LEGACY_ENTRY channels
    hide_controls = self.contents_widget.model.channel_info["status"] == 1000
    self.subscribe_button.setHidden(hide_controls)


# Traceback (KeyError)
INFO:Executor:Performing action: subscribe_unsubscribe
INFO:Executor:Executing action: <tribler_apptester.actions.subscribe_unsubscribe_action.SubscribeUnsubscribeAction object at 0x0342D550>
INFO:Executor:Executing code with task id: 6a7e8a86b8
[PID:7440] 2020-06-12 14:12:12,893 - INFO - CodeExecutor(52) - Code execution with task b'6a7e8a86b8' finished:
[PID:7440] 2020-06-12 14:12:12,893 - INFO - CodeExecutor(53) - Stdout of task b'6a7e8a86b8': Execution of task 6a7e8a86b8 completed

[PID:7440] 2020-06-12 14:12:13,361 - ERROR <tribler_window:107> root.on_exception(): Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\widgets\subscriptionswidget.py", line 49, in <lambda>
File "src\tribler-gui\tribler_gui\widgets\subscriptionswidget.py", line 39, in update_subscribe_button
KeyError: 'votes'

ERROR:Executor:********** TRIBLER CRASHED **********
ERROR:Executor:Tribler crashed after uptime of 1794.9829955101013 sec! Stack trace: Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\widgets\subscriptionswidget.py", line 49, in <lambda>
File "src\tribler-gui\tribler_gui\widgets\subscriptionswidget.py", line 39, in update_subscribe_button
KeyError: 'votes'

# Fixed code
def update_subscribe_button(self, remote_response=None):
    # A safeguard against race condition that happens when the user changed
    # the channel view before the response came in
    if self.isHidden():
        return
    if remote_response and "subscribed" in remote_response:
        self.contents_widget.model.channel_info["subscribed"] = remote_response[
            "subscribed"
        ]

    color = (
        "#FE6D01"
        if int(self.contents_widget.model.channel_info["subscribed"])
        else "#fff"
    )
    self.subscribe_button.setStyleSheet("border:none; color: %s" % color)
    self.subscribe_button.setText(
        format_votes(self.contents_widget.model.channel_info["votes"])
    )
# Buggy code
def __init__(self, state_dir, config_file=None):
    """
    Create a new TriblerConfig instance.

    :param config_file: path to existing config file
    :raises an InvalidConfigException if ConfigObj is invalid
    """
    self._logger = logging.getLogger(self.__class__.__name__)
    self._state_dir = Path(state_dir)
    self.config = ConfigObj(
        infile=(str(config_file) if config_file else None),
        configspec=str(CONFIG_SPEC_PATH),
        default_encoding="utf-8",
    )
    self.validate()
    self.selected_ports = {}


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/user/src/tribler-gui/tribler_gui/tribler_window.py", line 785, in on_add_torrent_browse_file
self.process_uri_request()
File "/home/user/src/tribler-gui/tribler_gui/tribler_window.py", line 502, in process_uri_request
self.start_download_from_uri(uri)
File "/home/user/src/tribler-gui/tribler_gui/tribler_window.py", line 839, in start_download_from_uri
[],
File "/home/user/src/tribler-gui/tribler_gui/tribler_window.py", line 516, in perform_start_download_request
is_writable, error = is_dir_writable(destination)
File "/home/user/src/tribler-gui/tribler_gui/utilities.py", line 221, in is_dir_writable
if not os.path.exists(path):
File "/home/vader/.pyenv/versions/3.7.4/lib/python3.7/genericpath.py", line 19, in exists
os.stat(path)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType

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

    :param config_file: path to existing config file
    :raises an InvalidConfigException if ConfigObj is invalid
    """
    self._logger = logging.getLogger(self.__class__.__name__)
    self._state_dir = Path(state_dir)
    self.config = ConfigObj(
        infile=(str(config_file) if config_file else None),
        configspec=str(CONFIG_SPEC_PATH),
        default_encoding="utf-8",
    )
    self.validate()
    self.selected_ports = {}

    # Set the default destination dir. The value should be in the config dict
    # because of the REST endpoint sending the whole dict to the GUI.
    # TODO: do not write the value into the config file if the user did not change it
    if self.config["download_defaults"]["saveas"] is None:
        self.config["download_defaults"]["saveas"] = str(
            self.abspath(get_default_dest_dir())
        )