gurudesh/pytracebugs huggingface dataset:
# Buggy code
def configure_shellwidget(self, give_focus=True):
    """Configure shellwidget after kernel is started"""
    if give_focus:
        self.get_control().setFocus()

    # Set exit callback
    self.shellwidget.set_exit_callback()

    # To save history
    self.shellwidget.executing.connect(self.add_to_history)

    # For Mayavi to run correctly
    self.shellwidget.executing.connect(self.shellwidget.set_backend_for_mayavi)

    # To update history after execution
    self.shellwidget.executed.connect(self.update_history)

    # To update the Variable Explorer after execution
    self.shellwidget.executed.connect(self.shellwidget.refresh_namespacebrowser)

    # To enable the stop button when executing a process
    self.shellwidget.executing.connect(self.enable_stop_button)

    # To disable the stop button after execution stopped
    self.shellwidget.executed.connect(self.disable_stop_button)

    # To show kernel restarted/died messages
    self.shellwidget.sig_kernel_restarted.connect(self.kernel_restarted_message)

    # To restart the kernel when errors happened while debugging
    # See issue 4003
    self.shellwidget.sig_dbg_kernel_restart.connect(self.restart_kernel)

    # To correctly change Matplotlib backend interactively
    self.shellwidget.executing.connect(self.shellwidget.change_mpl_backend)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def configure_shellwidget(self, give_focus=True):
    """Configure shellwidget after kernel is started"""
    if give_focus:
        self.get_control().setFocus()

    # Set exit callback
    self.shellwidget.set_exit_callback()

    # To save history
    self.shellwidget.executing.connect(self.add_to_history)

    # For Mayavi to run correctly
    self.shellwidget.executing.connect(self.shellwidget.set_backend_for_mayavi)

    # To update history after execution
    self.shellwidget.executed.connect(self.update_history)

    # To update the Variable Explorer after execution
    self.shellwidget.executed.connect(self.shellwidget.refresh_namespacebrowser)

    # To enable the stop button when executing a process
    self.shellwidget.executing.connect(self.enable_stop_button)

    # To disable the stop button after execution stopped
    self.shellwidget.executed.connect(self.disable_stop_button)

    # To show kernel restarted/died messages
    self.shellwidget.sig_kernel_restarted.connect(self.kernel_restarted_message)

    # To correctly change Matplotlib backend interactively
    self.shellwidget.executing.connect(self.shellwidget.change_mpl_backend)
# Buggy code
def __init__(self, parent=None):
    QTextEdit.__init__(self, parent)
    BaseEditMixin.__init__(self)
    TracebackLinksMixin.__init__(self)
    GetHelpMixin.__init__(self)

    self.calltip_widget = CallTipWidget(self, hide_timer_on=False)
    self.found_results = []

    # To not use Spyder calltips obtained through the monitor
    self.calltips = False


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def __init__(self, parent=None):
    QTextEdit.__init__(self, parent)
    BaseEditMixin.__init__(self)
    TracebackLinksMixin.__init__(self)
    GetHelpMixin.__init__(self)
    BrowseHistoryMixin.__init__(self)

    self.calltip_widget = CallTipWidget(self, hide_timer_on=False)
    self.found_results = []

    # To not use Spyder calltips obtained through the monitor
    self.calltips = False
# Buggy code
def write_to_stdin(self, line):
    """Send raw characters to the IPython kernel through stdin"""
    wait_loop = QEventLoop()
    self.kernel_client.iopub_channel.flush()
    self.sig_prompt_ready.connect(wait_loop.quit)
    self.kernel_client.input(line)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_prompt_ready.disconnect(wait_loop.quit)
    wait_loop = None

    # Run post exec commands
    self._post_exec_input(line)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def write_to_stdin(self, line):
    """Send raw characters to the IPython kernel through stdin"""
    self.kernel_client.input(line)
# Buggy code
def _handle_input_request(self, msg):
    """
    Reimplemented to be able to handle requests when we ask for
    hidden inputs
    """
    self.kernel_client.iopub_channel.flush()
    if not self._hidden:

        def callback(line):
            self.kernel_client.input(line)

        if self._reading:
            self._reading = False
        self._readline(
            msg["content"]["prompt"],
            callback=callback,
            password=msg["content"]["password"],
        )
    else:
        # This is what we added, i.e. not doing anything if
        # Spyder asks for silent inputs
        pass


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def _handle_input_request(self, msg):
    """Save history and add a %plot magic."""
    if self._hidden:
        raise RuntimeError("Request for raw input during hidden execution.")

    # Make sure that all output from the SUB channel has been processed
    # before entering readline mode.
    self.kernel_client.iopub_channel.flush()

    def callback(line):
        # Save history to browse it later
        self._control.history.append(line)

        # This is the Spyder addition: add a %plot magic to display
        # plots while debugging
        if line.startswith("%plot "):
            line = line.split()[-1]
            code = "__spy_code__ = get_ipython().run_cell('%s')" % line
            self.kernel_client.input(code)
        else:
            self.kernel_client.input(line)

    if self._reading:
        self._reading = False
    self._readline(
        msg["content"]["prompt"], callback=callback, password=msg["content"]["password"]
    )
# Buggy code
def callback(line):
    self.kernel_client.input(line)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def callback(line):
    # Save history to browse it later
    self._control.history.append(line)

    # This is the Spyder addition: add a %plot magic to display
    # plots while debugging
    if line.startswith("%plot "):
        line = line.split()[-1]
        code = "__spy_code__ = get_ipython().run_cell('%s')" % line
        self.kernel_client.input(code)
    else:
        self.kernel_client.input(line)
# Buggy code
def is_defined(self, objtxt, force_import=False):
    """Return True if object is defined"""
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method(
        "get_ipython().kernel.is_defined('%s', force_import=%s)"
        % (objtxt, force_import)
    )
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def is_defined(self, objtxt, force_import=False):
    """Return True if object is defined"""
    if self._reading:
        return
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method(
        "get_ipython().kernel.is_defined('%s', force_import=%s)"
        % (objtxt, force_import)
    )
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply
# Buggy code
def get_doc(self, objtxt):
    """Get object documentation dictionary"""
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def get_doc(self, objtxt):
    """Get object documentation dictionary"""
    if self._reading:
        return
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply
# Buggy code
def get_source(self, objtxt):
    """Get object source"""
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method("get_ipython().kernel.get_source('%s')" % objtxt)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def get_source(self, objtxt):
    """Get object source"""
    if self._reading:
        return
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method("get_ipython().kernel.get_source('%s')" % objtxt)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply
# Buggy code
def get_value(self, name):
    """Ask kernel for a value"""
    # Don't ask for values while reading (ipdb) is active
    if self._reading:
        raise ValueError(
            _(
                "Inspecting and setting values while debugging "
                "in IPython consoles is not supported yet by "
                "Spyder."
            )
        )

    # Wait until the kernel returns the value
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_execute("get_ipython().kernel.get_value('%s')" % name)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    # Handle exceptions
    if self._kernel_value is None:
        if self._kernel_reply:
            msg = self._kernel_reply[:]
            self._kernel_reply = None
            raise ValueError(msg)

    return self._kernel_value


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def get_value(self, name):
    """Ask kernel for a value"""
    code = "get_ipython().kernel.get_value('%s')" % name
    if self._reading:
        method = self.kernel_client.input
        code = "!" + code
    else:
        method = self.silent_execute

    # Wait until the kernel returns the value
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    method(code)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    # Handle exceptions
    if self._kernel_value is None:
        if self._kernel_reply:
            msg = self._kernel_reply[:]
            self._kernel_reply = None
            raise ValueError(msg)

    return self._kernel_value
# Buggy code
def set_value(self, name, value):
    """Set value for a variable"""
    value = to_text_string(value)
    self.silent_execute("get_ipython().kernel.set_value('%s', %s)" % (name, value))


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def set_value(self, name, value):
    """Set value for a variable"""
    value = to_text_string(value)
    code = "get_ipython().kernel.set_value('%s', %s)" % (name, value)
    if self._reading:
        self.kernel_client.input("!" + code)
    else:
        self.silent_execute(code)
# Buggy code
def remove_value(self, name):
    """Remove a variable"""
    self.silent_execute("get_ipython().kernel.remove_value('%s')" % name)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def remove_value(self, name):
    """Remove a variable"""
    code = "get_ipython().kernel.remove_value('%s')" % name
    if self._reading:
        self.kernel_client.input("!" + code)
    else:
        self.silent_execute(code)
# Buggy code
def copy_value(self, orig_name, new_name):
    """Copy a variable"""
    self.silent_execute(
        "get_ipython().kernel.copy_value('%s', '%s')" % (orig_name, new_name)
    )


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def copy_value(self, orig_name, new_name):
    """Copy a variable"""
    code = "get_ipython().kernel.copy_value('%s', '%s')" % (orig_name, new_name)
    if self._reading:
        self.kernel_client.input("!" + code)
    else:
        self.silent_execute(code)
# Buggy code
def load_data(self, filename, ext):
    # Wait until the kernel tries to load the file
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method(
        r"get_ipython().kernel.load_data('%s', '%s')" % (filename, ext)
    )
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def load_data(self, filename, ext):
    if self._reading:
        message = _("Loading this kind of data while debugging is not supported.")
        QMessageBox.warning(self, _("Warning"), message)
        return
    # Wait until the kernel tries to load the file
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method(
        r"get_ipython().kernel.load_data('%s', '%s')" % (filename, ext)
    )
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply
# Buggy code
def save_namespace(self, filename):
    # Wait until the kernel tries to save the file
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method(r"get_ipython().kernel.save_namespace('%s')" % filename)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def save_namespace(self, filename):
    if self._reading:
        message = _("Saving data while debugging is not supported.")
        QMessageBox.warning(self, _("Warning"), message)
        return
    # Wait until the kernel tries to save the file
    wait_loop = QEventLoop()
    self.sig_got_reply.connect(wait_loop.quit)
    self.silent_exec_method(r"get_ipython().kernel.save_namespace('%s')" % filename)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_got_reply.disconnect(wait_loop.quit)
    wait_loop = None

    return self._kernel_reply
# Buggy code
def _handle_data_message(self, msg):
    """
    Handle raw (serialized) data sent by the kernel

    We only handle data asked by Spyder, in case people use
    publish_data for other purposes.
    """
    # Deserialize data
    try:
        data = deserialize_object(msg["buffers"])[0]
    except Exception as msg:
        self._kernel_value = None
        self._kernel_reply = repr(msg)
        self.sig_got_reply.emit()
        return

    # We only handle data asked by Spyder
    value = data.get("__spy_data__", None)
    if value is not None:
        if isinstance(value, CannedObject):
            value = value.get_object()
        self._kernel_value = value
        self.sig_got_reply.emit()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def _handle_data_message(self, msg):
    """
    Handle raw (serialized) data sent by the kernel

    We only handle data asked by Spyder, in case people use
    publish_data for other purposes.
    """
    # Deserialize data
    try:
        data = deserialize_object(msg["buffers"])[0]
    except Exception as msg:
        self._kernel_value = None
        self._kernel_reply = repr(msg)
        self.sig_got_reply.emit()
        return

    # Receive values asked for Spyder
    value = data.get("__spy_data__", None)
    if value is not None:
        if isinstance(value, CannedObject):
            value = value.get_object()
        self._kernel_value = value
        self.sig_got_reply.emit()
        return

    # Receive Pdb state and dispatch it
    pdb_state = data.get("__spy_pdb_state__", None)
    if pdb_state is not None and isinstance(pdb_state, dict):
        self.refresh_from_pdb(pdb_state)
# Buggy code
def set_cwd(self, dirname):
    """Set shell current working directory."""
    return self.silent_execute("get_ipython().kernel.set_cwd(r'{}')".format(dirname))


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def set_cwd(self, dirname):
    """Set shell current working directory."""
    code = "get_ipython().kernel.set_cwd(r'{}')".format(dirname)
    if self._reading:
        self.kernel_client.input("!" + code)
    else:
        self.silent_execute(code)
# Buggy code
def clear_console(self):
    self.execute("%clear")


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def clear_console(self):
    if self._reading:
        self.dbg_exec_magic("clear")
    else:
        self.execute("%clear")
# Buggy code
def reset_namespace(self, force=False):
    """Reset the namespace by removing all names defined by the user."""
    reset_str = _("Reset IPython namespace")
    warn_str = _(
        "All user-defined variables will be removed."
        "<br>Are you sure you want to reset the namespace?"
    )
    if not force:
        reply = QMessageBox.question(
            self, reset_str, warn_str, QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            self.execute("%reset -f")
    else:
        self.silent_execute("%reset -f")


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def reset_namespace(self, force=False):
    """Reset the namespace by removing all names defined by the user."""
    reset_str = _("Reset IPython namespace")
    warn_str = _(
        "All user-defined variables will be removed."
        "<br>Are you sure you want to reset the namespace?"
    )
    if not force:
        reply = QMessageBox.question(
            self, reset_str, warn_str, QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            if self._reading:
                self.dbg_exec_magic("reset", "-f")
            else:
                self.execute("%reset -f")
    else:
        if self._reading:
            self.dbg_exec_magic("reset", "-f")
        else:
            self.silent_execute("%reset -f")
# Buggy code
def __init__(self):
    pass


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def __init__(self):
    self.history = []
    self.histidx = None
    self.hist_wholeline = False
# Buggy code
def __init__(self, parent, history_filename, profile=False, initial_message=None):
    """
    parent : specifies the parent widget
    """
    ConsoleBaseWidget.__init__(self, parent)
    SaveHistoryMixin.__init__(self)

    # Prompt position: tuple (line, index)
    self.current_prompt_pos = None
    self.new_input_line = True

    # History
    self.histidx = None
    self.hist_wholeline = False
    assert is_text_string(history_filename)
    self.history_filename = history_filename
    self.history = self.load_history()

    # Session
    self.historylog_filename = CONF.get(
        "main", "historylog_filename", get_conf_path("history.log")
    )

    # Context menu
    self.menu = None
    self.setup_context_menu()

    # Simple profiling test
    self.profile = profile

    # Buffer to increase performance of write/flush operations
    self.__buffer = []
    if initial_message:
        self.__buffer.append(initial_message)

    self.__timestamp = 0.0
    self.__flushtimer = QTimer(self)
    self.__flushtimer.setSingleShot(True)
    self.__flushtimer.timeout.connect(self.flush)

    # Give focus to widget
    self.setFocus()

    # Cursor width
    self.setCursorWidth(CONF.get("main", "cursor/width"))


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def __init__(self, parent, history_filename, profile=False, initial_message=None):
    """
    parent : specifies the parent widget
    """
    ConsoleBaseWidget.__init__(self, parent)
    SaveHistoryMixin.__init__(self)
    BrowseHistoryMixin.__init__(self)

    # Prompt position: tuple (line, index)
    self.current_prompt_pos = None
    self.new_input_line = True

    # History
    assert is_text_string(history_filename)
    self.history_filename = history_filename
    self.history = self.load_history()

    # Session
    self.historylog_filename = CONF.get(
        "main", "historylog_filename", get_conf_path("history.log")
    )

    # Context menu
    self.menu = None
    self.setup_context_menu()

    # Simple profiling test
    self.profile = profile

    # Buffer to increase performance of write/flush operations
    self.__buffer = []
    if initial_message:
        self.__buffer.append(initial_message)

    self.__timestamp = 0.0
    self.__flushtimer = QTimer(self)
    self.__flushtimer.setSingleShot(True)
    self.__flushtimer.timeout.connect(self.flush)

    # Give focus to widget
    self.setFocus()

    # Cursor width
    self.setCursorWidth(CONF.get("main", "cursor/width"))
# Buggy code
def get_index_from_key(self, key):
    try:
        return self.createIndex(self.keys.index(key), 0)
    except ValueError:
        return QModelIndex()


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def get_index_from_key(self, key):
    try:
        return self.createIndex(self.keys.index(key), 0)
    except (RuntimeError, ValueError):
        return QModelIndex()
# Buggy code
def plot(self, name, funcname):
    """Plot item"""
    self.shellwidget.execute("%%varexp --%s %s" % (funcname, name))


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def plot(self, name, funcname):
    """Plot item"""
    sw = self.shellwidget
    if sw._reading:
        sw.dbg_exec_magic("varexp", "--%s %s" % (funcname, name))
    else:
        sw.execute("%%varexp --%s %s" % (funcname, name))
# Buggy code
def imshow(self, name):
    """Show item's image"""
    self.shellwidget.execute("%%varexp --imshow %s" % name)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def imshow(self, name):
    """Show item's image"""
    sw = self.shellwidget
    if sw._reading:
        sw.dbg_exec_magic("varexp", "--imshow %s" % name)
    else:
        sw.execute("%%varexp --imshow %s" % name)
# Buggy code
def show_image(self, name):
    """Show image (item is a PIL image)"""
    command = "%s.show()" % name
    self.shellwidget.execute(command)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 459, in \<lambda>
lambda eid=id(editor): self.editor_accepted(eid))
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 467, in editor_accepted
index = data['model'].get_index_from_key(data['key'])
File "C:\Python27\lib\site-packages\spyderlib\widgets\dicteditor.py", line 219, in get_index_from_key
return self.createIndex(self.keys.index(key), 0)
RuntimeError: wrapped C/C++ object of type DictModel has been deleted

# Fixed code
def show_image(self, name):
    """Show image (item is a PIL image)"""
    command = "%s.show()" % name
    sw = self.shellwidget
    if sw._reading:
        sw.kernel_client.input(command)
    else:
        sw.execute(command)
# Buggy code
def _sel_to_text(self, cell_range):
    """Copy an array portion to a unicode string"""
    if not cell_range:
        return
    row_min, row_max, col_min, col_max = get_idx_rect(cell_range)
    if col_min == 0 and col_max == (self.model().cols_loaded - 1):
        # we've selected a whole column. It isn't possible to
        # select only the first part of a column without loading more,
        # so we can treat it as intentional and copy the whole thing
        col_max = self.model().total_cols - 1
    if row_min == 0 and row_max == (self.model().rows_loaded - 1):
        row_max = self.model().total_rows - 1

    _data = self.model().get_data()
    if PY3:
        output = io.BytesIO()
    else:
        output = io.StringIO()
    try:
        np.savetxt(
            output, _data[row_min : row_max + 1, col_min : col_max + 1], delimiter="\t"
        )
    except:
        QMessageBox.warning(
            self, _("Warning"), _("It was not possible to copy values for this array")
        )
        return
    contents = output.getvalue().decode("utf-8")
    output.close()
    return contents


# Traceback (NameError)
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\Spyder\spyder\spyder\widgets\variableexplorer\arrayeditor.py", line 469, in keyPressEvent
if event == QKeySequence.Copy:
NameError: name 'QKeySequence' is not defined
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\Spyder\spyder\spyder\widgets\variableexplorer\arrayeditor.py", line 469, in keyPressEvent
if event == QKeySequence.Copy:
NameError: name 'QKeySequence' is not defined```

# Fixed code
def _sel_to_text(self, cell_range):
    """Copy an array portion to a unicode string"""
    if not cell_range:
        return
    row_min, row_max, col_min, col_max = get_idx_rect(cell_range)
    if col_min == 0 and col_max == (self.model().cols_loaded - 1):
        # we've selected a whole column. It isn't possible to
        # select only the first part of a column without loading more,
        # so we can treat it as intentional and copy the whole thing
        col_max = self.model().total_cols - 1
    if row_min == 0 and row_max == (self.model().rows_loaded - 1):
        row_max = self.model().total_rows - 1

    _data = self.model().get_data()
    if PY3:
        output = io.BytesIO()
    else:
        output = io.StringIO()
    try:
        np.savetxt(
            output,
            _data[row_min : row_max + 1, col_min : col_max + 1],
            delimiter="\t",
            fmt=self.model().get_format(),
        )
    except:
        QMessageBox.warning(
            self, _("Warning"), _("It was not possible to copy values for this array")
        )
        return
    contents = output.getvalue().decode("utf-8")
    output.close()
    return contents
# Buggy code
def write_to_stdin(self, line):
    """Send raw characters to the IPython kernel through stdin"""
    wait_loop = QEventLoop()
    self.sig_prompt_ready.connect(wait_loop.quit)
    self.kernel_client.input(line)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_prompt_ready.disconnect(wait_loop.quit)
    wait_loop = None

    # Run post exec commands
    self._post_exec_input(line)


# Traceback (TypeError)
Traceback (most recent call last):
File "D:\code\thirdparty\spyder\spyder\widgets\ipythonconsole\namespacebrowser.py", line 49, in <lambda>
self.namespacebrowser.process_remote_view(data))
File "D:\code\thirdparty\spyder\spyder\widgets\variableexplorer\namespacebrowser.py", line 232, in process_remote_view
self.set_data(remote_view)
File "D:\code\thirdparty\spyder\spyder\widgets\variableexplorer\namespacebrowser.py", line 243, in set_data
self.editor.set_data(data)
File "D:\code\thirdparty\spyder\spyder\widgets\variableexplorer\collectionseditor.py", line 830, in set_data
self.model.set_data(data, self.dictfilter)
File "D:\code\thirdparty\spyder\spyder\widgets\variableexplorer\collectionseditor.py", line 170, in set_data
self.set_size_and_type()
File "D:\code\thirdparty\spyder\spyder\widgets\variableexplorer\collectionseditor.py", line 185, in set_size_and_type
for index in range(start, stop) ]
TypeError: 'int' object has no attribute '__getitem__'

# Fixed code
def write_to_stdin(self, line):
    """Send raw characters to the IPython kernel through stdin"""
    wait_loop = QEventLoop()
    self.kernel_client.iopub_channel.flush()
    self.sig_prompt_ready.connect(wait_loop.quit)
    self.kernel_client.input(line)
    wait_loop.exec_()

    # Remove loop connection and loop
    self.sig_prompt_ready.disconnect(wait_loop.quit)
    wait_loop = None

    # Run post exec commands
    self._post_exec_input(line)
# Buggy code
def get_image_path(name, default="not_found.png"):
    """Return image absolute path"""
    for img_path in IMG_PATH:
        full_path = osp.join(img_path, name)
        if osp.isfile(full_path):
            return osp.abspath(full_path)
    if default is not None:
        return osp.abspath(osp.join(img_path, default))


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/bin/spyder3", line 3, in <module>
start.main()
File "/usr/lib/python3/dist-packages/spyder/app/start.py", line 103, in main
from spyder.app import mainwindow
File "/usr/lib/python3/dist-packages/spyder/app/mainwindow.py", line 120, in <module>
SPLASH = QSplashScreen(QPixmap(get_image_path('splash.svg'), 'svg'))
File "/usr/lib/python3/dist-packages/spyder/config/base.py", line 212, in get_image_path
return osp.abspath(osp.join(img_path, default))
UnboundLocalError: local variable 'img_path' referenced before assignment

# Fixed code
def get_image_path(name, default="not_found.png"):
    """Return image absolute path"""
    for img_path in IMG_PATH:
        full_path = osp.join(img_path, name)
        if osp.isfile(full_path):
            return osp.abspath(full_path)
    if default is not None:
        img_path = osp.join(get_module_path("spyder"), "images")
        return osp.abspath(osp.join(img_path, default))
# Buggy code
def refresh_save_all_action(self):
    """Enable 'Save All' if there are files to be saved"""
    editorstack = self.get_current_editorstack()
    state = any(finfo.editor.document().isModified() for finfo in editorstack.data)
    self.save_all_action.setEnabled(state)


# Traceback (AttributeError)
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'

# Fixed code
def refresh_save_all_action(self):
    """Enable 'Save All' if there are files to be saved"""
    editorstack = self.get_current_editorstack()
    if editorstack:
        state = any(finfo.editor.document().isModified() for finfo in editorstack.data)
        self.save_all_action.setEnabled(state)
# Buggy code
def refresh_save_all_action(self):
    """Enable 'Save All' if there are files to be saved"""
    editorstack = self.get_current_editorstack()
    state = any(
        finfo.editor.document().isModified() or finfo.newly_created
        for finfo in editorstack.data
    )
    self.save_all_action.setEnabled(state)


# Traceback (AttributeError)
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'
Traceback (most recent call last):
File "C:\Users\Daniel\Anaconda3\lib\site-packages\spyder\plugins\editor.py", line 1481, in refresh_save_all_action
for finfo in editorstack.data)
AttributeError: 'NoneType' object has no attribute 'data'

# Fixed code
def refresh_save_all_action(self):
    """Enable 'Save All' if there are files to be saved"""
    editorstack = self.get_current_editorstack()
    if editorstack:
        state = any(
            finfo.editor.document().isModified() or finfo.newly_created
            for finfo in editorstack.data
        )
        self.save_all_action.setEnabled(state)
# Buggy code
def __get_current_color(self):
    """Get the syntax highlighting color for the current cursor position"""
    cursor = self.textCursor()
    block = cursor.block()
    pos = cursor.position() - block.position()  # relative pos within block
    layout = block.layout()
    block_formats = layout.additionalFormats()

    if block_formats:
        # To easily grab current format for autoinsert_colons
        if cursor.atBlockEnd():
            current_format = block_formats[-1].format
        else:
            current_format = None
            for fmt in block_formats:
                if (pos >= fmt.start) and (pos < fmt.start + fmt.length):
                    current_format = fmt.format
        color = current_format.foreground().color().name()
        return color
    else:
        return None


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/rlaverde/code/spyder/spyder/widgets/sourcecode/codeeditor.py", line 2695, in keyPressEvent
cmt_or_str = self.in_comment_or_string()
File "/home/rlaverde/code/spyder/spyder/widgets/sourcecode/codeeditor.py", line 2392, in in_comment_or_string
current_color = self.__get_current_color()
File "/home/rlaverde/code/spyder/spyder/widgets/sourcecode/codeeditor.py", line 2384, in __get_current_color
color = current_format.foreground().color().name()
AttributeError: 'NoneType' object has no attribute 'foreground'

# Fixed code
def __get_current_color(self):
    """Get the syntax highlighting color for the current cursor position"""
    cursor = self.textCursor()
    block = cursor.block()
    pos = cursor.position() - block.position()  # relative pos within block
    layout = block.layout()
    block_formats = layout.additionalFormats()

    if block_formats:
        # To easily grab current format for autoinsert_colons
        if cursor.atBlockEnd():
            current_format = block_formats[-1].format
        else:
            current_format = None
            for fmt in block_formats:
                if (pos >= fmt.start) and (pos < fmt.start + fmt.length):
                    current_format = fmt.format
            if current_format is None:
                return None
        color = current_format.foreground().color().name()
        return color
    else:
        return None