gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_default_destination_dir(self):
    # set defaults downloads path
    value = self.config["download_defaults"]["saveas"]
    if not value:
        value = self.config["download_defaults"]["saveas"] = str(get_default_dest_dir())
    return self.abspath(value)


# 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 get_default_destination_dir(self):
    return Path(self.config["download_defaults"]["saveas"])
# Buggy code
def save_to_file(self, filename, data):
    base_dir = QFileDialog.getExistingDirectory(
        self, "Select an export directory", "", QFileDialog.ShowDirsOnly
    )
    if len(base_dir) > 0:
        dest_path = os.path.join(base_dir, filename)
        try:
            with open(dest_path, "wb") as torrent_file:
                torrent_file.write(json.dumps(data))
        except IOError as exc:
            ConfirmationDialog.show_error(
                self.window(), "Error exporting file", str(exc)
            )


# Traceback (TypeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\debug_window.py", line 750, in <lambda>
File "src\tribler-gui\tribler_gui\debug_window.py", line 763, in on_libtorrent_session_received
File "src\tribler-gui\tribler_gui\debug_window.py", line 771, in save_to_file
TypeError: a bytes-like object is required, not 'str'

# Fixed code
def save_to_file(self, filename, data):
    base_dir = QFileDialog.getExistingDirectory(
        self, "Select an export directory", "", QFileDialog.ShowDirsOnly
    )
    if len(base_dir) > 0:
        dest_path = os.path.join(base_dir, filename)
        try:
            with open(dest_path, "w") as torrent_file:
                torrent_file.write(json.dumps(data))
        except IOError as exc:
            ConfirmationDialog.show_error(
                self.window(), "Error exporting file", str(exc)
            )
# Buggy code
def update_torrent(self, peers, download):
    if not download.handle or not download.handle.is_valid():
        return

    peers = peers.intersection(download.handle.get_peer_info())
    if peers:
        if download not in self.bittorrent_peers:
            self.bittorrent_peers[download] = peers
        else:
            self.bittorrent_peers[download] = peers | self.bittorrent_peers[download]

        # If there are active circuits, add peers immediately. Otherwise postpone.
        if self.find_circuits():
            self.readd_bittorrent_peers()


# Traceback (RuntimeError)
[PID:2956] 2020-03-26 13:38:13,599 - ERROR <tribler_window:107> root.on_exception(): Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 114, in on_read_data
RuntimeError: Task was destroyed but it is pending!
--CONTEXT--
{'message': 'Task was destroyed but it is pending!', 'task': <Task pending coro=<TriblerTunnelCommunity.remove_circuit() running at src\tribler-core\tribler_core\modules\tunnel\community\triblertunnel_community.py:407> wait_for=<_GatheringFuture pending cb=[<TaskWakeupMethWrapper object at 0x000000001617A6D8>()]> cb=[TaskManager.register_task.<locals>.done_cb() at ipv8\taskmanager.py:105]>}

ERROR:Executor:********** TRIBLER CRASHED **********
ERROR:Executor:Tribler crashed after uptime of 1562.634765625 sec! Stack trace: Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 114, in on_read_data
RuntimeError: Task was destroyed but it is pending!
--CONTEXT--
{'message': 'Task was destroyed but it is pending!', 'task': <Task pending coro=<TriblerTunnelCommunity.remove_circuit() running at src\tribler-core\tribler_core\modules\tunnel\community\triblertunnel_community.py:407> wait_for=<_GatheringFuture pending cb=[<TaskWakeupMethWrapper object at 0x000000001617A6D8>()]> cb=[TaskManager.register_task.<locals>.done_cb() at ipv8\taskmanager.py:105]>}

# Fixed code
def update_torrent(self, peers, download):
    if not download.handle or not download.handle.is_valid():
        return

    peers = peers.intersection({pi.ip for pi in download.handle.get_peer_info()})
    if peers:
        if download not in self.bittorrent_peers:
            self.bittorrent_peers[download] = peers
        else:
            self.bittorrent_peers[download] = peers | self.bittorrent_peers[download]

        # If there are active circuits, add peers immediately. Otherwise postpone.
        if self.find_circuits():
            self.readd_bittorrent_peers()
# Buggy code
def on_should_change_video_time(self, position):
    self.freeze = True
    self.mediaplayer.stop()
    self.mediaplayer.play()
    self.mediaplayer.set_position(position)

    # Guess the current position
    duration = self.media.get_duration() / 1000
    self.window().video_player_time_label.setText(
        f"{seconds_to_string(duration * position)} / {seconds_to_string(duration)}"
    )


# Traceback (AttributeError)
Traceback (most recent call last):
File "tribler_gui/widgets/videoplayerpage.py", line 152, in on_should_change_video_time
AttributeError: 'NoneType' object has no attribute 'get_duration'

# Fixed code
def on_should_change_video_time(self, position):
    if not self.mediaplayer or not self.media:
        return

    self.freeze = True
    self.mediaplayer.stop()
    self.mediaplayer.play()
    self.mediaplayer.set_position(position)

    # Guess the current position
    duration = self.media.get_duration() / 1000
    self.window().video_player_time_label.setText(
        f"{seconds_to_string(duration * position)} / {seconds_to_string(duration)}"
    )
# Buggy code
def __init__(self, community, circuit_id, balance_future):
    super(BalanceRequestCache, self).__init__(
        community.request_cache, "balance-request", circuit_id
    )
    self.circuit_id = circuit_id
    self.balance_future = balance_future


# Traceback (RuntimeError)
[PID:3451] 2020-03-18 00:43:50,235 - ERROR <tribler_window:107> root.on_exception(): Traceback (most recent call last):
File "/home/vader/my_SRC/TRIBLER/tribler_ichorid/src/tribler-gui/tribler_gui/event_request_manager.py", line 114, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: Task was destroyed but it is pending!

# Fixed code
def __init__(self, community, circuit_id, balance_future):
    super(BalanceRequestCache, self).__init__(
        community.request_cache, "balance-request", circuit_id
    )
    self.circuit_id = circuit_id
    self.balance_future = balance_future
    self.register_future(self.balance_future)
# Buggy code
def copy(self):
    return DownloadConfig(
        ConfigObj(
            self.config, configspec=str(CONFIG_SPEC_PATH), default_encoding="utf-8"
        )
    )


# Traceback (RuntimeError)
[PID:30514] 2020-03-06 21:59:15,612 - ERROR <session:372> Session.unhandled_error_observer(): Got unhandled error: unsupported operand type(s) for /: 'NoneType' and 'str'
File "/home/vader/.pyenv/versions/3.7.4/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/home/tribler/src/pyipv8/ipv8/taskmanager.py", line 104, in done_cb
future.result()
File "/home/tribler/src/pyipv8/ipv8/taskmanager.py", line 13, in interval_runner
await task(*args)
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/libtorrent_mgr.py", line 701, in _invoke_states_cb
await result
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/libtorrent_mgr.py", line 718, in sesscb_states_callback
await self.update_hops(download, hops)
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/libtorrent_mgr.py", line 642, in update_hops
self.start_download(tdef=download.tdef, config=config)
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/libtorrent_mgr.py", line 501, in start_download
if not config.get_dest_dir().is_dir():
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/download_config.py", line 77, in get_dest_dir
dest_dir = self.state_dir / dest_dir
Traceback (most recent call last):
File "/home/tribler/src/tribler-gui/tribler_gui/event_request_manager.py", line 114, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: File "/home/vader/.pyenv/versions/3.7.4/lib/python3.7/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/home/tribler/src/pyipv8/ipv8/taskmanager.py", line 104, in done_cb
future.result()
File "/home/tribler/src/pyipv8/ipv8/taskmanager.py", line 13, in interval_runner
await task(*args)
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/libtorrent_mgr.py", line 701, in _invoke_states_cb
await result
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/libtorrent_mgr.py", line 718, in sesscb_states_callback
await self.update_hops(download, hops)
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/libtorrent_mgr.py", line 642, in update_hops
self.start_download(tdef=download.tdef, config=config)
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/libtorrent_mgr.py", line 501, in start_download
if not config.get_dest_dir().is_dir():
File "/home/tribler/src/tribler-core/tribler_core/modules/libtorrent/download_config.py", line 77, in get_dest_dir
dest_dir = self.state_dir / dest_dir

# Fixed code
def copy(self):
    return DownloadConfig(
        ConfigObj(
            self.config, configspec=str(CONFIG_SPEC_PATH), default_encoding="utf-8"
        ),
        state_dir=self.state_dir,
    )
# Buggy code
def is_dir_writable(path):
    """
    Checks if the directory is writable. Creates the directory if one does not exist.
    :param path: absolute path of directory
    :return: True if writable, False otherwise
    """
    try:
        if not os.path.exists(path):
            os.makedirs(path)
        open(os.path.join(path, "temp"), "w")
    except IOError as io_error:
        return False, io_error
    except OSError as os_error:
        return False, os_error
    else:
        os.remove(os.path.join(path, "temp"))
        return True, None


# Traceback (OSError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/tribler_window.py", line 780, in on_start_download_action
add_to_channel=self.dialog.dialog_widget.add_to_channel_checkbox.isChecked())
File "/usr/share/tribler/TriblerGUI/tribler_window.py", line 448, in perform_start_download_request
is_writable, error = is_dir_writable(destination)
File "/usr/share/tribler/TriblerGUI/utilities.py", line 227, in is_dir_writable
os.remove(os.path.join(path, 'temp'))
OSError: [Errno 26] Fichier texte occupé: '/home/mario/Partage/temp'

# Fixed code
def is_dir_writable(path):
    """
    Checks if the directory is writable. Creates the directory if one does not exist.
    :param path: absolute path of directory
    :return: True if writable, False otherwise
    """

    random_name = "tribler_temp_delete_me_" + str(uuid4())
    try:
        if not os.path.exists(path):
            os.makedirs(path)
        open(os.path.join(path, random_name), "w")
        os.remove(os.path.join(path, random_name))
    except IOError as io_error:
        return False, io_error
    except OSError as os_error:
        return False, os_error
    else:
        return True, None
# Buggy code
def get_updated_channels(cls):
    return select(
        g
        for g in cls
        if g.subscribed
        and (g.local_version < g.timestamp)
        and g.public_key != database_blob(cls._my_key.pub().key_to_bin()[10:])
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\core_manager.py", line 121, in on_received_state
RuntimeError: [Failure instance: Traceback: <class 'AssertionError'>: INFOHASH has invalid length: 48
Tribler\Core\Modules\gigachannel_manager.py:112:service_channels
Tribler\Core\Modules\gigachannel_manager.py:150:check_channels_updates
lib\site-packages\twisted\internet\defer.py:1613:unwindGenerator
lib\site-packages\twisted\internet\defer.py:1529:_cancellableInlineCallbacks
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:1418:_inlineCallbacks
Tribler\Core\Modules\gigachannel_manager.py:226:download_channel
Tribler\Core\TorrentDef.py:494:__init__
]

# Fixed code
def get_updated_channels(cls):
    return select(
        g
        for g in cls
        if g.subscribed
        and g.status != LEGACY_ENTRY
        and (g.local_version < g.timestamp)
        and g.public_key != database_blob(cls._my_key.pub().key_to_bin()[10:])
    )
# Buggy code
def eventFilter(self, source, event):
    if (
        event.type() == QEvent.KeyRelease
        and self.isVisible()
        and not self.window().top_search_bar.hasFocus()
        and event.key() == Qt.Key_Space
    ):
        self.on_play_pause_button_click()
    return QWidget.eventFilter(self, source, event)


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\downloadspage.py", line 342, in on_remove_download_dialog
File "TriblerGUI\widgets\videoplayerpage.py", line 244, in reset_player
TypeError: setIcon(self, QIcon): argument 1 has unexpected type 'NoneType'

# Fixed code
def eventFilter(self, source, event):
    if (
        event.type() == QEvent.KeyRelease
        and self.isVisible()
        and not self.window().top_search_bar.hasFocus()
        and event.key() == Qt.Key_Space
        and self.instance
    ):
        self.on_play_pause_button_click()
    return QWidget.eventFilter(self, source, event)
# Buggy code
def run(self):
    """
    Run the upgrader if it is enabled in the config.

    Note that by default, upgrading is enabled in the config. It is then disabled
    after upgrading to Tribler 7.
    """
    # Before any upgrade, prepare a separate state directory for the update version so it does not affect the
    # older version state directory. This allows for safe rollback.
    self.version_manager.setup_state_directory_for_upgrade()

    d = self.upgrade_72_to_pony()
    d.addCallback(self.upgrade_pony_db_6to7)
    self.upgrade_config_to_74()
    return d


# Traceback (ValueError)
ERROR   1576450617.34                 community:695  (TriblerTunnelCommunity)  Exception occurred while handling packet!
Traceback (most recent call last):
File "/home/tribler/tribler/Tribler/pyipv8/ipv8/messaging/anonymization/community.py", line 692, in on_packet_from_circuit
self.decode_map_private[msg_id](source_address, data, circuit_id)
File "/home/tribler/tribler/Tribler/pyipv8/ipv8/messaging/anonymization/community.py", line 76, in wrapper
return inner_wrapper(self, source_address, data)
File "/home/tribler/tribler/Tribler/pyipv8/ipv8/lazy_community.py", line 104, in wrapper
return func(self, source_address, *unpacked)
File "/home/tribler/tribler/Tribler/pyipv8/ipv8/messaging/anonymization/community.py", line 74, in inner_wrapper
return func(inner_self, inner_source_address, *combo)
File "/home/tribler/tribler/Tribler/pyipv8/ipv8/messaging/anonymization/community.py", line 774, in on_created
self._ours_on_created_extended(circuit, payload)
File "/home/tribler/tribler/Tribler/community/triblertunnel/community.py", line 447, in _ours_on_created_extended
super(TriblerTunnelCommunity, self)._ours_on_created_extended(circuit, payload)
File "/home/tribler/tribler/Tribler/pyipv8/ipv8/messaging/anonymization/community.py", line 551, in _ours_on_created_extended
payload.auth, hop.public_key.key.pk)
File "/home/tribler/tribler/Tribler/pyipv8/ipv8/messaging/anonymization/tunnelcrypto.py", line 51, in verify_and_generate_shared_secret
libnacl.crypto_auth_verify(auth, dh_received, shared_secret)
File "/home/tribler/.local/lib/python3.7/site-packages/libnacl/__init__.py", line 887, in crypto_auth_verify
raise ValueError('Invalid secret key')
ValueError: Invalid secret key

# Fixed code
def run(self):
    """
    Run the upgrader if it is enabled in the config.

    Note that by default, upgrading is enabled in the config. It is then disabled
    after upgrading to Tribler 7.
    """
    # Before any upgrade, prepare a separate state directory for the update version so it does not affect the
    # older version state directory. This allows for safe rollback.
    self.version_manager.setup_state_directory_for_upgrade()
    self.session.init_keypair()

    d = self.upgrade_72_to_pony()
    d.addCallback(self.upgrade_pony_db_6to7)
    self.upgrade_config_to_74()
    return d
# Buggy code
async def start_tribler():
    config = TriblerConfig()
    global trace_logger

    # Enable tracer if --trace-debug or --trace-exceptions flag is present in sys.argv
    trace_logger = check_and_enable_code_tracing("core")

    priority_order = config.get_cpu_priority_order()
    set_process_priority(pid=os.getpid(), priority_order=priority_order)

    config.set_http_api_port(int(api_port))
    # If the API key is set to an empty string, it will remain disabled
    if config.get_http_api_key() != "":
        config.set_http_api_key(api_key)
    config.set_http_api_enabled(True)

    # Check if we are already running a Tribler instance
    process_checker = ProcessChecker(config.get_state_dir())
    if process_checker.already_running:
        return
    process_checker.create_lock_file()

    session = Session(config)

    signal.signal(
        signal.SIGTERM, lambda signum, stack: shutdown(session, signum, stack)
    )
    await session.start()


# Traceback (ImportError)
Jan 17 17:17:37 prxmx3 python3[28437]: Traceback (most recent call last):
Jan 17 17:17:37 prxmx3 python3[28437]:   File "src/tribler-core/run_tribler_headless.py", line 16, in <module>
Jan 17 17:17:37 prxmx3 python3[28437]:     from tribler_core.session import Session
Jan 17 17:17:37 prxmx3 python3[28437]:   File "/opt/tribler/src/tribler-core/tribler_core/session.py", line 47, in <module>
Jan 17 17:17:37 prxmx3 python3[28437]:     from tribler_core.modules.metadata_store.gigachannel_manager import GigaChannelManager
Jan 17 17:17:37 prxmx3 python3[28437]:   File "/opt/tribler/src/tribler-core/tribler_core/modules/metadata_store/gigachannel_manager.py", line 4, in <module>
Jan 17 17:17:37 prxmx3 python3[28437]:     from ipv8.taskmanager import TaskManager, task
Jan 17 17:17:37 prxmx3 python3[28437]: ImportError: cannot import name 'task' from 'ipv8.taskmanager' (/opt/tribler/src/anydex/anydex/../pyipv8/ipv8/taskmanager.py)

# Fixed code
async def start_tribler():
    config = TriblerConfig()
    global trace_logger

    # Enable tracer if --trace-debug or --trace-exceptions flag is present in sys.argv
    trace_logger = check_and_enable_code_tracing("core")

    priority_order = config.get_cpu_priority_order()
    set_process_priority(pid=os.getpid(), priority_order=priority_order)

    config.set_http_api_port(int(api_port))
    # If the API key is set to an empty string, it will remain disabled
    if config.get_http_api_key() not in ("", api_key):
        config.set_http_api_key(api_key)
        config.write()  # Immediately write the API key so other applications can use it
    config.set_http_api_enabled(True)

    # Check if we are already running a Tribler instance
    process_checker = ProcessChecker(config.get_state_dir())
    if process_checker.already_running:
        return
    process_checker.create_lock_file()

    session = Session(config)

    signal.signal(
        signal.SIGTERM, lambda signum, stack: shutdown(session, signum, stack)
    )
    await session.start()
# Buggy code
def circuit_removed(self, _, __, circuit, additional_info):
    self.session.ipv8.network.remove_by_address(circuit.peer.address)
    if self.log_circuits:
        with open(
            os.path.join(self.session.config.get_state_dir(), "circuits.log"), "a"
        ) as out_file:
            duration = time.time() - circuit.creation_time
            out_file.write(
                "%d,%f,%d,%d,%s\n"
                % (
                    circuit.circuit_id,
                    duration,
                    circuit.bytes_up,
                    circuit.bytes_down,
                    additional_info,
                )
            )


# Traceback (ImportError)
Jan 17 17:17:37 prxmx3 python3[28437]: Traceback (most recent call last):
Jan 17 17:17:37 prxmx3 python3[28437]:   File "src/tribler-core/run_tribler_headless.py", line 16, in <module>
Jan 17 17:17:37 prxmx3 python3[28437]:     from tribler_core.session import Session
Jan 17 17:17:37 prxmx3 python3[28437]:   File "/opt/tribler/src/tribler-core/tribler_core/session.py", line 47, in <module>
Jan 17 17:17:37 prxmx3 python3[28437]:     from tribler_core.modules.metadata_store.gigachannel_manager import GigaChannelManager
Jan 17 17:17:37 prxmx3 python3[28437]:   File "/opt/tribler/src/tribler-core/tribler_core/modules/metadata_store/gigachannel_manager.py", line 4, in <module>
Jan 17 17:17:37 prxmx3 python3[28437]:     from ipv8.taskmanager import TaskManager, task
Jan 17 17:17:37 prxmx3 python3[28437]: ImportError: cannot import name 'task' from 'ipv8.taskmanager' (/opt/tribler/src/anydex/anydex/../pyipv8/ipv8/taskmanager.py)

# Fixed code
def circuit_removed(self, circuit, additional_info):
    self.session.ipv8.network.remove_by_address(circuit.peer.address)
    if self.log_circuits:
        with open(
            os.path.join(self.session.config.get_state_dir(), "circuits.log"), "a"
        ) as out_file:
            duration = time.time() - circuit.creation_time
            out_file.write(
                "%d,%f,%d,%d,%s\n"
                % (
                    circuit.circuit_id,
                    duration,
                    circuit.bytes_up,
                    circuit.bytes_down,
                    additional_info,
                )
            )
# Buggy code
def setData(self, index, new_value, role=None):
    if role != Qt.EditRole:
        return True
    public_key = self.data_items[index.row()]["public_key"]
    id_ = self.data_items[index.row()]["id"]
    attribute_name = self.columns[index.column()]
    attribute_name = "tags" if attribute_name == "category" else attribute_name
    attribute_name = "title" if attribute_name == "name" else attribute_name
    attribute_name = "subscribed" if attribute_name == "votes" else attribute_name

    def on_row_update_results(response):
        if not response:
            return
        data_item_dict = index.model().data_items[index.row()]
        for key, _ in data_item_dict.items():
            if key in response:
                data_item_dict[key] = response[key]
        self.info_changed.emit([data_item_dict])

    TriblerNetworkRequest(
        "metadata/%s/%s" % (public_key, id_),
        on_row_update_results,
        method="PATCH",
        raw_data=json.dumps({attribute_name: new_value}),
    )

    # TODO: reload the whole row from DB instead of just changing the displayed value
    self.data_items[index.row()][self.columns[index.column()]] = new_value
    return True


# Traceback (IndexError)
Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/src/tribler-gui/tribler_gui/widgets/tablecontentmodel.py", line 416, in on_row_update_results
data_item_dict = index.model().data_items[index.row()]
IndexError: list index out of range

# Fixed code
def setData(self, index, new_value, role=None):
    if role != Qt.EditRole:
        return True
    public_key = self.data_items[index.row()]["public_key"]
    id_ = self.data_items[index.row()]["id"]
    attribute_name = self.columns[index.column()]
    attribute_name = "tags" if attribute_name == "category" else attribute_name
    attribute_name = "title" if attribute_name == "name" else attribute_name
    attribute_name = "subscribed" if attribute_name == "votes" else attribute_name

    def on_row_update_results(response):
        if not response:
            return
        item_row = self.item_uid_map.get(combine_pk_id(public_key, id_))
        if item_row is None:
            return
        data_item_dict = index.model().data_items[item_row]
        data_item_dict.update(response)
        self.info_changed.emit([data_item_dict])

    TriblerNetworkRequest(
        "metadata/%s/%s" % (public_key, id_),
        on_row_update_results,
        method="PATCH",
        raw_data=json.dumps({attribute_name: new_value}),
    )

    # TODO: reload the whole row from DB instead of just changing the displayed value
    self.data_items[index.row()][self.columns[index.column()]] = new_value
    return True
# Buggy code
def on_row_update_results(response):
    if not response:
        return
    data_item_dict = index.model().data_items[index.row()]
    for key, _ in data_item_dict.items():
        if key in response:
            data_item_dict[key] = response[key]
    self.info_changed.emit([data_item_dict])


# Traceback (IndexError)
Traceback (most recent call last):
File "/home/vader/src/TRIBLER/Tribler/src/tribler-gui/tribler_gui/widgets/tablecontentmodel.py", line 416, in on_row_update_results
data_item_dict = index.model().data_items[index.row()]
IndexError: list index out of range

# Fixed code
def on_row_update_results(response):
    if not response:
        return
    item_row = self.item_uid_map.get(combine_pk_id(public_key, id_))
    if item_row is None:
        return
    data_item_dict = index.model().data_items[item_row]
    data_item_dict.update(response)
    self.info_changed.emit([data_item_dict])
# Buggy code
def get_session_settings(self, lt_session):
    return self.ltsettings.get(lt_session, {})


# Traceback (AttributeError)
INFO    1575206079.86             LibtorrentMgr:671  (LibtorrentMgr)  start_download: Starting in VOD mode
ERROR   1575206081.50    LibtorrentDownloadImpl:805  (LibtorrentDownloadImpl)  Resume data failed to save: <class 'Tribler.Core.exceptions.SaveResumeDataError'>: torrent has no metadata
INFO    1575206091.40                    tunnel:469  (Swarm)  Skipping lookup for swarm b'...'
INFO    1575206101.40                    tunnel:462  (Swarm)  Performing DHT lookup for swarm b'...'
INFO    1575206109.52    LibtorrentDownloadImpl:452  (LibtorrentDownloadImpl)  LibtorrentDownloadImpl: skipping set_piece_priority
Traceback (most recent call last):
File "Tribler\Core\Video\VideoServer.py", line 102, in process_request_thread
File "lib\socketserver.py", line 360, in finish_request
File "Tribler\Core\Video\VideoServer.py", line 124, in __init__
File "lib\socketserver.py", line 720, in __init__
File "lib\http\server.py", line 426, in handle
File "lib\http\server.py", line 414, in handle_one_request
File "Tribler\Core\Video\VideoServer.py", line 197, in do_GET
File "Tribler\Core\Video\VideoServer.py", line 76, in get_vod_stream
File "Tribler\Core\Video\VideoServer.py", line 91, in get_vod_destination
AttributeError: 'LibtorrentDownloadImpl' object has no attribute 'get_selected_files'
ERROR   1575206111.41                      util:68   (ipv8.util)  Deferred errback fired: [Failure instance: Traceback (failure with no frames): <class 'RuntimeError'>: Peers request timeout

# Fixed code
def get_session_settings(self, lt_session):
    return deepcopy(self.ltsettings.get(lt_session, {}))
# Buggy code
def get_metainfo(self):
    return lt.bdecode(
        base64.b64decode(self.config["state"]["metainfo"].encode("utf-8"))
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'RuntimeError'>: expected value (list, dict, int or string) in bencoded string
site-packages/twisted/internet/base.py:1283:run
site-packages/twisted/internet/base.py:1292:mainLoop
site-packages/twisted/internet/base.py:913:runUntilCurrent
site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
site-packages/twisted/internet/defer.py:151:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:578:_task_process_alerts
]

# Fixed code
def get_metainfo(self):
    return bdecode_compat(
        base64.b64decode(self.config["state"]["metainfo"].encode("utf-8"))
    )
# Buggy code
def get_engineresumedata(self):
    return lt.bdecode(
        base64.b64decode(self.config["state"]["engineresumedata"].encode("utf-8"))
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'RuntimeError'>: expected value (list, dict, int or string) in bencoded string
site-packages/twisted/internet/base.py:1283:run
site-packages/twisted/internet/base.py:1292:mainLoop
site-packages/twisted/internet/base.py:913:runUntilCurrent
site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
site-packages/twisted/internet/defer.py:151:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:578:_task_process_alerts
]

# Fixed code
def get_engineresumedata(self):
    return bdecode_compat(
        base64.b64decode(self.config["state"]["engineresumedata"].encode("utf-8"))
    )
# Buggy code
def on_metadata_received_alert(self, alert):
    torrent_info = get_info_from_handle(self.handle)
    if not torrent_info:
        return

    metadata = {b"info": lt.bdecode(torrent_info.metadata())}

    trackers = [ensure_binary(tracker["url"]) for tracker in self.handle.trackers()]
    if trackers:
        if len(trackers) > 1:
            metadata[b"announce-list"] = [trackers]
        else:
            metadata[b"announce"] = trackers[0]

    try:
        self.tdef = TorrentDef.load_from_dict(metadata)
    except ValueError as ve:
        self._logger.exception(ve)
        return

    try:
        torrent_files = lt.torrent_info(metadata).files()
    except RuntimeError:
        self._logger.warning("Torrent contains no files!")
        torrent_files = []

    self.orig_files = [ensure_text(torrent_file.path) for torrent_file in torrent_files]
    self.set_corrected_infoname()
    self.set_filepieceranges()
    self.set_selected_files()

    self.checkpoint()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'RuntimeError'>: expected value (list, dict, int or string) in bencoded string
site-packages/twisted/internet/base.py:1283:run
site-packages/twisted/internet/base.py:1292:mainLoop
site-packages/twisted/internet/base.py:913:runUntilCurrent
site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
site-packages/twisted/internet/defer.py:151:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:578:_task_process_alerts
]

# Fixed code
def on_metadata_received_alert(self, alert):
    torrent_info = get_info_from_handle(self.handle)
    if not torrent_info:
        return

    metadata = {b"info": bdecode_compat(torrent_info.metadata())}

    trackers = [ensure_binary(tracker["url"]) for tracker in self.handle.trackers()]
    if trackers:
        if len(trackers) > 1:
            metadata[b"announce-list"] = [trackers]
        else:
            metadata[b"announce"] = trackers[0]

    try:
        self.tdef = TorrentDef.load_from_dict(metadata)
    except ValueError as ve:
        self._logger.exception(ve)
        return

    try:
        torrent_files = lt.torrent_info(metadata).files()
    except RuntimeError:
        self._logger.warning("Torrent contains no files!")
        torrent_files = []

    self.orig_files = [ensure_text(torrent_file.path) for torrent_file in torrent_files]
    self.set_corrected_infoname()
    self.set_filepieceranges()
    self.set_selected_files()

    self.checkpoint()
# Buggy code
def _task_process_alerts(self):
    for hops, ltsession in self.ltsessions.items():
        if ltsession:
            for alert in ltsession.pop_alerts():
                self.process_alert(alert, hops=hops)

    # We have a separate session for metainfo requests.
    # For this session we are only interested in the metadata_received_alert.
    if self.ltsession_metainfo:
        for alert in self.ltsession_metainfo.pop_alerts():
            if alert.__class__.__name__ == "metadata_received_alert":
                self.check_metainfo(str(alert.handle.info_hash()))
            elif alert.__class__.__name__ == "dht_pkt_alert":
                # We received a raw DHT message - decode it and check whether it is a BEP33 message.
                decoded = bdecode(alert.pkt_buf)
                if decoded and "r" in decoded:
                    if "BFsd" in decoded["r"] and "BFpe" in decoded["r"]:
                        self.dht_health_manager.received_bloomfilters(
                            decoded["r"]["id"],
                            bytearray(decoded["r"]["BFsd"]),
                            bytearray(decoded["r"]["BFpe"]),
                        )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'RuntimeError'>: expected value (list, dict, int or string) in bencoded string
site-packages/twisted/internet/base.py:1283:run
site-packages/twisted/internet/base.py:1292:mainLoop
site-packages/twisted/internet/base.py:913:runUntilCurrent
site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
site-packages/twisted/internet/defer.py:151:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:578:_task_process_alerts
]

# Fixed code
def _task_process_alerts(self):
    for hops, ltsession in self.ltsessions.items():
        if ltsession:
            for alert in ltsession.pop_alerts():
                self.process_alert(alert, hops=hops)

    # We have a separate session for metainfo requests.
    # For this session we are only interested in the metadata_received_alert.
    if self.ltsession_metainfo:
        for alert in self.ltsession_metainfo.pop_alerts():
            if alert.__class__.__name__ == "metadata_received_alert":
                self.check_metainfo(str(alert.handle.info_hash()))
            elif alert.__class__.__name__ == "dht_pkt_alert":
                # We received a raw DHT message - decode it and check whether it is a BEP33 message.
                decoded = bdecode_compat(alert.pkt_buf)
                if decoded and "r" in decoded:
                    if "BFsd" in decoded["r"] and "BFpe" in decoded["r"]:
                        self.dht_health_manager.received_bloomfilters(
                            decoded["r"]["id"],
                            bytearray(decoded["r"]["BFsd"]),
                            bytearray(decoded["r"]["BFpe"]),
                        )
# Buggy code
def _on_torrent_created(result):
    """
    Success callback
    :param result: from create_torrent_file
    """
    metainfo_dict = bdecode(result["metainfo"])

    if export_dir and os.path.exists(export_dir):
        save_path = os.path.join(export_dir, "%s.torrent" % name)
        with open(save_path, "wb") as fd:
            fd.write(result["metainfo"])

    # Download this torrent if specified
    if "download" in args and args["download"] and args["download"][0] == "1":
        download_config = DownloadConfig()
        download_config.set_dest_dir(
            result["base_path"] if len(file_path_list) == 1 else result["base_dir"]
        )
        try:
            self.session.lm.ltmgr.start_download(
                tdef=TorrentDef(metainfo=metainfo_dict), dconfig=download_config
            )
        except DuplicateDownloadException:
            self._logger.warning("The created torrent is already being downloaded.")

    request.write(
        json.twisted_dumps(
            {"torrent": base64.b64encode(result["metainfo"]).decode("utf-8")}
        )
    )
    # If the above request.write failed, the request will have already been finished
    if not request.finished:
        request.finish()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'RuntimeError'>: expected value (list, dict, int or string) in bencoded string
site-packages/twisted/internet/base.py:1283:run
site-packages/twisted/internet/base.py:1292:mainLoop
site-packages/twisted/internet/base.py:913:runUntilCurrent
site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
site-packages/twisted/internet/defer.py:151:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:578:_task_process_alerts
]

# Fixed code
def _on_torrent_created(result):
    """
    Success callback
    :param result: from create_torrent_file
    """
    metainfo_dict = bdecode_compat(result["metainfo"])

    if export_dir and os.path.exists(export_dir):
        save_path = os.path.join(export_dir, "%s.torrent" % name)
        with open(save_path, "wb") as fd:
            fd.write(result["metainfo"])

    # Download this torrent if specified
    if "download" in args and args["download"] and args["download"][0] == "1":
        download_config = DownloadConfig()
        download_config.set_dest_dir(
            result["base_path"] if len(file_path_list) == 1 else result["base_dir"]
        )
        try:
            self.session.lm.ltmgr.start_download(
                tdef=TorrentDef(metainfo=metainfo_dict), dconfig=download_config
            )
        except DuplicateDownloadException:
            self._logger.warning("The created torrent is already being downloaded.")

    request.write(
        json.twisted_dumps(
            {"torrent": base64.b64encode(result["metainfo"]).decode("utf-8")}
        )
    )
    # If the above request.write failed, the request will have already been finished
    if not request.finished:
        request.finish()
# Buggy code
def _on_loaded(response):
    if response.startswith(b"magnet"):
        _, infohash, _ = parse_magnetlink(response)
        if infohash:
            self.session.lm.ltmgr.get_metainfo(infohash, timeout=20).addCallback(
                on_got_metainfo
            )
            return

    # Otherwise, we directly invoke the on_got_metainfo method
    try:
        decoded_response = bdecode(response)
        on_got_metainfo(decoded_response)
    except RuntimeError:
        # The decoding failed - handle it like a None metainfo
        on_got_metainfo(None)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'RuntimeError'>: expected value (list, dict, int or string) in bencoded string
site-packages/twisted/internet/base.py:1283:run
site-packages/twisted/internet/base.py:1292:mainLoop
site-packages/twisted/internet/base.py:913:runUntilCurrent
site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
site-packages/twisted/internet/defer.py:151:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:578:_task_process_alerts
]

# Fixed code
def _on_loaded(response):
    if response.startswith(b"magnet"):
        _, infohash, _ = parse_magnetlink(response)
        if infohash:
            self.session.lm.ltmgr.get_metainfo(infohash, timeout=20).addCallback(
                on_got_metainfo
            )
            return

    # Otherwise, we directly invoke the on_got_metainfo method
    try:
        decoded_response = bdecode_compat(response)
        on_got_metainfo(decoded_response)
    except RuntimeError:
        # The decoding failed - handle it like a None metainfo
        on_got_metainfo(None)
# Buggy code
def load_from_memory(bencoded_data):
    """
    Load some bencoded data into a TorrentDef.
    :param bencoded_data: The bencoded data to decode and use as metainfo
    """
    metainfo = bdecode(bencoded_data)
    # Some versions of libtorrent will not raise an exception when providing invalid data.
    # This issue is present in 1.0.8 (included with Tribler 7.3.0), but has been fixed since at least 1.2.1.
    if metainfo is None:
        raise ValueError("Data is not a bencoded string")
    return TorrentDef.load_from_dict(metainfo)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'RuntimeError'>: expected value (list, dict, int or string) in bencoded string
site-packages/twisted/internet/base.py:1283:run
site-packages/twisted/internet/base.py:1292:mainLoop
site-packages/twisted/internet/base.py:913:runUntilCurrent
site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
site-packages/twisted/internet/defer.py:151:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:578:_task_process_alerts
]

# Fixed code
def load_from_memory(bencoded_data):
    """
    Load some bencoded data into a TorrentDef.
    :param bencoded_data: The bencoded data to decode and use as metainfo
    """
    metainfo = bdecode_compat(bencoded_data)
    # Some versions of libtorrent will not raise an exception when providing invalid data.
    # This issue is present in 1.0.8 (included with Tribler 7.3.0), but has been fixed since at least 1.2.1.
    if metainfo is None:
        raise ValueError("Data is not a bencoded string")
    return TorrentDef.load_from_dict(metainfo)
# Buggy code
def save(self, torrent_filepath=None):
    """
    Generate the metainfo and save the torrent file.
    :param torrent_filepath: An optional absolute path to where to save the generated .torrent file.
    """
    torrent_dict = create_torrent_file(
        self.files_list, self.torrent_parameters, torrent_filepath=torrent_filepath
    )
    self.metainfo = bdecode(torrent_dict["metainfo"])
    self.copy_metainfo_to_torrent_parameters()
    self.infohash = torrent_dict["infohash"]


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 114, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'RuntimeError'>: expected value (list, dict, int or string) in bencoded string
site-packages/twisted/internet/base.py:1283:run
site-packages/twisted/internet/base.py:1292:mainLoop
site-packages/twisted/internet/base.py:913:runUntilCurrent
site-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
site-packages/twisted/internet/defer.py:151:maybeDeferred
Tribler/Core/Libtorrent/LibtorrentMgr.py:578:_task_process_alerts
]

# Fixed code
def save(self, torrent_filepath=None):
    """
    Generate the metainfo and save the torrent file.
    :param torrent_filepath: An optional absolute path to where to save the generated .torrent file.
    """
    torrent_dict = create_torrent_file(
        self.files_list, self.torrent_parameters, torrent_filepath=torrent_filepath
    )
    self.metainfo = bdecode_compat(torrent_dict["metainfo"])
    self.copy_metainfo_to_torrent_parameters()
    self.infohash = torrent_dict["infohash"]
# Buggy code
def add_torrent(self, torrentdl, atp):
    # If we are collecting the torrent for this infohash, abort this first.
    ltsession = self.get_session(atp.pop("hops", 0))

    if "ti" in atp:
        infohash = str(atp["ti"].info_hash())
    elif "url" in atp:
        infohash = hexlify(parse_magnetlink(atp["url"])[1])
    else:
        raise ValueError("No ti or url key in add_torrent_params")

    # Check if we added this torrent before
    known = {str(h.info_hash()): h for h in ltsession.get_torrents()}
    existing_handle = known.get(infohash)
    if existing_handle:
        self.torrents[infohash] = (torrentdl, ltsession)
        return succeed(existing_handle)

    if infohash in self.torrents:
        self._logger.info(
            "Torrent already exists in the downloads. Infohash:%s", hexlify(infohash)
        )

    # Otherwise, add it anew
    ltsession.async_add_torrent(encode_atp(atp))
    self.torrents[infohash] = (torrentdl, ltsession)
    self._logger.debug("Adding torrent %s", infohash)
    return torrentdl.deferred_added


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

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

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

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

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

File "Tribler\Core\Libtorrent\LibtorrentDownloadImpl.py", line 231, in schedule_create_engine

File "Tribler\Core\Libtorrent\LibtorrentDownloadImpl.py", line 329, in network_create_engine_wrapper

File "Tribler\Core\Libtorrent\LibtorrentMgr.py", line 334, in add_torrent

File "Tribler\Core\Utilities\unicode.py", line 71, in hexlify

builtins.TypeError: a bytes-like object is required, not 'str'

# Fixed code
def add_torrent(self, torrentdl, atp):
    # If we are collecting the torrent for this infohash, abort this first.
    ltsession = self.get_session(atp.pop("hops", 0))

    if "ti" in atp:
        infohash = str(atp["ti"].info_hash())
    elif "url" in atp:
        infohash = hexlify(parse_magnetlink(atp["url"])[1])
    else:
        raise ValueError("No ti or url key in add_torrent_params")

    # Check if we added this torrent before
    known = {str(h.info_hash()): h for h in ltsession.get_torrents()}
    existing_handle = known.get(infohash)
    if existing_handle:
        self.torrents[infohash] = (torrentdl, ltsession)
        return succeed(existing_handle)

    if infohash in self.torrents:
        self._logger.info(
            "Torrent already exists in the downloads. Infohash:%s",
            hexlify(ensure_binary(infohash)),
        )

    # Otherwise, add it anew
    ltsession.async_add_torrent(encode_atp(atp))
    self.torrents[infohash] = (torrentdl, ltsession)
    self._logger.debug("Adding torrent %s", infohash)
    return torrentdl.deferred_added