gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _format_fields(self, fields, title_width=12):
    """Formats a list of fields for display.

    Parameters
    ----------
    fields : list
      A list of 2-tuples: (field_title, field_content)
    title_width : int
      How many characters to pad titles to. Default 12.
    """
    out = []
    header = self.__head
    for title, content in fields:
        if len(content.splitlines()) > 1:
            title = header(title + ":") + "\n"
        else:
            title = header((title + ":").ljust(title_width))
        out.append(title + content)
    return "\n".join(out)


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def _format_fields(self, fields, title_width=12):
    """Formats a list of fields for display.

    Parameters
    ----------
    fields : list
      A list of 2-tuples: (field_title, field_content)
    title_width : int
      How many characters to pad titles to. Default 12.
    """
    out = []
    header = self.__head
    for title, content in fields:
        if len(content.splitlines()) > 1:
            title = header(title + ":") + "\n"
        else:
            title = header((title + ":").ljust(title_width))
        out.append(cast_unicode(title) + cast_unicode(content))
    return "\n".join(out)
# Buggy code
def tkinter_clipboard_get():
    """Get the clipboard's text using Tkinter.

    This is the default on systems that are not Windows or OS X. It may
    interfere with other UI toolkits and should be replaced with an
    implementation that uses that toolkit.
    """
    try:
        import Tkinter
    except ImportError:
        raise TryNext(
            "Getting text from the clipboard on this platform requires Tkinter."
        )
    root = Tkinter.Tk()
    root.withdraw()
    text = root.clipboard_get()
    root.destroy()
    return text


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def tkinter_clipboard_get():
    """Get the clipboard's text using Tkinter.

    This is the default on systems that are not Windows or OS X. It may
    interfere with other UI toolkits and should be replaced with an
    implementation that uses that toolkit.
    """
    try:
        import Tkinter
    except ImportError:
        raise TryNext(
            "Getting text from the clipboard on this platform requires Tkinter."
        )
    root = Tkinter.Tk()
    root.withdraw()
    text = root.clipboard_get()
    root.destroy()
    text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
    return text
# Buggy code
def less(self, arg_s):
    """Show a file through the pager.

    Files ending in .py are syntax-highlighted."""
    if not arg_s:
        raise UsageError("Missing filename.")

    cont = open(arg_s).read()
    if arg_s.endswith(".py"):
        cont = self.shell.pycolorize(cont)
    page.page(cont)


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def less(self, arg_s):
    """Show a file through the pager.

    Files ending in .py are syntax-highlighted."""
    if not arg_s:
        raise UsageError("Missing filename.")

    cont = open(arg_s).read()
    if arg_s.endswith(".py"):
        cont = self.shell.pycolorize(
            openpy.read_py_file(arg_s, skip_encoding_cookie=False)
        )
    else:
        cont = open(arg_s).read()
    page.page(cont)
# Buggy code
def merge_branch(repo, branch):
    """try to merge the givent branch into the current one

    If something does not goes smoothly, merge is aborted

    Returns True if merge sucessfull, False otherwise
    """
    # Delete the branch first
    try:
        check_call(["git", "pull", "--no-edit", repo, branch])
    except CalledProcessError:
        check_call(["git", "merge", "--abort"])
        return False
    return True


# Traceback (subprocess.CalledProcessError)
(master)longs[ipython]> git mpr -m 2179
error: unknown option `no-edit'
usage: git fetch [<options>] [<repository> [<refspec>...]]
or: git fetch [<options>] <group>
or: git fetch --multiple [<options>] [(<repository> | <group>)...]
or: git fetch --all [<options>]

-v, --verbose         be more verbose
-q, --quiet           be more quiet
--all                 fetch from all remotes
-a, --append          append to .git/FETCH_HEAD instead of overwriting
--upload-pack <path>  path to upload pack on remote end
-f, --force           force overwrite of local branch
-m, --multiple        fetch from multiple remotes
-t, --tags            fetch all tags and associated objects
-n                    do not fetch all tags (--no-tags)
-p, --prune           prune remote-tracking branches no longer on remote
--recurse-submodules[=<on-demand>]
control recursive fetching of submodules
--dry-run             dry run
-k, --keep            keep downloaded pack
-u, --update-head-ok  allow updating of HEAD ref
--progress            force progress reporting
--depth <depth>       deepen history of shallow clone

fatal: There is no merge to abort (MERGE_HEAD missing).
Traceback (most recent call last):
File "/home/fperez/usr/bin//git-mpr", line 117, in <module>
main()
File "/home/fperez/usr/bin//git-mpr", line 107, in main
merge_pr(num)
File "/home/fperez/usr/bin//git-mpr", line 46, in merge_pr
branch=branch,
File "/home/fperez/usr/bin//git-mpr", line 29, in merge_branch
check_call(['git', 'merge', '--abort'])
File "/usr/lib/python2.7/subprocess.py", line 511, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['git', 'merge', '--abort']' returned non-zero exit status 128

# Fixed code
def merge_branch(repo, branch):
    """try to merge the givent branch into the current one

    If something does not goes smoothly, merge is aborted

    Returns True if merge sucessfull, False otherwise
    """
    # Delete the branch first
    try:
        check_call(["git", "pull", repo, branch], stdin=io.open(os.devnull))
    except CalledProcessError:
        check_call(["git", "merge", "--abort"])
        return False
    return True
# Buggy code
def pycmd2argv(cmd):
    r"""Take the path of a python command and return a list (argv-style).

    This only works on Python based command line programs and will find the
    location of the ``python`` executable using ``sys.executable`` to make
    sure the right version is used.

    For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
    .com or .bat, and [, cmd] otherwise.

    Parameters
    ----------
    cmd : string
      The path of the command.

    Returns
    -------
    argv-style list.
    """
    ext = os.path.splitext(cmd)[1]
    if ext in [".exe", ".com", ".bat"]:
        return [cmd]
    else:
        if sys.platform == "win32":
            # The -u option here turns on unbuffered output, which is required
            # on Win32 to prevent wierd conflict and problems with Twisted.
            # Also, use sys.executable to make sure we are picking up the
            # right python exe.
            return [sys.executable, "-u", cmd]
        else:
            return [sys.executable, cmd]


# Traceback (AssertionError)
FAIL: Test that prun does not clobber string escapes (GH #1302)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\python26\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "c:\python\external\ipython\IPython\testing\decorators.py", line 228, in skipper_func
return f(*args, **kwargs)
File "c:\python\external\ipython\IPython\core\tests\test_magic.py", line 396, in test_prun_quotes
nt.assert_equal(_ip.user_ns['x'], '\t')
AssertionError: ' ' != '\t'
raise self.failureException, \
(None or '%r != %r' % (' ', '\t'))

# Fixed code
def pycmd2argv(cmd):
    r"""Take the path of a python command and return a list (argv-style).

    This only works on Python based command line programs and will find the
    location of the ``python`` executable using ``sys.executable`` to make
    sure the right version is used.

    For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
    .com or .bat, and [, cmd] otherwise.

    Parameters
    ----------
    cmd : string
      The path of the command.

    Returns
    -------
    argv-style list.
    """
    ext = os.path.splitext(cmd)[1]
    if ext in [".exe", ".com", ".bat"]:
        return [cmd]
    else:
        if sys.platform == "win32":
            return [sys.executable, cmd]
        else:
            return [sys.executable, cmd]
# Buggy code
def _showtraceback(self, etype, evalue, stb):
    exc_content = {
        "traceback": stb,
        "ename": unicode(etype.__name__),
        "evalue": unicode(evalue),
    }

    dh = self.displayhook
    # Send exception info over pub socket for other clients than the caller
    # to pick up
    topic = None
    if dh.topic:
        topic = dh.topic.replace(b"pyout", b"pyerr")

    exc_msg = dh.session.send(
        dh.pub_socket, "pyerr", json_clean(exc_content), dh.parent_header, ident=topic
    )

    # FIXME - Hack: store exception info in shell object.  Right now, the
    # caller is reading this info after the fact, we need to fix this logic
    # to remove this hack.  Even uglier, we need to store the error status
    # here, because in the main loop, the logic that sets it is being
    # skipped because runlines swallows the exceptions.
    exc_content["status"] = "error"
    self._reply_content = exc_content
    # /FIXME

    return exc_content


# Traceback (UnicodeDecodeError)
UnicodeDecodeError Traceback (most recent call last)
/Users/jonathantaylor/ipython/IPython/core/interactiveshell.pyc in run_code(self, code_obj)
2722 self.CustomTB(etype,value,tb)
2723 except:
-> 2724 self.showtraceback()
2725 else:
2726 outflag = 0

/Users/jonathantaylor/ipython/IPython/core/interactiveshell.pyc in showtraceback(self, exc_tuple, filename, tb_offset, exception_only)
1713 value, tb, tb_offset=tb_offset)
1714
-> 1715 self._showtraceback(etype, value, stb)
1716 if self.call_pdb:
1717 # drop into debugger

/Users/jonathantaylor/ipython/IPython/zmq/zmqshell.pyc in showtraceback(self, etype, evalue, stb)
505 u'traceback' : stb,
506 u'ename' : unicode(etype.name_),
--> 507 u'evalue' : unicode(evalue)
508 }
509

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 132: ordinal not in range(128)'

# Fixed code
def _showtraceback(self, etype, evalue, stb):
    exc_content = {
        "traceback": stb,
        "ename": unicode(etype.__name__),
        "evalue": safe_unicode(evalue),
    }

    dh = self.displayhook
    # Send exception info over pub socket for other clients than the caller
    # to pick up
    topic = None
    if dh.topic:
        topic = dh.topic.replace(b"pyout", b"pyerr")

    exc_msg = dh.session.send(
        dh.pub_socket, "pyerr", json_clean(exc_content), dh.parent_header, ident=topic
    )

    # FIXME - Hack: store exception info in shell object.  Right now, the
    # caller is reading this info after the fact, we need to fix this logic
    # to remove this hack.  Even uglier, we need to store the error status
    # here, because in the main loop, the logic that sets it is being
    # skipped because runlines swallows the exceptions.
    exc_content["status"] = "error"
    self._reply_content = exc_content
    # /FIXME

    return exc_content
# Buggy code
def new_notebook(metadata=None, worksheets=None):
    """Create a notebook by name, id and a list of worksheets."""
    nb = NotebookNode()
    nb.nbformat = nbformat
    if worksheets is None:
        nb.worksheets = []
    else:
        nb.worksheets = list(worksheets)
    if metadata is None:
        nb.metadata = new_metadata()
    else:
        nb.metadata = NotebookNode(metadata)
    return nb


# Traceback (TypeError)
%notebook -e foo.py
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/source/packaging/pandas/pandas_build_virtenv/<ipython-input-245-d2b2edf081ed> in <module>()
----> 1 get_ipython().magic(u'notebook -e foo.py')

/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s, next_input)
1996                 self._magic_locals = sys._getframe(1).f_locals
1997             with self.builtin_trap:
-> 1998                 result = fn(magic_args)
1999             # Ensure we're not keeping object references around:

2000             self._magic_locals = {}

/usr/lib/python2.7/dist-packages/IPython/core/magic.pyc in magic_notebook(self, s)
3547                 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3548             worksheet = current.new_worksheet(cells=cells)
-> 3549             nb = current.new_notebook(name=name,worksheets=[worksheet])
3550             with open(fname, 'w') as f:
3551                 current.write(nb, f, format);

TypeError: new_notebook() got an unexpected keyword argument 'name'

# Fixed code
def new_notebook(name=None, metadata=None, worksheets=None):
    """Create a notebook by name, id and a list of worksheets."""
    nb = NotebookNode()
    nb.nbformat = nbformat
    if worksheets is None:
        nb.worksheets = []
    else:
        nb.worksheets = list(worksheets)
    if metadata is None:
        nb.metadata = new_metadata()
    else:
        nb.metadata = NotebookNode(metadata)
    if name is not None:
        nb.metadata.name = unicode(name)
    return nb
# Buggy code
def writes(self, nb, **kwargs):
    kwargs["cls"] = BytesEncoder
    kwargs["indent"] = 1
    kwargs["sort_keys"] = True
    kwargs["separators"] = (",", ": ")
    if kwargs.pop("split_lines", True):
        nb = split_lines(copy.deepcopy(nb))
    return json.dumps(nb, **kwargs)


# Traceback (TypeError)
%notebook -e foo.py
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/source/packaging/pandas/pandas_build_virtenv/<ipython-input-245-d2b2edf081ed> in <module>()
----> 1 get_ipython().magic(u'notebook -e foo.py')

/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s, next_input)
1996                 self._magic_locals = sys._getframe(1).f_locals
1997             with self.builtin_trap:
-> 1998                 result = fn(magic_args)
1999             # Ensure we're not keeping object references around:

2000             self._magic_locals = {}

/usr/lib/python2.7/dist-packages/IPython/core/magic.pyc in magic_notebook(self, s)
3547                 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3548             worksheet = current.new_worksheet(cells=cells)
-> 3549             nb = current.new_notebook(name=name,worksheets=[worksheet])
3550             with open(fname, 'w') as f:
3551                 current.write(nb, f, format);

TypeError: new_notebook() got an unexpected keyword argument 'name'

# Fixed code
def writes(self, nb, **kwargs):
    kwargs["cls"] = BytesEncoder
    kwargs["indent"] = 1
    kwargs["sort_keys"] = True
    kwargs["separators"] = (",", ": ")
    if kwargs.pop("split_lines", True):
        nb = split_lines(copy.deepcopy(nb))
    return py3compat.str_to_unicode(json.dumps(nb, **kwargs), "utf-8")
# Buggy code
def read(self, fp, **kwargs):
    """Read a notebook from a file like object"""
    return self.read(fp.read(), **kwargs)


# Traceback (TypeError)
%notebook -e foo.py
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/source/packaging/pandas/pandas_build_virtenv/<ipython-input-245-d2b2edf081ed> in <module>()
----> 1 get_ipython().magic(u'notebook -e foo.py')

/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s, next_input)
1996                 self._magic_locals = sys._getframe(1).f_locals
1997             with self.builtin_trap:
-> 1998                 result = fn(magic_args)
1999             # Ensure we're not keeping object references around:

2000             self._magic_locals = {}

/usr/lib/python2.7/dist-packages/IPython/core/magic.pyc in magic_notebook(self, s)
3547                 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3548             worksheet = current.new_worksheet(cells=cells)
-> 3549             nb = current.new_notebook(name=name,worksheets=[worksheet])
3550             with open(fname, 'w') as f:
3551                 current.write(nb, f, format);

TypeError: new_notebook() got an unexpected keyword argument 'name'

# Fixed code
def read(self, fp, **kwargs):
    """Read a notebook from a file like object"""
    nbs = fp.read()
    if not py3compat.PY3 and not isinstance(nbs, unicode):
        nbs = py3compat.str_to_unicode(nbs)
    return self.reads(nbs, **kwargs)
# Buggy code
def write(self, nb, fp, **kwargs):
    """Write a notebook to a file like object"""
    return fp.write(self.writes(nb, **kwargs))


# Traceback (TypeError)
%notebook -e foo.py
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/source/packaging/pandas/pandas_build_virtenv/<ipython-input-245-d2b2edf081ed> in <module>()
----> 1 get_ipython().magic(u'notebook -e foo.py')

/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s, next_input)
1996                 self._magic_locals = sys._getframe(1).f_locals
1997             with self.builtin_trap:
-> 1998                 result = fn(magic_args)
1999             # Ensure we're not keeping object references around:

2000             self._magic_locals = {}

/usr/lib/python2.7/dist-packages/IPython/core/magic.pyc in magic_notebook(self, s)
3547                 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3548             worksheet = current.new_worksheet(cells=cells)
-> 3549             nb = current.new_notebook(name=name,worksheets=[worksheet])
3550             with open(fname, 'w') as f:
3551                 current.write(nb, f, format);

TypeError: new_notebook() got an unexpected keyword argument 'name'

# Fixed code
def write(self, nb, fp, **kwargs):
    """Write a notebook to a file like object"""
    nbs = self.writes(nb, **kwargs)
    if not py3compat.PY3 and not isinstance(nbs, unicode):
        # this branch is likely only taken for JSON on Python 2
        nbs = py3compat.str_to_unicode(nbs)
    return fp.write(nbs)
# Buggy code
def list_profiles(self):
    self.update_profiles()
    result = [self.profile_info(p) for p in self.profiles.keys()]
    result.sort()
    return result


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/tornado/web.py", line 954, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "/usr/lib/python3/dist-packages/tornado/web.py", line 1667, in wrapper
return method(self, *args, **kwargs)
File "/usr/lib/python3/dist-packages/IPython/frontend/html/notebook/handlers.py", line 676, in get
self.finish(jsonapi.dumps(cm.list_profiles()))
File "/usr/lib/python3/dist-packages/IPython/frontend/html/notebook/clustermanager.py", line 95, in list_profiles
result.sort()
TypeError: unorderable types: dict() < dict()

# Fixed code
def list_profiles(self):
    self.update_profiles()
    result = [self.profile_info(p) for p in sorted(self.profiles.keys())]
    return result
# Buggy code
def arg_split(commandline, posix=False):
    """Split a command line's arguments in a shell-like manner.

    This is a special version for windows that use a ctypes call to CommandLineToArgvW
    to do the argv splitting. The posix paramter is ignored.
    """
    # CommandLineToArgvW returns path to executable if called with empty string.
    if commandline.strip() == "":
        return []
    argvn = c_int()
    result_pointer = CommandLineToArgvW(
        py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn)
    )
    result_array_type = LPCWSTR * argvn.value
    result = [arg for arg in result_array_type.from_address(result_pointer)]
    retval = LocalFree(result_pointer)
    return result


# Traceback (SyntaxError)
ERROR: test shlex issues with timeit (#1109)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\python26\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "c:\python\external\ipython\IPython\core\tests\test_magic.py", line 350, in test_timeit_shlex
_ip.magic('timeit -n1 "this is a bug".count(" ")')
File "c:\python\external\ipython\IPython\core\interactiveshell.py", line 1995, in magic
result = fn(magic_args)
File "c:\python\external\ipython\IPython\core\magic.py", line 1893, in magic_timeit
code = compile(src, "<magic-timeit>", "exec")
File "<magic-timeit>", line 6
this is a bug.count( )
^
SyntaxError: invalid syntax

# Fixed code
def arg_split(commandline, posix=False, strict=True):
    """Split a command line's arguments in a shell-like manner.

    This is a special version for windows that use a ctypes call to CommandLineToArgvW
    to do the argv splitting. The posix paramter is ignored.

    If strict=False, process_common.arg_split(...strict=False) is used instead.
    """
    # CommandLineToArgvW returns path to executable if called with empty string.
    if commandline.strip() == "":
        return []
    if not strict:
        # not really a cl-arg, fallback on _process_common
        return py_arg_split(commandline, posix=posix, strict=strict)
    argvn = c_int()
    result_pointer = CommandLineToArgvW(
        py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn)
    )
    result_array_type = LPCWSTR * argvn.value
    result = [arg for arg in result_array_type.from_address(result_pointer)]
    retval = LocalFree(result_pointer)
    return result
# Buggy code
def publish(self, source, data, metadata=None):
    if metadata is None:
        metadata = {}
    self._validate_data(source, data, metadata)
    content = {}
    content["source"] = source
    _encode_binary(data)
    content["data"] = data
    content["metadata"] = metadata
    self.session.send(
        self.pub_socket, "display_data", content, parent=self.parent_header
    )


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\python\external\ipy-bugs\run_qtcons_bug.py in <module>()
2
3 a=[]
----> 4 a.apppend(u"åäö")

AttributeError: 'list' object has no attribute 'apppend'

# Fixed code
def publish(self, source, data, metadata=None):
    if metadata is None:
        metadata = {}
    self._validate_data(source, data, metadata)
    content = {}
    content["source"] = source
    _encode_binary(data)
    content["data"] = data
    content["metadata"] = metadata
    self.session.send(
        self.pub_socket, "display_data", json_clean(content), parent=self.parent_header
    )
# Buggy code
def _showtraceback(self, etype, evalue, stb):
    exc_content = {
        "traceback": stb,
        "ename": unicode(etype.__name__),
        "evalue": unicode(evalue),
    }

    dh = self.displayhook
    # Send exception info over pub socket for other clients than the caller
    # to pick up
    exc_msg = dh.session.send(dh.pub_socket, "pyerr", exc_content, dh.parent_header)

    # FIXME - Hack: store exception info in shell object.  Right now, the
    # caller is reading this info after the fact, we need to fix this logic
    # to remove this hack.  Even uglier, we need to store the error status
    # here, because in the main loop, the logic that sets it is being
    # skipped because runlines swallows the exceptions.
    exc_content["status"] = "error"
    self._reply_content = exc_content
    # /FIXME

    return exc_content


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\python\external\ipy-bugs\run_qtcons_bug.py in <module>()
2
3 a=[]
----> 4 a.apppend(u"åäö")

AttributeError: 'list' object has no attribute 'apppend'

# Fixed code
def _showtraceback(self, etype, evalue, stb):
    exc_content = {
        "traceback": stb,
        "ename": unicode(etype.__name__),
        "evalue": unicode(evalue),
    }

    dh = self.displayhook
    # Send exception info over pub socket for other clients than the caller
    # to pick up
    exc_msg = dh.session.send(
        dh.pub_socket, "pyerr", json_clean(exc_content), dh.parent_header
    )

    # FIXME - Hack: store exception info in shell object.  Right now, the
    # caller is reading this info after the fact, we need to fix this logic
    # to remove this hack.  Even uglier, we need to store the error status
    # here, because in the main loop, the logic that sets it is being
    # skipped because runlines swallows the exceptions.
    exc_content["status"] = "error"
    self._reply_content = exc_content
    # /FIXME

    return exc_content
# Buggy code
def _exec_file(self, fname):
    full_filename = filefind(fname, [".", self.ipython_dir])
    # Make sure that the running script gets a proper sys.argv as if it
    # were run from a system shell.
    save_argv = sys.argv
    sys.argv = sys.argv[sys.argv.index(fname) :]
    try:
        if os.path.isfile(full_filename):
            if full_filename.endswith(".ipy"):
                self.log.info("Running file in user namespace: %s" % full_filename)
                self.shell.safe_execfile_ipy(full_filename)
            else:
                # default to python, even without extension
                self.log.info("Running file in user namespace: %s" % full_filename)
                # Ensure that __file__ is always defined to match Python behavior
                self.shell.user_ns["__file__"] = fname
                try:
                    self.shell.safe_execfile(full_filename, self.shell.user_ns)
                finally:
                    del self.shell.user_ns["__file__"]
    finally:
        sys.argv = save_argv


# Traceback (ValueError)
[TerminalIPythonApp] Unknown error in handling IPythonApp.exec_files:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
c:\python\external\ipython-js\IPython\core\shellapp.pyc in _exec_file(self, fname
192         # were run from a system shell.

193         save_argv = sys.argv
--> 194         sys.argv = sys.argv[sys.argv.index(fname):]
195         try:
196             if os.path.isfile(full_filename):

ValueError: list.index(x): x not in list

# Fixed code
def _exec_file(self, fname):
    try:
        full_filename = filefind(fname, [".", self.ipython_dir])
    except IOError as e:
        self.log.warn("File not found: %r" % fname)
        return
    # Make sure that the running script gets a proper sys.argv as if it
    # were run from a system shell.
    save_argv = sys.argv
    sys.argv = [full_filename] + self.extra_args[1:]
    try:
        if os.path.isfile(full_filename):
            if full_filename.endswith(".ipy"):
                self.log.info("Running file in user namespace: %s" % full_filename)
                self.shell.safe_execfile_ipy(full_filename)
            else:
                # default to python, even without extension
                self.log.info("Running file in user namespace: %s" % full_filename)
                # Ensure that __file__ is always defined to match Python behavior
                self.shell.user_ns["__file__"] = fname
                try:
                    self.shell.safe_execfile(full_filename, self.shell.user_ns)
                finally:
                    del self.shell.user_ns["__file__"]
    finally:
        sys.argv = save_argv
# Buggy code
def _handle_object_info_reply(self, rep):
    """Handle replies for call tips."""
    cursor = self._get_cursor()
    info = self._request_info.get("call_tip")
    if (
        info
        and info.id == rep["parent_header"]["msg_id"]
        and info.pos == cursor.position()
    ):
        # Get the information for a call tip.  For now we format the call
        # line as string, later we can pass False to format_call and
        # syntax-highlight it ourselves for nicer formatting in the
        # calltip.
        if rep["content"]["ismagic"]:
            # Don't generate a call-tip for magics. Ideally, we should
            # generate a tooltip, but not on ( like we do for actual
            # callables.
            call_info, doc = None, None
        else:
            call_info, doc = call_tip(rep["content"], format_call=True)
        if call_info or doc:
            self._call_tip_widget.show_call_info(call_info, doc)


# Traceback (KeyError)
{'content': {'oname': 'range'},
'header': {'username': 'mspacek', 'msg_id': 0, 'session': 'b744a851-3e62-4d64-930b-71ddefde10b0'},
'msg_type': 'object_info_request',
'parent_header': {}}
{'content': {'docstring': 'range([start,] stop[, step]) -> list of integers\n\nReturn a list containing an arithmetic progression of integers.\nrange(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\nWhen step is given, it specifies the increment (or decrement).\nFor example, range(4) returns [0, 1, 2, 3].  The end point is omitted!\nThese are exactly the valid indices for a list of 4 elements.'}, 'header': {'username': u'kernel', 'msg_id': 0, 'session': 'c2c4ed08-9765-43c9-b3cf-558331f61237'}, 'parent_header': {'username': 'mspacek', 'msg_id': 0, 'session': 'b744a851-3e62-4d64-930b-71ddefde10b0'}, 'msg_type': 'object_info_reply'}
Traceback (most recent call last):
File "/home/mspacek/source/ipython/IPython/frontend/qt/base_frontend_mixin.py", line 102, in _dispatch
handler(msg)
File "/home/mspacek/source/ipython/IPython/frontend/qt/console/frontend_widget.py", line 363, in _handle_object_info_reply
if rep['content']['ismagic']:
KeyError: 'ismagic'

# Fixed code
def _handle_object_info_reply(self, rep):
    """Handle replies for call tips."""
    cursor = self._get_cursor()
    info = self._request_info.get("call_tip")
    if (
        info
        and info.id == rep["parent_header"]["msg_id"]
        and info.pos == cursor.position()
    ):
        # Get the information for a call tip.  For now we format the call
        # line as string, later we can pass False to format_call and
        # syntax-highlight it ourselves for nicer formatting in the
        # calltip.
        content = rep["content"]
        # if this is from pykernel, 'docstring' will be the only key
        if content.get("ismagic", False):
            # Don't generate a call-tip for magics. Ideally, we should
            # generate a tooltip, but not on ( like we do for actual
            # callables.
            call_info, doc = None, None
        else:
            call_info, doc = call_tip(content, format_call=True)
        if call_info or doc:
            self._call_tip_widget.show_call_info(call_info, doc)
# Buggy code
def _handle_pyout(self, msg):
    """Handle display hook output."""
    if not self._hidden and self._is_from_this_session(msg):
        self._append_plain_text(msg["content"]["data"]["text/plain"] + "\n")


# Traceback (KeyError)
{'content': {'oname': 'range'},
'header': {'username': 'mspacek', 'msg_id': 0, 'session': 'b744a851-3e62-4d64-930b-71ddefde10b0'},
'msg_type': 'object_info_request',
'parent_header': {}}
{'content': {'docstring': 'range([start,] stop[, step]) -> list of integers\n\nReturn a list containing an arithmetic progression of integers.\nrange(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\nWhen step is given, it specifies the increment (or decrement).\nFor example, range(4) returns [0, 1, 2, 3].  The end point is omitted!\nThese are exactly the valid indices for a list of 4 elements.'}, 'header': {'username': u'kernel', 'msg_id': 0, 'session': 'c2c4ed08-9765-43c9-b3cf-558331f61237'}, 'parent_header': {'username': 'mspacek', 'msg_id': 0, 'session': 'b744a851-3e62-4d64-930b-71ddefde10b0'}, 'msg_type': 'object_info_reply'}
Traceback (most recent call last):
File "/home/mspacek/source/ipython/IPython/frontend/qt/base_frontend_mixin.py", line 102, in _dispatch
handler(msg)
File "/home/mspacek/source/ipython/IPython/frontend/qt/console/frontend_widget.py", line 363, in _handle_object_info_reply
if rep['content']['ismagic']:
KeyError: 'ismagic'

# Fixed code
def _handle_pyout(self, msg):
    """Handle display hook output."""
    if not self._hidden and self._is_from_this_session(msg):
        data = msg["content"]["data"]
        if isinstance(data, basestring):
            # plaintext data from pure Python kernel
            text = data
        else:
            # formatted output from DisplayFormatter (IPython kernel)
            text = data.get("text/plain", "")
        self._append_plain_text(text + "\n")
# Buggy code
def save_svg(string, parent=None):
    """Prompts the user to save an SVG document to disk.

    Parameters:
    -----------
    string : basestring
        A Python string containing a SVG document.

    parent : QWidget, optional
        The parent to use for the file dialog.

    Returns:
    --------
    The name of the file to which the document was saved, or None if the save
    was cancelled.
    """
    dialog = QtGui.QFileDialog(parent, "Save SVG Document")
    dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
    dialog.setDefaultSuffix("svg")
    dialog.setNameFilter("SVG document (*.svg)")
    if dialog.exec_():
        filename = dialog.selectedFiles()[0]
        f = open(filename, "w")
        try:
            f.write(string)
        finally:
            f.close()
        return filename
    return None


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/home/mspacek/source/ipython/IPython/frontend/qt/console/rich_ipython_widget.py", line 60, in <lambda>
lambda: save_svg(svg, self._control))
File "/home/mspacek/source/ipython/IPython/frontend/qt/svg.py", line 32, in save_svg
f.write(string)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2212' in position 12271: ordinal not in range(128)

# Fixed code
def save_svg(string, parent=None):
    """Prompts the user to save an SVG document to disk.

    Parameters:
    -----------
    string : basestring
        A Python string containing a SVG document.

    parent : QWidget, optional
        The parent to use for the file dialog.

    Returns:
    --------
    The name of the file to which the document was saved, or None if the save
    was cancelled.
    """
    if isinstance(string, unicode):
        string = string.encode("utf-8")

    dialog = QtGui.QFileDialog(parent, "Save SVG Document")
    dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
    dialog.setDefaultSuffix("svg")
    dialog.setNameFilter("SVG document (*.svg)")
    if dialog.exec_():
        filename = dialog.selectedFiles()[0]
        f = open(filename, "w")
        try:
            f.write(string)
        finally:
            f.close()
        return filename
    return None
# Buggy code
def get_pool(self, num=None):
    """Gets a pool of workers to do some parallel work.

    pool will be cached, which implies that one should be very clear how
    many processes one needs, as it's allocated at most once. Subsequent
    calls of get_pool() will reuse the cached pool.

    Args:
        num(int): Number of workers one needs.
    Returns:
        pool(multiprocessing.Pool): A pool of workers.
    """
    if self.pool is None:
        processes = self.get_processes(num or self.processes)
        logging.info("Calling multiprocessing.Pool(%d)", processes)
        self.pool = multiprocessing.Pool(processes)
    return self.pool


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-f4067f5432d2> in <module>()
8
9 linear_qubit_op.dot(state)
---> 10 linear_qubit_op.dot(state)

~/environments/ofc/lib/python3.5/site-packages/scipy/sparse/linalg/interface.py in dot(self, x)
360
361             if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1:
--> 362                 return self.matvec(x)
363             elif x.ndim == 2:
364                 return self.matmat(x)

~/environments/ofc/lib/python3.5/site-packages/scipy/sparse/linalg/interface.py in matvec(self, x)
217             raise ValueError('dimension mismatch')
218
--> 219         y = self._matvec(x)
220
221         if isinstance(x, np.matrix):

~/environments/ofc/lib/python3.5/site-packages/openfermion/utils/_linear_qubit_operator.py in _matvec(self, x)
185         vecs = pool.imap_unordered(apply_operator,
186                                    [(operator, x)
--> 187                                     for operator in self.linear_operators])
188         pool.close()
189         pool.join()

/usr/lib/python3.5/multiprocessing/pool.py in imap_unordered(self, func, iterable, chunksize)
300         '''
301         if self._state != RUN:
--> 302             raise ValueError("Pool not running")
303         if chunksize == 1:
304             result = IMapUnorderedIterator(self._cache)

ValueError: Pool not running

# Fixed code
def get_pool(self, num=None):
    """Gets a pool of workers to do some parallel work.

    pool will be cached, which implies that one should be very clear how
    many processes one needs, as it's allocated at most once. Subsequent
    calls of get_pool() will reuse the cached pool.

    Args:
        num(int): Number of workers one needs.
    Returns:
        pool(multiprocessing.Pool): A pool of workers.
    """
    processes = self.get_processes(num or self.processes)
    logging.info("Calling multiprocessing.Pool(%d)", processes)
    return multiprocessing.Pool(processes)
# Buggy code
def get_safe(self, key, default=None, path=None, type_t=()):
    """
    Get values in format
    """
    path = path or []
    value = self.get(key, default)
    if not isinstance(value, (dict)):
        if isinstance(value, type_t) or not type_t:
            return [(value, (path[:] + [key]))]

    results = []
    for sub_v, sub_path in value.items_safe(path + [key]):
        if isinstance(sub_v, type_t) or not type_t:
            results.append((sub_v, sub_path))

    return results


# Traceback (AttributeError)
2020-02-17 15:24:57,775 - cfnlint - DEBUG - Completed linting of file: .\test.yml
E0002 Unknown exception while processing rule E3028: Traceback (most recent call last):
File "c:\python36\lib\site-packages\cfnlint\rules\__init__.py", line 203, in run_check
return check(*args)
File "c:\python36\lib\site-packages\cfnlint\rules\__init__.py", line 89, in wrapper
results = match_function(self, filename, cfn, *args, **kwargs)
File "c:\python36\lib\site-packages\cfnlint\rules\__init__.py", line 122, in matchall_resource_properties
return self.match_resource_properties(resource_properties, property_type, path, cfn)  # pylint: disable=E1102
File "c:\python36\lib\site-packages\cfnlint\rules\resources\rds\AuroraScalingConfiguration.py", line 44, in match_resource_properties
matches.extend(self.check(properties, path, cfn))
File "c:\python36\lib\site-packages\cfnlint\rules\resources\rds\AuroraScalingConfiguration.py", line 30, in check
engine = properties.get_safe('EngineMode', type_t=six.string_types)
File "c:\python36\lib\site-packages\cfnlint\decode\node.py", line 125, in get_safe
for sub_v, sub_path in value.items_safe(path + [key]):
AttributeError: 'NoneType' object has no attribute 'items_safe'
.\test.yml:1:1

# Fixed code
def get_safe(self, key, default=None, path=None, type_t=()):
    """
    Get values in format
    """
    path = path or []
    value = self.get(key, default)
    if value is None and default is None:
        # if default is None and value is None return empty list
        return []

    # if the value is the default make sure that the default value is of type_t when specified
    if bool(type_t) and value == default and not isinstance(default, type_t):
        raise ValueError('"default" type should be of "type_t"')

    # when not a dict see if if the value is of the right type
    results = []
    if not isinstance(value, (dict)):
        if isinstance(value, type_t) or not type_t:
            return [(value, (path[:] + [key]))]
    else:
        for sub_v, sub_path in value.items_safe(path + [key]):
            if isinstance(sub_v, type_t) or not type_t:
                results.append((sub_v, sub_path))

    return results
# Buggy code
def __deepcopy__(self, memo):
    cls = self.__class__
    result = cls.__new__(cls, self.start_mark, self.end_mark)
    memo[id(self)] = result
    for _, v in enumerate(self):
        result.append(deepcopy(v, memo))

    return result


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/bin/cfn-lint", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/site-packages/cfnlint/__main__.py", line 36, in main
args.regions, args.override_spec))
File "/usr/local/lib/python2.7/site-packages/cfnlint/core.py", line 46, in run_cli
return run_checks(filename, template, rules, regions)
File "/usr/local/lib/python2.7/site-packages/cfnlint/core.py", line 316, in run_checks
matches.extend(runner.transform())
File "/usr/local/lib/python2.7/site-packages/cfnlint/__init__.py", line 894, in transform
matches = transform.transform_template()
File "/usr/local/lib/python2.7/site-packages/cfnlint/transform.py", line 115, in transform_template
sam_translator.translate(sam_template=self._template, parameter_values={}))
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/translator/translator.py", line 71, in translate
translated = macro.to_cloudformation(**kwargs)
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/model/sam_resources.py", line 501, in to_cloudformation
rest_api, deployment, stage = api_generator.to_cloudformation()
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/model/api/api_generator.py", line 160, in to_cloudformation
rest_api = self._construct_rest_api()
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/model/api/api_generator.py", line 69, in _construct_rest_api
self._add_cors()
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/model/api/api_generator.py", line 212, in _add_cors
self.definition_body = editor.swagger
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/swagger/swagger.py", line 298, in swagger
return copy.deepcopy(self._doc)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/site-packages/cfnlint/decode/node.py", line 75, in __deepcopy__
result = cls.__new__(cls, self.start_mark, self.end_mark)
AttributeError: 'dict_node' object has no attribute 'start_mark'

# Fixed code
def __deepcopy__(self, memo):
    result = list_node([], self.start_mark, self.end_mark)
    memo[id(self)] = result
    for _, v in enumerate(self):
        result.append(deepcopy(v, memo))

    return result
# Buggy code
def __deepcopy__(self, memo):
    cls = self.__class__
    result = cls.__new__(cls, self.start_mark, self.end_mark)
    memo[id(self)] = result
    for k, v in self.items():
        result[deepcopy(k)] = deepcopy(v, memo)

    return result


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/bin/cfn-lint", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/site-packages/cfnlint/__main__.py", line 36, in main
args.regions, args.override_spec))
File "/usr/local/lib/python2.7/site-packages/cfnlint/core.py", line 46, in run_cli
return run_checks(filename, template, rules, regions)
File "/usr/local/lib/python2.7/site-packages/cfnlint/core.py", line 316, in run_checks
matches.extend(runner.transform())
File "/usr/local/lib/python2.7/site-packages/cfnlint/__init__.py", line 894, in transform
matches = transform.transform_template()
File "/usr/local/lib/python2.7/site-packages/cfnlint/transform.py", line 115, in transform_template
sam_translator.translate(sam_template=self._template, parameter_values={}))
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/translator/translator.py", line 71, in translate
translated = macro.to_cloudformation(**kwargs)
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/model/sam_resources.py", line 501, in to_cloudformation
rest_api, deployment, stage = api_generator.to_cloudformation()
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/model/api/api_generator.py", line 160, in to_cloudformation
rest_api = self._construct_rest_api()
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/model/api/api_generator.py", line 69, in _construct_rest_api
self._add_cors()
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/model/api/api_generator.py", line 212, in _add_cors
self.definition_body = editor.swagger
File "/Users/eaddingtonwhite/Library/Python/2.7/lib/python/site-packages/samtranslator/swagger/swagger.py", line 298, in swagger
return copy.deepcopy(self._doc)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 174, in deepcopy
y = copier(memo)
File "/usr/local/lib/python2.7/site-packages/cfnlint/decode/node.py", line 75, in __deepcopy__
result = cls.__new__(cls, self.start_mark, self.end_mark)
AttributeError: 'dict_node' object has no attribute 'start_mark'

# Fixed code
def __deepcopy__(self, memo):
    result = dict_node(self, self.start_mark, self.end_mark)
    memo[id(self)] = result
    for k, v in self.items():
        result[deepcopy(k)] = deepcopy(v, memo)

    return result