gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, parent):
    QTabWidget.__init__(self, parent)
    self.current_download = None
    self.files_widgets = {}  # dict of file name -> widget


# Traceback (TypeError)
Traceback (most recent call last):
File "src\run_tribler.py", line 179, in <module>
File "src\tribler-gui\tribler_gui\utilities.py", line 382, in trackback_wrapper
File "src\tribler-gui\tribler_gui\widgets\downloadsdetailstabwidget.py", line 183, in on_right_click_file_item
tribler_gui.utilities.CreationTraceback

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\utilities.py", line 385, in trackback_wrapper
File "src\tribler-gui\tribler_gui\utilities.py", line 382, in trackback_wrapper
TypeError: <lambda>() takes 0 positional arguments but 1 was given

# Fixed code
def __init__(self, parent):
    QTabWidget.__init__(self, parent)
    self.current_download = None
    self.files_widgets = {}  # dict of file name -> widget
    self.selected_files_info = []
# Buggy code
def on_files_included(self, files_data):
    included_list = self.get_included_file_list()
    for file_data in files_data:
        if not file_data["index"] in included_list:
            included_list.append(file_data["index"])

    self.set_included_files(included_list)


# Traceback (TypeError)
Traceback (most recent call last):
File "src\run_tribler.py", line 179, in <module>
File "src\tribler-gui\tribler_gui\utilities.py", line 382, in trackback_wrapper
File "src\tribler-gui\tribler_gui\widgets\downloadsdetailstabwidget.py", line 183, in on_right_click_file_item
tribler_gui.utilities.CreationTraceback

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\utilities.py", line 385, in trackback_wrapper
File "src\tribler-gui\tribler_gui\utilities.py", line 382, in trackback_wrapper
TypeError: <lambda>() takes 0 positional arguments but 1 was given

# Fixed code
def on_files_included(self, *args):
    included_list = self.get_included_file_list()
    for file_data in self.selected_files_info:
        if not file_data["index"] in included_list:
            included_list.append(file_data["index"])

    self.set_included_files(included_list)
# Buggy code
def on_files_excluded(self, files_data):
    included_list = self.get_included_file_list()
    for file_data in files_data:
        if file_data["index"] in included_list:
            included_list.remove(file_data["index"])

    self.set_included_files(included_list)


# Traceback (TypeError)
Traceback (most recent call last):
File "src\run_tribler.py", line 179, in <module>
File "src\tribler-gui\tribler_gui\utilities.py", line 382, in trackback_wrapper
File "src\tribler-gui\tribler_gui\widgets\downloadsdetailstabwidget.py", line 183, in on_right_click_file_item
tribler_gui.utilities.CreationTraceback

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\utilities.py", line 385, in trackback_wrapper
File "src\tribler-gui\tribler_gui\utilities.py", line 382, in trackback_wrapper
TypeError: <lambda>() takes 0 positional arguments but 1 was given

# Fixed code
def on_files_excluded(self, *args):
    included_list = self.get_included_file_list()
    for file_data in self.selected_files_info:
        if file_data["index"] in included_list:
            included_list.remove(file_data["index"])

    self.set_included_files(included_list)
# Buggy code
def on_reload_torrent_info(self):
    """
    This method is called when user clicks the QLabel text showing loading or error message. Here, we reset
    the number of retries to fetch the metainfo. Note color of QLabel is also reset to white.
    """
    self.dialog_widget.loading_files_label.setStyleSheet("color:#ffffff;")
    self.metainfo_retries = 0
    self.perform_files_request()


# Traceback (TypeError)
Traceback (most recent call last):
File "src\run_tribler.py", line 179, in <module>
File "src\tribler-gui\tribler_gui\widgets\tablecontentdelegate.py", line 190, in editorEvent
File "src\tribler-gui\tribler_gui\widgets\tableiconbuttons.py", line 40, in check_clicked
File "src\tribler-gui\tribler_gui\utilities.py", line 382, in trackback_wrapper
File "src\tribler-gui\tribler_gui\widgets\lazytableview.py", line 124, in start_download_from_index
File "src\tribler-gui\tribler_gui\tribler_window.py", line 833, in start_download_from_uri
File "src\tribler-gui\tribler_gui\dialogs\startdownloaddialog.py", line 61, in __init__
tribler_gui.utilities.CreationTraceback

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\utilities.py", line 385, in trackback_wrapper
File "src\tribler-gui\tribler_gui\utilities.py", line 382, in trackback_wrapper
TypeError: on_reload_torrent_info() takes 1 positional argument but 2 were given

# Fixed code
def on_reload_torrent_info(self, *args):
    """
    This method is called when user clicks the QLabel text showing loading or error message. Here, we reset
    the number of retries to fetch the metainfo. Note color of QLabel is also reset to white.
    """
    self.dialog_widget.loading_files_label.setStyleSheet("color:#ffffff;")
    self.metainfo_retries = 0
    self.perform_files_request()
# Buggy code
def on_reload_torrent_info(self, checked):
    """
    This method is called when user clicks the QLabel text showing loading or error message. Here, we reset
    the number of retries to fetch the metainfo. Note color of QLabel is also reset to white.
    """
    self.dialog_widget.loading_files_label.setStyleSheet("color:#ffffff;")
    self.metainfo_retries = 0
    self.perform_files_request()


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/<user>/Projects/github.com/Tribler/tribler/src/tribler-gui/tribler_gui/widgets/clickablewidgets.py", line 10, in mousePressEvent
self.clicked.emit(False)
TypeError: ClickableLabel.clicked[] signal has 0 argument(s) but 1 provided

# Fixed code
def on_reload_torrent_info(self):
    """
    This method is called when user clicks the QLabel text showing loading or error message. Here, we reset
    the number of retries to fetch the metainfo. Note color of QLabel is also reset to white.
    """
    self.dialog_widget.loading_files_label.setStyleSheet("color:#ffffff;")
    self.metainfo_retries = 0
    self.perform_files_request()
# Buggy code
def mousePressEvent(self, event):
    self.clicked.emit(False)
    QLabel.mousePressEvent(self, event)


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/<user>/Projects/github.com/Tribler/tribler/src/tribler-gui/tribler_gui/widgets/clickablewidgets.py", line 10, in mousePressEvent
self.clicked.emit(False)
TypeError: ClickableLabel.clicked[] signal has 0 argument(s) but 1 provided

# Fixed code
def mousePressEvent(self, event):
    self.clicked.emit()
    QLabel.mousePressEvent(self, event)
# Buggy code
def __init__(self, parent):
    QWidget.__init__(self, parent)
    self.setStyleSheet("background-color: rgba(30, 30, 30, 0.75);")

    self.dialog_widget = QWidget(self)

    connect(self.window().resize_event, self.on_main_window_resize)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/<user>/src/tribler/src/run_tribler.py", line 154, in <module>
sys.exit(app.exec_())
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/utilities.py", line 382, in trackback_wrapper
callback(*args, **kwargs)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/widgets/lazytableview.py", line 42, in <lambda>
connect(self.doubleClicked, lambda item: self.on_table_item_clicked(item, doubleclick=True))
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/widgets/lazytableview.py", line 94, in on_table_item_clicked
self.torrent_doubleclicked.emit(data_item)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/utilities.py", line 382, in trackback_wrapper
callback(*args, **kwargs)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/widgets/lazytableview.py", line 127, in start_download_from_dataitem
self.window().start_download_from_uri(data_item2uri(data_item))
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/tribler_window.py", line 822, in start_download_from_uri
self.dialog = StartDownloadDialog(self, self.download_uri)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/dialogs/startdownloaddialog.py", line 124, in __init__
self.perform_files_request()
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/dialogs/startdownloaddialog.py", line 162, in perform_files_request
self.rest_request = TriblerNetworkRequest(request, self.on_received_metainfo, capture_core_errors=False)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/tribler_request_manager.py", line 176, in __init__
connect(self.received_json, self.reply_callback)
tribler_gui.utilities.CreationTraceback
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/utilities.py", line 385, in trackback_wrapper
raise exc from source_exc
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/utilities.py", line 382, in trackback_wrapper
callback(*args, **kwargs)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/dialogs/startdownloaddialog.py", line 192, in on_received_metainfo
self.perform_files_request()
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/dialogs/startdownloaddialog.py", line 158, in perform_files_request
direct = not self.dialog_widget.anon_download_checkbox.isChecked()
RuntimeError: wrapped C/C++ object of type QCheckBox has been deleted

# Fixed code
def __init__(self, parent):
    QWidget.__init__(self, parent)
    self.setStyleSheet("background-color: rgba(30, 30, 30, 0.75);")

    self.dialog_widget = QWidget(self)
    self.closed = False
    connect(self.window().resize_event, self.on_main_window_resize)
# Buggy code
def close_dialog(self, checked=False):
    try:
        self.setParent(None)
        self.deleteLater()
    except RuntimeError:
        pass


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/<user>/src/tribler/src/run_tribler.py", line 154, in <module>
sys.exit(app.exec_())
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/utilities.py", line 382, in trackback_wrapper
callback(*args, **kwargs)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/widgets/lazytableview.py", line 42, in <lambda>
connect(self.doubleClicked, lambda item: self.on_table_item_clicked(item, doubleclick=True))
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/widgets/lazytableview.py", line 94, in on_table_item_clicked
self.torrent_doubleclicked.emit(data_item)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/utilities.py", line 382, in trackback_wrapper
callback(*args, **kwargs)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/widgets/lazytableview.py", line 127, in start_download_from_dataitem
self.window().start_download_from_uri(data_item2uri(data_item))
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/tribler_window.py", line 822, in start_download_from_uri
self.dialog = StartDownloadDialog(self, self.download_uri)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/dialogs/startdownloaddialog.py", line 124, in __init__
self.perform_files_request()
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/dialogs/startdownloaddialog.py", line 162, in perform_files_request
self.rest_request = TriblerNetworkRequest(request, self.on_received_metainfo, capture_core_errors=False)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/tribler_request_manager.py", line 176, in __init__
connect(self.received_json, self.reply_callback)
tribler_gui.utilities.CreationTraceback
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/utilities.py", line 385, in trackback_wrapper
raise exc from source_exc
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/utilities.py", line 382, in trackback_wrapper
callback(*args, **kwargs)
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/dialogs/startdownloaddialog.py", line 192, in on_received_metainfo
self.perform_files_request()
File "/home/<user>/src/tribler/src/tribler-gui/tribler_gui/dialogs/startdownloaddialog.py", line 158, in perform_files_request
direct = not self.dialog_widget.anon_download_checkbox.isChecked()
RuntimeError: wrapped C/C++ object of type QCheckBox has been deleted

# Fixed code
def close_dialog(self, checked=False):
    try:
        self.setParent(None)
        self.deleteLater()
        self.closed = True
    except RuntimeError:
        pass
# Buggy code
def on_tracker_error_alert(self, alert):
    peers = self.tracker_status[alert.url][0] if alert.url in self.tracker_status else 0
    if alert.msg:
        status = "Error: " + alert.msg
    elif alert.status_code > 0:
        status = "HTTP status code %d" % alert.status_code
    elif alert.status_code == 0:
        status = "Timeout"
    else:
        status = "Not working"

    self.tracker_status[alert.url] = [peers, status]


# Traceback (RuntimeError)
Traceback (most recent call last):,
File "tribler_gui/event_request_manager.py", line 116, in on_read_data,
RuntimeError: 'utf-8' codec can't decode bytes in position 0-2: invalid continuation byte,
--LONG TEXT--,
Traceback (most recent call last):,
File "asyncio/events.py", line 81, in _run,
File "ipv8/taskmanager.py", line 131, in done_cb,
File "ipv8/taskmanager.py", line 18, in interval_runner,
File "ipv8/util.py", line 55, in call_async,
File "tribler_core/modules/libtorrent/download_manager.py", line 464, in _task_process_alerts,
File "tribler_core/modules/libtorrent/download_manager.py", line 350, in process_alert,
File "tribler_core/modules/libtorrent/download.py", line 220, in process_alert,
File "tribler_core/modules/libtorrent/download.py", line 279, in on_tracker_error_alert,
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-2: invalid continuation byte,
--CONTEXT--,
{'message': "Exception in callback TaskManager.register_task.<locals>.done_cb(<Task finishe...uation byte')>) at ipv8/taskmanager.py:128", 'exception': UnicodeDecodeError('utf-8', b'\xf2\x90\x80\xe4\xaf\xbf\xe7\x9b\x83\xf4\xa3\x95\xff\x91\xbc\xf0\x80\x92\xe2\x86\x96\xf2\x99\x89\xf9\x98\xb6\xf0\x82\xac\xe9\xa2\xab\xe2\xbf\xb8\xeb\xa9\x82\xe0\x86\xa7\xf9\xb7\x97\xe8\xab\xb7\xfc\x85\x9c\xe0\x98\x82\xf5\xb1\x85\xe1\xac\x85\xe5\xbc\x9b\xe6\xae\xa0\xf3\x9d\x84\xeb\xad\x82\xfe\x8e\x9b\xea\xb2\x8f\xf8\x9d\x8c\xf...
]

# Fixed code
def on_tracker_error_alert(self, alert):
    # try-except block here is a workaround and has been added to solve
    # https://github.com/Tribler/tribler/issues/5740
    try:
        url = alert.url
    except UnicodeDecodeError as e:
        self._logger.exception(e)
        return

    peers = self.tracker_status[url][0] if url in self.tracker_status else 0
    if alert.msg:
        status = "Error: " + alert.msg
    elif alert.status_code > 0:
        status = "HTTP status code %d" % alert.status_code
    elif alert.status_code == 0:
        status = "Timeout"
    else:
        status = "Not working"

    self.tracker_status[url] = [peers, status]
# Buggy code
def _fix_state_config(config):
    for section, option in [("state", "metainfo"), ("state", "engineresumedata")]:
        value = config.get(section, option, literal_eval=False)
        try:
            value = str(
                refactoring_tool.refactor_string(value + "\n", option + "_2to3")
            )
            ungarbled_dict = recursive_ungarble_metainfo(ast.literal_eval(value))
            value = ungarbled_dict or ast.literal_eval(value)
            config.set(
                section, option, base64.b64encode(lt.bencode(value)).decode("utf-8")
            )
        except (ValueError, SyntaxError, ParseError) as ex:
            logger.error(
                "Config could not be fixed, probably corrupted. Exception: %s %s",
                type(ex),
                str(ex),
            )
            return None
    return config


# Traceback (RuntimeError)
RuntimeError: ('unsupported operand type(s) for +: \'NoneType\' and \'str\'\n--LONG TEXT--\nTraceback (most recent call last):\n  File "src\\run_tribler.py", line 84, in start_tribler\n  File "src\\tribler-core\\tribler_core\\session.py", line 294, in start\n  File "src\\tribler-core\\tribler_core\\upgrade\\upgrade.py", line 95, in run\n  File "src\\tribler-core\\tribler_core\\upgrade\\config_converter.py", line 34, in convert_config_to_tribler74\n  File "src\\tribler-core\\tribler_core\\upgrade\\config_...

# Fixed code
def _fix_state_config(config):
    for section, option in [("state", "metainfo"), ("state", "engineresumedata")]:
        value = config.get(section, option, literal_eval=False)
        if not value or not refactoring_tool:
            continue

        try:
            value = str(
                refactoring_tool.refactor_string(value + "\n", option + "_2to3")
            )
            ungarbled_dict = recursive_ungarble_metainfo(ast.literal_eval(value))
            value = ungarbled_dict or ast.literal_eval(value)
            config.set(
                section, option, base64.b64encode(lt.bencode(value)).decode("utf-8")
            )
        except (ValueError, SyntaxError, ParseError) as ex:
            logger.error(
                "Config could not be fixed, probably corrupted. Exception: %s %s",
                type(ex),
                str(ex),
            )
            return None
    return config
# Buggy code
def write(self):
    """
    Write the configuration to the config file in the state dir as specified in the config.
    """
    if not self.get_state_dir().exists():
        os.makedirs(self.get_state_dir())
    self.config.filename = self.get_state_dir() / CONFIG_FILENAME
    self.config.write()


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
[
Traceback (most recent call last):,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 130, in <lambda>,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 70, in on_error,
tribler_gui.event_request_manager.CoreConnectTimeoutError: Could not connect with the Tribler Core within 60 seconds,
[PID:13160] 2020-12-09 18:45:30,590 - ERROR <base_events:1707> asyncio.default_exception_handler(): Task exception was never retrieved,
future: <Task finished name='Task-1' coro=<start_tribler_core.<locals>.start_tribler() done, defined at src\run_tribler.py:53> exception=FileExistsError(17, 'Cannot create a file when that file already exists')>,
Traceback (most recent call last):,
File "src\run_tribler.py", line 71, in start_tribler,
File "src\tribler-core\tribler_core\config\tribler_config.py", line 92, in write,
File "lib\os.py", line 223, in makedirs,
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\<user>\\AppData\\Roaming\\.Tribler\\7.6'
]

# Fixed code
def write(self):
    """
    Write the configuration to the config file in the state dir as specified in the config.
    """
    state_dir = self.get_state_dir()
    if not state_dir.exists():
        os.makedirs(state_dir, exist_ok=True)
    self.config.filename = state_dir / CONFIG_FILENAME
    self.config.write()
# Buggy code
def init(sentry_url="", scrubber=None):
    """Initialization.

    This method should be called in each process that uses SentryReporter.

    Args:
        sentry_url: URL for Sentry server. If it is empty then Sentry's
            sending mechanism will not be initialized.

        scrubber: a class that will be used for scrubbing sending events.
            Only a single method should be implemented in the class:
            ```
                def scrub_event(self, event):
                    pass
            ```
    Returns:
        Sentry Guard.
    """
    SentryReporter._logger.info(f"Init: {sentry_url}")

    SentryReporter._scrubber = scrubber
    return sentry_sdk.init(
        sentry_url,
        release=None,
        # https://docs.sentry.io/platforms/python/configuration/integrations/
        integrations=[
            LoggingIntegration(
                level=logging.INFO,  # Capture info and above as breadcrumbs
                event_level=logging.ERROR,  # Send errors as events
            ),
            ThreadingIntegration(propagate_hub=True),
        ],
        before_send=SentryReporter._before_send,
    )


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
[
Traceback (most recent call last):,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 138, in <lambda>,
File "src\tribler-gui\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:8592] 2020-11-01 18:45:18,015 - ERROR <rest_manager:38> tribler_core.restapi.rest_manager.error_middleware(): Tribler is shutting down,
Traceback (most recent call last):,
File "src\tribler-core\tribler_core\restapi\rest_manager.py", line 35, in error_middleware,
Exception: Tribler is shutting down
]

# Fixed code
def init(sentry_url="", scrubber=None):
    """Initialization.

    This method should be called in each process that uses SentryReporter.

    Args:
        sentry_url: URL for Sentry server. If it is empty then Sentry's
            sending mechanism will not be initialized.

        scrubber: a class that will be used for scrubbing sending events.
            Only a single method should be implemented in the class:
            ```
                def scrub_event(self, event):
                    pass
            ```
    Returns:
        Sentry Guard.
    """
    SentryReporter._logger.debug(f"Init: {sentry_url}")
    SentryReporter._scrubber = scrubber
    return sentry_sdk.init(
        sentry_url,
        release=None,
        # https://docs.sentry.io/platforms/python/configuration/integrations/
        integrations=[
            LoggingIntegration(
                level=logging.INFO,  # Capture info and above as breadcrumbs
                event_level=logging.ERROR,  # Send errors as events
            ),
            ThreadingIntegration(propagate_hub=True),
        ],
        before_send=SentryReporter._before_send,
    )
# Buggy code
def set_user(user_id):
    """Set the user to identify the event on a Sentry server

    The algorithm is the following:
    1. Calculate hash from `user_id`.
    2. Generate fake user, based on the hash.

    No real `user_id` will be used in Sentry.

    Args:
        user_id: Real user id.

    Returns:
        Generated user (dictionary: {id, username}).
    """
    # calculate hash to keep real `user_id` in secret
    user_id_hash = md5(user_id).hexdigest()

    SentryReporter._logger.info(f"Set user: {user_id_hash}")

    Faker.seed(user_id_hash)
    user_name = Faker().name()
    user = {"id": user_id_hash, "username": user_name}

    sentry_sdk.set_user(user)
    return user


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
[
Traceback (most recent call last):,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 138, in <lambda>,
File "src\tribler-gui\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:8592] 2020-11-01 18:45:18,015 - ERROR <rest_manager:38> tribler_core.restapi.rest_manager.error_middleware(): Tribler is shutting down,
Traceback (most recent call last):,
File "src\tribler-core\tribler_core\restapi\rest_manager.py", line 35, in error_middleware,
Exception: Tribler is shutting down
]

# Fixed code
def set_user(user_id):
    """Set the user to identify the event on a Sentry server

    The algorithm is the following:
    1. Calculate hash from `user_id`.
    2. Generate fake user, based on the hash.

    No real `user_id` will be used in Sentry.

    Args:
        user_id: Real user id.

    Returns:
        Generated user (dictionary: {id, username}).
    """
    # calculate hash to keep real `user_id` in secret
    user_id_hash = md5(user_id).hexdigest()

    SentryReporter._logger.debug(f"Set user: {user_id_hash}")

    Faker.seed(user_id_hash)
    user_name = Faker().name()
    user = {"id": user_id_hash, "username": user_name}

    sentry_sdk.set_user(user)
    return user
# Buggy code
def allow_sending_globally(value, info=None):
    """Setter for `_allow_sending_global` variable.

    It globally allows or disallows Sentry to send events.
    If `_allow_sending_in_thread` is not set, then `_allow_sending_global`
    will be used.

    Args:
        value: Bool
        info: String that will be used as an indicator of allowing or
        disallowing reason (or the place from which this method has been
        invoked).

    Returns:
        None
    """
    SentryReporter._logger.info(f"Allow sending globally: {value}. Info: {info}")
    SentryReporter._allow_sending_global = value


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
[
Traceback (most recent call last):,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 138, in <lambda>,
File "src\tribler-gui\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:8592] 2020-11-01 18:45:18,015 - ERROR <rest_manager:38> tribler_core.restapi.rest_manager.error_middleware(): Tribler is shutting down,
Traceback (most recent call last):,
File "src\tribler-core\tribler_core\restapi\rest_manager.py", line 35, in error_middleware,
Exception: Tribler is shutting down
]

# Fixed code
def allow_sending_globally(value, info=None):
    """Setter for `_allow_sending_global` variable.

    It globally allows or disallows Sentry to send events.
    If `_allow_sending_in_thread` is not set, then `_allow_sending_global`
    will be used.

    Args:
        value: Bool
        info: String that will be used as an indicator of allowing or
        disallowing reason (or the place from which this method has been
        invoked).

    Returns:
        None
    """
    SentryReporter._logger.debug(f"Allow sending globally: {value}. Info: {info}")
    SentryReporter._allow_sending_global = value
# Buggy code
def allow_sending_in_thread(value, info=None):
    """Setter for `_allow_sending` variable.

    It allows or disallows Sentry to send events in the current thread.
    If `_allow_sending_in_thread` is not set, then `_allow_sending_global`
    will be used.

    Args:
        value: Bool
        info: String that will be used as an indicator of allowing or
        disallowing reason (or the place from which this method has been
        invoked).

    Returns:
        None
    """
    SentryReporter._logger.info(f"Allow sending in thread: {value}. Info: {info}")
    SentryReporter._allow_sending_in_thread.set(value)


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
[
Traceback (most recent call last):,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 138, in <lambda>,
File "src\tribler-gui\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:8592] 2020-11-01 18:45:18,015 - ERROR <rest_manager:38> tribler_core.restapi.rest_manager.error_middleware(): Tribler is shutting down,
Traceback (most recent call last):,
File "src\tribler-core\tribler_core\restapi\rest_manager.py", line 35, in error_middleware,
Exception: Tribler is shutting down
]

# Fixed code
def allow_sending_in_thread(value, info=None):
    """Setter for `_allow_sending` variable.

    It allows or disallows Sentry to send events in the current thread.
    If `_allow_sending_in_thread` is not set, then `_allow_sending_global`
    will be used.

    Args:
        value: Bool
        info: String that will be used as an indicator of allowing or
        disallowing reason (or the place from which this method has been
        invoked).

    Returns:
        None
    """
    SentryReporter._logger.debug(f"Allow sending in thread: {value}. Info: {info}")
    SentryReporter._allow_sending_in_thread.set(value)
# Buggy code
def __init__(self, value=True, description="", reporter=None):
    """Initialising a value and a reporter

    Args:
        value: Value that will be used for passing in
            `SentryReporter.allow_sending`.
        description: Will be used while logging.
        reporter: Instance of a reporter. This argument mostly use for
            testing purposes.
    """
    self._logger = logging.getLogger(self.__class__.__name__)
    self._logger.info(f"Value: {value}, description: {description}")

    self._value = value
    self._saved_state = None
    self._reporter = reporter or SentryReporter()


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
[
Traceback (most recent call last):,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 138, in <lambda>,
File "src\tribler-gui\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:8592] 2020-11-01 18:45:18,015 - ERROR <rest_manager:38> tribler_core.restapi.rest_manager.error_middleware(): Tribler is shutting down,
Traceback (most recent call last):,
File "src\tribler-core\tribler_core\restapi\rest_manager.py", line 35, in error_middleware,
Exception: Tribler is shutting down
]

# Fixed code
def __init__(self, value=True, description="", reporter=None):
    """Initialising a value and a reporter

    Args:
        value: Value that will be used for passing in
            `SentryReporter.allow_sending`.
        description: Will be used while logging.
        reporter: Instance of a reporter. This argument mostly use for
            testing purposes.
    """
    self._logger = logging.getLogger(self.__class__.__name__)
    self._logger.debug(f"Value: {value}, description: {description}")

    self._value = value
    self._saved_state = None
    self._reporter = reporter or SentryReporter()
# Buggy code
def __enter__(self):
    """Set SentryReporter.allow_sending(value)"""
    self._logger.info("Enter")
    self._saved_state = self._reporter.get_allow_sending()

    self._reporter.allow_sending_in_thread(
        self._value, "AllowSentryReports.__enter__()"
    )
    return self._reporter


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
[
Traceback (most recent call last):,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 138, in <lambda>,
File "src\tribler-gui\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:8592] 2020-11-01 18:45:18,015 - ERROR <rest_manager:38> tribler_core.restapi.rest_manager.error_middleware(): Tribler is shutting down,
Traceback (most recent call last):,
File "src\tribler-core\tribler_core\restapi\rest_manager.py", line 35, in error_middleware,
Exception: Tribler is shutting down
]

# Fixed code
def __enter__(self):
    """Set SentryReporter.allow_sending(value)"""
    self._logger.debug("Enter")
    self._saved_state = self._reporter.get_allow_sending()

    self._reporter.allow_sending_in_thread(
        self._value, "AllowSentryReports.__enter__()"
    )
    return self._reporter
# Buggy code
def __exit__(self, exc_type, exc_val, exc_tb):
    """Restore SentryReporter.allow_sending(old_value)"""
    self._logger.info("Exit")
    self._reporter.allow_sending_in_thread(
        self._saved_state, "AllowSentryReports.__exit__()"
    )


# Traceback (tribler_gui.event_request_manager.CoreConnectTimeoutError)
[
Traceback (most recent call last):,
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 138, in <lambda>,
File "src\tribler-gui\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:8592] 2020-11-01 18:45:18,015 - ERROR <rest_manager:38> tribler_core.restapi.rest_manager.error_middleware(): Tribler is shutting down,
Traceback (most recent call last):,
File "src\tribler-core\tribler_core\restapi\rest_manager.py", line 35, in error_middleware,
Exception: Tribler is shutting down
]

# Fixed code
def __exit__(self, exc_type, exc_val, exc_tb):
    """Restore SentryReporter.allow_sending(old_value)"""
    self._logger.debug("Exit")
    self._reporter.allow_sending_in_thread(
        self._saved_state, "AllowSentryReports.__exit__()"
    )
# Buggy code
def query_random_peer(self) -> None:
    """
    Query a random peer neighbouring peer and ask their bandwidth transactions.
    """
    peers = list(self.network.verified_peers)
    random_peer = self.random.choice(peers)
    if random_peer:
        self.query_transactions(random_peer)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/vader/my_SRC/TRIBLER/tribler_ichorid/src/tribler-gui/tribler_gui/event_request_manager.py", line 102, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: Cannot choose from an empty sequence
--LONG TEXT--
Traceback (most recent call last):
File "/home/vader/.pyenv/versions/3.8.2/lib/python3.8/asyncio/events.py", line 81, in _run
self._context.run(self._callback, *self._args)
File "/home/vader/my_SRC/TRIBLER/tribler_ichorid/src/pyipv8/ipv8/taskmanager.py", line 131, in done_cb
future.result()
File "/home/vader/my_SRC/TRIBLER/tribler_ichorid/src/pyipv8/ipv8/taskmanager.py", line 18, in interval_runner
await task(*args)
File "/home/vader/my_SRC/TRIBLER/tribler_ichorid/src/pyipv8/ipv8/util.py", line 35, in call_async
return func(*args, **kwargs)
File "/home/vader/my_SRC/TRIBLER/tribler_ichorid/src/tribler-core/tribler_core/modules/bandwidth_accounting/community.py", line 157, in query_random_peer
random_peer = self.random.choice(peers)
File "/home/vader/.pyenv/versions/3.8.2/lib/python3.8/random.py", line 290, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

--CONTEXT--
{'message': "Exception in callback TaskManager.register_task.<locals>.done_cb(<Task finishe...ty sequence')>) at /home/vader/my_SRC/TRIBLER/tribler_ichorid/src/pyipv8/ipv8/taskmanager.py:128", 'exception': IndexError('Cannot choose from an empty sequence'), 'handle': <Handle TaskManager.register_task.<locals>.done_cb(<Task finishe...ty sequence')>) at /home/vader/my_SRC/TRIBLER/tribler_ichorid/src/pyipv8/ipv8/taskmanager.py:128>}

# Fixed code
def query_random_peer(self) -> None:
    """
    Query a random peer neighbouring peer and ask their bandwidth transactions.
    """
    peers = list(self.network.verified_peers)
    if peers:
        random_peer = self.random.choice(peers)
        self.query_transactions(random_peer)
# Buggy code
async def _connect_tcp(self, target_addr):
    try:
        socket.inet_aton(target_addr[0])
        address_type = ADDRESS_TYPE_IPV4
    except (ValueError, OSError):
        address_type = ADDRESS_TYPE_DOMAIN_NAME

    request = CommandRequest(
        SOCKS_VERSION, REQ_CMD_CONNECT, 0, (address_type, *target_addr)
    )
    data = await self._send(socks5_serializer.pack_serializable(request))
    response, _ = socks5_serializer.unpack_serializable(CommandResponse, data)

    if response.version != SOCKS_VERSION:
        raise Socks5Error("Unsupported proxy server")

    if response.reply > 0:
        raise Socks5Error("TCP connect failed")

    self.connected_to = target_addr


# Traceback (ValueError)
[PID:34076] 2020-10-31 20:08:42,494 - ERROR <community:352> TriblerTunnelCommunity.on_packet(): Exception occurred while handling packet!
Traceback (most recent call last):
File "/home/tribler/src/pyipv8/ipv8/community.py", line 348, in on_packet
result = handler(source_address, data)
File "/home/tribler/src/pyipv8/ipv8/messaging/anonymization/community.py", line 611, in on_cell
cell.decrypt(self.crypto, circuit=circuit, relay_session_keys=self.relay_session_keys.get(circuit_id))
File "/home/tribler/src/pyipv8/ipv8/messaging/anonymization/payload.py", line 265, in decrypt
self.message = crypto.decrypt_str(self.message,
File "/home/tribler/src/pyipv8/ipv8/messaging/anonymization/tunnelcrypto.py", line 87, in decrypt_str
return aesgcm.decrypt(salt + content, 0)
File "/home/tribler/.pyenv/versions/tribler382/lib/python3.8/site-packages/libnacl/aead.py", line 59, in decrypt
return libnacl.crypto_aead_chacha20poly1305_ietf_decrypt(ctxt, aad, nonce, self.sk)
File "/home/tribler/.pyenv/versions/tribler382/lib/python3.8/site-packages/libnacl/__init__.py", line 829, in crypto_aead_chacha20poly1305_ietf_decrypt
raise ValueError('Failed to decrypt message')
ValueError: Failed to decrypt message

# Fixed code
async def _connect_tcp(self, target_addr):
    try:
        socket.inet_aton(target_addr[0])
    except (ValueError, OSError):
        target_addr = DomainAddress(*target_addr)

    request = CommandRequest(SOCKS_VERSION, REQ_CMD_CONNECT, 0, target_addr)
    data = await self._send(socks5_serializer.pack_serializable(request))
    response, _ = socks5_serializer.unpack_serializable(CommandResponse, data)

    if response.version != SOCKS_VERSION:
        raise Socks5Error("Unsupported proxy server")

    if response.reply > 0:
        raise Socks5Error("TCP connect failed")

    self.connected_to = target_addr
# Buggy code
def pack(self, data):
    # If the address_type is omitted we assume it's a IPv4 address
    if len(data) == 2 or data[0] == ADDRESS_TYPE_IPV4:
        offset = int(len(data) == 3)
        return struct.pack(
            ">B4sH", ADDRESS_TYPE_IPV4, socket.inet_aton(data[offset]), data[offset + 1]
        )

    host = data[1].encode()
    return struct.pack(">BB", data[0], len(host)) + host + struct.pack(">H", data[2])


# Traceback (ValueError)
[PID:34076] 2020-10-31 20:08:42,494 - ERROR <community:352> TriblerTunnelCommunity.on_packet(): Exception occurred while handling packet!
Traceback (most recent call last):
File "/home/tribler/src/pyipv8/ipv8/community.py", line 348, in on_packet
result = handler(source_address, data)
File "/home/tribler/src/pyipv8/ipv8/messaging/anonymization/community.py", line 611, in on_cell
cell.decrypt(self.crypto, circuit=circuit, relay_session_keys=self.relay_session_keys.get(circuit_id))
File "/home/tribler/src/pyipv8/ipv8/messaging/anonymization/payload.py", line 265, in decrypt
self.message = crypto.decrypt_str(self.message,
File "/home/tribler/src/pyipv8/ipv8/messaging/anonymization/tunnelcrypto.py", line 87, in decrypt_str
return aesgcm.decrypt(salt + content, 0)
File "/home/tribler/.pyenv/versions/tribler382/lib/python3.8/site-packages/libnacl/aead.py", line 59, in decrypt
return libnacl.crypto_aead_chacha20poly1305_ietf_decrypt(ctxt, aad, nonce, self.sk)
File "/home/tribler/.pyenv/versions/tribler382/lib/python3.8/site-packages/libnacl/__init__.py", line 829, in crypto_aead_chacha20poly1305_ietf_decrypt
raise ValueError('Failed to decrypt message')
ValueError: Failed to decrypt message

# Fixed code
def pack(self, data):
    if isinstance(data, DomainAddress):
        host = data[0].encode()
        return (
            struct.pack(">BB", ADDRESS_TYPE_DOMAIN_NAME, len(host))
            + host
            + struct.pack(">H", data[1])
        )
    if isinstance(data, tuple):
        return struct.pack(
            ">B4sH", ADDRESS_TYPE_IPV4, socket.inet_aton(data[0]), data[1]
        )
    raise InvalidAddressException("Invalid address type")
# Buggy code
async def do_payout(self, mid):
    """
    Perform a payout to a given mid. First, determine the outstanding balance. Then resolve the node in the DHT.
    """
    if mid not in self.tribler_peers:
        return None

    total_bytes = sum(self.tribler_peers[mid].values())

    self.logger.info("Doing direct payout to %s (%d bytes)", hexlify(mid), total_bytes)
    try:
        nodes = await self.dht.connect_peer(mid)
    except Exception as e:
        self.logger.warning("Error while doing DHT lookup for payouts, error %s", e)
        return None

    self.logger.debug("Received %d nodes for DHT lookup", len(nodes))
    if nodes:
        try:
            await self.bandwidth_community.do_payout(nodes[0], total_bytes)
        except Exception as e:
            self.logger.error("Error while doing bandwidth payout, error %s", e)
            return None

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


# Traceback (IndexError)
[PID:22044] 2020-10-31 17:02:03,593 - ERROR <taskmanager:135> PayoutManager.done_cb(): Task resulted in error: list index out of range
Traceback (most recent call last):
File "/home/tribler/src/pyipv8/ipv8/taskmanager.py", line 131, in done_cb
future.result()
File "/home//tribler/src/tribler-core/tribler_core/modules/payout_manager.py", line 47, in do_payout
return nodes[0]
IndexError: list index out of range

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

    total_bytes = sum(self.tribler_peers[mid].values())

    self.logger.info("Doing direct payout to %s (%d bytes)", hexlify(mid), total_bytes)
    try:
        nodes = await self.dht.connect_peer(mid)
    except Exception as e:
        self.logger.warning("Error while doing DHT lookup for payouts, error %s", e)
        return None

    self.logger.debug("Received %d nodes for DHT lookup", len(nodes))
    if not nodes:
        return None

    try:
        await self.bandwidth_community.do_payout(nodes[0], total_bytes)
    except Exception as e:
        self.logger.error("Error while doing bandwidth payout, error %s", e)
        return None

    # Remove the outstanding bytes; otherwise we will payout again
    self.tribler_peers.pop(mid, None)
    return nodes[0]
# Buggy code
def get_libtorrent_max_upload_rate(self):
    """
    Gets the maximum upload rate (kB / s).

    :return: the maximum upload rate in kB / s
    """
    return self.config["libtorrent"].as_int("max_upload_rate")


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError: Overflow error when setting libtorrent sessions with settings: {'upload_rate_limit': 1024, 'download_rate_limit': 1023999999998976}
--LONG TEXT--
Traceback (most recent call last):
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 593, in set_session_settings
OverflowError: Python int too large to convert to C long

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "src\run_tribler.py", line 81, in start_tribler
File "src\tribler-core\tribler_core\session.py", line 460, in start
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 107, in initialize
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 265, in get_session
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 247, in create_session
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 597, in set_session_settings
OverflowError: Overflow error when setting libtorrent sessions with settings: {'upload_rate_limit': 1024, 'download_rate_limit': 1023999999998976}

--CONTEXT--
{'message': 'Task exception was never retrieved', 'exception': OverflowError("Overflow error when setting libtorrent sessions with settings: {'upload_rate_limit': 1024, 'download_rate_limit': 1023999999998976}"), 'future': <Task finished name='Task-1' coro=<start_tribler_core.<locals>.start_tribler() done, defined at src\run_tribler.py:50> exception=OverflowError("Overflow error when setting libtorrent sessions with settings: {'upload_rate_limit': 1024, 'download_rate_limit': 1023999999998976}")>}

# Fixed code
def get_libtorrent_max_upload_rate(self):
    """
    Gets the maximum upload rate (kB / s).

    :return: the maximum upload rate in kB / s
    """
    return min(
        self.config["libtorrent"].as_int("max_upload_rate"), MAX_LIBTORRENT_RATE_LIMIT
    )
# Buggy code
def get_libtorrent_max_download_rate(self):
    """
    Gets the maximum download rate (kB / s).

    :return: the maximum download rate in kB / s
    """
    return self.config["libtorrent"].as_int("max_download_rate")


# Traceback (RuntimeError)
Traceback (most recent call last):
File "src\tribler-gui\tribler_gui\event_request_manager.py", line 116, in on_read_data
RuntimeError: Overflow error when setting libtorrent sessions with settings: {'upload_rate_limit': 1024, 'download_rate_limit': 1023999999998976}
--LONG TEXT--
Traceback (most recent call last):
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 593, in set_session_settings
OverflowError: Python int too large to convert to C long

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "src\run_tribler.py", line 81, in start_tribler
File "src\tribler-core\tribler_core\session.py", line 460, in start
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 107, in initialize
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 265, in get_session
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 247, in create_session
File "src\tribler-core\tribler_core\modules\libtorrent\download_manager.py", line 597, in set_session_settings
OverflowError: Overflow error when setting libtorrent sessions with settings: {'upload_rate_limit': 1024, 'download_rate_limit': 1023999999998976}

--CONTEXT--
{'message': 'Task exception was never retrieved', 'exception': OverflowError("Overflow error when setting libtorrent sessions with settings: {'upload_rate_limit': 1024, 'download_rate_limit': 1023999999998976}"), 'future': <Task finished name='Task-1' coro=<start_tribler_core.<locals>.start_tribler() done, defined at src\run_tribler.py:50> exception=OverflowError("Overflow error when setting libtorrent sessions with settings: {'upload_rate_limit': 1024, 'download_rate_limit': 1023999999998976}")>}

# Fixed code
def get_libtorrent_max_download_rate(self):
    """
    Gets the maximum download rate (kB / s).

    :return: the maximum download rate in kB / s
    """
    return min(
        self.config["libtorrent"].as_int("max_download_rate"), MAX_LIBTORRENT_RATE_LIMIT
    )