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

Issue:
Empty mkdocs_theme.yml breaks build
Hello! In the docs its [stated](https://www.mkdocs.org/dev-guide/themes/#theme-configuration) that a theme **can** have an empty `mkdocs_theme.yml` file:

> However, if the theme offers no configuration options, the file is still required and can be left blank.

Unfortunately this seems to have changed recently and now themes with empty `mkdocs_theme.yml` files are causing an exception when building:

```shell
> mkdocs build --verbose
DEBUG   -  Loading configuration file: ./mkdocs.yml
DEBUG   -  Loaded theme configuration for 'custom_theme' from
           './venv/lib/python3.12/site-packages/custom_theme/mkdocs_theme.yml':
           None
Traceback (most recent call last):
  [...]
  File "./venv/lib/python3.12/site-packages/mkdocs/config/config_options.py", line 868, in run_validation
    return theme.Theme(**theme_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "./venv/lib/python3.12/site-packages/mkdocs/theme.py", line 61, in __init__
    self._load_theme_config(name)
  File "./venv/lib/python3.12/site-packages/mkdocs/theme.py", line 143, in _load_theme_config
    if parent_theme := theme_config.pop('extends', None):
                       ^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'pop'
```



Discussion:

Resolving patch:
diff --git a/mkdocs/theme.py b/mkdocs/theme.py
--- a/mkdocs/theme.py
+++ b/mkdocs/theme.py
@@ -138,6 +138,9 @@ def _load_theme_config(self, name: str) -> None:
                 f"Please upgrade to a current version of the theme."
             )
 
+        if theme_config is None:
+            theme_config = {}
+
         log.debug(f"Loaded theme configuration for '{name}' from '{file_path}': {theme_config}")
 
         if parent_theme := theme_config.pop('extends', None):


Test patch:
diff --git a/mkdocs/tests/theme_tests.py b/mkdocs/tests/theme_tests.py
--- a/mkdocs/tests/theme_tests.py
+++ b/mkdocs/tests/theme_tests.py
@@ -104,3 +104,22 @@ def test_inherited_theme(self):
                 ],
             )
             self.assertEqual(theme.static_templates, {'sitemap.xml', 'child.html', 'parent.html'})
+
+    def test_empty_config_file(self):
+        # Test for themes with *empty* mkdocs_theme.yml.
+        # See https://github.com/mkdocs/mkdocs/issues/3699
+        m = mock.Mock(
+            # yaml.load returns "None" for an empty file
+            side_effect=[None]
+        )
+        with mock.patch('yaml.load', m) as m:
+            theme = Theme(name='mkdocs')
+            # Should only have the default name and locale __vars set in
+            # Theme.__init__()
+            self.assertEqual(
+                dict(theme),
+                {
+                    'name': 'mkdocs',
+                    'locale': parse_locale('en'),
+                },
+            )
Repository: ipython/ipython

Issue:
UnicodeEncodeError in qt.svg.save_svg
Matplotlib defaults to "axes.unicode_minus  : True", which means plots with minus signs in them that you try to save to svg have at least that one unicode character. Running `ipython-qtconsole --pylab=inline`, typing `plot(range(-1, 10))`, right clicking the image, and saving it as svg results in:

```
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)
```

I guess the svg string needs to be encoded in UTF-8 before being written to file.



Discussion:

Resolving patch:
diff --git a/IPython/frontend/qt/svg.py b/IPython/frontend/qt/svg.py
--- a/IPython/frontend/qt/svg.py
+++ b/IPython/frontend/qt/svg.py
@@ -21,6 +21,9 @@ def save_svg(string, parent=None):
     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')


Test patch:
Repository: ipython/ipython

Issue:
Indented command hits error
We previously allowed entered code to be indented, for convenient pasting from editors, web pages, etc. This no longer works in 0.11rc1: `<space><space>a=1` gives an IndentationError.

I think previously we solved this by prepending `if True:\n`  if the first line was indented, although I don't know if there's a neater solution.



Discussion:

Resolving patch:
diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -1605,6 +1605,16 @@ def showsyntaxerror(self, filename=None):
                     value = msg, (filename, lineno, offset, line)
         stb = self.SyntaxTB.structured_traceback(etype, value, [])
         self._showtraceback(etype, value, stb)
+    
+    # This is overridden in TerminalInteractiveShell to show a message about
+    # the %paste magic.
+    def showindentationerror(self):
+        """Called by run_cell when there's an IndentationError in code entered
+        at the prompt.
+        
+        This is overridden in TerminalInteractiveShell to show a message about
+        the %paste magic."""
+        self.showsyntaxerror()
 
     #-------------------------------------------------------------------------
     # Things related to readline
@@ -2273,6 +2283,10 @@ def run_cell(self, raw_cell, store_history=True):
                 with self.display_trap:
                     try:
                         code_ast = ast.parse(cell, filename=cell_name)
+                    except IndentationError:
+                        self.showindentationerror()
+                        self.execution_count += 1
+                        return None
                     except (OverflowError, SyntaxError, ValueError, TypeError,
                             MemoryError):
                         self.showsyntaxerror()
diff --git a/IPython/frontend/terminal/interactiveshell.py b/IPython/frontend/terminal/interactiveshell.py
--- a/IPython/frontend/terminal/interactiveshell.py
+++ b/IPython/frontend/terminal/interactiveshell.py
@@ -588,6 +588,10 @@ def magic_paste(self, parameter_s=''):
             write("## -- End pasted text --\n")
             
         self._execute_block(block, par)
+    
+    def showindentationerror(self):
+        super(TerminalInteractiveShell, self).showindentationerror()
+        print("If you want to paste code into IPython, try the %paste magic function.")
 
 
 InteractiveShellABC.register(TerminalInteractiveShell)


Test patch:
Repository: ipython/ipython

Issue:
Handle bad config files better
If the config file has a syntax error, IPython crashes with the "Oops, ipython crashed. We do our best to make it stable, but..." thing.



Discussion:

Resolving patch:
diff --git a/IPython/config/application.py b/IPython/config/application.py
--- a/IPython/config/application.py
+++ b/IPython/config/application.py
@@ -366,8 +366,13 @@ def parse_command_line(self, argv=None):
     def load_config_file(self, filename, path=None):
         """Load a .py based config file by filename and path."""
         loader = PyFileConfigLoader(filename, path=path)
-        config = loader.load_config()
-        self.update_config(config)
+        try:
+            config = loader.load_config()
+        except Exception:
+            self.log.error("Exception while loading config file %s [path=%s]"%
+                            (filename, path), exc_info=True)
+        else:
+            self.update_config(config)
     
     def generate_config_file(self):
         """generate default config file from Configurables"""


Test patch:
Repository: ipython/ipython

Issue:
non-ascii in __doc__ string crashes qtconsole kernel when showing tooltip
If there is a regular str object with non-ascii characers in a **doc** string. Then the kernel crashes when showing a tooltip for that object.  Using master ee9e1d9.

Example run the script in https://gist.github.com/1198484

typing a( at a prompt will show the tooltip

typing b( at a prompt will crash the kernel



Discussion:
`jsonutil.json_clean()` inappropriately treats `basestring` as safe, when bytes objects are most certainly not safe.  Should be a tiny fix.


Resolving patch:
diff --git a/IPython/utils/jsonutil.py b/IPython/utils/jsonutil.py
--- a/IPython/utils/jsonutil.py
+++ b/IPython/utils/jsonutil.py
@@ -12,6 +12,7 @@
 #-----------------------------------------------------------------------------
 # stdlib
 import re
+import sys
 import types
 from datetime import datetime
 
@@ -121,14 +122,17 @@ def json_clean(obj):
     """
     # types that are 'atomic' and ok in json as-is.  bool doesn't need to be
     # listed explicitly because bools pass as int instances
-    atomic_ok = (basestring, int, float, types.NoneType)
+    atomic_ok = (unicode, int, float, types.NoneType)
     
     # containers that we need to convert into lists
     container_to_list = (tuple, set, types.GeneratorType)
     
     if isinstance(obj, atomic_ok):
         return obj
-
+    
+    if isinstance(obj, bytes):
+        return obj.decode(sys.getdefaultencoding(), 'replace')
+    
     if isinstance(obj, container_to_list) or (
         hasattr(obj, '__iter__') and hasattr(obj, 'next')):
         obj = list(obj)


Test patch:
Repository: ipython/ipython

Issue:
ls broken after merge of #1089
After the merge of #1089 ls in the qtconsole prints blank lines and not the contents of the dir.
On ubuntu 11.10 using python2.7



Discussion:
This affects everything - '\r\n' is not being properly treated as a newline, because the carriage-return action is clearing the line.

Confirmed, on mac os also. Havent done bisect but it's between 2f41c98 and bdcfcc6

It's definitely the carriage return action.  '\r' effectively clears a line, so '\r\n' line-endings (which come from pexpect - affecting all system calls on Unix, and all everything on Windows) effectively replace each line with '\n'.  The proper action should be to catch '\r', as long as it is _not_ followed by '\n'.


Resolving patch:
diff --git a/IPython/frontend/qt/console/ansi_code_processor.py b/IPython/frontend/qt/console/ansi_code_processor.py
--- a/IPython/frontend/qt/console/ansi_code_processor.py
+++ b/IPython/frontend/qt/console/ansi_code_processor.py
@@ -38,7 +38,7 @@
 OSC_SUBPATTERN = '\](.*?)[\x07\x1b]'
 ANSI_PATTERN = ('\x01?\x1b(%s|%s)\x02?' % \
                 (CSI_SUBPATTERN, OSC_SUBPATTERN))
-ANSI_OR_SPECIAL_PATTERN = re.compile('(\b|\r)|(?:%s)' % ANSI_PATTERN)
+ANSI_OR_SPECIAL_PATTERN = re.compile('(\b|\r(?!\n))|(?:%s)' % ANSI_PATTERN)
 SPECIAL_PATTERN = re.compile('([\f])')
 
 #-----------------------------------------------------------------------------


Test patch:
diff --git a/IPython/frontend/qt/console/tests/test_ansi_code_processor.py b/IPython/frontend/qt/console/tests/test_ansi_code_processor.py
--- a/IPython/frontend/qt/console/tests/test_ansi_code_processor.py
+++ b/IPython/frontend/qt/console/tests/test_ansi_code_processor.py
@@ -105,12 +105,21 @@ def test_formfeed(self):
     def test_carriage_return(self):
         """ Are carriage return characters processed correctly?
         """
-        string = 'foo\rbar' # form feed
+        string = 'foo\rbar' # carriage return
         self.assertEquals(list(self.processor.split_string(string)), ['foo', '', 'bar'])
         self.assertEquals(len(self.processor.actions), 1)
         action = self.processor.actions[0]
         self.assertEquals(action.action, 'carriage-return')
 
+    def test_carriage_return_newline(self):
+        """transform CRLF to LF"""
+        string = 'foo\rbar\r\ncat\r\n' # carriage return and newline
+        # only one CR action should occur, and '\r\n' should transform to '\n'
+        self.assertEquals(list(self.processor.split_string(string)), ['foo', '', 'bar\r\ncat\r\n'])
+        self.assertEquals(len(self.processor.actions), 1)
+        action = self.processor.actions[0]
+        self.assertEquals(action.action, 'carriage-return')
+
     def test_beep(self):
         """ Are beep characters processed correctly?
         """
Repository: ipython/ipython

Issue:
double pylab greeting with c.InteractiveShellApp.pylab = "tk" in zmqconsole
I added  c.InteractiveShellApp.pylab = "tk" to my config to get pylab with the zmqconsole.
you then get two pylab greetings when you start it:

```
ipython console
Welcome to pylab, a matplotlib-based Python environment [backend: TkAgg].
For more information, type 'help(pylab)'.
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-3395.json

Welcome to pylab, a matplotlib-based Python environment [backend: TkAgg].
For more information, type 'help(pylab)'.
```

adding only c.TerminalIPythonApp.pylab = "tk" to the config will give you one greeting but pylab won't work which is a bit confusing.



Discussion:
This will be solved by a refactoring: there should be a single kernel object anywhere and then a single frontend object a local client would be a frontend with an in-process kernel.

I hope to get to make that big cleanup in the spring.

This is a minor oversight in the two-process frontend, which inherits from the Terminal application, but doesn't override `init_gui_and_pylab()` to be a no-op.

Do you want to take a stab at fixing it?  An eventual refactor will make this impossible by construction, but for now doing overrides in the subclasses is necessary and we alrady do it in multiple places, so we might as well ship 0.12 without this issue...

Sure, it's two lines, PR incoming


Resolving patch:
diff --git a/IPython/frontend/terminal/console/app.py b/IPython/frontend/terminal/console/app.py
--- a/IPython/frontend/terminal/console/app.py
+++ b/IPython/frontend/terminal/console/app.py
@@ -118,6 +118,10 @@ def init_shell(self):
                         display_banner=False, profile_dir=self.profile_dir,
                         ipython_dir=self.ipython_dir, kernel_manager=self.kernel_manager)
 
+    def init_gui_pylab(self):
+        # no-op, because we don't want to import matplotlib in the frontend.
+        pass
+
     def handle_sigint(self, *args):
         if self.shell._executing:
             if self.kernel_manager.has_kernel:


Test patch:
Repository: ipython/ipython

Issue:
double newline from %loadpy in python notebook (at least on mac)
 I suspect that it double count /r/n as two new lines. When I use %loadpy from python notebook(from stable 0.12) I expect something like

``` python
import pickle
from itertools import product
#get tmp.pck from prepareplotdata.py
f = open('tmp.pck')
m = pickle.load(f)
```

But I got something like

``` python
import pickle

from itertools import product

#get tmp.pck from prepareplotdata.py

f = open('tmp.pck')

m = pickle.load(f)

```



Discussion:
Up on closer inspection it is the server side this is what I got Notebook.handle_shell_reply in e.data

```
{"parent_header":
  {"username":"username","msg_id":"49C2620FD9F34A4FAD75D5655CC7415E",
  "msg_type":"execute_request",
  "session":"439FD9883D22482098055D869FC61668"},
"msg_type":"execute_reply",
"msg_id":"a7f8a644-4959-470b-bedf-cdb7fdc58e90",
"content":
  {"status":"ok",
   "execution_count":10,
   "user_variables":{},
   "payload":
      [{"text":"#single new line after this\n\n#double new line after this\n\n\n\n#triple newline after this\n\n\n\n\n\n#no newline at the end",
       "source":"IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input"}],
   "user_expressions":{}},
"header":
  {"username":"kernel",
   "session":"e49e9d26-4fdc-419d-b51d-364299bdc070",
   "msg_id":"a7f8a644-4959-470b-bedf-cdb7fdc58e90",
   "msg_type":"execute_reply"}
}
```

1 new line got converted into 2 new lines
2 new lines got converted into 4 new lines
3 new lines got converted into 6 new lines


Resolving patch:
diff --git a/IPython/core/magic.py b/IPython/core/magic.py
--- a/IPython/core/magic.py
+++ b/IPython/core/magic.py
@@ -2173,12 +2173,13 @@ def magic_loadpy(self, arg_s):
             # logic, going with utf-8 is a simple solution likely to be right
             # in most real-world cases.
             linesource = fileobj.read().decode('utf-8', 'replace').splitlines()
+            fileobj.close()
         else:
-            fileobj = linesource = open(arg_s)
+            with open(arg_s) as fileobj:
+                linesource = fileobj.read().splitlines()
         
         # Strip out encoding declarations
         lines = [l for l in linesource if not _encoding_declaration_re.match(l)]
-        fileobj.close()
         
         self.set_next_input(os.linesep.join(lines))
 


Test patch:
Repository: ipython/ipython

Issue:
in Hub: registration_timeout must be an integer, but heartmonitor.period is CFloat
In parallel.controller.hub, the registration_timeout is set to max(5000, 2*self.heartmonitor.period) and must be an integer, but self.heartmonitor.period is a float. 

So, when the period is more than 2500 (doesn't happen with the default value of 1000;  only with user-modified values that are higher), a validation error occurs and the hub doesn't start.



Discussion:
@minrk, a simple `int(...)` around that should do the trick, no?

Indeed, that would fix it, though there's no reason the two shouldn't be the same type.  Since these are millisecond times, I will make them both Integer (sub millisecond precision makes no sense).


Resolving patch:
diff --git a/IPython/parallel/controller/heartmonitor.py b/IPython/parallel/controller/heartmonitor.py
--- a/IPython/parallel/controller/heartmonitor.py
+++ b/IPython/parallel/controller/heartmonitor.py
@@ -23,7 +23,7 @@
 from zmq.eventloop import ioloop, zmqstream
 
 from IPython.config.configurable import LoggingConfigurable
-from IPython.utils.traitlets import Set, Instance, CFloat
+from IPython.utils.traitlets import Set, Instance, CFloat, Integer
 
 from IPython.parallel.util import asbytes
 
@@ -64,7 +64,7 @@ class HeartMonitor(LoggingConfigurable):
     pongstream: an XREP stream
     period: the period of the heartbeat in milliseconds"""
 
-    period=CFloat(1000, config=True,
+    period = Integer(1000, config=True,
         help='The frequency at which the Hub pings the engines for heartbeats '
         '(in ms)',
     )


Test patch:
Repository: ipython/ipython

Issue:
TaskScheduler.hwm default value
The current default value is 0, which minimizes task latency with greedy assignment.  However, this is suboptimal for some (especially heterogeneous) workloads, and surprising for many users.  It may be more sensible to make the default value 1, which is more friendly for novice users, who can get confused by the greedy assignment.

This is a tiny change, but posting here so there's a record of the decision.



Discussion:
+1 for the change, thanks for making the record here!


Resolving patch:
diff --git a/IPython/parallel/controller/scheduler.py b/IPython/parallel/controller/scheduler.py
--- a/IPython/parallel/controller/scheduler.py
+++ b/IPython/parallel/controller/scheduler.py
@@ -131,13 +131,23 @@ class TaskScheduler(SessionFactory):
 
     """
 
-    hwm = Integer(0, config=True, shortname='hwm',
+    hwm = Integer(1, config=True,
         help="""specify the High Water Mark (HWM) for the downstream
         socket in the Task scheduler. This is the maximum number
-        of allowed outstanding tasks on each engine."""
+        of allowed outstanding tasks on each engine.
+        
+        The default (1) means that only one task can be outstanding on each
+        engine.  Setting TaskScheduler.hwm=0 means there is no limit, and the
+        engines continue to be assigned tasks while they are working,
+        effectively hiding network latency behind computation, but can result
+        in an imbalance of work when submitting many heterogenous tasks all at
+        once.  Any positive value greater than one is a compromise between the
+        two.
+
+        """
     )
     scheme_name = Enum(('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin'),
-        'leastload', config=True, shortname='scheme', allow_none=False,
+        'leastload', config=True, allow_none=False,
         help="""select the task scheduler scheme  [default: Python LRU]
         Options are: 'pure', 'lru', 'plainrandom', 'weighted', 'twobin','leastload'"""
     )


Test patch:
Repository: ipython/ipython

Issue:
Input parsing with %prun clobbers escapes
Running this command, where `foo.csv` is a tab-separated file

```
In [3]: %prun -s cumulative table = read_table('foo.csv', sep="\t")
```

it blows up and I stepped up to the top level to see that `sep` has been passed as `t` and not `\t`



Discussion:
on it, another parse_options issue - removing the line `parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")` in prun and adding `posix=False` to `parse_options` seems to solve it, writing test and looking for other places to apply the fix now


Resolving patch:
diff --git a/IPython/core/magic.py b/IPython/core/magic.py
--- a/IPython/core/magic.py
+++ b/IPython/core/magic.py
@@ -1391,12 +1391,10 @@ def magic_prun(self, parameter_s ='',user_mode=1,
         """
 
         opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
-        # protect user quote marks
-        parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
 
         if user_mode:  # regular user call
             opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
-                                              list_all=1)
+                                              list_all=1, posix=False)
             namespace = self.shell.user_ns
         else:  # called to run a program by %run -p
             try:


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
@@ -358,3 +358,9 @@ def test_timeit_shlex():
 def test_timeit_arguments():
     "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
     _ip.magic("timeit ('#')")
+
+@dec.skipif(_ip.magic_prun == _ip.profile_missing_notice)
+def test_prun_quotes():
+    "Test that prun does not clobber string escapes (GH #1302)"
+    _ip.magic("prun -q x = '\t'")
+    nt.assert_equal(_ip.user_ns['x'], '\t')