gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _on_remove_failure(failure):
    """
    Error callback
    :param failure: from remove_download
    """
    self._logger.exception(failure)
    request.write(return_handled_exception(request, failure.value))
    request.finish()


# Traceback (exceptions.RuntimeError)
Unhandled error in Deferred:


Traceback (most recent call last):
File "/opt/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py", line 487, in _task_process_alerts
self.process_alert(alert)
File "/opt/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py", line 336, in process_alert
self.torrents[info_hash][0].deferred_removed.callback(None)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 393, in callback
self._startRunCallbacks(result)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 501, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 588, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/opt/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py", line 336, in _on_remove_failure
request.finish()
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 224, in finish
return http.Request.finish(self)
File "/usr/lib/python2.7/dist-packages/twisted/web/http.py", line 865, in finish
"Request.finish called on a request after its connection was lost; "
exceptions.RuntimeError: Request.finish called on a request after its connection was lost; use Request.notifyFinish to keep track of this.
ERROR:root:Traceback (most recent call last):
File "/opt/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.RuntimeError'>: Request.finish called on a request after its connection was lost; use Request.notifyFinish to keep track of this.
/opt/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py:487:_task_process_alerts
/opt/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py:336:process_alert
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:393:callback
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:501:_startRunCallbacks
--- <exception caught here> ---
/usr/lib/python2.7/dist-packages/twisted/internet/defer.py:588:_runCallbacks
/opt/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py:336:_on_remove_failure
/usr/lib/python2.7/dist-packages/twisted/web/server.py:224:finish
/usr/lib/python2.7/dist-packages/twisted/web/http.py:865:finish

# Fixed code
def _on_remove_failure(failure):
    """
    Error callback
    :param failure: from remove_download
    """
    self._logger.exception(failure)
    request.write(return_handled_exception(request, failure.value))
    # If the above request.write failed, the request will have already been finished
    if not request.finished:
        request.finish()
# Buggy code
def render_POST(self, request):
    """
    .. http:post:: /settings

    A POST request to this endpoint will update Tribler settings. A JSON-dictionary should be passed as body
    contents.

        **Example request**:

        .. sourcecode:: none

            curl -X POST http://localhost:8085/settings --data "{"

        **Example response**:

        .. sourcecode:: javascript

            {
                "modified": True
            }
    """
    settings_dict = json.loads(request.content.read())
    self.parse_settings_dict(settings_dict)
    self.session.save_session_config()

    return json.dumps({"modified": True})


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\tribler_window.py", line 332, in received_settings
RuntimeError: {"error": {"message": "", "code": "UnicodeDecodeError", "handled": false, "trace": [" File \"lib\\site-packages\\twisted\\web\\server.py\", line 190, in process\n", " File \"lib\\site-packages\\twisted\\web\\server.py\", line 241, in render\n", " File \"lib\\site-packages\\twisted\\web\\resource.py\", line 250, in render\n", " File \"Tribler\\Core\\Modules\\restapi\\settings_endpoint.py\", line 61, in render_GET\n", " File \"lib\\json\\__init__.py\", line 243, in dumps\n", " File \"lib\\json\\encoder.py\", line 207, in encode\n", " File \"lib\\json\\encoder.py\", line 270, in iterencode\n"]}}

# Fixed code
def render_POST(self, request):
    """
    .. http:post:: /settings

    A POST request to this endpoint will update Tribler settings. A JSON-dictionary should be passed as body
    contents.

        **Example request**:

        .. sourcecode:: none

            curl -X POST http://localhost:8085/settings --data "{"

        **Example response**:

        .. sourcecode:: javascript

            {
                "modified": True
            }
    """
    settings_dict = json.loads(request.content.read(), encoding="latin_1")
    self.parse_settings_dict(settings_dict)
    self.session.save_session_config()

    return json.dumps({"modified": True})
# Buggy code
def get_literal_value(value):
    try:
        return ast.literal_eval(value)
    except (ValueError, SyntaxError):
        return value


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\tribler_window.py", line 332, in received_settings
RuntimeError: {"error": {"message": "", "code": "UnicodeDecodeError", "handled": false, "trace": [" File \"lib\\site-packages\\twisted\\web\\server.py\", line 190, in process\n", " File \"lib\\site-packages\\twisted\\web\\server.py\", line 241, in render\n", " File \"lib\\site-packages\\twisted\\web\\resource.py\", line 250, in render\n", " File \"Tribler\\Core\\Modules\\restapi\\settings_endpoint.py\", line 61, in render_GET\n", " File \"lib\\json\\__init__.py\", line 243, in dumps\n", " File \"lib\\json\\encoder.py\", line 207, in encode\n", " File \"lib\\json\\encoder.py\", line 270, in iterencode\n"]}}

# Fixed code
def get_literal_value(value):
    try:
        return ast.literal_eval(value)
    except (ValueError, SyntaxError, TypeError):
        return value
# Buggy code
def render_POST(self, request):
    """
    .. http:post:: /settings

    A POST request to this endpoint will update Tribler settings. A JSON-dictionary should be passed as body
    contents.

        **Example request**:

        .. sourcecode:: none

            curl -X POST http://localhost:8085/settings --data "{"

        **Example response**:

        .. sourcecode:: javascript

            {
                "modified": True
            }
    """
    settings_dict = json.loads(request.content.read())
    self.parse_settings_dict(settings_dict)
    self.session.config.write()

    return json.dumps({"modified": True})


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\tribler_window.py", line 332, in received_settings
RuntimeError: {"error": {"message": "", "code": "UnicodeDecodeError", "handled": false, "trace": [" File \"lib\\site-packages\\twisted\\web\\server.py\", line 190, in process\n", " File \"lib\\site-packages\\twisted\\web\\server.py\", line 241, in render\n", " File \"lib\\site-packages\\twisted\\web\\resource.py\", line 250, in render\n", " File \"Tribler\\Core\\Modules\\restapi\\settings_endpoint.py\", line 61, in render_GET\n", " File \"lib\\json\\__init__.py\", line 243, in dumps\n", " File \"lib\\json\\encoder.py\", line 207, in encode\n", " File \"lib\\json\\encoder.py\", line 270, in iterencode\n"]}}

# Fixed code
def render_POST(self, request):
    """
    .. http:post:: /settings

    A POST request to this endpoint will update Tribler settings. A JSON-dictionary should be passed as body
    contents.

        **Example request**:

        .. sourcecode:: none

            curl -X POST http://localhost:8085/settings --data "{"

        **Example response**:

        .. sourcecode:: javascript

            {
                "modified": True
            }
    """
    settings_dict = json.loads(request.content.read(), encoding="latin_1")
    self.parse_settings_dict(settings_dict)
    self.session.config.write()

    return json.dumps({"modified": True})
# Buggy code
def __init__(self, session):
    resource.Resource.__init__(self)
    self.session = session


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 163, in <lambda>
exclude_action.triggered.connect(lambda: self.on_files_excluded(selected_files_info))
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 188, in on_files_excluded
self.set_included_files(included_list)
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in set_included_files
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in <genexpr>
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/usr/lib/python2.7/urllib.py", line 1299, in quote_plus
s = quote(s, safe + ' ')
File "/usr/lib/python2.7/urllib.py", line 1294, in quote
return ''.join(map(quoter, s))
KeyError: u'\u0413'

# Fixed code
def __init__(self, session):
    resource.Resource.__init__(self)
    self.session = session
    self._logger = logging.getLogger(self.__class__.__name__)
# Buggy code
def get_included_file_list(self):
    return [
        unicode(file_info["name"])
        for file_info in self.current_download["files"]
        if file_info["included"]
    ]


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 163, in <lambda>
exclude_action.triggered.connect(lambda: self.on_files_excluded(selected_files_info))
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 188, in on_files_excluded
self.set_included_files(included_list)
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in set_included_files
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in <genexpr>
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/usr/lib/python2.7/urllib.py", line 1299, in quote_plus
s = quote(s, safe + ' ')
File "/usr/lib/python2.7/urllib.py", line 1294, in quote
return ''.join(map(quoter, s))
KeyError: u'\u0413'

# Fixed code
def get_included_file_list(self):
    return [
        file_info["index"]
        for file_info in self.current_download["files"]
        if file_info["included"]
    ]
# 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["name"] in included_list:
            included_list.append(file_data["name"])

    self.set_included_files(included_list)


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 163, in <lambda>
exclude_action.triggered.connect(lambda: self.on_files_excluded(selected_files_info))
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 188, in on_files_excluded
self.set_included_files(included_list)
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in set_included_files
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in <genexpr>
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/usr/lib/python2.7/urllib.py", line 1299, in quote_plus
s = quote(s, safe + ' ')
File "/usr/lib/python2.7/urllib.py", line 1294, in quote
return ''.join(map(quoter, s))
KeyError: u'\u0413'

# Fixed 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)
# 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["name"] in included_list:
            included_list.remove(file_data["name"])

    self.set_included_files(included_list)


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 163, in <lambda>
exclude_action.triggered.connect(lambda: self.on_files_excluded(selected_files_info))
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 188, in on_files_excluded
self.set_included_files(included_list)
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in set_included_files
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in <genexpr>
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/usr/lib/python2.7/urllib.py", line 1299, in quote_plus
s = quote(s, safe + ' ')
File "/usr/lib/python2.7/urllib.py", line 1294, in quote
return ''.join(map(quoter, s))
KeyError: u'\u0413'

# Fixed 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)
# Buggy code
def set_included_files(self, files):
    data_str = "".join("selected_files[]=%s&" % quote_plus(file) for file in files)[
        :-1
    ].encode("utf-8")
    self.request_mgr = TriblerRequestManager()
    self.request_mgr.perform_request(
        "downloads/%s" % self.current_download["infohash"],
        lambda _: None,
        method="PATCH",
        data=data_str,
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 163, in <lambda>
exclude_action.triggered.connect(lambda: self.on_files_excluded(selected_files_info))
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 188, in on_files_excluded
self.set_included_files(included_list)
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in set_included_files
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/home/tribler/tribler/TriblerGUI/widgets/downloadsdetailstabwidget.py", line 191, in <genexpr>
data_str = ''.join(u"selected_files[]=%s&amp;" % quote_plus(file) for file in files)[:-1].encode('utf-8')
File "/usr/lib/python2.7/urllib.py", line 1299, in quote_plus
s = quote(s, safe + ' ')
File "/usr/lib/python2.7/urllib.py", line 1294, in quote
return ''.join(map(quoter, s))
KeyError: u'\u0413'

# Fixed code
def set_included_files(self, files):
    data_str = "".join("selected_files[]=%s&" % ind for ind in files)[:-1]
    self.request_mgr = TriblerRequestManager()
    self.request_mgr.perform_request(
        "downloads/%s" % self.current_download["infohash"],
        lambda _: None,
        method="PATCH",
        data=data_str,
    )
# Buggy code
def on_link_e2e(self, messages):
    for message in messages:
        circuit = self.exit_sockets[int(message.source[8:])]
        relay_circuit = self.rendezvous_point_for[message.payload.cookie]

        self.remove_exit_socket(circuit.circuit_id, "linking circuit")
        self.remove_exit_socket(relay_circuit.circuit_id, "linking circuit")

        self.send_cell(
            [message.candidate],
            "linked-e2e",
            (circuit.circuit_id, message.payload.identifier),
        )

        self.relay_from_to[circuit.circuit_id] = RelayRoute(
            relay_circuit.circuit_id, relay_circuit.sock_addr, True
        )
        self.relay_from_to[relay_circuit.circuit_id] = RelayRoute(
            circuit.circuit_id, circuit.sock_addr, True
        )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 91, in on_read_data
RuntimeError: [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'int' object has no attribute 'decode'
lib\site-packages\twisted\internet\base.py:1195:run
lib\site-packages\twisted\internet\base.py:1204:mainLoop
lib\site-packages\twisted\internet\base.py:825:runUntilCurrent
lib\site-packages\twisted\internet\task.py:239:__call__
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:149:maybeDeferred
Tribler\dispersy\util.py:37:helper
Tribler\community\tunnel\tunnel_community.py:445:do_circuits
Tribler\community\tunnel\tunnel_community.py:484:do_remove
Tribler\community\tunnel\tunnel_community.py:689:remove_relay
Tribler\community\tunnel\tunnel_community.py:534:copy_shallow_candidate
]

# Fixed code
def on_link_e2e(self, messages):
    for message in messages:
        circuit = self.exit_sockets[int(message.source[8:])]
        relay_circuit = self.rendezvous_point_for[message.payload.cookie]

        self.remove_exit_socket(circuit.circuit_id, "linking circuit")
        self.remove_exit_socket(relay_circuit.circuit_id, "linking circuit")

        self.send_cell(
            [message.candidate],
            "linked-e2e",
            (circuit.circuit_id, message.payload.identifier),
        )

        self.relay_from_to[circuit.circuit_id] = RelayRoute(
            relay_circuit.circuit_id,
            relay_circuit.sock_addr,
            True,
            mid=relay_circuit.mid,
        )
        self.relay_from_to[relay_circuit.circuit_id] = RelayRoute(
            circuit.circuit_id, circuit.sock_addr, True, mid=circuit.mid
        )
# Buggy code
def __init__(self, parent):
    QTabWidget.__init__(self, parent)
    self.current_download = None
    self.request_mgr = None
    self.files_widgets = {}  # dict of file name -> widget
    self.tracker_widgets = {}  # dict of tracker URL -> widget


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 91, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 101, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/selectreactor.py", line 149, in _doReadOrWrite
why = getattr(selectable, method)()
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 208, in doRead
return self._dataReceived(data)
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 214, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/usr/share/tribler/Tribler/community/tunnel/Socks5/server.py", line 114, in dataReceived
if not self._try_request():
File "/usr/share/tribler/Tribler/community/tunnel/Socks5/server.py", line 169, in _try_request
offset, request = conversion.decode_request(0, self.buffer)
File "/usr/share/tribler/Tribler/community/tunnel/Socks5/conversion.py", line 174, in decode_request
offset, destination_address = __decode_address(address_type, offset, data)
File "/usr/share/tribler/Tribler/community/tunnel/Socks5/conversion.py", line 149, in __decode_address
raise ValueError("Unsupported address type %r" % address_type )
exceptions.ValueError: Unsupported address type 5

# Fixed code
def __init__(self, parent):
    QTabWidget.__init__(self, parent)
    self.current_download = None
    self.request_mgr = None
    self.files_widgets = {}  # dict of file name -> widget
# Buggy code
def initialize_details_widget(self):
    self.window().download_files_list.customContextMenuRequested.connect(
        self.on_right_click_file_item
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 91, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 101, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/selectreactor.py", line 149, in _doReadOrWrite
why = getattr(selectable, method)()
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 208, in doRead
return self._dataReceived(data)
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 214, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/usr/share/tribler/Tribler/community/tunnel/Socks5/server.py", line 114, in dataReceived
if not self._try_request():
File "/usr/share/tribler/Tribler/community/tunnel/Socks5/server.py", line 169, in _try_request
offset, request = conversion.decode_request(0, self.buffer)
File "/usr/share/tribler/Tribler/community/tunnel/Socks5/conversion.py", line 174, in decode_request
offset, destination_address = __decode_address(address_type, offset, data)
File "/usr/share/tribler/Tribler/community/tunnel/Socks5/conversion.py", line 149, in __decode_address
raise ValueError("Unsupported address type %r" % address_type )
exceptions.ValueError: Unsupported address type 5

# Fixed code
def initialize_details_widget(self):
    self.window().download_files_list.customContextMenuRequested.connect(
        self.on_right_click_file_item
    )
    self.setCurrentIndex(0)
# Buggy code
def __init__(self, circuit_id, sock_addr, rendezvous_relay=False, mid=0):
    """
    @type sock_addr: (str, int)
    @type circuit_id: int
    @return:
    """

    self.sock_addr = sock_addr
    self.circuit_id = circuit_id
    self.creation_time = time.time()
    self.last_incoming = time.time()
    self.bytes_up = self.bytes_down = 0
    self.rendezvous_relay = rendezvous_relay
    self.mid = 0


# Traceback (exceptions.AttributeError)
RNING:TunnelLogger:Got pong (1949740343) from ('95.211.155.142', 49889),
I am <Member 90334 17a4a82c3fabd656074b9c83947e6695ce345b22>
WARNING:SearchCommunity:message from <Candidate 211.116.88.46:7759>
cannot be found in the request cache, skipping it
WARNING:TunnelLogger:Removing relay 1245271599 too old
WARNING:TunnelLogger:Removing relay 377303990 too old
Unhandled Error
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/local/git/tribler-test/TriblerGUI/core_manager.py", line 65, in
start_tribler_core
reactor.run()
File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line
1195, in run
self.mainLoop()
File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line
1204, in mainLoop
self.runUntilCurrent()
--- <exception caught here> ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line
798, in runUntilCurrent
f(*a, **kw)
File
"/local/git/tribler-test/Tribler/community/multichain/community.py",
line 414, in on_tunnel_remove
if self._public_key > candidate.get_member().public_key:
exceptions.AttributeError: 'NoneType' object has no attribute 'public_key'

# Fixed code
def __init__(self, circuit_id, sock_addr, rendezvous_relay=False, mid=None):
    """
    @type sock_addr: (str, int)
    @type circuit_id: int
    @return:
    """

    self.sock_addr = sock_addr
    self.circuit_id = circuit_id
    self.creation_time = time.time()
    self.last_incoming = time.time()
    self.bytes_up = self.bytes_down = 0
    self.rendezvous_relay = rendezvous_relay
    self.mid = mid
# Buggy code
def decrypt_str(self, content, key, salt):
    # content contains the gcm tag and salt_explicit in plaintext
    salt_explicit, gcm_tag = struct.unpack_from("!q16s", content)
    cipher = Cipher(
        algorithms.AES(key),
        modes.GCM(
            initialization_vector=self._bulid_iv(salt, salt_explicit), tag=gcm_tag
        ),
        backend=default_backend(),
    ).decryptor()
    return cipher.update(content[24:]) + cipher.finalize()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 85, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: Unhandled Error
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/usr/share/tribler/TriblerGUI/core_manager.py", line 65, in start_tribler_core
reactor.run()
File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1194, in run
self.mainLoop()
File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 1203, in mainLoop
self.runUntilCurrent()
--- <exception caught here> ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 798, in runUntilCurrent
f(*a, **kw)
File "/usr/share/tribler/Tribler/community/tunnel/tunnel_community.py", line 1158, in on_data
encrypted = self.crypto_in(circuit_id, encrypted, is_data=True)
File "/usr/share/tribler/Tribler/community/tunnel/tunnel_community.py", line 1299, in crypto_in
hop.session_keys[ORIGINATOR_SALT])
File "/usr/share/tribler/Tribler/community/tunnel/crypto/tunnelcrypto.py", line 76, in decrypt_str
salt_explicit, gcm_tag = struct.unpack_from('!q16s', content)
struct.error: unpack_from requires a buffer of at least 24 bytes

# Fixed code
def decrypt_str(self, content, key, salt):
    # content contains the gcm tag and salt_explicit in plaintext
    if len(content) < 24:
        raise CryptoException("truncated content")

    salt_explicit, gcm_tag = struct.unpack_from("!q16s", content)
    cipher = Cipher(
        algorithms.AES(key),
        modes.GCM(
            initialization_vector=self._bulid_iv(salt, salt_explicit), tag=gcm_tag
        ),
        backend=default_backend(),
    ).decryptor()
    return cipher.update(content[24:]) + cipher.finalize()
# Buggy code
def __init__(self, session, cid, infohash):
    BaseChannelsEndpoint.__init__(self, session)
    self.cid = cid
    self.infohash = infohash


# Traceback (AssertionError)
I: test_add_torrent_from_magnet_to_channel_without_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... ok
I: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... 2016-07-04 16:21:10,891 [ERROR] The reactor was dirty:
I: 2016-07-04 16:21:10,894 [ERROR] >     <DelayedCall 0x9792a968 [0.772477149963s] called=0 cancelled=0 LoopingCall<5>(ChannelCommunity.take_step, *(), **{})()>
I: 2016-07-04 16:21:10,897 [ERROR] >     <DelayedCall 0x978549e0 [4.73240303993s] called=0 cancelled=0 LoopingCall<5.0>(ChannelCommunity._periodically_clean_delayed, *(), **{})()>
I: ERROR
I: ======================================================================
I: ERROR: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint)
I: ----------------------------------------------------------------------
I: Traceback (most recent call last):
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 274, in tearDown
I:     super(TestAsServer, self).tearDown(annotate=False)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Utilities/twisted_thread.py", line 151, in errback
I:     failure.raiseException()
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
I:     current.result = callback(current.result, *args, **kw)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 143, in checkReactor
I:     self.assertFalse(delayed_calls, "The reactor was dirty when tearing down the test")
I: AssertionError: The reactor was dirty when tearing down the test
I: ----------------------------------------------------------------------

# Fixed code
def __init__(self, session, cid, path):
    BaseChannelsEndpoint.__init__(self, session)
    self.cid = cid
    self.path = path
    self.deferred = Deferred()
# Buggy code
def on_request_error(error):
    error.trap(SchemeNotSupported, ConnectError, DNSLookupError)
    self._logger.error("Error when performing version check request: %s", error)


# Traceback (AssertionError)
I: test_add_torrent_from_magnet_to_channel_without_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... ok
I: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... 2016-07-04 16:21:10,891 [ERROR] The reactor was dirty:
I: 2016-07-04 16:21:10,894 [ERROR] >     <DelayedCall 0x9792a968 [0.772477149963s] called=0 cancelled=0 LoopingCall<5>(ChannelCommunity.take_step, *(), **{})()>
I: 2016-07-04 16:21:10,897 [ERROR] >     <DelayedCall 0x978549e0 [4.73240303993s] called=0 cancelled=0 LoopingCall<5.0>(ChannelCommunity._periodically_clean_delayed, *(), **{})()>
I: ERROR
I: ======================================================================
I: ERROR: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint)
I: ----------------------------------------------------------------------
I: Traceback (most recent call last):
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 274, in tearDown
I:     super(TestAsServer, self).tearDown(annotate=False)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Utilities/twisted_thread.py", line 151, in errback
I:     failure.raiseException()
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
I:     current.result = callback(current.result, *args, **kw)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 143, in checkReactor
I:     self.assertFalse(delayed_calls, "The reactor was dirty when tearing down the test")
I: AssertionError: The reactor was dirty when tearing down the test
I: ----------------------------------------------------------------------

# Fixed code
def on_request_error(failure):
    failure.trap(SchemeNotSupported, ConnectError, DNSLookupError)
    self._logger.error("Error when performing version check request: %s", failure)
# Buggy code
def load_from_url(url):
    """
    If the URL starts with 'http:' load a BT .torrent or Tribler .tstream
    file from the URL and convert it into a TorrentDef. If the URL starts
    with our URL scheme, we convert the URL to a URL-compatible TorrentDef.

    If we can't download the .torrent file, this method returns None.

    @param url URL
    @return TorrentDef.
    """
    # Class method, no locking required
    try:
        # TODO Martijn: this request should be done using Twisted
        response = requests.get(url, timeout=30, verify=False)
        if response.ok:
            return TorrentDef.load_from_memory(response.content)

    except InvalidSchema:
        pass


# Traceback (AssertionError)
I: test_add_torrent_from_magnet_to_channel_without_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... ok
I: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... 2016-07-04 16:21:10,891 [ERROR] The reactor was dirty:
I: 2016-07-04 16:21:10,894 [ERROR] >     <DelayedCall 0x9792a968 [0.772477149963s] called=0 cancelled=0 LoopingCall<5>(ChannelCommunity.take_step, *(), **{})()>
I: 2016-07-04 16:21:10,897 [ERROR] >     <DelayedCall 0x978549e0 [4.73240303993s] called=0 cancelled=0 LoopingCall<5.0>(ChannelCommunity._periodically_clean_delayed, *(), **{})()>
I: ERROR
I: ======================================================================
I: ERROR: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint)
I: ----------------------------------------------------------------------
I: Traceback (most recent call last):
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 274, in tearDown
I:     super(TestAsServer, self).tearDown(annotate=False)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Utilities/twisted_thread.py", line 151, in errback
I:     failure.raiseException()
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
I:     current.result = callback(current.result, *args, **kw)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 143, in checkReactor
I:     self.assertFalse(delayed_calls, "The reactor was dirty when tearing down the test")
I: AssertionError: The reactor was dirty when tearing down the test
I: ----------------------------------------------------------------------

# Fixed code
def load_from_url(url):
    """
    Load a BT .torrent or Tribler .tstream file from the URL and
    convert it into a TorrentDef.

    @param url URL
    @return Deferred
    """

    # Class method, no locking required
    def _on_response(data):
        return TorrentDef.load_from_memory(data)

    deferred = http_get(url)
    deferred.addCallback(_on_response)
    return deferred
# Buggy code
def __init__(self, parent):
    HomePanel.__init__(self, parent, "Recent Activity", SEPARATOR_GREY, (1, 0))
    session = self.utility.session
    session.add_observer(self.on_tunnel_remove, NTFY_TUNNEL, [NTFY_REMOVE])


# Traceback (AssertionError)
I: test_add_torrent_from_magnet_to_channel_without_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... ok
I: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... 2016-07-04 16:21:10,891 [ERROR] The reactor was dirty:
I: 2016-07-04 16:21:10,894 [ERROR] >     <DelayedCall 0x9792a968 [0.772477149963s] called=0 cancelled=0 LoopingCall<5>(ChannelCommunity.take_step, *(), **{})()>
I: 2016-07-04 16:21:10,897 [ERROR] >     <DelayedCall 0x978549e0 [4.73240303993s] called=0 cancelled=0 LoopingCall<5.0>(ChannelCommunity._periodically_clean_delayed, *(), **{})()>
I: ERROR
I: ======================================================================
I: ERROR: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint)
I: ----------------------------------------------------------------------
I: Traceback (most recent call last):
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 274, in tearDown
I:     super(TestAsServer, self).tearDown(annotate=False)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Utilities/twisted_thread.py", line 151, in errback
I:     failure.raiseException()
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
I:     current.result = callback(current.result, *args, **kw)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 143, in checkReactor
I:     self.assertFalse(delayed_calls, "The reactor was dirty when tearing down the test")
I: AssertionError: The reactor was dirty when tearing down the test
I: ----------------------------------------------------------------------

# Fixed code
def __init__(self, parent):
    HomePanel.__init__(self, parent, "Recent Activity", SEPARATOR_GREY, (1, 0))
    session = self.utility.session
    # TODO(emilon): This observer should be removed when shutting down.
    session.add_observer(self.on_tunnel_remove, NTFY_TUNNEL, [NTFY_REMOVE])
# Buggy code
def on_tunnel_remove(self, subject, change_type, tunnel, candidate):
    self.onActivity(
        "Tunnel removed with: [Up = "
        + str(tunnel.bytes_up)
        + " bytes | Down = "
        + str(tunnel.bytes_down)
        + " bytes]"
    )


# Traceback (AssertionError)
I: test_add_torrent_from_magnet_to_channel_without_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... ok
I: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint) ... 2016-07-04 16:21:10,891 [ERROR] The reactor was dirty:
I: 2016-07-04 16:21:10,894 [ERROR] >     <DelayedCall 0x9792a968 [0.772477149963s] called=0 cancelled=0 LoopingCall<5>(ChannelCommunity.take_step, *(), **{})()>
I: 2016-07-04 16:21:10,897 [ERROR] >     <DelayedCall 0x978549e0 [4.73240303993s] called=0 cancelled=0 LoopingCall<5.0>(ChannelCommunity._periodically_clean_delayed, *(), **{})()>
I: ERROR
I: ======================================================================
I: ERROR: test_add_torrent_from_url_to_channel_with_description (Tribler.Test.Core.Modules.RestApi.Channels.test_channels_torrents_endpoint.TestModifyChannelTorrentEndpoint)
I: ----------------------------------------------------------------------
I: Traceback (most recent call last):
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 274, in tearDown
I:     super(TestAsServer, self).tearDown(annotate=False)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Utilities/twisted_thread.py", line 151, in errback
I:     failure.raiseException()
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
I:     current.result = callback(current.result, *args, **kw)
I:   File "/data/data/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Test/test_as_server.py", line 143, in checkReactor
I:     self.assertFalse(delayed_calls, "The reactor was dirty when tearing down the test")
I: AssertionError: The reactor was dirty when tearing down the test
I: ----------------------------------------------------------------------

# Fixed code
def on_tunnel_remove(self, subject, change_type, tunnel, candidate):
    if not self:
        return
    self.onActivity(
        "Tunnel removed with: [Up = "
        + str(tunnel.bytes_up)
        + " bytes | Down = "
        + str(tunnel.bytes_down)
        + " bytes]"
    )
# Buggy code
def process_alert(self, alert, alert_type):
    if alert.category() in [
        lt.alert.category_t.error_notification,
        lt.alert.category_t.performance_warning,
    ]:
        self._logger.debug(
            "LibtorrentDownloadImpl: alert %s with message %s", alert_type, alert
        )

    alert_types = (
        "tracker_reply_alert",
        "tracker_error_alert",
        "tracker_warning_alert",
        "metadata_received_alert",
        "file_renamed_alert",
        "performance_alert",
        "torrent_checked_alert",
        "torrent_finished_alert",
        "save_resume_data_alert",
    )

    if alert_type in alert_types:
        getattr(self, "on_" + alert_type)(alert)
    else:
        self.update_lt_stats()


# Traceback (AssertionError)
ERROR   1472497939.37  LaunchManyCore:637   Exception while checkpointing: tails-i386-2.3
Traceback (most recent call last):
File "/home/vi/home/tribler/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py", line 634, in network_checkpoint_callback
self.save_download_pstate(infohash, pstate)
File "/home/vi/home/tribler/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py", line 808, in save_download_pstate
self.downloads[infohash].save_resume_data())
File "/home/vi/home/tribler/tribler/Tribler/dispersy/taskmanager.py", line 41, in register_task
assert not self.is_pending_task_active(name), name
AssertionError: save_pstate 1862.259269

# Fixed code
def process_alert(self, alert, alert_type):
    if alert.category() in [
        lt.alert.category_t.error_notification,
        lt.alert.category_t.performance_warning,
    ]:
        self._logger.debug(
            "LibtorrentDownloadImpl: alert %s with message %s", alert_type, alert
        )

    alert_types = (
        "tracker_reply_alert",
        "tracker_error_alert",
        "tracker_warning_alert",
        "metadata_received_alert",
        "file_renamed_alert",
        "performance_alert",
        "torrent_checked_alert",
        "torrent_finished_alert",
        "save_resume_data_alert",
        "save_resume_data_failed_alert",
    )

    if alert_type in alert_types:
        getattr(self, "on_" + alert_type)(alert)
    else:
        self.update_lt_stats()
# Buggy code
def on_save_resume_data_alert(self, alert):
    """
    alert to handle save_resume_data_alert
    it will assign stored resume data in an attribute,
        and write it to a file
    """
    resume_data = alert.resume_data

    if not self.pstate_for_restart:
        self.pstate_for_restart = self.network_get_persistent_state()

    self.pstate_for_restart.set("state", "engineresumedata", resume_data)
    self._logger.debug(
        "%s get resume data %s", hexlify(resume_data["info-hash"]), resume_data
    )

    # save it to file
    basename = hexlify(resume_data["info-hash"]) + ".state"
    filename = os.path.join(self.session.get_downloads_pstate_dir(), basename)

    self._logger.debug("tlm: network checkpointing: to file %s", filename)

    self.pstate_for_restart.write_file(filename)

    # fire callback for all deferreds_resume
    for deferred_r in self.deferreds_resume:
        deferred_r.callback(resume_data)

    # empties the deferred list
    self.deferreds_resume = []


# Traceback (AssertionError)
ERROR   1472497939.37  LaunchManyCore:637   Exception while checkpointing: tails-i386-2.3
Traceback (most recent call last):
File "/home/vi/home/tribler/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py", line 634, in network_checkpoint_callback
self.save_download_pstate(infohash, pstate)
File "/home/vi/home/tribler/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py", line 808, in save_download_pstate
self.downloads[infohash].save_resume_data())
File "/home/vi/home/tribler/tribler/Tribler/dispersy/taskmanager.py", line 41, in register_task
assert not self.is_pending_task_active(name), name
AssertionError: save_pstate 1862.259269

# Fixed code
def on_save_resume_data_alert(self, alert):
    """
    Callback for the alert that contains the resume data of a specific download.
    This resume data will be written to a file on disk.
    """
    resume_data = alert.resume_data

    self.pstate_for_restart = self.get_persistent_download_config()
    self.pstate_for_restart.set("state", "engineresumedata", resume_data)
    self._logger.debug(
        "%s get resume data %s", hexlify(resume_data["info-hash"]), resume_data
    )

    # save it to file
    basename = hexlify(resume_data["info-hash"]) + ".state"
    filename = os.path.join(self.session.get_downloads_pstate_dir(), basename)

    self._logger.debug("tlm: network checkpointing: to file %s", filename)

    self.pstate_for_restart.write_file(filename)

    # fire callback for all deferreds_resume
    for deferred_r in self.deferreds_resume:
        deferred_r.callback(resume_data)

    # empties the deferred list
    self.deferreds_resume = []
# Buggy code
def save_resume_data(self):
    """
    method to save resume data.
    """
    # only call libtorrent save resume in the first call
    if not self.deferreds_resume:
        self.handle.save_resume_data()

    defer_resume = Deferred()
    defer_resume.addErrback(self._on_resume_err)

    self.deferreds_resume.append(defer_resume)

    return defer_resume


# Traceback (AssertionError)
ERROR   1472497939.37  LaunchManyCore:637   Exception while checkpointing: tails-i386-2.3
Traceback (most recent call last):
File "/home/vi/home/tribler/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py", line 634, in network_checkpoint_callback
self.save_download_pstate(infohash, pstate)
File "/home/vi/home/tribler/tribler/Tribler/Core/APIImplementation/LaunchManyCore.py", line 808, in save_download_pstate
self.downloads[infohash].save_resume_data())
File "/home/vi/home/tribler/tribler/Tribler/dispersy/taskmanager.py", line 41, in register_task
assert not self.is_pending_task_active(name), name
AssertionError: save_pstate 1862.259269

# Fixed code
def save_resume_data(self):
    """
    Save the resume data of a download. This method returns a deferred that fires when the resume data is available.
    Note that this method only calls save_resume_data once on subsequent calls.
    """
    if not self.deferreds_resume:
        self.get_handle().addCallback(lambda handle: handle.save_resume_data())

    defer_resume = Deferred()
    defer_resume.addErrback(self._on_resume_err)

    self.deferreds_resume.append(defer_resume)

    return defer_resume