Branch merge
diff --git a/Include/pyerrors.h b/Include/pyerrors.h
index edc8218..8b6322b 100644
--- a/Include/pyerrors.h
+++ b/Include/pyerrors.h
@@ -208,8 +208,6 @@
     );
 
 #ifdef MS_WINDOWS
-PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilenameObject(
-    int, const char *);
 PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename(
     int ierr,
     const char *filename        /* decoded from the filesystem encoding */
diff --git a/Lib/http/cookiejar.py b/Lib/http/cookiejar.py
index 7f7f55b..9d798e8 100644
--- a/Lib/http/cookiejar.py
+++ b/Lib/http/cookiejar.py
@@ -29,6 +29,7 @@
            'FileCookieJar', 'LWPCookieJar', 'LoadError', 'MozillaCookieJar']
 
 import copy
+import datetime
 import re
 import time
 import urllib.parse, urllib.request
@@ -97,10 +98,12 @@
     1994-11-24 08:49:37Z
 
     """
-    if t is None: t = time.time()
-    year, mon, mday, hour, min, sec = time.gmtime(t)[:6]
+    if t is None:
+        dt = datetime.datetime.utcnow()
+    else:
+        dt = datetime.datetime.utcfromtimestamp(t)
     return "%04d-%02d-%02d %02d:%02d:%02dZ" % (
-        year, mon, mday, hour, min, sec)
+        dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
 
 def time2netscape(t=None):
     """Return a string representing time in seconds since epoch, t.
@@ -113,10 +116,13 @@
     Wed, DD-Mon-YYYY HH:MM:SS GMT
 
     """
-    if t is None: t = time.time()
-    year, mon, mday, hour, min, sec, wday = time.gmtime(t)[:7]
+    if t is None:
+        dt = datetime.datetime.utcnow()
+    else:
+        dt = datetime.datetime.utcfromtimestamp(t)
     return "%s %02d-%s-%04d %02d:%02d:%02d GMT" % (
-        DAYS[wday], mday, MONTHS[mon-1], year, hour, min, sec)
+        DAYS[dt.weekday()], dt.day, MONTHS[dt.month-1],
+        dt.year, dt.hour, dt.minute, dt.second)
 
 
 UTC_ZONES = {"GMT": None, "UTC": None, "UT": None, "Z": None}
diff --git a/Lib/socket.py b/Lib/socket.py
index 1e28549..5715034 100644
--- a/Lib/socket.py
+++ b/Lib/socket.py
@@ -112,6 +112,9 @@
                                 s[7:])
         return s
 
+    def __getstate__(self):
+        raise TypeError("Cannot serialize socket object")
+
     def dup(self):
         """dup() -> socket object
 
diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py
index a16e0e3..39ebc26 100644
--- a/Lib/test/test_httpservers.py
+++ b/Lib/test/test_httpservers.py
@@ -38,8 +38,8 @@
         self.test_object = test_object
 
     def run(self):
-        self.server = HTTPServer(('', 0), self.request_handler)
-        self.test_object.PORT = self.server.socket.getsockname()[1]
+        self.server = HTTPServer(('localhost', 0), self.request_handler)
+        self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
         self.test_object.server_started.set()
         self.test_object = None
         try:
@@ -66,7 +66,7 @@
         support.threading_cleanup(*self._threads)
 
     def request(self, uri, method='GET', body=None, headers={}):
-        self.connection = http.client.HTTPConnection('localhost', self.PORT)
+        self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
         self.connection.request(method, uri, body, headers)
         return self.connection.getresponse()
 
@@ -107,7 +107,7 @@
 
     def setUp(self):
         BaseTestCase.setUp(self)
-        self.con = http.client.HTTPConnection('localhost', self.PORT)
+        self.con = http.client.HTTPConnection(self.HOST, self.PORT)
         self.con.connect()
 
     def test_command(self):
diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py
index e40f763..35aa7fa 100644
--- a/Lib/test/test_os.py
+++ b/Lib/test/test_os.py
@@ -97,6 +97,25 @@
             self.assertEqual(fobj.read().splitlines(),
                 [b"bacon", b"eggs", b"spam"])
 
+    def write_windows_console(self, *args):
+        retcode = subprocess.call(args,
+            # use a new console to not flood the test output
+            creationflags=subprocess.CREATE_NEW_CONSOLE,
+            # use a shell to hide the console window (SW_HIDE)
+            shell=True)
+        self.assertEqual(retcode, 0)
+
+    @unittest.skipUnless(sys.platform == 'win32',
+                         'test specific to the Windows console')
+    def test_write_windows_console(self):
+        # Issue #11395: the Windows console returns an error (12: not enough
+        # space error) on writing into stdout if stdout mode is binary and the
+        # length is greater than 66,000 bytes (or less, depending on heap
+        # usage).
+        code = "print('x' * 100000)"
+        self.write_windows_console(sys.executable, "-c", code)
+        self.write_windows_console(sys.executable, "-u", "-c", code)
+
 
 class TemporaryFileTests(unittest.TestCase):
     def setUp(self):
diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py
index d761a73..8b23ae9 100644
--- a/Lib/test/test_socket.py
+++ b/Lib/test/test_socket.py
@@ -18,6 +18,7 @@
 from weakref import proxy
 import signal
 import math
+import pickle
 try:
     import fcntl
 except ImportError:
@@ -764,6 +765,12 @@
             fp.close()
             self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
 
+    def test_pickle(self):
+        sock = socket.socket()
+        with sock:
+            for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+                self.assertRaises(TypeError, pickle.dumps, sock, protocol)
+
 
 @unittest.skipUnless(thread, 'Threading required for this test.')
 class BasicTCPTest(SocketConnectedTest):
diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py
index 7266e27..2b58093 100644
--- a/Lib/test/test_time.py
+++ b/Lib/test/test_time.py
@@ -295,12 +295,8 @@
         except ValueError:
             # strftime() is limited to [1; 9999] with Visual Studio
             return
-        # Issue #10864: OpenIndiana is limited to 4 digits,
-        # but Python doesn't raise a ValueError
-        #self.assertEqual(text, '12345')
-        #self.assertEqual(self.yearstr(123456789), '123456789')
-        self.assertIn(text, ('2345', '12345'))
-        self.assertIn(self.yearstr(123456789), ('123456789', '6789'))
+        self.assertEqual(text, '12345')
+        self.assertEqual(self.yearstr(123456789), '123456789')
 
 class _Test2dYear(_BaseYearTest):
     accept2dyear = 1
diff --git a/Misc/NEWS b/Misc/NEWS
index 87477c9..ba1d424 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,12 @@
 Core and Builtins
 -----------------
 
+- Issue #11395: io.FileIO().write() clamps the data length to 32,767 bytes on
+  Windows if the file is a TTY to workaround a Windows bug. The Windows console
+  returns an error (12: not enough space error) on writing into stdout if
+  stdout mode is binary and the length is greater than 66,000 bytes (or less,
+  depending on heap usage).
+
 - Issue #11320: fix bogus memory management in Modules/getpath.c, leading to
   a possible crash when calling Py_SetPath().
 
@@ -78,8 +84,13 @@
 - Issue #11371: Mark getopt error messages as localizable.  Patch by Filip
   Gruszczyński.
 
+- Issue #5537: Fix time2isoz() and time2netscape() functions of
+  httplib.cookiejar for expiration year greater than 2038 on 32-bit systems.
+
 - Issue #4391: Use proper gettext plural forms in optparse.
 
+- Issue #11127: Raise a TypeError when trying to pickle a socket object.
+
 - Issue #11563: Connection:close header is sent by requests using URLOpener
   class which helps in closing of sockets after connection is over. Patch
   contributions by Jeff McNeil and Nadeem Vawda.
diff --git a/Modules/_io/fileio.c b/Modules/_io/fileio.c
index f96f2e2..1aa5ee9 100644
--- a/Modules/_io/fileio.c
+++ b/Modules/_io/fileio.c
@@ -712,7 +712,14 @@
         errno = 0;
         len = pbuf.len;
 #if defined(MS_WIN64) || defined(MS_WINDOWS)
-        if (len > INT_MAX)
+        if (len > 32767 && isatty(self->fd)) {
+            /* Issue #11395: the Windows console returns an error (12: not
+               enough space error) on writing into stdout if stdout mode is
+               binary and the length is greater than 66,000 bytes (or less,
+               depending on heap usage). */
+            len = 32767;
+        }
+        else if (len > INT_MAX)
             len = INT_MAX;
         n = write(self->fd, pbuf.buf, (int)len);
 #else
diff --git a/Modules/timemodule.c b/Modules/timemodule.c
index 86b73a5..c3b51ef 100644
--- a/Modules/timemodule.c
+++ b/Modules/timemodule.c
@@ -476,9 +476,8 @@
 
 #if defined(_MSC_VER) || defined(sun)
     if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
-        PyErr_Format(PyExc_ValueError,
-                     "strftime() requires year in [1; 9999]",
-                     buf.tm_year + 1900);
+        PyErr_SetString(PyExc_ValueError,
+                        "strftime() requires year in [1; 9999]");
         return NULL;
     }
 #endif
diff --git a/Python/pythonrun.c b/Python/pythonrun.c
index 8e97d7f..38b2ab8 100644
--- a/Python/pythonrun.c
+++ b/Python/pythonrun.c
@@ -147,7 +147,7 @@
         goto error;
 
     name_utf8 = _PyUnicode_AsString(name);
-    if (name == NULL)
+    if (name_utf8 == NULL)
         goto error;
     name_str = strdup(name_utf8);
     Py_DECREF(name);