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

Issue:
Tab completion for method arguments shows other functions args.
With the below example class the args list that shows up when tab completing has arguments from other methods on the class that share the same root name.

```python
class Test:
    def meth(self, meth_arg1):
        print("meth")
    
    def meth_1(self, meth1_arg1, meth1_arg2):
        print("meth1")
    
    def meth_2(self, meth2_arg1, meth2_arg2):
        print("meth2")
```

![jupyter_autocomplete](https://user-images.githubusercontent.com/1692218/47118621-aa20e580-d21c-11e8-8ba5-7e3de2a1937e.png)

Using jupyter==1.0.0, ipython==7.0.1


Discussion:
@meeseeksdev tag tab-completion 

Resolving patch:
diff --git a/IPython/core/completer.py b/IPython/core/completer.py
--- a/IPython/core/completer.py
+++ b/IPython/core/completer.py
@@ -1538,24 +1538,19 @@ def python_func_kw_matches(self,text):
 
             usedNamedArgs.add(token)
 
-        # lookup the candidate callable matches either using global_matches
-        # or attr_matches for dotted names
-        if len(ids) == 1:
-            callableMatches = self.global_matches(ids[0])
-        else:
-            callableMatches = self.attr_matches('.'.join(ids[::-1]))
         argMatches = []
-        for callableMatch in callableMatches:
-            try:
-                namedArgs = self._default_arguments(eval(callableMatch,
-                                                        self.namespace))
-            except:
-                continue
+        try:
+            callableObj = '.'.join(ids[::-1])
+            namedArgs = self._default_arguments(eval(callableObj,
+                                                    self.namespace))
 
             # Remove used named arguments from the list, no need to show twice
             for namedArg in set(namedArgs) - usedNamedArgs:
                 if namedArg.startswith(text):
                     argMatches.append(u"%s=" %namedArg)
+        except:
+            pass
+            
         return argMatches
 
     def dict_key_matches(self, text):


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
@@ -1027,3 +1027,23 @@ def test_snake_case_completion():
     _, matches = ip.complete("s_", "print(s_f")
     nt.assert_in('some_three', matches)
     nt.assert_in('some_four', matches)
+
+def test_mix_terms():
+    ip = get_ipython()
+    from textwrap import dedent
+    ip.Completer.use_jedi = False
+    ip.ex(dedent("""
+        class Test:
+            def meth(self, meth_arg1):
+                print("meth")
+
+            def meth_1(self, meth1_arg1, meth1_arg2):
+                print("meth1")
+
+            def meth_2(self, meth2_arg1, meth2_arg2):
+                print("meth2")
+        test = Test()
+        """))
+    _, matches = ip.complete(None, "test.meth(")
+    nt.assert_in('meth_arg1=', matches)
+    nt.assert_not_in('meth2_arg1=', matches)
Repository: ipython/ipython

Issue:
Wrong autoindent for  class method. 
```
class F:
    def a(self):<enter>
```

Only 4 spaces are inserted. 



Discussion:

Resolving patch:
diff --git a/IPython/core/inputtransformer2.py b/IPython/core/inputtransformer2.py
--- a/IPython/core/inputtransformer2.py
+++ b/IPython/core/inputtransformer2.py
@@ -599,7 +599,7 @@ def check_complete(self, cell: str):
             else:
                 continue
 
-        if ends_with_newline:
+        if not ends_with_newline:
             # Append an newline for consistent tokenization
             # See https://bugs.python.org/issue33899
             cell += '\n'
@@ -644,10 +644,13 @@ def check_complete(self, cell: str):
 
         newline_types = {tokenize.NEWLINE, tokenize.COMMENT, tokenize.ENDMARKER}
 
-        # Remove newline_types for the list of tokens
-        while len(tokens_by_line) > 1 and len(tokens_by_line[-1]) == 1 \
-                and tokens_by_line[-1][-1].type in newline_types:
-            tokens_by_line.pop()
+        # Pop the last line which only contains DEDENTs and ENDMARKER
+        last_token_line = None
+        if {t.type for t in tokens_by_line[-1]} in [
+            {tokenize.DEDENT, tokenize.ENDMARKER},
+            {tokenize.ENDMARKER}
+        ] and len(tokens_by_line) > 1:
+            last_token_line = tokens_by_line.pop()
 
         while tokens_by_line[-1] and tokens_by_line[-1][-1].type in newline_types:
             tokens_by_line[-1].pop()
@@ -680,7 +683,7 @@ def check_complete(self, cell: str):
             if res is None:
                 return 'incomplete', find_last_indent(lines)
 
-        if tokens_by_line[-1][-1].type == tokenize.DEDENT:
+        if last_token_line and last_token_line[0].type == tokenize.DEDENT:
             if ends_with_newline:
                 return 'complete', None
             return 'incomplete', find_last_indent(lines)


Test patch:
diff --git a/IPython/core/tests/test_inputtransformer2.py b/IPython/core/tests/test_inputtransformer2.py
--- a/IPython/core/tests/test_inputtransformer2.py
+++ b/IPython/core/tests/test_inputtransformer2.py
@@ -207,6 +207,7 @@ def test_check_complete():
     cc = ipt2.TransformerManager().check_complete
     nt.assert_equal(cc("a = 1"), ('complete', None))
     nt.assert_equal(cc("for a in range(5):"), ('incomplete', 4))
+    nt.assert_equal(cc("for a in range(5):\n    if a > 0:"), ('incomplete', 8))
     nt.assert_equal(cc("raise = 2"), ('invalid', None))
     nt.assert_equal(cc("a = [1,\n2,"), ('incomplete', 0))
     nt.assert_equal(cc(")"), ('incomplete', 0))
Repository: ipython/ipython

Issue:
Better warning for windows users when using %run
After working on #10079, I thought it would be better to give windows users an explanation as to why they are receiving that error. Currently it just shows them a standard error with code that looks odd, but works on *nix systems:
`ERROR:root:File "'../test.py'.py" not found.`

I added a `warn` call to try to help:
```
  warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
ERROR:root:File `"'../test.py'.py"` not found.
```

I hopped that this would point them into the right direction. Especially if they are new users.

I am not sure if using a `warn()` is the best way to handle this, so let me know any thoughts.


Discussion:

Resolving patch:
diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py
--- a/IPython/core/magics/execution.py
+++ b/IPython/core/magics/execution.py
@@ -16,6 +16,7 @@
 import time
 import timeit
 import math
+import re
 from pdb import Restart
 
 # cProfile was added in Python2.5
@@ -646,7 +647,9 @@ def run(self, parameter_s='', runner=None,
                 return
             arg_lst = [modpath] + arg_lst
         try:
-            filename = file_finder(arg_lst[0])
+            fpath = None # initialize to make sure fpath is in scope later
+            fpath = arg_lst[0]
+            filename = file_finder(fpath)
         except IndexError:
             warn('you must provide at least a filename.')
             print('\n%run:\n', oinspect.getdoc(self.run))
@@ -656,6 +659,8 @@ def run(self, parameter_s='', runner=None,
                 msg = str(e)
             except UnicodeError:
                 msg = e.message
+            if os.name == 'nt' and re.match(r"^'.*'$",fpath):
+                warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
             error(msg)
             return
 


Test patch:
Repository: ipython/ipython

Issue:
Reenable jedi by default
8 months ago, in #11076, Jedi was disabled because an issue was still present that was in a new release “weeks later”. We should reenable it already!


Discussion:

Resolving patch:
diff --git a/IPython/core/completer.py b/IPython/core/completer.py
--- a/IPython/core/completer.py
+++ b/IPython/core/completer.py
@@ -576,9 +576,9 @@ class Completer(Configurable):
         """
     ).tag(config=True)
 
-    use_jedi = Bool(default_value=False,
+    use_jedi = Bool(default_value=JEDI_INSTALLED,
                     help="Experimental: Use Jedi to generate autocompletions. "
-                    "Off by default.").tag(config=True)
+                    "Default to True if jedi is installed.").tag(config=True)
 
     jedi_compute_type_timeout = Int(default_value=400,
         help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.


Test patch:
Repository: ipython/ipython

Issue:
autoreload fails with tensors
Reproducing the bug
===============

hola.py
```
import torch

class Bhai:
    three_ones = torch.ones(3)

    pass
```

test.ipynb
```
In[1]:
%load_ext autoreload
%autoreload 2

In[2]:
from hola import *

In[3]:
# before executing this cell modify something minor (like adding a space) in `hola.py`
print("hello")
```

Before executing the third cell modify something minor (like adding a space) in `hola.py`. I get this error

```
[autoreload of hola failed: Traceback (most recent call last):
  File "/home/sanyam/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 244, in check
    superreload(m, reload, self.old_objects)
  File "/home/sanyam/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 393, in superreload
    update_generic(old_obj, new_obj)
  File "/home/sanyam/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 330, in update_generic
    update(a, b)
  File "/home/sanyam/miniconda3/lib/python3.6/site-packages/IPython/extensions/autoreload.py", line 278, in update_class
    if old_obj == new_obj:
RuntimeError: bool value of Tensor with more than one value is ambiguous
]

```


Discussion:
Autoreload is something of a brittle hack; it doesn't sit well with the way Python usually works, so it will probably always have issues in corner cases. But if you can figure  out a safe way to fix this one which is unlikely to break anything else, feel free to make a pull request.

Resolving patch:
diff --git a/IPython/extensions/autoreload.py b/IPython/extensions/autoreload.py
--- a/IPython/extensions/autoreload.py
+++ b/IPython/extensions/autoreload.py
@@ -274,7 +274,9 @@ def update_class(old, new):
         old_obj = getattr(old, key)
         try:
             new_obj = getattr(new, key)
-            if old_obj == new_obj:
+            # explicitly checking that comparison returns True to handle
+            # cases where `==` doesn't return a boolean.
+            if (old_obj == new_obj) is True:
                 continue
         except AttributeError:
             # obsolete attribute: remove it


Test patch:
Repository: ipython/ipython

Issue:
Using 'type()' in qtconsole results in TypeError
ipykernel-5.1.0
IPython-7.2.0
qtconsole-4.4.3
tornado-5.1.1

both Linux and Mac  (Anaconda, version 2018.12, python 3.7)

In qtconsole, trying to use 'type()' results in a TypeError.  The error occurs immediately when entering 'type(', meaning as soon as I type the open-parenthesis character.  Possibly some sort of completion error?  Commenting out lines 863-868 of 'IPython/core/oinspect.py' removes the error.

Traceback follows:
```
Traceback (most recent call last):
  File "/Users/localuser/anaconda3/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 267, in dispatch_shell
    yield gen.maybe_future(handler(stream, idents, msg))
  File "/Users/localuser/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 1133, in run
    value = future.result()
  File "/Users/localuser/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 326, in wrapper
    yielded = next(result)
  File "/Users/localuser/anaconda3/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 593, in inspect_request
    content.get('detail_level', 0),
  File "/Users/localuser/anaconda3/lib/python3.7/site-packages/ipykernel/ipkernel.py", line 411, in do_inspect
    detail_level=detail_level
  File "/Users/localuser/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 1765, in object_inspect_mime
    detail_level=detail_level
  File "/Users/localuser/anaconda3/lib/python3.7/site-packages/IPython/core/oinspect.py", line 600, in _get_info
    info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
  File "/Users/localuser/anaconda3/lib/python3.7/site-packages/IPython/core/oinspect.py", line 863, in _info
    names = [sub.__name__ for sub in obj.__subclasses__()]
TypeError: descriptor '__subclasses__' of 'type' object needs an argument
```


Discussion:
Or just `type?` in plain IPython. 

Resolving patch:
diff --git a/IPython/core/oinspect.py b/IPython/core/oinspect.py
--- a/IPython/core/oinspect.py
+++ b/IPython/core/oinspect.py
@@ -860,7 +860,7 @@ def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
             if init_ds:
                 out['init_docstring'] = init_ds
 
-            names = [sub.__name__ for sub in obj.__subclasses__()]
+            names = [sub.__name__ for sub in type.__subclasses__(obj)]
             if len(names) < 10:
                 all_names = ', '.join(names)
             else:


Test patch:
diff --git a/IPython/core/tests/test_oinspect.py b/IPython/core/tests/test_oinspect.py
--- a/IPython/core/tests/test_oinspect.py
+++ b/IPython/core/tests/test_oinspect.py
@@ -363,6 +363,12 @@ def test_pinfo_nonascii():
     ip.user_ns['nonascii2'] = nonascii2
     ip._inspect('pinfo', 'nonascii2', detail_level=1)
 
+def test_pinfo_type():
+    """
+    type can fail in various edge case, for example `type.__subclass__()`
+    """
+    ip._inspect('pinfo', 'type')
+
 
 def test_pinfo_docstring_no_source():
     """Docstring should be included with detail_level=1 if there is no source"""
Repository: ipython/ipython

Issue:
return outside of function does not cause syntax error
For example, this succeeds if executed in a cell:

```python
def f():
    pass
return 5
```

Matthias Bussonnier mentioned there had been similar issues with break and continue: https://groups.google.com/forum/#!topic/jupyter/EpJWG3rPK90

He suggested the issue might be somewhere here: https://github.com/ipython/ipython/blob/master/IPython/core/async_helpers.py#L94-L118


Discussion:

Resolving patch:
diff --git a/IPython/core/async_helpers.py b/IPython/core/async_helpers.py
--- a/IPython/core/async_helpers.py
+++ b/IPython/core/async_helpers.py
@@ -112,6 +112,7 @@ def generic_visit(self, node):
         if isinstance(node, func_types) and should_traverse:
             self.depth += 1
             super().generic_visit(node)
+            self.depth -= 1
         elif isinstance(node, invalid_types_by_depth[self.depth]):
             raise SyntaxError()
         else:


Test patch:
diff --git a/IPython/core/tests/test_async_helpers.py b/IPython/core/tests/test_async_helpers.py
--- a/IPython/core/tests/test_async_helpers.py
+++ b/IPython/core/tests/test_async_helpers.py
@@ -139,7 +139,13 @@ def test_top_level_return_error(self):
             tl_err_test_cases = self._get_top_level_cases()
             tl_err_test_cases.extend(self._get_ry_syntax_errors())
 
-            vals = ('return', 'yield', 'yield from (_ for _ in range(3))')
+            vals = ('return', 'yield', 'yield from (_ for _ in range(3))',
+                    dedent('''
+                        def f():
+                            pass
+                        return
+                        '''),
+                    )
 
             for test_name, test_case in tl_err_test_cases:
                 # This example should work if 'pass' is used as the value
Repository: ipython/ipython

Issue:
IPython 7.6 problem with %%time
In IPython 7.6, the `%%time` magic is messing with the workspace. Looks like the last variable is never assigned in the workspace. This is a pretty serious error.

IPython 7.5.0 worked fine, so I assume it's related to https://github.com/ipython/ipython/pull/11716/. Also works fine when there's exactly one statement inside the cell.

```
In [1]:
%%time
a = 1
b = 2
c = 3
```

Wall time: 0 ns

```
In [2]:
a, b, c
```

```
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-6fd489e9d195> in <module>
----> 1 a, b, c

NameError: name 'c' is not defined
```


Discussion:
Thanks for the report (this an previous issue), 
I'll try to get a fix and a minor release soon.

Resolving patch:
diff --git a/IPython/core/magics/execution.py b/IPython/core/magics/execution.py
--- a/IPython/core/magics/execution.py
+++ b/IPython/core/magics/execution.py
@@ -1281,13 +1281,11 @@ def time(self,line='', cell=None, local_ns=None):
             mode = 'exec'
             source = '<timed exec>'
             # multi-line %%time case
-            if len(expr_ast.body) > 1 :
-                expr_val=expr_ast.body[-1]
-                code_val = self.shell.compile(ast.Expression(expr_val.value)
-                                                , '<timed eval>'
-                                                , 'eval')
-                expr_ast=expr_ast.body[:-1]
+            if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr):
+                expr_val= expr_ast.body[-1]
+                expr_ast = expr_ast.body[:-1]
                 expr_ast = Module(expr_ast, [])
+                expr_val = ast.Expression(expr_val.value)
 
         t0 = clock()
         code = self.shell.compile(expr_ast, source, mode)
@@ -1312,8 +1310,9 @@ def time(self,line='', cell=None, local_ns=None):
                 exec(code, glob, local_ns)
                 out=None
                 # multi-line %%time case
-                if expr_val and isinstance(expr_val, ast.Expr):
-                    out = eval(code_val, glob, local_ns)  
+                if expr_val is not None:
+                    code_2 = self.shell.compile(expr_val, source, 'eval')
+                    out = eval(code_2, glob, local_ns)
             except:
                 self.shell.showtraceback()
                 return


Test patch:
diff --git a/IPython/core/tests/test_magic.py b/IPython/core/tests/test_magic.py
--- a/IPython/core/tests/test_magic.py
+++ b/IPython/core/tests/test_magic.py
@@ -400,6 +400,15 @@ def test_time():
         with tt.AssertPrints("hihi", suppress=False):
             ip.run_cell("f('hi')")
 
+def test_time_last_not_expression():
+    ip.run_cell("%%time\n"
+                "var_1 = 1\n"
+                "var_2 = 2\n")
+    assert ip.user_ns['var_1'] == 1
+    del ip.user_ns['var_1']
+    assert ip.user_ns['var_2'] == 2
+    del ip.user_ns['var_2']
+    
 
 @dec.skip_win32
 def test_time2():
Repository: ipython/ipython

Issue:
remove cast_unicode from the %save magic. 
This needs to find wether in `code.py` line 336 cmds is always str, 
if not cast upstream, and repeat. 


```
 cmds = self.shell.find_user_code(codefrom,raw)
```


 - [x] Does find_user_code(codefrom,raw) always return a string ? (interactiveshell.py:3568)
   - [x] `self.extract_input_lines(target, raw=raw)` str ?
   - [x] `openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)` str ?
      -  [x] `source_to_unicode` str ? 
   - [x] `return response.read().decode('latin1')` str ? yes.
   - [x] `return object_info['source']` str ?
      - [x] `type self.object_inspect(target, detail_level=1)` ?  Dict[str, str| None]
         - [x] `self.inspector.info` return type ?  Dict[str, str| None]
         - [x] `oinspect.object_info` return type ? Dict[str, str| None]
   - [x] `return Macro.value` str ? yes
   - [x] `return f.read()` str ? Yes open file latin 1. 


Discussion:
Ok, I went through all the path, and they all seem to return str. 

Resolving patch:
diff --git a/IPython/core/magics/code.py b/IPython/core/magics/code.py
--- a/IPython/core/magics/code.py
+++ b/IPython/core/magics/code.py
@@ -29,7 +29,6 @@
 from IPython.core.magic import Magics, magics_class, line_magic
 from IPython.core.oinspect import find_file, find_source_lines
 from IPython.testing.skipdoctest import skip_doctest
-from IPython.utils import py3compat
 from IPython.utils.contexts import preserve_keys
 from IPython.utils.path import get_py_filename
 from warnings import warn
@@ -214,9 +213,9 @@ def save(self, parameter_s=''):
         force = 'f' in opts
         append = 'a' in opts
         mode = 'a' if append else 'w'
-        ext = u'.ipy' if raw else u'.py'
+        ext = '.ipy' if raw else '.py'
         fname, codefrom = args[0], " ".join(args[1:])
-        if not fname.endswith((u'.py',u'.ipy')):
+        if not fname.endswith(('.py','.ipy')):
             fname += ext
         file_exists = os.path.isfile(fname)
         if file_exists and not force and not append:
@@ -233,14 +232,13 @@ def save(self, parameter_s=''):
         except (TypeError, ValueError) as e:
             print(e.args[0])
             return
-        out = py3compat.cast_unicode(cmds)
         with io.open(fname, mode, encoding="utf-8") as f:
             if not file_exists or not append:
-                f.write(u"# coding: utf-8\n")
-            f.write(out)
+                f.write("# coding: utf-8\n")
+            f.write(cmds)
             # make sure we end on a newline
-            if not out.endswith(u'\n'):
-                f.write(u'\n')
+            if not cmds.endswith('\n'):
+                f.write('\n')
         print('The following commands were written to file `%s`:' % fname)
         print(cmds)
 


Test patch:
Repository: ipython/ipython

Issue:
IPython.core.page:snip_print seem to be unused. 
```
IPython/core/page.py
346:def snip_print(str,width = 75,print_full = 0,header = ''):
```

Should likely be removed. 
Remove try/except import for Py2 compat



Discussion:

Resolving patch:
diff --git a/IPython/core/page.py b/IPython/core/page.py
--- a/IPython/core/page.py
+++ b/IPython/core/page.py
@@ -341,32 +341,3 @@ def page_more():
             return False
         else:
             return True
-
-
-def snip_print(str,width = 75,print_full = 0,header = ''):
-    """Print a string snipping the midsection to fit in width.
-
-    print_full: mode control:
-    
-      - 0: only snip long strings
-      - 1: send to page() directly.
-      - 2: snip long strings and ask for full length viewing with page()
-    
-    Return 1 if snipping was necessary, 0 otherwise."""
-
-    if print_full == 1:
-        page(header+str)
-        return 0
-
-    print(header, end=' ')
-    if len(str) < width:
-        print(str)
-        snip = 0
-    else:
-        whalf = int((width -5)/2)
-        print(str[:whalf] + ' <...> ' + str[-whalf:])
-        snip = 1
-    if snip and print_full == 2:
-        if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
-            page(str)
-    return snip


Test patch: