internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: ipython/ipython

Issue:
Legacy cleanup
IPython/core/debbuger.py contains the following:

```
#######################################################################
# XXX Hack!  Use python-2.5 compatible code for this call, because with
# all of our changes, we've drifted from the pdb api in 2.6.  For now,
# changing:
#
#line = linecache.getline(filename, lineno, self.curframe.f_globals)
# to:
#
line = linecache.getline(filename, lineno)
#
# does the trick.  But in reality, we need to fix this by reconciling
# our updates with the new Pdb APIs in Python 2.6.
#
# End hack.  The rest of this method is copied verbatim from 2.6 pdb.py
#######################################################################
```

Should be easy to clean/test. Marking as Sprint friendly quickfix as we dropped 2.5 and 2.6 support. 



Discussion:

Resolving patch:
diff --git a/IPython/core/debugger.py b/IPython/core/debugger.py
--- a/IPython/core/debugger.py
+++ b/IPython/core/debugger.py
@@ -558,36 +558,3 @@ def do_psource(self, arg):
         namespaces = [('Locals', self.curframe.f_locals),
                       ('Globals', self.curframe.f_globals)]
         self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
-
-    def checkline(self, filename, lineno):
-        """Check whether specified line seems to be executable.
-
-        Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
-        line or EOF). Warning: testing is not comprehensive.
-        """
-        #######################################################################
-        # XXX Hack!  Use python-2.5 compatible code for this call, because with
-        # all of our changes, we've drifted from the pdb api in 2.6.  For now,
-        # changing:
-        #
-        #line = linecache.getline(filename, lineno, self.curframe.f_globals)
-        # to:
-        #
-        line = linecache.getline(filename, lineno)
-        #
-        # does the trick.  But in reality, we need to fix this by reconciling
-        # our updates with the new Pdb APIs in Python 2.6.
-        #
-        # End hack.  The rest of this method is copied verbatim from 2.6 pdb.py
-        #######################################################################
-
-        if not line:
-            print('End of file', file=self.stdout)
-            return 0
-        line = line.strip()
-        # Don't allow setting breakpoint at a blank line
-        if (not line or (line[0] == '#') or
-             (line[:3] == '"""') or line[:3] == "'''"):
-            print('*** Blank or comment', file=self.stdout)
-            return 0
-        return lineno


Test patch:
Repository: ipython/ipython

Issue:
Load more history into readline buffer at startup
I'm curious why, at startup in core/interactiveshell.py, the readline history is populated with a hard coded value of only 1000 (instead of, say, the configuration parameter history_length) history entries.

I've personally wished I had more history.



Discussion:
I don't see any problem with making this configurable if you would like to make a PR. I probably wouldn't make it fill the readline history (10k entries by default), because I doubt most users want to go that far back, and it presumably has some cost in startup time.


Resolving patch:
diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -391,6 +391,13 @@ def _prompt_trait_changed(self, name, old, new):
 
     history_length = Integer(10000, config=True)
 
+    history_load_length = Integer(1000, config=True, help=
+        """
+        The number of saved history entries to be loaded
+        into the readline buffer at startup.
+        """
+    )
+
     # The readline stuff will eventually be moved to the terminal subclass
     # but for now, we can't do that as readline is welded in everywhere.
     readline_use = CBool(True, config=True)
@@ -1996,7 +2003,7 @@ def refill_readline_hist(self):
         self.readline.clear_history()
         stdin_encoding = sys.stdin.encoding or "utf-8"
         last_cell = u""
-        for _, _, cell in self.history_manager.get_tail(1000,
+        for _, _, cell in self.history_manager.get_tail(self.history_load_length,
                                                         include_latest=True):
             # Ignore blank lines and consecutive duplicates
             cell = cell.rstrip()


Test patch:
Repository: ipython/ipython

Issue:
Add longlist support in ipdb.
Tracking closed PR #3350.

Add `longlist` support in ipdb, at least in Python 2.x. `longlist` seems to already be present in Python 3.x.

Add longlist support in ipdb.
Tracking closed PR #3350.

Add `longlist` support in ipdb, at least in Python 2.x. `longlist` seems to already be present in Python 3.x.



Discussion:
`longlist` is supported in Python 3, but the displayed code isn't syntax-highlighted, which is a serious shortcoming when reading those big blocks of code. Any chance we can get syntax highlighting for `longlist`?

`longlist` is supported in Python 3, but the displayed code isn't syntax-highlighted, which is a serious shortcoming when reading those big blocks of code. Any chance we can get syntax highlighting for `longlist`?


Resolving patch:
diff --git a/IPython/core/debugger.py b/IPython/core/debugger.py
--- a/IPython/core/debugger.py
+++ b/IPython/core/debugger.py
@@ -28,6 +28,7 @@
 
 import bdb
 import functools
+import inspect
 import linecache
 import sys
 
@@ -513,6 +514,28 @@ def do_list(self, arg):
 
     do_l = do_list
 
+    def getsourcelines(self, obj):
+        lines, lineno = inspect.findsource(obj)
+        if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
+            # must be a module frame: do not try to cut a block out of it
+            return lines, 1
+        elif inspect.ismodule(obj):
+            return lines, 1
+        return inspect.getblock(lines[lineno:]), lineno+1
+
+    def do_longlist(self, arg):
+        self.lastcmd = 'longlist'
+        filename = self.curframe.f_code.co_filename
+        breaklist = self.get_file_breaks(filename)
+        try:
+            lines, lineno = self.getsourcelines(self.curframe)
+        except OSError as err:
+            self.error(err)
+            return
+        last = lineno + len(lines)
+        self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
+    do_ll = do_longlist
+
     def do_pdef(self, arg):
         """Print the call signature for any callable object.
 


Test patch:
Repository: ipython/ipython

Issue:
added %matplotlib --list so backends are easily visible
linked to #8444 adding --list argument to show the available backends



Discussion:

Resolving patch:
diff --git a/IPython/core/magics/pylab.py b/IPython/core/magics/pylab.py
--- a/IPython/core/magics/pylab.py
+++ b/IPython/core/magics/pylab.py
@@ -42,6 +42,8 @@ class PylabMagics(Magics):
     @skip_doctest
     @line_magic
     @magic_arguments.magic_arguments()
+    @magic_arguments.argument('-l', '--list', action='store_true',
+                              help='Show available matplotlib backends')
     @magic_gui_arg
     def matplotlib(self, line=''):
         """Set up matplotlib to work interactively.
@@ -83,10 +85,20 @@ def matplotlib(self, line=''):
         But you can explicitly request a different GUI backend::
 
             In [3]: %matplotlib qt
+
+        You can list the available backends using the -l/--list option
+
+           In [4]: %matplotlib --list
+           Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg',
+            'gtk', 'tk', 'inline']
         """
         args = magic_arguments.parse_argstring(self.matplotlib, line)
-        gui, backend = self.shell.enable_matplotlib(args.gui)
-        self._show_matplotlib_backend(args.gui, backend)
+        if args.list:
+            backends_list = list(backends.keys())
+            print("Available matplotlib backends: %s" % backends_list)
+        else:
+            gui, backend = self.shell.enable_matplotlib(args.gui)
+            self._show_matplotlib_backend(args.gui, backend)
 
     @skip_doctest
     @line_magic


Test patch:
Repository: ipython/ipython

Issue:
Template path initialization doesn't handle unicode strings
We package IPython as a .par file and for some reason this makes the `_template_path` a unicode string. Unfortunately, this breaks `template_path` initialization in 3.x since that only checks for ascii strings (https://github.com/ipython/ipython/blob/8b0eef4cb37a85b8a35784f82799352188d90ca3/IPython/html/notebookapp.py#L157). The line should instead check whether `_template_path` is not a list.



Discussion:
should be fixed by jupyter/notebook#177


Resolving patch:
diff --git a/IPython/html/notebookapp.py b/IPython/html/notebookapp.py
--- a/IPython/html/notebookapp.py
+++ b/IPython/html/notebookapp.py
@@ -154,7 +154,7 @@ def init_settings(self, ipython_app, kernel_manager, contents_manager,
             "template_path",
             ipython_app.template_file_path,
         )
-        if isinstance(_template_path, str):
+        if isinstance(_template_path, py3compat.string_types):
             _template_path = (_template_path,)
         template_path = [os.path.expanduser(path) for path in _template_path]
 


Test patch:
Repository: ipython/ipython

Issue:
Can't break exception chaining with 'from None'
In plain Python:

```
>>> try:
...   1/0
... except ZeroDivisionError:
...   raise ValueError("foo") from None
... 
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: foo
```

Same code in IPython produces:

```
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-2-68918cb585bc> in <module>()
      1 try:
----> 2     1/0
      3 except ZeroDivisionError:

ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-2-68918cb585bc> in <module>()
      2     1/0
      3 except ZeroDivisionError:
----> 4     raise ValueError("Noooo") from None

ValueError: Noooo
```

Thanks @jhamrick for pointing this out 



Discussion:

Resolving patch:
diff --git a/IPython/core/ultratb.py b/IPython/core/ultratb.py
--- a/IPython/core/ultratb.py
+++ b/IPython/core/ultratb.py
@@ -985,6 +985,8 @@ def get_chained_exception(exception_value):
             cause = getattr(exception_value, '__cause__', None)
             if cause:
                 return cause
+            if getattr(exception_value, '__suppress_context__', False):
+                return None
             return getattr(exception_value, '__context__', None)
 
         chained_evalue = get_chained_exception(evalue)


Test patch:
diff --git a/IPython/core/tests/test_ultratb.py b/IPython/core/tests/test_ultratb.py
--- a/IPython/core/tests/test_ultratb.py
+++ b/IPython/core/tests/test_ultratb.py
@@ -173,6 +173,13 @@ class Python3ChainedExceptionsTest(unittest.TestCase):
     raise KeyError('uh')
     """
 
+    SUPPRESS_CHAINING_CODE = """
+try:
+    1/0
+except Exception:
+    raise ValueError("Yikes") from None
+    """
+
     def test_direct_cause_error(self):
         if PY3:
             with tt.AssertPrints(["KeyError", "NameError", "direct cause"]):
@@ -182,3 +189,9 @@ def test_exception_during_handling_error(self):
         if PY3:
             with tt.AssertPrints(["KeyError", "NameError", "During handling"]):
                 ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE)
+
+    def test_suppress_exception_chaining(self):
+        if PY3:
+            with tt.AssertNotPrints("ZeroDivisionError"), \
+                    tt.AssertPrints("ValueError", suppress=False):
+                ip.run_cell(self.SUPPRESS_CHAINING_CODE)
Repository: ipython/ipython

Issue:
Wrong string in nbconvert.py?
I was confused when the shim referred me to import from "IPython_nbconvert" but couldn't find any information on such a module or make sense of it. Shouldn't it be "nbconvert"? Or is there a detail that I missed?



Discussion:
Oops. Nice catch. Are you willing to  send a PR ?


Resolving patch:
diff --git a/IPython/nbconvert.py b/IPython/nbconvert.py
--- a/IPython/nbconvert.py
+++ b/IPython/nbconvert.py
@@ -10,7 +10,7 @@
 from IPython.utils.shimmodule import ShimModule, ShimWarning
 
 warn("The `IPython.nbconvert` package has been deprecated. "
-     "You should import from ipython_nbconvert instead.", ShimWarning)
+     "You should import from nbconvert instead.", ShimWarning)
 
 # Unconditionally insert the shim into sys.modules so that further import calls
 # trigger the custom attribute access above


Test patch:
Repository: ipython/ipython

Issue:
Deduplicate notebook from jupyter/notebook
See https://github.com/ipython/ipython/pull/8777  and https://github.com/jupyter/notebook/pull/363 among other, notebooks should not be in 2 places.



Discussion:

Resolving patch:
diff --git a/examples/Notebook/nbpackage/__init__.py b/examples/IPython Kernel/nbpackage/__init__.py
similarity index 100%
rename from examples/Notebook/nbpackage/__init__.py
rename to examples/IPython Kernel/nbpackage/__init__.py
diff --git a/examples/Notebook/nbpackage/nbs/__init__.py b/examples/IPython Kernel/nbpackage/nbs/__init__.py
similarity index 100%
rename from examples/Notebook/nbpackage/nbs/__init__.py
rename to examples/IPython Kernel/nbpackage/nbs/__init__.py


Test patch:
Repository: ipython/ipython

Issue:
Tab display of docstring in function args failing with multiline statement above
My setup:
- IPython 3.2.1
- Clean profile (no local configuration)
- Python 2.7.10
- Mac OS X 10.10.3

I've noticed some strange autocomplete issues since updating to V3 and I think I isolated the root of the problem (or at least one problem...). It seems that tab-display of a function docstring shows the wrong docstring if there is a multi-line statement above the object you are trying to inspect. For example:

``` python
a = (1,
     2,
     3)

int()
map()
```

If you put the cursor in the parens in `int()` and Shift+Tab, the docstring for `map` pops up instead.

See video of behavior here:
https://www.youtube.com/watch?v=Zevyejt37Qk&feature=youtu.be



Discussion:

Resolving patch:
diff --git a/IPython/utils/tokenutil.py b/IPython/utils/tokenutil.py
--- a/IPython/utils/tokenutil.py
+++ b/IPython/utils/tokenutil.py
@@ -108,7 +108,7 @@ def token_at_cursor(cell, cursor_pos=0):
             break
         
         tokens.append(tok)
-        if tok.token == tokenize2.NEWLINE:
+        if tok.token in (tokenize2.NEWLINE, tokenize2.NL):
             offset += len(tok.line)
     
     if call_names:


Test patch:
diff --git a/IPython/utils/tests/test_tokenutil.py b/IPython/utils/tests/test_tokenutil.py
--- a/IPython/utils/tests/test_tokenutil.py
+++ b/IPython/utils/tests/test_tokenutil.py
@@ -13,7 +13,7 @@ def expect_token(expected, cell, cursor_pos):
         if offset + len(line) >= cursor_pos:
             break
         else:
-            offset += len(line)
+            offset += len(line)+1
     column = cursor_pos - offset
     line_with_cursor = '%s|%s' % (line[:column], line[column:])
     nt.assert_equal(token, expected,
@@ -88,3 +88,15 @@ def test_line_at_cursor():
     (line, offset) = line_at_cursor(cell, cursor_pos=11)
     assert line == "", ("Expected '', got %r" % line)
     assert offset == 0, ("Expected '', got %r" % line)
+
+def test_muliline_statement():
+    cell = """a = (1,
+    3)
+
+int()
+map()
+"""
+    for c in range(16, 22):
+        yield lambda: expect_token("int", cell, c)
+    for c in range(22, 28):
+        yield lambda: expect_token("map", cell, c)
Repository: ipython/ipython

Issue:
didn't write code at first line in %%writefile 
``` python
%%writefile test.py
# coding: utf-8
print('안녕하세요')

%run test.py
  File "~/test.py", line 2
    print('안녕하세요')
                  ^
SyntaxError: Non-ASCII character '\xec' in file ~/test.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
```

first line is ignored in %%writefile.

But is ok. Add one new line

``` python
%%writefile test.py

# coding: utf-8
print('안녕하세요')

%run test.py
# 안녕하세요
```



Discussion:

Resolving patch:
diff --git a/IPython/core/inputsplitter.py b/IPython/core/inputsplitter.py
--- a/IPython/core/inputsplitter.py
+++ b/IPython/core/inputsplitter.py
@@ -484,8 +484,8 @@ def __init__(self, line_input_checker=True, physical_line_transforms=None,
                                              leading_indent(),
                                              classic_prompt(),
                                              ipy_prompt(),
-                                             strip_encoding_cookie(),
                                              cellmagic(end_on_blank_line=line_input_checker),
+                                             strip_encoding_cookie(),
                                             ]
         
         self.assemble_logical_lines = assemble_logical_lines()


Test patch:
diff --git a/IPython/core/tests/test_inputsplitter.py b/IPython/core/tests/test_inputsplitter.py
--- a/IPython/core/tests/test_inputsplitter.py
+++ b/IPython/core/tests/test_inputsplitter.py
@@ -496,7 +496,7 @@ def reset(self):
 if __name__ == '__main__':
     # A simple demo for interactive experimentation.  This code will not get
     # picked up by any test suite.
-    from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
+    from IPython.core.inputsplitter import IPythonInputSplitter
 
     # configure here the syntax to use, prompt and whether to autoindent
     #isp, start_prompt = InputSplitter(), '>>> '
@@ -592,6 +592,16 @@ def test_incremental(self):
         sp.push('\n')
         # This should accept a blank line and carry on until the cell is reset
         nt.assert_true(sp.push_accepts_more()) #3
+    
+    def test_no_strip_coding(self):
+        src = '\n'.join([
+            '%%writefile foo.py',
+            '# coding: utf-8',
+            'print(u"üñîçø∂é")',
+        ])
+        out = self.sp.transform_cell(src)
+        nt.assert_in('# coding: utf-8', out)
+
 
 class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
     sp = isp.IPythonInputSplitter(line_input_checker=True)
Repository: ipython/ipython

Issue:
Output of %magic? is not very helpful
The output of `%magic?` (in the qtconsole) is contains some text about magic functions, followed by

```
%2to3:
    Callable object storing the details of one alias.

    Instances are registered as magic functions to allow use of aliases.
%2to3-27:
    Callable object storing the details of one alias.

    Instances are registered as magic functions to allow use of aliases.
%2to3-35:
    Callable object storing the details of one alias.

    Instances are registered as magic functions to allow use of aliases.
%7z:
    Callable object storing the details of one alias.

    Instances are registered as magic functions to allow use of aliases.
%7za:
    Callable object storing the details of one alias.

    Instances are registered as magic functions to allow use of aliases.
<elided>
```

which I guess is just the list of all executables in my PATH.
After some scrolling I find the actual magics interspersed in between.

Arch Linux standard packages

```
Jupyter QtConsole 4.0.1
Python 3.5.0 (default, Sep 20 2015, 11:28:25) 
Type "copyright", "credits" or "license" for more information.

IPython 4.0.0 -- An enhanced Interactive Python.
```



Discussion:

Resolving patch:
diff --git a/IPython/core/alias.py b/IPython/core/alias.py
--- a/IPython/core/alias.py
+++ b/IPython/core/alias.py
@@ -131,6 +131,7 @@ def __init__(self, shell, name, cmd):
         self.shell = shell
         self.name = name
         self.cmd = cmd
+        self.__doc__ = "Alias for `!{}`".format(cmd)
         self.nargs = self.validate()
 
     def validate(self):


Test patch:
Repository: ipython/ipython

Issue:
%aimport autocompletion
Currently %aimport autocompletes on variable names, rather than on module names, which is obviously not very useful.
I didn't check whether other magics could likewise benefit from a better autocompleter.



Discussion:

Resolving patch:
diff --git a/IPython/core/completerlib.py b/IPython/core/completerlib.py
--- a/IPython/core/completerlib.py
+++ b/IPython/core/completerlib.py
@@ -223,7 +223,7 @@ def module_completion(line):
         return ['import ']
 
     # 'from xy<tab>' or 'import xy<tab>'
-    if nwords < 3 and (words[0] in ['import','from']) :
+    if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
         if nwords == 1:
             return get_root_modules()
         mod = words[1].split('.')
diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -2103,6 +2103,7 @@ def init_completer(self):
 
         self.set_hook('complete_command', module_completer, str_key = 'import')
         self.set_hook('complete_command', module_completer, str_key = 'from')
+        self.set_hook('complete_command', module_completer, str_key = '%aimport')
         self.set_hook('complete_command', magic_run_completer, str_key = '%run')
         self.set_hook('complete_command', cd_completer, str_key = '%cd')
         self.set_hook('complete_command', reset_completer, str_key = '%reset')


Test patch:
diff --git a/IPython/core/tests/test_completer.py b/IPython/core/tests/test_completer.py
--- a/IPython/core/tests/test_completer.py
+++ b/IPython/core/tests/test_completer.py
@@ -13,11 +13,11 @@
 import nose.tools as nt
 
 from traitlets.config.loader import Config
+from IPython import get_ipython
 from IPython.core import completer
 from IPython.external.decorators import knownfailureif
 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
 from IPython.utils.generics import complete_object
-from IPython.utils import py3compat
 from IPython.utils.py3compat import string_types, unicode_type
 from IPython.testing import decorators as dec
 
@@ -760,3 +760,21 @@ def test_dict_key_completion_invalids():
     _, matches = complete(line_buffer="empty['")
     _, matches = complete(line_buffer="name_error['")
     _, matches = complete(line_buffer="d['\\")  # incomplete escape
+
+def test_aimport_module_completer():
+    ip = get_ipython()
+    _, matches = ip.complete('i', '%aimport i')
+    nt.assert_in('io', matches)
+    nt.assert_not_in('int', matches)
+
+def test_import_module_completer():
+    ip = get_ipython()
+    _, matches = ip.complete('i', 'import i')
+    nt.assert_in('io', matches)
+    nt.assert_not_in('int', matches)
+
+def test_from_module_completer():
+    ip = get_ipython()
+    _, matches = ip.complete('B', 'from io import B')
+    nt.assert_in('BytesIO', matches)
+    nt.assert_not_in('BaseException', matches)