gurudesh/pytracebugs huggingface dataset:
# Buggy code
def restart(self, initialdlstatus=None):
    """Restart the Download"""
    # Called by any thread
    self._logger.debug("LibtorrentDownloadImpl: restart: %s", self.tdef.get_name())

    with self.dllock:
        if self.handle is None:
            self.error = None

            def schedule_create_engine(_):
                self.cew_scheduled = True
                create_engine_wrapper_deferred = self.network_create_engine_wrapper(
                    self.pstate_for_restart,
                    initialdlstatus,
                    share_mode=self.get_share_mode(),
                )
                create_engine_wrapper_deferred.addCallback(
                    self.session.lm.on_download_wrapper_created
                )

            can_create_engine_deferred = self.can_create_engine_wrapper()
            can_create_engine_deferred.addCallback(schedule_create_engine)
        else:
            self.handle.resume()
            self.set_vod_mode(self.get_mode() == DLMODE_VOD)


# 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 restart(self, initialdlstatus=None):
    """Restart the Download"""
    # Called by any thread
    self._logger.debug("LibtorrentDownloadImpl: restart: %s", self.tdef.get_name())

    with self.dllock:
        if self.handle is None:
            self.error = None

            def schedule_create_engine(_):
                self.cew_scheduled = True
                create_engine_wrapper_deferred = self.network_create_engine_wrapper(
                    self.pstate_for_restart,
                    initialdlstatus,
                    share_mode=self.get_share_mode(),
                )
                create_engine_wrapper_deferred.addCallback(
                    self.session.lm.on_download_handle_created
                )

            can_create_engine_deferred = self.can_create_engine_wrapper()
            can_create_engine_deferred.addCallback(schedule_create_engine)
        else:
            self.handle.resume()
            self.set_vod_mode(self.get_mode() == DLMODE_VOD)
# Buggy code
def schedule_create_engine(_):
    self.cew_scheduled = True
    create_engine_wrapper_deferred = self.network_create_engine_wrapper(
        self.pstate_for_restart, initialdlstatus, share_mode=self.get_share_mode()
    )
    create_engine_wrapper_deferred.addCallback(
        self.session.lm.on_download_wrapper_created
    )


# 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 schedule_create_engine(_):
    self.cew_scheduled = True
    create_engine_wrapper_deferred = self.network_create_engine_wrapper(
        self.pstate_for_restart, initialdlstatus, share_mode=self.get_share_mode()
    )
    create_engine_wrapper_deferred.addCallback(
        self.session.lm.on_download_handle_created
    )
# Buggy code
def checkpoint(self):
    """Called by any thread"""
    if self._checkpoint_disabled:
        self._logger.warning(
            "Ignoring checkpoint() call as is checkpointing disabled for this download."
        )
    else:
        infohash, pstate = self.network_checkpoint()
        reactor.callFromThread(self.session.lm.save_download_pstate, infohash, pstate)


# 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 checkpoint(self):
    """
    Checkpoint this download. Returns a deferred that fires when the checkpointing is completed.
    """
    if self._checkpoint_disabled or not self.handle or not self.handle.is_valid():
        self._logger.warning(
            "Ignoring checkpoint() call as checkpointing is disabled for this download "
            "or the handle is not ready."
        )
        return succeed(None)

    return self.save_resume_data()
# Buggy code
def add_peer(self, addr):
    """Add a peer address from 3rd source (not tracker, not DHT) to this download.
    @param (hostname_ip,port) tuple
    """
    self.handle.connect_peer(addr, 0)


# 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 add_peer(self, addr):
    """Add a peer address from 3rd source (not tracker, not DHT) to this download.
    @param (hostname_ip,port) tuple
    """
    self.get_handle().addCallback(lambda handle: handle.connect_peer(addr, 0))
# Buggy code
def set_priority(self, prio):
    self.handle.set_priority(prio)


# 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 set_priority(self, prio):
    self.get_handle().addCallback(lambda handle: handle.set_priority(prio))
# Buggy code
def dlconfig_changed_callback(self, section, name, new_value, old_value):
    if section == "downloadconfig" and name == "max_upload_rate":
        self.handle.set_upload_limit(int(new_value * 1024))
    elif section == "downloadconfig" and name == "max_download_rate":
        self.handle.set_download_limit(int(new_value * 1024))
    elif section == "downloadconfig" and name in ["correctedfilename", "super_seeder"]:
        return False
    return True


# 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 dlconfig_changed_callback(self, section, name, new_value, old_value):
    if section == "downloadconfig" and name == "max_upload_rate":
        self.get_handle().addCallback(
            lambda handle: handle.set_upload_limit(int(new_value * 1024))
        )
    elif section == "downloadconfig" and name == "max_download_rate":
        self.get_handle().addCallback(
            lambda handle: handle.set_download_limit(int(new_value * 1024))
        )
    elif section == "downloadconfig" and name in ["correctedfilename", "super_seeder"]:
        return False
    return True
# Buggy code
def set_share_mode(self, share_mode):
    self.handle.set_share_mode(share_mode)


# 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 set_share_mode(self, share_mode):
    self.get_handle().addCallback(lambda handle: handle.set_share_mode(share_mode))
# Buggy code
def checkHandleAndSynchronize(default=None):
    def wrap(f):
        def invoke_func(*args, **kwargs):
            download = args[0]
            with download.dllock:
                if download.handle and download.handle.is_valid():
                    return f(*args, **kwargs)
            return default

        return invoke_func

    return wrap


# 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 checkHandleAndSynchronize(default=None):
    """
    Return the libtorrent handle if it's available, else return the default value
    """

    def wrap(f):
        def invoke_func(*args, **kwargs):
            download = args[0]
            with download.dllock:
                if download.handle and download.handle.is_valid():
                    return f(*args, **kwargs)
            return default

        return invoke_func

    return wrap
# Buggy code
def invoke_func(*args, **kwargs):
    download = args[0]
    with download.dllock:
        if download.handle and download.handle.is_valid():
            return f(*args, **kwargs)
        elif not download.session.lm.shutdownstarttime:
            lambda_f = lambda a=args, kwa=kwargs: invoke_func(*a, **kwa)
            random_id = "".join(random.choice("0123456789abcdef") for _ in xrange(30))
            reactor.callFromThread(
                lambda: download.register_task(
                    "check_handle_%s" % random_id, reactor.callLater(1, lambda_f)
                )
            )
        return default


# 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 invoke_func(*args, **kwargs):
    download = args[0]
    with download.dllock:
        if download.handle and download.handle.is_valid():
            return f(*args, **kwargs)
    return default
# Buggy code
def wrap(f):
    def invoke_func(*args, **kwargs):
        download = args[0]
        with download.dllock:
            if download.handle and download.handle.is_valid():
                return f(*args, **kwargs)
            elif not download.session.lm.shutdownstarttime:
                lambda_f = lambda a=args, kwa=kwargs: invoke_func(*a, **kwa)
                random_id = "".join(
                    random.choice("0123456789abcdef") for _ in xrange(30)
                )
                reactor.callFromThread(
                    lambda: download.register_task(
                        "check_handle_%s" % random_id, reactor.callLater(1, lambda_f)
                    )
                )
            return default

    return invoke_func


# 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 wrap(f):
    def invoke_func(*args, **kwargs):
        download = args[0]
        with download.dllock:
            if download.handle and download.handle.is_valid():
                return f(*args, **kwargs)
        return default

    return invoke_func
# 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_pstate_sessconfig()

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


# 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 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})
# Buggy code
def load_checkpoint(self):
    """
    Restart Downloads from a saved checkpoint, if any. Note that we fetch information from the user download
    choices since it might be that a user has stopped a download. In that case, the download should not be
    resumed immediately when being loaded by libtorrent.
    """
    initialdlstatus_dict = {}
    for infohash, state in self.tribler_config.get_download_states().iteritems():
        if state == "stop":
            initialdlstatus_dict[infohash] = DLSTATUS_STOPPED

    self.lm.load_checkpoint(initialdlstatus_dict=initialdlstatus_dict)


# 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 load_checkpoint(_):
    if self.get_libtorrent():
        self.load_checkpoint()
# Buggy code
def start(self):
    """Create the LaunchManyCore instance and start it"""

    # Create engine with network thread
    startup_deferred = self.lm.register(self, self.sesslock)

    if self.get_libtorrent():
        self.load_checkpoint()

    self.sessconfig.set_callback(self.lm.sessconfig_changed_callback)

    return startup_deferred


# 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 start(self):
    """
    Start a Tribler session by initializing the LaunchManyCore class.
    Returns a deferred that fires when the Tribler session is ready for use.
    """
    startup_deferred = self.lm.register(self, self.sesslock)

    def load_checkpoint(_):
        if self.get_libtorrent():
            self.load_checkpoint()

    self.sessconfig.set_callback(self.lm.sessconfig_changed_callback)

    return startup_deferred.addCallback(load_checkpoint)
# Buggy code
def shutdown(self, checkpoint=True, gracetime=2.0, hacksessconfcheckpoint=True):
    """Checkpoints the session and closes it, stopping the download engine.
    @param checkpoint Whether to checkpoint the Session state on shutdown.
    @param gracetime Time to allow for graceful shutdown + signoff (seconds).
    """
    # Has to be called from the reactor thread
    assert isInIOThread()

    @inlineCallbacks
    def on_early_shutdown_complete(_):
        """
        Callback that gets called when the early shutdown has been compelted.
        Continues the shutdown procedure that is dependant on the early shutdown.
        :param _: ignored parameter of the Deferred
        """
        yield self.checkpoint_shutdown(
            stop=True,
            checkpoint=checkpoint,
            gracetime=gracetime,
            hacksessconfcheckpoint=hacksessconfcheckpoint,
        )
        if self.sqlite_db:
            self.sqlite_db.close()
        self.sqlite_db = None

    return self.lm.early_shutdown().addCallback(on_early_shutdown_complete)


# 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 shutdown(self):
    """
    Checkpoints the session and closes it, stopping the download engine.
    This method has to be called from the reactor thread.
    """
    assert isInIOThread()

    @inlineCallbacks
    def on_early_shutdown_complete(_):
        """
        Callback that gets called when the early shutdown has been completed.
        Continues the shutdown procedure that is dependant on the early shutdown.
        :param _: ignored parameter of the Deferred
        """
        self.save_session_config()
        yield self.checkpoint_downloads()
        self.lm.shutdown_downloads()
        self.lm.network_shutdown()

        if self.sqlite_db:
            self.sqlite_db.close()
        self.sqlite_db = None

    return self.lm.early_shutdown().addCallback(on_early_shutdown_complete)
# Buggy code
def on_early_shutdown_complete(_):
    """
    Callback that gets called when the early shutdown has been compelted.
    Continues the shutdown procedure that is dependant on the early shutdown.
    :param _: ignored parameter of the Deferred
    """
    yield self.checkpoint_shutdown(
        stop=True,
        checkpoint=checkpoint,
        gracetime=gracetime,
        hacksessconfcheckpoint=hacksessconfcheckpoint,
    )
    if self.sqlite_db:
        self.sqlite_db.close()
    self.sqlite_db = None


# 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_early_shutdown_complete(_):
    """
    Callback that gets called when the early shutdown has been completed.
    Continues the shutdown procedure that is dependant on the early shutdown.
    :param _: ignored parameter of the Deferred
    """
    self.save_session_config()
    yield self.checkpoint_downloads()
    self.lm.shutdown_downloads()
    self.lm.network_shutdown()

    if self.sqlite_db:
        self.sqlite_db.close()
    self.sqlite_db = None
# Buggy code
def signal_handler(sig, _):
    msg("Received shut down signal %s" % sig)
    if not self._stopping:
        self._stopping = True
        self.session.shutdown().addCallback(on_shutdown)


# 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 signal_handler(sig, _):
    msg("Received shut down signal %s" % sig)
    if not self._stopping:
        self._stopping = True
        self.session.shutdown().addCallback(on_tribler_shutdown)
# Buggy code
def set_state_callback(self, usercallback, getpeerlist=False, delay=0.0):
    """Called by any thread"""
    with self.dllock:
        network_get_state_lambda = lambda: self.network_get_state(
            usercallback, getpeerlist
        )
        self.session.lm.threadpool.add_task(network_get_state_lambda, delay)


# Traceback (isError)
Regression

Tribler.Test.Core.Modules.RestApi.test_downloads_endpoint.TestDownloadsEndpoint.test_remove_download_no_remove_data_param (from nosetests)
Failing for the past 1 build (Since Failed#2109 )
Took 4.4 sec.
Error Message

Test raised 1 unhandled Twisted exceptions:
[{'log_namespace': u'log_legacy', 'log_time': 1467938979.639, 'format': '%(log_legacy)s', 'log_system': '-', 'log_legacy': <twisted.logger._stdlib.StringifiableFromEvent object at 0x06D22830>, 'log_level': <LogLevel=critical>, 'system': '-', 'isError': 1, 'failure': <twisted.python.failure.Failure exceptions.AttributeError: 'NoneType' object has no attribute 'add_task'>, 'time': 1467938979.639, 'log_text': 'Unhandled Error\nTraceback (most recent call last):\n  File "C:\\Python27\\lib\\threading.py", line 763, in run\n    self.__target(*self.__args, **self.__kwargs)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Utilities\\twisted_thread.py", line 55, in _reactor_runner\n    reactor.run(installSignalHandlers=False)\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1194, in run\n    self.mainLoop()\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1203, in mainLoop\n    self.runUntilCurrent()\n--- <exception caught here> ---\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 825, in runUntilCurrent\n    call.func(*call.args, **call.kw)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 27, in <lambda>\n    lambda_f = lambda a = args, kwa = kwargs: invoke_func(*a, **kwa)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 28, in invoke_func\n    download.session.lm.threadpool.add_task(lambda_f, 1)\nexceptions.AttributeError: \'NoneType\' object has no attribute \'add_task\'\n', 'log_format': u'{log_text}', 'message': (), 'why': None}]

# Fixed code
def set_state_callback(self, usercallback, getpeerlist=False):
    """Called by any thread"""
    with self.dllock:
        reactor.callFromThread(
            lambda: self.network_get_state(usercallback, getpeerlist)
        )
# Buggy code
def session_getstate_usercallback_target():
    when, getpeerlist = usercallback(ds)
    if when > 0.0 and self.session.lm.threadpool:
        # Schedule next invocation, either on general or DL specific
        self.session.lm.threadpool.add_task(
            lambda: self.network_get_state(usercallback, getpeerlist), when
        )


# Traceback (isError)
Regression

Tribler.Test.Core.Modules.RestApi.test_downloads_endpoint.TestDownloadsEndpoint.test_remove_download_no_remove_data_param (from nosetests)
Failing for the past 1 build (Since Failed#2109 )
Took 4.4 sec.
Error Message

Test raised 1 unhandled Twisted exceptions:
[{'log_namespace': u'log_legacy', 'log_time': 1467938979.639, 'format': '%(log_legacy)s', 'log_system': '-', 'log_legacy': <twisted.logger._stdlib.StringifiableFromEvent object at 0x06D22830>, 'log_level': <LogLevel=critical>, 'system': '-', 'isError': 1, 'failure': <twisted.python.failure.Failure exceptions.AttributeError: 'NoneType' object has no attribute 'add_task'>, 'time': 1467938979.639, 'log_text': 'Unhandled Error\nTraceback (most recent call last):\n  File "C:\\Python27\\lib\\threading.py", line 763, in run\n    self.__target(*self.__args, **self.__kwargs)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Utilities\\twisted_thread.py", line 55, in _reactor_runner\n    reactor.run(installSignalHandlers=False)\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1194, in run\n    self.mainLoop()\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1203, in mainLoop\n    self.runUntilCurrent()\n--- <exception caught here> ---\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 825, in runUntilCurrent\n    call.func(*call.args, **call.kw)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 27, in <lambda>\n    lambda_f = lambda a = args, kwa = kwargs: invoke_func(*a, **kwa)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 28, in invoke_func\n    download.session.lm.threadpool.add_task(lambda_f, 1)\nexceptions.AttributeError: \'NoneType\' object has no attribute \'add_task\'\n', 'log_format': u'{log_text}', 'message': (), 'why': None}]

# Fixed code
def session_getstate_usercallback_target():
    when, getpeerlist = usercallback(ds)
    if when > 0.0 and not self.session.lm.shutdownstarttime:
        # Schedule next invocation, either on general or DL specific
        def reschedule_cb():
            dc = reactor.callLater(
                when, lambda: self.network_get_state(usercallback, getpeerlist)
            )
            self.register_task("downloads_cb", dc)

        reactor.callFromThread(reschedule_cb)
# Buggy code
def checkpoint(self):
    """Called by any thread"""
    if self._checkpoint_disabled:
        self._logger.warning(
            "Ignoring checkpoint() call as is checkpointing disabled for this download."
        )
    else:
        infohash, pstate = self.network_checkpoint()
        checkpoint = lambda: self.session.lm.save_download_pstate(infohash, pstate)
        self.session.lm.threadpool.add_task(checkpoint, 0)


# Traceback (isError)
Regression

Tribler.Test.Core.Modules.RestApi.test_downloads_endpoint.TestDownloadsEndpoint.test_remove_download_no_remove_data_param (from nosetests)
Failing for the past 1 build (Since Failed#2109 )
Took 4.4 sec.
Error Message

Test raised 1 unhandled Twisted exceptions:
[{'log_namespace': u'log_legacy', 'log_time': 1467938979.639, 'format': '%(log_legacy)s', 'log_system': '-', 'log_legacy': <twisted.logger._stdlib.StringifiableFromEvent object at 0x06D22830>, 'log_level': <LogLevel=critical>, 'system': '-', 'isError': 1, 'failure': <twisted.python.failure.Failure exceptions.AttributeError: 'NoneType' object has no attribute 'add_task'>, 'time': 1467938979.639, 'log_text': 'Unhandled Error\nTraceback (most recent call last):\n  File "C:\\Python27\\lib\\threading.py", line 763, in run\n    self.__target(*self.__args, **self.__kwargs)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Utilities\\twisted_thread.py", line 55, in _reactor_runner\n    reactor.run(installSignalHandlers=False)\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1194, in run\n    self.mainLoop()\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1203, in mainLoop\n    self.runUntilCurrent()\n--- <exception caught here> ---\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 825, in runUntilCurrent\n    call.func(*call.args, **call.kw)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 27, in <lambda>\n    lambda_f = lambda a = args, kwa = kwargs: invoke_func(*a, **kwa)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 28, in invoke_func\n    download.session.lm.threadpool.add_task(lambda_f, 1)\nexceptions.AttributeError: \'NoneType\' object has no attribute \'add_task\'\n', 'log_format': u'{log_text}', 'message': (), 'why': None}]

# Fixed code
def checkpoint(self):
    """Called by any thread"""
    if self._checkpoint_disabled:
        self._logger.warning(
            "Ignoring checkpoint() call as is checkpointing disabled for this download."
        )
    else:
        infohash, pstate = self.network_checkpoint()
        reactor.callFromThread(self.session.lm.save_download_pstate, infohash, pstate)
# Buggy code
def invoke_func(*args, **kwargs):
    download = args[0]
    with download.dllock:
        if download.handle and download.handle.is_valid():
            return f(*args, **kwargs)
        else:
            lambda_f = lambda a=args, kwa=kwargs: invoke_func(*a, **kwa)
            download.session.lm.threadpool.add_task(lambda_f, 1)
            return default


# Traceback (isError)
Regression

Tribler.Test.Core.Modules.RestApi.test_downloads_endpoint.TestDownloadsEndpoint.test_remove_download_no_remove_data_param (from nosetests)
Failing for the past 1 build (Since Failed#2109 )
Took 4.4 sec.
Error Message

Test raised 1 unhandled Twisted exceptions:
[{'log_namespace': u'log_legacy', 'log_time': 1467938979.639, 'format': '%(log_legacy)s', 'log_system': '-', 'log_legacy': <twisted.logger._stdlib.StringifiableFromEvent object at 0x06D22830>, 'log_level': <LogLevel=critical>, 'system': '-', 'isError': 1, 'failure': <twisted.python.failure.Failure exceptions.AttributeError: 'NoneType' object has no attribute 'add_task'>, 'time': 1467938979.639, 'log_text': 'Unhandled Error\nTraceback (most recent call last):\n  File "C:\\Python27\\lib\\threading.py", line 763, in run\n    self.__target(*self.__args, **self.__kwargs)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Utilities\\twisted_thread.py", line 55, in _reactor_runner\n    reactor.run(installSignalHandlers=False)\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1194, in run\n    self.mainLoop()\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1203, in mainLoop\n    self.runUntilCurrent()\n--- <exception caught here> ---\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 825, in runUntilCurrent\n    call.func(*call.args, **call.kw)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 27, in <lambda>\n    lambda_f = lambda a = args, kwa = kwargs: invoke_func(*a, **kwa)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 28, in invoke_func\n    download.session.lm.threadpool.add_task(lambda_f, 1)\nexceptions.AttributeError: \'NoneType\' object has no attribute \'add_task\'\n', 'log_format': u'{log_text}', 'message': (), 'why': None}]

# Fixed code
def invoke_func(*args, **kwargs):
    download = args[0]
    with download.dllock:
        if download.handle and download.handle.is_valid():
            return f(*args, **kwargs)
        elif not download.session.lm.shutdownstarttime:
            lambda_f = lambda a=args, kwa=kwargs: invoke_func(*a, **kwa)
            random_id = "".join(random.choice("0123456789abcdef") for _ in xrange(30))
            reactor.callFromThread(
                lambda: download.register_task(
                    "check_handle_%s" % random_id, reactor.callLater(1, lambda_f)
                )
            )
        return default
# Buggy code
def delInstance(cls, *args, **kw):
    with cls.__singleton_lock:
        GUIDBProducer.__single = None


# Traceback (isError)
Regression

Tribler.Test.Core.Modules.RestApi.test_downloads_endpoint.TestDownloadsEndpoint.test_remove_download_no_remove_data_param (from nosetests)
Failing for the past 1 build (Since Failed#2109 )
Took 4.4 sec.
Error Message

Test raised 1 unhandled Twisted exceptions:
[{'log_namespace': u'log_legacy', 'log_time': 1467938979.639, 'format': '%(log_legacy)s', 'log_system': '-', 'log_legacy': <twisted.logger._stdlib.StringifiableFromEvent object at 0x06D22830>, 'log_level': <LogLevel=critical>, 'system': '-', 'isError': 1, 'failure': <twisted.python.failure.Failure exceptions.AttributeError: 'NoneType' object has no attribute 'add_task'>, 'time': 1467938979.639, 'log_text': 'Unhandled Error\nTraceback (most recent call last):\n  File "C:\\Python27\\lib\\threading.py", line 763, in run\n    self.__target(*self.__args, **self.__kwargs)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Utilities\\twisted_thread.py", line 55, in _reactor_runner\n    reactor.run(installSignalHandlers=False)\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1194, in run\n    self.mainLoop()\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1203, in mainLoop\n    self.runUntilCurrent()\n--- <exception caught here> ---\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 825, in runUntilCurrent\n    call.func(*call.args, **call.kw)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 27, in <lambda>\n    lambda_f = lambda a = args, kwa = kwargs: invoke_func(*a, **kwa)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 28, in invoke_func\n    download.session.lm.threadpool.add_task(lambda_f, 1)\nexceptions.AttributeError: \'NoneType\' object has no attribute \'add_task\'\n', 'log_format': u'{log_text}', 'message': (), 'why': None}]

# Fixed code
def delInstance(cls, *args, **kw):
    if GUIDBProducer.hasInstance():
        GUIDBProducer.__single.cancel_all_pending_tasks()
    with cls.__singleton_lock:
        GUIDBProducer.__single = None
# Buggy code
def Remove(self, uId):
    if uId in self.uIds:
        self._logger.debug("GUIDBHandler: removing Task(%s)", uId)

        with self.uIdsLock:
            self.uIds.discard(uId)

            if __debug__:
                self.nrCallbacks[uId] = self.nrCallbacks.get(uId, 0) - 1

        self.utility.session.lm.threadpool.cancel_pending_task(uId)


# Traceback (isError)
Regression

Tribler.Test.Core.Modules.RestApi.test_downloads_endpoint.TestDownloadsEndpoint.test_remove_download_no_remove_data_param (from nosetests)
Failing for the past 1 build (Since Failed#2109 )
Took 4.4 sec.
Error Message

Test raised 1 unhandled Twisted exceptions:
[{'log_namespace': u'log_legacy', 'log_time': 1467938979.639, 'format': '%(log_legacy)s', 'log_system': '-', 'log_legacy': <twisted.logger._stdlib.StringifiableFromEvent object at 0x06D22830>, 'log_level': <LogLevel=critical>, 'system': '-', 'isError': 1, 'failure': <twisted.python.failure.Failure exceptions.AttributeError: 'NoneType' object has no attribute 'add_task'>, 'time': 1467938979.639, 'log_text': 'Unhandled Error\nTraceback (most recent call last):\n  File "C:\\Python27\\lib\\threading.py", line 763, in run\n    self.__target(*self.__args, **self.__kwargs)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Utilities\\twisted_thread.py", line 55, in _reactor_runner\n    reactor.run(installSignalHandlers=False)\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1194, in run\n    self.mainLoop()\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1203, in mainLoop\n    self.runUntilCurrent()\n--- <exception caught here> ---\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 825, in runUntilCurrent\n    call.func(*call.args, **call.kw)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 27, in <lambda>\n    lambda_f = lambda a = args, kwa = kwargs: invoke_func(*a, **kwa)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 28, in invoke_func\n    download.session.lm.threadpool.add_task(lambda_f, 1)\nexceptions.AttributeError: \'NoneType\' object has no attribute \'add_task\'\n', 'log_format': u'{log_text}', 'message': (), 'why': None}]

# Fixed code
def Remove(self, uId):
    if uId in self.uIds:
        self._logger.debug("GUIDBHandler: removing Task(%s)", uId)

        with self.uIdsLock:
            self.uIds.discard(uId)

            if __debug__:
                self.nrCallbacks[uId] = self.nrCallbacks.get(uId, 0) - 1

        self.cancel_pending_task(uId)
# Buggy code
def guiservthread_checkpoint_timer(self):
    """Periodically checkpoint Session"""
    if self.done:
        return
    try:
        self._logger.info("main: Checkpointing Session")
        self.utility.session.checkpoint()

        self.utility.session.lm.threadpool.call_in_thread(
            SESSION_CHECKPOINT_INTERVAL, self.guiservthread_checkpoint_timer
        )
    except:
        print_exc()


# Traceback (isError)
Regression

Tribler.Test.Core.Modules.RestApi.test_downloads_endpoint.TestDownloadsEndpoint.test_remove_download_no_remove_data_param (from nosetests)
Failing for the past 1 build (Since Failed#2109 )
Took 4.4 sec.
Error Message

Test raised 1 unhandled Twisted exceptions:
[{'log_namespace': u'log_legacy', 'log_time': 1467938979.639, 'format': '%(log_legacy)s', 'log_system': '-', 'log_legacy': <twisted.logger._stdlib.StringifiableFromEvent object at 0x06D22830>, 'log_level': <LogLevel=critical>, 'system': '-', 'isError': 1, 'failure': <twisted.python.failure.Failure exceptions.AttributeError: 'NoneType' object has no attribute 'add_task'>, 'time': 1467938979.639, 'log_text': 'Unhandled Error\nTraceback (most recent call last):\n  File "C:\\Python27\\lib\\threading.py", line 763, in run\n    self.__target(*self.__args, **self.__kwargs)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Utilities\\twisted_thread.py", line 55, in _reactor_runner\n    reactor.run(installSignalHandlers=False)\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1194, in run\n    self.mainLoop()\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 1203, in mainLoop\n    self.runUntilCurrent()\n--- <exception caught here> ---\n  File "C:\\Python27\\lib\\site-packages\\twisted\\internet\\base.py", line 825, in runUntilCurrent\n    call.func(*call.args, **call.kw)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 27, in <lambda>\n    lambda_f = lambda a = args, kwa = kwargs: invoke_func(*a, **kwa)\n  File "C:\\workspace\\jenkins\\workspace\\GH_Tribler_PR_tests_win32\\tribler\\Tribler\\Core\\Libtorrent\\__init__.py", line 28, in invoke_func\n    download.session.lm.threadpool.add_task(lambda_f, 1)\nexceptions.AttributeError: \'NoneType\' object has no attribute \'add_task\'\n', 'log_format': u'{log_text}', 'message': (), 'why': None}]

# Fixed code
def guiservthread_checkpoint_timer(self):
    """Periodically checkpoint Session"""
    self._logger.info("main: Checkpointing Session")
    return deferToThread(self.utility.session.checkpoint)
# Buggy code
def isInThreadPool():
    """
    Check if we are currently on one of twisted threadpool threads.
    """
    return bool(reactor.threadpool) and current_thread() in reactor.threadpool.threads


# Traceback (exceptions.AttributeError)
Unhandled Error
Traceback (most recent call last):
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/base.py", line 417, in fireEvent
DeferredList(beforeResults).addCallback(self._continueFiring)
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 317, in addCallback
callbackKeywords=kw)
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 306, in addCallbacks
self._runCallbacks()
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/defer.py", line 588, in _runCallbacks
current.result = callback(current.result, *args, **kw)
--- <exception caught here> ---
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/twisted/internet/base.py", line 430, in _continueFiring
callable(*args, **kwargs)
File "/data/user/0/org.tribler.android/files/tribler_plugin.py", line 93, in start_tribler
upgrader = self.session.prestart()
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Session.py", line 192, in prestart
self.upgrader.run()
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Upgrade/upgrade.py", line 39, in run
failed, has_to_upgrade = self.check_should_upgrade()
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/dispersy/util.py", line 46, in helper
return blockingCallFromThread(reactor, func, *args, **kargs)
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/dispersy/util.py", line 225, in blockingCallFromThread
return f(*args, **kwargs)
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Upgrade/upgrade.py", line 97, in check_should_upgrade
self.notify_done()
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Upgrade/upgrade.py", line 79, in notify_done
self.session.notifier.notify(NTFY_UPGRADER, NTFY_FINISHED, None)
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/CacheDB/Notifier.py", line 126, in notify
callInThreadPool(task, *args)
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Utilities/twisted_utils.py", line 46, in callInThreadPool
if isInThreadPool():
File "/data/user/0/org.tribler.android/files/lib/python2.7/site-packages/Tribler/Core/Utilities/twisted_utils.py", line 56, in isInThreadPool
return current_thread() in reactor.threadpool.threads
exceptions.AttributeError: 'NoneType' object has no attribute 'threads'

# Fixed code
def isInThreadPool():
    """
    Check if we are currently on one of twisted threadpool threads.
    """
    threadpool = reactor.getThreadPool()
    return threadpool is not None and current_thread() in threadpool.threads