gurudesh/pytracebugs huggingface dataset:
# Buggy code
def parse_feed(self):
    rss_parser = RSSFeedParser()

    def_list = []

    for rss_item in rss_parser.parse(self.rss_url, self._url_cache):
        if self._to_stop:
            return None

        torrent_deferred = getPage(rss_item["torrent_url"].encode("utf-8"))
        torrent_deferred.addCallback(
            lambda t, r=rss_item: self.on_got_torrent(t, rss_item=r)
        )
        def_list.append(torrent_deferred)

    return DeferredList(def_list, consumeErrors=True)


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI/widgets/editchannelpage.py", line 556, in on_rss_feeds_refreshed
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def parse_feed(self):
    rss_parser = RSSFeedParser()

    def on_rss_items(rss_items):
        def_list = []
        for rss_item in rss_items:
            if self._to_stop:
                continue

            torrent_url = rss_item["torrent_url"].encode("utf-8")
            if torrent_url.startswith("magnet:"):
                self._logger.warning(
                    "Tribler does not support adding magnet links to a channel from a RSS feed."
                )
                continue

            torrent_deferred = getPage(torrent_url)
            torrent_deferred.addCallbacks(
                lambda t, r=rss_item: self.on_got_torrent(t, rss_item=r),
                self.on_got_torrent_error,
            )
            def_list.append(torrent_deferred)

        return DeferredList(def_list, consumeErrors=True)

    return rss_parser.parse(self.rss_url, self._url_cache).addCallback(on_rss_items)
# Buggy code
def _task_scrape(self):
    self.parse_feed()

    if not self._to_stop:
        # schedule the next scraping task
        self._logger.info(
            "Finish scraping %s, schedule task after %s",
            self.rss_url,
            self.check_interval,
        )
        self.register_task(
            "rss_scrape", reactor.callLater(self.check_interval, self._task_scrape)
        )


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI/widgets/editchannelpage.py", line 556, in on_rss_feeds_refreshed
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def _task_scrape(self):
    deferred = self.parse_feed()

    if not self._to_stop:
        # schedule the next scraping task
        self._logger.info(
            "Finish scraping %s, schedule task after %s",
            self.rss_url,
            self.check_interval,
        )
        self.register_task(
            "rss_scrape", reactor.callLater(self.check_interval, self._task_scrape)
        )

    return deferred
# Buggy code
def parse(self, url, cache):
    """Parses a RSS feed. This methods supports RSS 2.0 and Media RSS."""
    feed = feedparser.parse(url)

    for item in feed.entries:
        # ignore the ones that we have seen before
        link = item.get("link", None)
        if link is None or cache.has(link):
            continue

        title = self._html2plaintext(item["title"]).strip()
        description = self._html2plaintext(item.get("media_description", "")).strip()
        torrent_url = item["link"]

        thumbnail_list = []
        media_thumbnail_list = item.get("media_thumbnail", None)
        if media_thumbnail_list:
            for thumbnail in media_thumbnail_list:
                thumbnail_list.append(thumbnail["url"])

        # assemble the information
        parsed_item = {
            "title": title,
            "description": description,
            "torrent_url": torrent_url,
            "thumbnail_list": thumbnail_list,
        }

        yield parsed_item


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI/widgets/editchannelpage.py", line 556, in on_rss_feeds_refreshed
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def parse(self, url, cache):
    """
    Parses a RSS feed. This methods supports RSS 2.0 and Media RSS.
    """

    def on_rss_response(response):
        feed = feedparser.parse(response)
        feed_items = []

        for item in feed.entries:
            # ignore the ones that we have seen before
            link = item.get("link", None)
            if link is None or cache.has(link):
                continue

            title = self._html2plaintext(item["title"]).strip()
            description = self._html2plaintext(
                item.get("media_description", "")
            ).strip()
            torrent_url = item["link"]

            thumbnail_list = []
            media_thumbnail_list = item.get("media_thumbnail", None)
            if media_thumbnail_list:
                for thumbnail in media_thumbnail_list:
                    thumbnail_list.append(thumbnail["url"])

            # assemble the information
            parsed_item = {
                "title": title,
                "description": description,
                "torrent_url": torrent_url,
                "thumbnail_list": thumbnail_list,
            }

            feed_items.append(parsed_item)

        return feed_items

    def on_rss_error(failure):
        self._logger.error("Error when fetching RSS feed: %s", failure)

    return http_get(str(url)).addCallbacks(on_rss_response, on_rss_error)
# Buggy code
def __init__(
    self, session, channel_community, rss_url, check_interval=DEFAULT_CHECK_INTERVAL
):
    super(ChannelRssParser, self).__init__()
    self._logger = logging.getLogger(self.__class__.__name__)

    self.session = session
    self.channel_community = channel_community
    self.rss_url = rss_url
    self.check_interval = check_interval

    self._url_cache = None

    self._pending_metadata_requests = {}

    self._to_stop = False

    self.running = False


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI/widgets/editchannelpage.py", line 556, in on_rss_feeds_refreshed
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def __init__(self):
    self._logger = logging.getLogger(self.__class__.__name__)
# Buggy code
def render_POST(self, request):
    """
    .. http:post:: /channels/discovered/(string: channelid)/recheckfeeds

    Rechecks all rss feeds in your channel. Returns error 404 if you channel does not exist.

        **Example request**:

        .. sourcecode:: none

            curl -X POST http://localhost:8085/channels/discovered/recheckrssfeeds

        **Example response**:

        .. sourcecode:: javascript

            {
                "rechecked": True
            }

        :statuscode 404: if you have not created a channel.
    """
    channel_obj, error = self.get_my_channel_obj_or_error(request)
    if channel_obj is None:
        return error

    channel_obj.refresh_all_feeds()

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


# Traceback (TypeError)
Traceback (most recent call last):
File "TriblerGUI/widgets/editchannelpage.py", line 556, in on_rss_feeds_refreshed
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def render_POST(self, request):
    """
    .. http:post:: /channels/discovered/(string: channelid)/recheckfeeds

    Rechecks all rss feeds in your channel. Returns error 404 if you channel does not exist.

        **Example request**:

        .. sourcecode:: none

            curl -X POST http://localhost:8085/channels/discovered/recheckrssfeeds

        **Example response**:

        .. sourcecode:: javascript

            {
                "rechecked": True
            }

        :statuscode 404: if you have not created a channel.
    """
    channel_obj, error = self.get_my_channel_obj_or_error(request)
    if channel_obj is None:
        return error

    def on_refreshed(_):
        request.write(json.dumps({"rechecked": True}))
        request.finish()

    def on_refresh_error(failure):
        self._logger.exception(failure.value)
        request.write(BaseChannelsEndpoint.return_500(self, request, failure.value))
        request.finish()

    channel_obj.refresh_all_feeds().addCallbacks(on_refreshed, on_refresh_error)

    return NOT_DONE_YET
# Buggy code
def connect(self):
    """
    Creates a connection message and calls the socket manager to send it.
    """
    # Initiate the connection
    message = struct.pack("!qii", self._connection_id, self.action, self.transaction_id)
    self.socket_mgr.send_request(message, self)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 99, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'socket.error'>: [Errno 51] Network is unreachable
twisted/internet/base.py:828:runUntilCurrent
Tribler/Core/TorrentChecker/torrent_checker.py:128:_task_select_tracker
Tribler/Core/TorrentChecker/session.py:569:connect_to_tracker
twisted/internet/defer.py:308:addCallbacks
--- <exception caught here> ---
twisted/internet/defer.py:651:_runCallbacks
Tribler/Core/TorrentChecker/session.py:479:on_ip_address_resolved
twisted/internet/posixbase.py:369:listenUDP
twisted/internet/udp.py:179:startListening
twisted/internet/udp.py:217:_connectToProtocol
twisted/internet/protocol.py:725:makeConnection
twisted/internet/protocol.py:689:doStart
Tribler/Core/TorrentChecker/session.py:382:startProtocol
twisted/internet/udp.py:340:connect
socket.py:228:meth
]

# Fixed code
def connect(self):
    """
    Creates a connection message and calls the socket manager to send it.
    """
    if not self.socket_mgr.transport:
        self.failed(msg="UDP socket transport not ready")
        return

    # Initiate the connection
    message = struct.pack("!qii", self._connection_id, self.action, self.transaction_id)
    self.socket_mgr.send_request(message, self)
# Buggy code
def initialize(self):
    self._torrent_db = self.tribler_session.open_dbhandler(NTFY_TORRENTS)
    self._reschedule_tracker_select()
    self.socket_mgr = UdpSocketManager()
    self.udp_port = reactor.listenUDP(0, self.socket_mgr)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI/event_request_manager.py", line 99, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'socket.error'>: [Errno 51] Network is unreachable
twisted/internet/base.py:828:runUntilCurrent
Tribler/Core/TorrentChecker/torrent_checker.py:128:_task_select_tracker
Tribler/Core/TorrentChecker/session.py:569:connect_to_tracker
twisted/internet/defer.py:308:addCallbacks
--- <exception caught here> ---
twisted/internet/defer.py:651:_runCallbacks
Tribler/Core/TorrentChecker/session.py:479:on_ip_address_resolved
twisted/internet/posixbase.py:369:listenUDP
twisted/internet/udp.py:179:startListening
twisted/internet/udp.py:217:_connectToProtocol
twisted/internet/protocol.py:725:makeConnection
twisted/internet/protocol.py:689:doStart
Tribler/Core/TorrentChecker/session.py:382:startProtocol
twisted/internet/udp.py:340:connect
socket.py:228:meth
]

# Fixed code
def initialize(self):
    self._torrent_db = self.tribler_session.open_dbhandler(NTFY_TORRENTS)
    self._reschedule_tracker_select()
    self.socket_mgr = UdpSocketManager()
    self.create_socket_or_schedule()
# Buggy code
def received_search_result_channel(self, result):
    # Ignore channels that have a small amount of torrents or have no votes
    if result["torrents"] <= 2 or result["votes"] == 0:
        return
    if self.is_duplicate_channel(result):
        return
    channel_index = bisect_right(
        result, self.search_results["channels"], is_torrent=False
    )
    self.window().search_results_list.insert_item(
        channel_index, (ChannelListItem, result)
    )
    self.search_results["channels"].insert(channel_index, result)
    self.update_num_search_results()


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/widgets/searchresultspage.py", line 101, in received_search_result_torrent
torrent_index + len(self.search_results['channels']), (ChannelTorrentListItem, result))
File "/usr/share/tribler/TriblerGUI/widgets/lazyloadlist.py", line 42, in insert_item
self.load_item(index)
File "/usr/share/tribler/TriblerGUI/widgets/lazyloadlist.py", line 29, in load_item
data_item = self.data_items[index]
IndexError: list index out of range

# Fixed code
def received_search_result_channel(self, result):
    # Ignore channels that have a small amount of torrents or have no votes
    if result["torrents"] <= 2 or result["votes"] == 0:
        return
    if self.is_duplicate_channel(result):
        return
    channel_index = min(
        bisect_right(result, self.search_results["channels"], is_torrent=False),
        len(self.search_results["channels"]),
    )
    self.window().search_results_list.insert_item(
        channel_index, (ChannelListItem, result)
    )
    self.search_results["channels"].insert(channel_index, result)
    self.update_num_search_results()
# Buggy code
def received_search_result_torrent(self, result):
    if self.is_duplicate_torrent(result):
        return
    torrent_index = bisect_right(
        result, self.search_results["torrents"], is_torrent=True
    )
    self.search_results["torrents"].insert(torrent_index, result)
    self.window().search_results_list.insert_item(
        torrent_index + len(self.search_results["channels"]),
        (ChannelTorrentListItem, result),
    )
    self.update_num_search_results()


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/widgets/searchresultspage.py", line 101, in received_search_result_torrent
torrent_index + len(self.search_results['channels']), (ChannelTorrentListItem, result))
File "/usr/share/tribler/TriblerGUI/widgets/lazyloadlist.py", line 42, in insert_item
self.load_item(index)
File "/usr/share/tribler/TriblerGUI/widgets/lazyloadlist.py", line 29, in load_item
data_item = self.data_items[index]
IndexError: list index out of range

# Fixed code
def received_search_result_torrent(self, result):
    if self.is_duplicate_torrent(result):
        return
    torrent_index = min(
        bisect_right(result, self.search_results["torrents"], is_torrent=True),
        len(self.search_results["torrents"]),
    )
    self.search_results["torrents"].insert(torrent_index, result)
    self.window().search_results_list.insert_item(
        torrent_index + len(self.search_results["channels"]),
        (ChannelTorrentListItem, result),
    )
    self.update_num_search_results()
# Buggy code
def on_received_search_completions(self, completions):
    self.received_search_completions.emit(completions)
    self.search_completion_model.setStringList(completions["completions"])


# Traceback (TypeError)
ERROR   1507902146.61  tribler_window:77    Traceback (most recent call last):
File "C:\Users\goqs\Documents\tribler\TriblerGUI\tribler_window.py", line 327, in on_received_search_completions
self.search_completion_model.setStringList(completions["completions"])
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def on_received_search_completions(self, completions):
    if completions is None:
        return
    self.received_search_completions.emit(completions)
    self.search_completion_model.setStringList(completions["completions"])
# Buggy code
def on_metainfo_timeout(_):
    request.setResponseCode(http.REQUEST_TIMEOUT)
    request.write(json.dumps({"error": "timeout"}))
    self.finish_request(request)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'writeSequence'
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:653:_runCallbacks
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:1117:_cbDeferred
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:459:callback
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:567:_startRunCallbacks
--- <exception caught here> ---
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:653:_runCallbacks
/usr/share/tribler/Tribler/Core/Modules/restapi/torrents_endpoint.py:218:on_request_error
/usr/lib/python2.7/site-packages/twisted/web/server.py:234:write
/usr/lib/python2.7/site-packages/twisted/web/http.py:1084:write
]

# Fixed code
def on_metainfo_timeout(_):
    if not request.finished:
        request.setResponseCode(http.REQUEST_TIMEOUT)
        request.write(json.dumps({"error": "timeout"}))
    # If the above request.write failed, the request will have already been finished
    if not request.finished:
        self.finish_request(request)
# Buggy code
def on_request_error(failure):
    request.setResponseCode(http.BAD_REQUEST)
    request.write(json.dumps({"error": failure.getErrorMessage()}))
    self.finish_request(request)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 99, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'writeSequence'
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:653:_runCallbacks
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:1117:_cbDeferred
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:459:callback
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:567:_startRunCallbacks
--- <exception caught here> ---
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:653:_runCallbacks
/usr/share/tribler/Tribler/Core/Modules/restapi/torrents_endpoint.py:218:on_request_error
/usr/lib/python2.7/site-packages/twisted/web/server.py:234:write
/usr/lib/python2.7/site-packages/twisted/web/http.py:1084:write
]

# Fixed code
def on_request_error(failure):
    if not request.finished:
        request.setResponseCode(http.BAD_REQUEST)
        request.write(json.dumps({"error": failure.getErrorMessage()}))
    # If the above request.write failed, the request will have already been finished
    if not request.finished:
        self.finish_request(request)
# Buggy code
def on_lookup_error(failure):
    failure.trap(ConnectError, DNSLookupError)
    request.setResponseCode(http.INTERNAL_SERVER_ERROR)
    request.write(json.dumps({"error": failure.getErrorMessage()}))
    self.finish_request(request)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "TriblerGUI\event_request_manager.py", line 99, in on_read_data
RuntimeError: [Failure instance: Traceback: <class 'Tribler.Core.exceptions.HttpError'>: <class 'Tribler.Core.exceptions.HttpError'>: None
lib\site-packages\twisted\internet\defer.py:567:_startRunCallbacks
lib\site-packages\twisted\internet\defer.py:653:_runCallbacks
lib\site-packages\twisted\internet\defer.py:459:callback
lib\site-packages\twisted\internet\defer.py:567:_startRunCallbacks
--- <exception caught here> ---
lib\site-packages\twisted\internet\defer.py:653:_runCallbacks
Tribler\Core\Modules\restapi\torrentinfo_endpoint.py:80:on_lookup_error
lib\site-packages\twisted\python\failure.py:346:trap
lib\site-packages\twisted\internet\defer.py:653:_runCallbacks
Tribler\Core\Utilities\utilities.py:208:_on_response
]

# Fixed code
def on_lookup_error(failure):
    failure.trap(ConnectError, DNSLookupError, HttpError)
    request.setResponseCode(http.INTERNAL_SERVER_ERROR)
    request.write(json.dumps({"error": failure.getErrorMessage()}))
    self.finish_request(request)
# Buggy code
def on_play_request_done(self, result):
    self.window().left_menu_button_video_player.click()
    self.window().video_player_page.set_torrent_infohash(self.torrent_info["infohash"])
    self.window().left_menu_playlist.set_loading()


# Traceback (AttributeError)
Traceback (most recent call last):
File "TriblerGUI\widgets\channel_torrent_list_item.py", line 78, in on_play_request_done
AttributeError: 'NoneType' object has no attribute 'window'

# Fixed code
def on_play_request_done(self, result):
    if not self:
        return
    self.window().left_menu_button_video_player.click()
    self.window().video_player_page.set_torrent_infohash(self.torrent_info["infohash"])
    self.window().left_menu_playlist.set_loading()
# Buggy code
def get_default_state_dir(home_dir_postfix=".Tribler"):
    """Get the default application state directory."""
    state_directory_variable = "${TSTATEDIR}"
    state_directory = os.path.expandvars(state_directory_variable)
    if state_directory and state_directory != state_directory_variable:
        return state_directory

    if os.path.isdir(home_dir_postfix):
        return os.path.abspath(home_dir_postfix)

    application_directory = get_appstate_dir()
    return os.path.join(application_directory, home_dir_postfix)


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

# Fixed code
def get_default_state_dir(home_dir_postfix=".Tribler"):
    """Get the default application state directory."""
    if "TSTATEDIR" in os.environ:
        return os.environ["TSTATEDIR"]

    if os.path.isdir(home_dir_postfix):
        return os.path.abspath(home_dir_postfix)

    application_directory = get_appstate_dir()
    return os.path.join(application_directory, home_dir_postfix)
# Buggy code
def _on_create_failure(failure):
    """
    Error callback
    :param failure: from create_torrent_file
    """
    failure.trap(IOError, UnicodeDecodeError, RuntimeError)
    self._logger.exception(failure)
    request.write(return_handled_exception(request, failure.value))
    request.finish()


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

# Fixed code
def _on_create_failure(failure):
    """
    Error callback
    :param failure: from create_torrent_file
    """
    failure.trap(IOError, UnicodeDecodeError, RuntimeError)
    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 __init__(self, session):
    resource.Resource.__init__(self)

    child_handler_dict = {
        "circuits": DebugCircuitsEndpoint,
        "open_files": DebugOpenFilesEndpoint,
        "open_sockets": DebugOpenSocketsEndpoint,
        "threads": DebugThreadsEndpoint,
        "cpu_history": DebugCPUHistoryEndpoint,
        "memory_history": DebugMemoryHistoryEndpoint,
    }

    for path, child_cls in child_handler_dict.iteritems():
        self.putChild(path, child_cls(session))


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

# Fixed code
def __init__(self, session):
    resource.Resource.__init__(self)

    child_handler_dict = {
        "circuits": DebugCircuitsEndpoint,
        "open_files": DebugOpenFilesEndpoint,
        "open_sockets": DebugOpenSocketsEndpoint,
        "threads": DebugThreadsEndpoint,
        "cpu": DebugCPUEndpoint,
        "memory": DebugMemoryEndpoint,
        "log": DebugLogEndpoint,
    }

    for path, child_cls in child_handler_dict.iteritems():
        self.putChild(path, child_cls(session))
# Buggy code
def render_GET(self, request):
    """
    .. http:get:: /debug/cpu_history

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

        **Example request**:

        .. sourcecode:: none

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

        **Example response**:

        .. sourcecode:: javascript

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


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

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

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

        **Example request**:

        .. sourcecode:: none

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

        **Example response**:

        .. sourcecode:: javascript

            {
                "cpu_history": [{
                    "time": 1504015291214,
                    "cpu": 3.4,
                }, ...]
            }
    """
    return json.dumps(
        {"cpu_history": self.session.lm.resource_monitor.get_cpu_history_dict()}
    )
# Buggy code
def render_GET(self, request):
    """
    .. http:get:: /debug/memory_history

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

        **Example request**:

        .. sourcecode:: none

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

        **Example response**:

        .. sourcecode:: javascript

            {
                "memory_history": [{
                    "time": 1504015291214,
                    "mem": 324324,
                }, ...]
            }
    """
    return json.dumps(
        {"memory_history": self.session.lm.resource_monitor.get_memory_history_dict()}
    )


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

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

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

        **Example request**:

        .. sourcecode:: none

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

        **Example response**:

        .. sourcecode:: javascript

            {
                "memory_history": [{
                    "time": 1504015291214,
                    "mem": 324324,
                }, ...]
            }
    """
    return json.dumps(
        {"memory_history": self.session.lm.resource_monitor.get_memory_history_dict()}
    )
# Buggy code
def __init__(self, session):
    self._logger = logging.getLogger(self.__class__.__name__)
    self._session = session

    self._tracker_id_to_url_dict = {}
    self._tracker_dict = {}

    # if a tracker fails this amount of times in a roll, its 'is_alive' will be marked as 0 (dead).
    self._max_tracker_failures = MAX_TRACKER_FAILURES

    # A "dead" tracker will be retired every this amount of time (in seconds)
    self._tracker_retry_interval = TRACKER_RETRY_INTERVAL


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

# Fixed code
def __init__(self, session):
    self._logger = logging.getLogger(self.__class__.__name__)
    self._session = session
# Buggy code
def get_tracker_info(self, tracker_url):
    """
    Gets the tracker information with the given tracker URL.
    :param tracker_url: The given tracker URL.
    :return: The tracker info dict if exists, None otherwise.
    """
    sanitized_tracker_url = get_uniformed_tracker_url(tracker_url)
    return self._tracker_dict.get(sanitized_tracker_url)


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

# Fixed code
def get_tracker_info(self, tracker_url):
    """
    Gets the tracker information with the given tracker URL.
    :param tracker_url: The given tracker URL.
    :return: The tracker info dict if exists, None otherwise.
    """
    sanitized_tracker_url = (
        get_uniformed_tracker_url(tracker_url) if tracker_url != "DHT" else tracker_url
    )
    try:
        sql_stmt = "SELECT tracker_id, tracker, last_check, failures, is_alive FROM TrackerInfo WHERE tracker = ?"
        result = self._session.sqlite_db.execute(
            sql_stmt, (sanitized_tracker_url,)
        ).next()
    except StopIteration:
        return None

    return {
        "id": result[0],
        "last_check": result[2],
        "failures": result[3],
        "is_alive": bool(result[4]),
    }
# Buggy code
def get_next_tracker_for_auto_check(self):
    """
    Gets the next tracker for automatic tracker-checking.
    :return: The next tracker for automatic tracker-checking.
    """
    if len(self._tracker_dict) == 0:
        return

    next_tracker_url = None
    next_tracker_info = None

    sorted_tracker_list = sorted(
        self._tracker_dict.items(), key=lambda d: d[1]["last_check"]
    )

    for tracker_url, tracker_info in sorted_tracker_list:
        if tracker_url == "DHT":
            next_tracker_url = tracker_url
            next_tracker_info = {"is_alive": True, "last_check": int(time.time())}
            break
        elif tracker_url != "no-DHT" and self.should_check_tracker(tracker_url):
            next_tracker_url = tracker_url
            next_tracker_info = tracker_info
            break

    if next_tracker_url is None:
        return
    return next_tracker_url, next_tracker_info


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

# Fixed code
def get_next_tracker_for_auto_check(self):
    """
    Gets the next tracker for automatic tracker-checking.
    :return: The next tracker for automatic tracker-checking.
    """
    try:
        sql_stmt = (
            "SELECT tracker FROM TrackerInfo WHERE tracker != 'no-DHT' AND tracker != 'DHT' AND "
            "last_check + ? <= strftime('%s','now') AND is_alive = 1 ORDER BY last_check LIMIT 1;"
        )
        result = self._session.sqlite_db.execute(
            sql_stmt, (TRACKER_RETRY_INTERVAL,)
        ).next()
    except StopIteration:
        return None

    return result[0]
# Buggy code
def clean_session(self, session):
    self.tribler_session.lm.tracker_manager.update_tracker_info(
        session.tracker_url, not session.is_failed
    )
    self.session_stop_defer_list.append(session.cleanup())

    # Remove the session from our session list dictionary
    self._session_list[session.tracker_url].remove(session)


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

# Fixed code
def clean_session(self, session):
    self.tribler_session.lm.tracker_manager.update_tracker_info(
        session.tracker_url, not session.is_failed
    )
    self.session_stop_defer_list.append(session.cleanup())

    # Remove the session from our session list dictionary
    self._session_list[session.tracker_url].remove(session)
    if (
        len(self._session_list[session.tracker_url]) == 0
        and session.tracker_url != "DHT"
    ):
        del self._session_list[session.tracker_url]
# Buggy code
def dump(obj, fp, ensure_ascii=True):
    """
    Attempt to json.dump() an object to a 'file'. This function provides additional info if the object can't
    be serialized.

    :param obj: the object to serialize.
    :param fp: the file-like object to write to.
    :param ensure_ascii: allow binary strings to be sent
    """
    try:
        json.dump(obj, fp, ensure_ascii=ensure_ascii)
    except UnicodeDecodeError as e:
        undumpables = _scan_iterable(obj)
        traces = "\n\t".join(["->".join(u) for u in undumpables])
        raise UnicodeDecodeError(
            e.encoding, str(obj), e.start, e.end, "could not dump:\n\t%s" % traces
        )


# Traceback (AssertionError)
Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')
Stacktrace

Traceback (most recent call last):
File "c:\python27\lib\unittest\case.py", line 329, in run
testMethod()
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\test_as_server.py", line 58, in check
result = fun(*argv, **kwargs)
File "C:\workspace\jenkins\workspace\GH_Tribler_PR_tests_win64\tribler\Tribler\Test\Core\Upgrade\test_config_upgrade_70_71.py", line 33, in test_read_test_libtribler_conf
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
File "c:\python27\lib\unittest\case.py", line 513, in assertEqual
assertion_func(first, second, msg=msg)
File "c:\python27\lib\unittest\case.py", line 753, in assertTupleEqual
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
File "c:\python27\lib\unittest\case.py", line 724, in assertSequenceEqual
self.fail(msg)
File "c:\python27\lib\unittest\case.py", line 410, in fail
raise self.failureException(msg)
AssertionError: Tuples differ: (2, ('127.0.0.1', [5, 4, 3, 2,... != (2, ('127.0.0.1', [5, 4, 3, 2,...

First differing element 2:
u'None'
''

- (2, ('127.0.0.1', [5, 4, 3, 2, 1]), u'None')
?                                     - ----

+ (2, ('127.0.0.1', [5, 4, 3, 2, 1]), '')

# Fixed code
def dump(obj, fp, ensure_ascii=True):
    """
    Attempt to json.dump() an object to a 'file'. This function provides additional info if the object can't
    be serialized.

    :param obj: the object to serialize.
    :param fp: the file-like object to write to.
    :param ensure_ascii: allow binary strings to be sent
    """
    try:
        json.dump(obj, fp, ensure_ascii=ensure_ascii)
    except UnicodeDecodeError as e:
        undumpables = _scan_iterable(obj)
        traces = "\n\t".join(["->".join(u) for u in undumpables])
        error = UnicodeDecodeError(
            e.encoding, str(obj), e.start, e.end, "could not dump:\n\t%s" % traces
        )
        error.message = str(error)
        raise error