We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
ERROR conda.core.link:_execute_actions(319): An error occurred while installing package 'defaults::qt-5.6.2-vc9_3'
```
Current conda install:

               platform : win-64
          conda version : 4.3.9
       conda is private : False
      conda-env version : 4.3.9
    conda-build version : 2.1.3
         python version : 2.7.13.final.0
       requests version : 2.12.4
       root environment : C:\Users\joelkim\Anaconda2  (writable)
    default environment : C:\Users\joelkim\Anaconda2
       envs directories : C:\Users\joelkim\Anaconda2\envs
          package cache : C:\Users\joelkim\Anaconda2\pkgs
           channel URLs : https://repo.continuum.io/pkgs/free/win-64
                          https://repo.continuum.io/pkgs/free/noarch
                          https://repo.continuum.io/pkgs/r/win-64
                          https://repo.continuum.io/pkgs/r/noarch
                          https://repo.continuum.io/pkgs/pro/win-64
                          https://repo.continuum.io/pkgs/pro/noarch
                          https://repo.continuum.io/pkgs/msys2/win-64
                          https://repo.continuum.io/pkgs/msys2/noarch
            config file : None
           offline mode : False
             user-agent : conda/4.3.9 requests/2.12.4 CPython/2.7.13 Windows/10 Windows/10.0.14393
```

I got this error when I tried to install qt:
```
> conda create -n test qt
Fetching package metadata ...........
Solving package specifications: .

Package plan for installation in environment C:\Users\joelkim\Anaconda2\envs\test:

The following NEW packages will be INSTALLED:

    icu:            57.1-vc9_0        [vc9]
    jpeg:           9b-vc9_0          [vc9]
    libpng:         1.6.27-vc9_0      [vc9]
    openssl:        1.0.2k-vc9_0      [vc9]
    pip:            9.0.1-py27_1
    python:         2.7.13-0
    qt:             5.6.2-vc9_3       [vc9]
    setuptools:     27.2.0-py27_1
    vs2008_runtime: 9.00.30729.5054-0
    wheel:          0.29.0-py27_0
    zlib:           1.2.8-vc9_3       [vc9]

Proceed ([y]/n)?

ERROR conda.core.link:_execute_actions(319): An error occurred while installing package 'defaults::qt-5.6.2-vc9_3'.
```
 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `conda/common/compat.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 # Try to keep compat small because it's imported by everything
3 # What is compat, and what isn't?
4 # If a piece of code is "general" and used in multiple modules, it goes here.
5 # If it's only used in one module, keep it in that module, preferably near the top.
6 from __future__ import absolute_import, division, print_function, unicode_literals
7 
8 from itertools import chain
9 from operator import methodcaller
10 from os import chmod, lstat
11 from os.path import islink
12 import sys
13 
14 on_win = bool(sys.platform == "win32")
15 
16 PY2 = sys.version_info[0] == 2
17 PY3 = sys.version_info[0] == 3
18 
19 
20 # #############################
21 # equivalent commands
22 # #############################
23 
24 if PY3:  # pragma: py2 no cover
25     string_types = str,
26     integer_types = int,
27     class_types = type,
28     text_type = str
29     binary_type = bytes
30     input = input
31     range = range
32 
33 elif PY2:  # pragma: py3 no cover
34     from types import ClassType
35     string_types = basestring,
36     integer_types = (int, long)
37     class_types = (type, ClassType)
38     text_type = unicode
39     binary_type = str
40     input = raw_input
41     range = xrange
42 
43 
44 # #############################
45 # equivalent imports
46 # #############################
47 
48 if PY3:  # pragma: py2 no cover
49     from io import StringIO
50     from itertools import zip_longest
51 elif PY2:  # pragma: py3 no cover
52     from cStringIO import StringIO
53     from itertools import izip as zip, izip_longest as zip_longest
54 
55 StringIO = StringIO
56 zip = zip
57 zip_longest = zip_longest
58 
59 
60 # #############################
61 # equivalent functions
62 # #############################
63 
64 if PY3:  # pragma: py2 no cover
65     def iterkeys(d, **kw):
66         return iter(d.keys(**kw))
67 
68     def itervalues(d, **kw):
69         return iter(d.values(**kw))
70 
71     def iteritems(d, **kw):
72         return iter(d.items(**kw))
73 
74     viewkeys = methodcaller("keys")
75     viewvalues = methodcaller("values")
76     viewitems = methodcaller("items")
77 
78     def lchmod(path, mode):
79         try:
80             chmod(path, mode, follow_symlinks=False)
81         except (TypeError, NotImplementedError, SystemError):
82             # On systems that don't allow permissions on symbolic links, skip
83             # links entirely.
84             if not islink(path):
85                 chmod(path, mode)
86 
87 
88     from collections import Iterable
89     def isiterable(obj):
90         return not isinstance(obj, string_types) and isinstance(obj, Iterable)
91 
92 elif PY2:  # pragma: py3 no cover
93     def iterkeys(d, **kw):
94         return d.iterkeys(**kw)
95 
96     def itervalues(d, **kw):
97         return d.itervalues(**kw)
98 
99     def iteritems(d, **kw):
100         return d.iteritems(**kw)
101 
102     viewkeys = methodcaller("viewkeys")
103     viewvalues = methodcaller("viewvalues")
104     viewitems = methodcaller("viewitems")
105 
106     try:
107         from os import lchmod as os_lchmod
108         lchmod = os_lchmod
109     except ImportError:
110         def lchmod(path, mode):
111             # On systems that don't allow permissions on symbolic links, skip
112             # links entirely.
113             if not islink(path):
114                 chmod(path, mode)
115 
116     def isiterable(obj):
117         return (hasattr(obj, '__iter__')
118                 and not isinstance(obj, string_types)
119                 and type(obj) is not type)
120 
121 
122 # #############################
123 # other
124 # #############################
125 
126 def with_metaclass(Type, skip_attrs=set(('__dict__', '__weakref__'))):
127     """Class decorator to set metaclass.
128 
129     Works with both Python 2 and Python 3 and it does not add
130     an extra class in the lookup order like ``six.with_metaclass`` does
131     (that is -- it copies the original class instead of using inheritance).
132 
133     """
134 
135     def _clone_with_metaclass(Class):
136         attrs = dict((key, value) for key, value in iteritems(vars(Class))
137                      if key not in skip_attrs)
138         return Type(Class.__name__, Class.__bases__, attrs)
139 
140     return _clone_with_metaclass
141 
142 
143 from collections import OrderedDict as odict
144 odict = odict
145 
146 NoneType = type(None)
147 primitive_types = tuple(chain(string_types, integer_types, (float, complex, bool, NoneType)))
148 
149 
150 def ensure_binary(value):
151     return value.encode('utf-8') if hasattr(value, 'encode') else value
152 
153 
154 def ensure_text_type(value):
155     return value.decode('utf-8') if hasattr(value, 'decode') else value
156 
157 
158 def ensure_unicode(value):
159     return value.decode('unicode_escape') if hasattr(value, 'decode') else value
160 
161 
162 # TODO: move this somewhere else
163 # work-around for python bug on Windows prior to python 3.2
164 # https://bugs.python.org/issue10027
165 # Adapted from the ntfsutils package, Copyright (c) 2012, the Mozilla Foundation
166 class CrossPlatformStLink(object):
167     _st_nlink = None
168 
169     def __call__(self, path):
170         return self.st_nlink(path)
171 
172     @classmethod
173     def st_nlink(cls, path):
174         if cls._st_nlink is None:
175             cls._initialize()
176         return cls._st_nlink(path)
177 
178     @classmethod
179     def _standard_st_nlink(cls, path):
180         return lstat(path).st_nlink
181 
182     @classmethod
183     def _windows_st_nlink(cls, path):
184         st_nlink = cls._standard_st_nlink(path)
185         if st_nlink != 0:
186             return st_nlink
187         else:
188             # cannot trust python on Windows when st_nlink == 0
189             # get value using windows libraries to be sure of its true value
190             # Adapted from the ntfsutils package, Copyright (c) 2012, the Mozilla Foundation
191             GENERIC_READ = 0x80000000
192             FILE_SHARE_READ = 0x00000001
193             OPEN_EXISTING = 3
194             hfile = cls.CreateFile(path, GENERIC_READ, FILE_SHARE_READ, None,
195                                    OPEN_EXISTING, 0, None)
196             if hfile is None:
197                 from ctypes import WinError
198                 raise WinError()
199             info = cls.BY_HANDLE_FILE_INFORMATION()
200             rv = cls.GetFileInformationByHandle(hfile, info)
201             cls.CloseHandle(hfile)
202             if rv == 0:
203                 from ctypes import WinError
204                 raise WinError()
205             return info.nNumberOfLinks
206 
207     @classmethod
208     def _initialize(cls):
209         if not on_win:
210             cls._st_nlink = cls._standard_st_nlink
211         else:
212             # http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858
213             import ctypes
214             from ctypes import POINTER
215             from ctypes.wintypes import DWORD, HANDLE, BOOL
216 
217             cls.CreateFile = ctypes.windll.kernel32.CreateFileW
218             cls.CreateFile.argtypes = [ctypes.c_wchar_p, DWORD, DWORD, ctypes.c_void_p,
219                                        DWORD, DWORD, HANDLE]
220             cls.CreateFile.restype = HANDLE
221 
222             # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724211
223             cls.CloseHandle = ctypes.windll.kernel32.CloseHandle
224             cls.CloseHandle.argtypes = [HANDLE]
225             cls.CloseHandle.restype = BOOL
226 
227             class FILETIME(ctypes.Structure):
228                 _fields_ = [("dwLowDateTime", DWORD),
229                             ("dwHighDateTime", DWORD)]
230 
231             class BY_HANDLE_FILE_INFORMATION(ctypes.Structure):
232                 _fields_ = [("dwFileAttributes", DWORD),
233                             ("ftCreationTime", FILETIME),
234                             ("ftLastAccessTime", FILETIME),
235                             ("ftLastWriteTime", FILETIME),
236                             ("dwVolumeSerialNumber", DWORD),
237                             ("nFileSizeHigh", DWORD),
238                             ("nFileSizeLow", DWORD),
239                             ("nNumberOfLinks", DWORD),
240                             ("nFileIndexHigh", DWORD),
241                             ("nFileIndexLow", DWORD)]
242             cls.BY_HANDLE_FILE_INFORMATION = BY_HANDLE_FILE_INFORMATION
243 
244             # http://msdn.microsoft.com/en-us/library/windows/desktop/aa364952
245             cls.GetFileInformationByHandle = ctypes.windll.kernel32.GetFileInformationByHandle
246             cls.GetFileInformationByHandle.argtypes = [HANDLE, POINTER(BY_HANDLE_FILE_INFORMATION)]
247             cls.GetFileInformationByHandle.restype = BOOL
248 
249             cls._st_nlink = cls._windows_st_nlink
250
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/conda/common/compat.py b/conda/common/compat.py
--- a/conda/common/compat.py
+++ b/conda/common/compat.py
@@ -152,7 +152,15 @@
 
 
 def ensure_text_type(value):
-    return value.decode('utf-8') if hasattr(value, 'decode') else value
+    if hasattr(value, 'decode'):
+        try:
+            return value.decode('utf-8')
+        except UnicodeDecodeError:
+            from requests.packages.chardet import detect
+            encoding = detect(value).get('encoding') or 'utf-8'
+            return value.decode(encoding)
+    else:
+        return value
 
 
 def ensure_unicode(value):

{"golden_diff": "diff --git a/conda/common/compat.py b/conda/common/compat.py\n--- a/conda/common/compat.py\n+++ b/conda/common/compat.py\n@@ -152,7 +152,15 @@\n \n \n def ensure_text_type(value):\n-    return value.decode('utf-8') if hasattr(value, 'decode') else value\n+    if hasattr(value, 'decode'):\n+        try:\n+            return value.decode('utf-8')\n+        except UnicodeDecodeError:\n+            from requests.packages.chardet import detect\n+            encoding = detect(value).get('encoding') or 'utf-8'\n+            return value.decode(encoding)\n+    else:\n+        return value\n \n \n def ensure_unicode(value):\n", "issue": "ERROR conda.core.link:_execute_actions(319): An error occurred while installing package 'defaults::qt-5.6.2-vc9_3'\n```\r\nCurrent conda install:\r\n\r\n               platform : win-64\r\n          conda version : 4.3.9\r\n       conda is private : False\r\n      conda-env version : 4.3.9\r\n    conda-build version : 2.1.3\r\n         python version : 2.7.13.final.0\r\n       requests version : 2.12.4\r\n       root environment : C:\\Users\\joelkim\\Anaconda2  (writable)\r\n    default environment : C:\\Users\\joelkim\\Anaconda2\r\n       envs directories : C:\\Users\\joelkim\\Anaconda2\\envs\r\n          package cache : C:\\Users\\joelkim\\Anaconda2\\pkgs\r\n           channel URLs : https://repo.continuum.io/pkgs/free/win-64\r\n                          https://repo.continuum.io/pkgs/free/noarch\r\n                          https://repo.continuum.io/pkgs/r/win-64\r\n                          https://repo.continuum.io/pkgs/r/noarch\r\n                          https://repo.continuum.io/pkgs/pro/win-64\r\n                          https://repo.continuum.io/pkgs/pro/noarch\r\n                          https://repo.continuum.io/pkgs/msys2/win-64\r\n                          https://repo.continuum.io/pkgs/msys2/noarch\r\n            config file : None\r\n           offline mode : False\r\n             user-agent : conda/4.3.9 requests/2.12.4 CPython/2.7.13 Windows/10 Windows/10.0.14393\r\n```\r\n\r\nI got this error when I tried to install qt:\r\n```\r\n> conda create -n test qt\r\nFetching package metadata ...........\r\nSolving package specifications: .\r\n\r\nPackage plan for installation in environment C:\\Users\\joelkim\\Anaconda2\\envs\\test:\r\n\r\nThe following NEW packages will be INSTALLED:\r\n\r\n    icu:            57.1-vc9_0        [vc9]\r\n    jpeg:           9b-vc9_0          [vc9]\r\n    libpng:         1.6.27-vc9_0      [vc9]\r\n    openssl:        1.0.2k-vc9_0      [vc9]\r\n    pip:            9.0.1-py27_1\r\n    python:         2.7.13-0\r\n    qt:             5.6.2-vc9_3       [vc9]\r\n    setuptools:     27.2.0-py27_1\r\n    vs2008_runtime: 9.00.30729.5054-0\r\n    wheel:          0.29.0-py27_0\r\n    zlib:           1.2.8-vc9_3       [vc9]\r\n\r\nProceed ([y]/n)?\r\n\r\nERROR conda.core.link:_execute_actions(319): An error occurred while installing package 'defaults::qt-5.6.2-vc9_3'.\r\n```\r\n \n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n# Try to keep compat small because it's imported by everything\n# What is compat, and what isn't?\n# If a piece of code is \"general\" and used in multiple modules, it goes here.\n# If it's only used in one module, keep it in that module, preferably near the top.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom itertools import chain\nfrom operator import methodcaller\nfrom os import chmod, lstat\nfrom os.path import islink\nimport sys\n\non_win = bool(sys.platform == \"win32\")\n\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\n\n\n# #############################\n# equivalent commands\n# #############################\n\nif PY3:  # pragma: py2 no cover\n    string_types = str,\n    integer_types = int,\n    class_types = type,\n    text_type = str\n    binary_type = bytes\n    input = input\n    range = range\n\nelif PY2:  # pragma: py3 no cover\n    from types import ClassType\n    string_types = basestring,\n    integer_types = (int, long)\n    class_types = (type, ClassType)\n    text_type = unicode\n    binary_type = str\n    input = raw_input\n    range = xrange\n\n\n# #############################\n# equivalent imports\n# #############################\n\nif PY3:  # pragma: py2 no cover\n    from io import StringIO\n    from itertools import zip_longest\nelif PY2:  # pragma: py3 no cover\n    from cStringIO import StringIO\n    from itertools import izip as zip, izip_longest as zip_longest\n\nStringIO = StringIO\nzip = zip\nzip_longest = zip_longest\n\n\n# #############################\n# equivalent functions\n# #############################\n\nif PY3:  # pragma: py2 no cover\n    def iterkeys(d, **kw):\n        return iter(d.keys(**kw))\n\n    def itervalues(d, **kw):\n        return iter(d.values(**kw))\n\n    def iteritems(d, **kw):\n        return iter(d.items(**kw))\n\n    viewkeys = methodcaller(\"keys\")\n    viewvalues = methodcaller(\"values\")\n    viewitems = methodcaller(\"items\")\n\n    def lchmod(path, mode):\n        try:\n            chmod(path, mode, follow_symlinks=False)\n        except (TypeError, NotImplementedError, SystemError):\n            # On systems that don't allow permissions on symbolic links, skip\n            # links entirely.\n            if not islink(path):\n                chmod(path, mode)\n\n\n    from collections import Iterable\n    def isiterable(obj):\n        return not isinstance(obj, string_types) and isinstance(obj, Iterable)\n\nelif PY2:  # pragma: py3 no cover\n    def iterkeys(d, **kw):\n        return d.iterkeys(**kw)\n\n    def itervalues(d, **kw):\n        return d.itervalues(**kw)\n\n    def iteritems(d, **kw):\n        return d.iteritems(**kw)\n\n    viewkeys = methodcaller(\"viewkeys\")\n    viewvalues = methodcaller(\"viewvalues\")\n    viewitems = methodcaller(\"viewitems\")\n\n    try:\n        from os import lchmod as os_lchmod\n        lchmod = os_lchmod\n    except ImportError:\n        def lchmod(path, mode):\n            # On systems that don't allow permissions on symbolic links, skip\n            # links entirely.\n            if not islink(path):\n                chmod(path, mode)\n\n    def isiterable(obj):\n        return (hasattr(obj, '__iter__')\n                and not isinstance(obj, string_types)\n                and type(obj) is not type)\n\n\n# #############################\n# other\n# #############################\n\ndef with_metaclass(Type, skip_attrs=set(('__dict__', '__weakref__'))):\n    \"\"\"Class decorator to set metaclass.\n\n    Works with both Python 2 and Python 3 and it does not add\n    an extra class in the lookup order like ``six.with_metaclass`` does\n    (that is -- it copies the original class instead of using inheritance).\n\n    \"\"\"\n\n    def _clone_with_metaclass(Class):\n        attrs = dict((key, value) for key, value in iteritems(vars(Class))\n                     if key not in skip_attrs)\n        return Type(Class.__name__, Class.__bases__, attrs)\n\n    return _clone_with_metaclass\n\n\nfrom collections import OrderedDict as odict\nodict = odict\n\nNoneType = type(None)\nprimitive_types = tuple(chain(string_types, integer_types, (float, complex, bool, NoneType)))\n\n\ndef ensure_binary(value):\n    return value.encode('utf-8') if hasattr(value, 'encode') else value\n\n\ndef ensure_text_type(value):\n    return value.decode('utf-8') if hasattr(value, 'decode') else value\n\n\ndef ensure_unicode(value):\n    return value.decode('unicode_escape') if hasattr(value, 'decode') else value\n\n\n# TODO: move this somewhere else\n# work-around for python bug on Windows prior to python 3.2\n# https://bugs.python.org/issue10027\n# Adapted from the ntfsutils package, Copyright (c) 2012, the Mozilla Foundation\nclass CrossPlatformStLink(object):\n    _st_nlink = None\n\n    def __call__(self, path):\n        return self.st_nlink(path)\n\n    @classmethod\n    def st_nlink(cls, path):\n        if cls._st_nlink is None:\n            cls._initialize()\n        return cls._st_nlink(path)\n\n    @classmethod\n    def _standard_st_nlink(cls, path):\n        return lstat(path).st_nlink\n\n    @classmethod\n    def _windows_st_nlink(cls, path):\n        st_nlink = cls._standard_st_nlink(path)\n        if st_nlink != 0:\n            return st_nlink\n        else:\n            # cannot trust python on Windows when st_nlink == 0\n            # get value using windows libraries to be sure of its true value\n            # Adapted from the ntfsutils package, Copyright (c) 2012, the Mozilla Foundation\n            GENERIC_READ = 0x80000000\n            FILE_SHARE_READ = 0x00000001\n            OPEN_EXISTING = 3\n            hfile = cls.CreateFile(path, GENERIC_READ, FILE_SHARE_READ, None,\n                                   OPEN_EXISTING, 0, None)\n            if hfile is None:\n                from ctypes import WinError\n                raise WinError()\n            info = cls.BY_HANDLE_FILE_INFORMATION()\n            rv = cls.GetFileInformationByHandle(hfile, info)\n            cls.CloseHandle(hfile)\n            if rv == 0:\n                from ctypes import WinError\n                raise WinError()\n            return info.nNumberOfLinks\n\n    @classmethod\n    def _initialize(cls):\n        if not on_win:\n            cls._st_nlink = cls._standard_st_nlink\n        else:\n            # http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858\n            import ctypes\n            from ctypes import POINTER\n            from ctypes.wintypes import DWORD, HANDLE, BOOL\n\n            cls.CreateFile = ctypes.windll.kernel32.CreateFileW\n            cls.CreateFile.argtypes = [ctypes.c_wchar_p, DWORD, DWORD, ctypes.c_void_p,\n                                       DWORD, DWORD, HANDLE]\n            cls.CreateFile.restype = HANDLE\n\n            # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724211\n            cls.CloseHandle = ctypes.windll.kernel32.CloseHandle\n            cls.CloseHandle.argtypes = [HANDLE]\n            cls.CloseHandle.restype = BOOL\n\n            class FILETIME(ctypes.Structure):\n                _fields_ = [(\"dwLowDateTime\", DWORD),\n                            (\"dwHighDateTime\", DWORD)]\n\n            class BY_HANDLE_FILE_INFORMATION(ctypes.Structure):\n                _fields_ = [(\"dwFileAttributes\", DWORD),\n                            (\"ftCreationTime\", FILETIME),\n                            (\"ftLastAccessTime\", FILETIME),\n                            (\"ftLastWriteTime\", FILETIME),\n                            (\"dwVolumeSerialNumber\", DWORD),\n                            (\"nFileSizeHigh\", DWORD),\n                            (\"nFileSizeLow\", DWORD),\n                            (\"nNumberOfLinks\", DWORD),\n                            (\"nFileIndexHigh\", DWORD),\n                            (\"nFileIndexLow\", DWORD)]\n            cls.BY_HANDLE_FILE_INFORMATION = BY_HANDLE_FILE_INFORMATION\n\n            # http://msdn.microsoft.com/en-us/library/windows/desktop/aa364952\n            cls.GetFileInformationByHandle = ctypes.windll.kernel32.GetFileInformationByHandle\n            cls.GetFileInformationByHandle.argtypes = [HANDLE, POINTER(BY_HANDLE_FILE_INFORMATION)]\n            cls.GetFileInformationByHandle.restype = BOOL\n\n            cls._st_nlink = cls._windows_st_nlink\n", "path": "conda/common/compat.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n# Try to keep compat small because it's imported by everything\n# What is compat, and what isn't?\n# If a piece of code is \"general\" and used in multiple modules, it goes here.\n# If it's only used in one module, keep it in that module, preferably near the top.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom itertools import chain\nfrom operator import methodcaller\nfrom os import chmod, lstat\nfrom os.path import islink\nimport sys\n\non_win = bool(sys.platform == \"win32\")\n\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\n\n\n# #############################\n# equivalent commands\n# #############################\n\nif PY3:  # pragma: py2 no cover\n    string_types = str,\n    integer_types = int,\n    class_types = type,\n    text_type = str\n    binary_type = bytes\n    input = input\n    range = range\n\nelif PY2:  # pragma: py3 no cover\n    from types import ClassType\n    string_types = basestring,\n    integer_types = (int, long)\n    class_types = (type, ClassType)\n    text_type = unicode\n    binary_type = str\n    input = raw_input\n    range = xrange\n\n\n# #############################\n# equivalent imports\n# #############################\n\nif PY3:  # pragma: py2 no cover\n    from io import StringIO\n    from itertools import zip_longest\nelif PY2:  # pragma: py3 no cover\n    from cStringIO import StringIO\n    from itertools import izip as zip, izip_longest as zip_longest\n\nStringIO = StringIO\nzip = zip\nzip_longest = zip_longest\n\n\n# #############################\n# equivalent functions\n# #############################\n\nif PY3:  # pragma: py2 no cover\n    def iterkeys(d, **kw):\n        return iter(d.keys(**kw))\n\n    def itervalues(d, **kw):\n        return iter(d.values(**kw))\n\n    def iteritems(d, **kw):\n        return iter(d.items(**kw))\n\n    viewkeys = methodcaller(\"keys\")\n    viewvalues = methodcaller(\"values\")\n    viewitems = methodcaller(\"items\")\n\n    def lchmod(path, mode):\n        try:\n            chmod(path, mode, follow_symlinks=False)\n        except (TypeError, NotImplementedError, SystemError):\n            # On systems that don't allow permissions on symbolic links, skip\n            # links entirely.\n            if not islink(path):\n                chmod(path, mode)\n\n\n    from collections import Iterable\n    def isiterable(obj):\n        return not isinstance(obj, string_types) and isinstance(obj, Iterable)\n\nelif PY2:  # pragma: py3 no cover\n    def iterkeys(d, **kw):\n        return d.iterkeys(**kw)\n\n    def itervalues(d, **kw):\n        return d.itervalues(**kw)\n\n    def iteritems(d, **kw):\n        return d.iteritems(**kw)\n\n    viewkeys = methodcaller(\"viewkeys\")\n    viewvalues = methodcaller(\"viewvalues\")\n    viewitems = methodcaller(\"viewitems\")\n\n    try:\n        from os import lchmod as os_lchmod\n        lchmod = os_lchmod\n    except ImportError:\n        def lchmod(path, mode):\n            # On systems that don't allow permissions on symbolic links, skip\n            # links entirely.\n            if not islink(path):\n                chmod(path, mode)\n\n    def isiterable(obj):\n        return (hasattr(obj, '__iter__')\n                and not isinstance(obj, string_types)\n                and type(obj) is not type)\n\n\n# #############################\n# other\n# #############################\n\ndef with_metaclass(Type, skip_attrs=set(('__dict__', '__weakref__'))):\n    \"\"\"Class decorator to set metaclass.\n\n    Works with both Python 2 and Python 3 and it does not add\n    an extra class in the lookup order like ``six.with_metaclass`` does\n    (that is -- it copies the original class instead of using inheritance).\n\n    \"\"\"\n\n    def _clone_with_metaclass(Class):\n        attrs = dict((key, value) for key, value in iteritems(vars(Class))\n                     if key not in skip_attrs)\n        return Type(Class.__name__, Class.__bases__, attrs)\n\n    return _clone_with_metaclass\n\n\nfrom collections import OrderedDict as odict\nodict = odict\n\nNoneType = type(None)\nprimitive_types = tuple(chain(string_types, integer_types, (float, complex, bool, NoneType)))\n\n\ndef ensure_binary(value):\n    return value.encode('utf-8') if hasattr(value, 'encode') else value\n\n\ndef ensure_text_type(value):\n    if hasattr(value, 'decode'):\n        try:\n            return value.decode('utf-8')\n        except UnicodeDecodeError:\n            from requests.packages.chardet import detect\n            encoding = detect(value).get('encoding') or 'utf-8'\n            return value.decode(encoding)\n    else:\n        return value\n\n\ndef ensure_unicode(value):\n    return value.decode('unicode_escape') if hasattr(value, 'decode') else value\n\n\n# TODO: move this somewhere else\n# work-around for python bug on Windows prior to python 3.2\n# https://bugs.python.org/issue10027\n# Adapted from the ntfsutils package, Copyright (c) 2012, the Mozilla Foundation\nclass CrossPlatformStLink(object):\n    _st_nlink = None\n\n    def __call__(self, path):\n        return self.st_nlink(path)\n\n    @classmethod\n    def st_nlink(cls, path):\n        if cls._st_nlink is None:\n            cls._initialize()\n        return cls._st_nlink(path)\n\n    @classmethod\n    def _standard_st_nlink(cls, path):\n        return lstat(path).st_nlink\n\n    @classmethod\n    def _windows_st_nlink(cls, path):\n        st_nlink = cls._standard_st_nlink(path)\n        if st_nlink != 0:\n            return st_nlink\n        else:\n            # cannot trust python on Windows when st_nlink == 0\n            # get value using windows libraries to be sure of its true value\n            # Adapted from the ntfsutils package, Copyright (c) 2012, the Mozilla Foundation\n            GENERIC_READ = 0x80000000\n            FILE_SHARE_READ = 0x00000001\n            OPEN_EXISTING = 3\n            hfile = cls.CreateFile(path, GENERIC_READ, FILE_SHARE_READ, None,\n                                   OPEN_EXISTING, 0, None)\n            if hfile is None:\n                from ctypes import WinError\n                raise WinError()\n            info = cls.BY_HANDLE_FILE_INFORMATION()\n            rv = cls.GetFileInformationByHandle(hfile, info)\n            cls.CloseHandle(hfile)\n            if rv == 0:\n                from ctypes import WinError\n                raise WinError()\n            return info.nNumberOfLinks\n\n    @classmethod\n    def _initialize(cls):\n        if not on_win:\n            cls._st_nlink = cls._standard_st_nlink\n        else:\n            # http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858\n            import ctypes\n            from ctypes import POINTER\n            from ctypes.wintypes import DWORD, HANDLE, BOOL\n\n            cls.CreateFile = ctypes.windll.kernel32.CreateFileW\n            cls.CreateFile.argtypes = [ctypes.c_wchar_p, DWORD, DWORD, ctypes.c_void_p,\n                                       DWORD, DWORD, HANDLE]\n            cls.CreateFile.restype = HANDLE\n\n            # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724211\n            cls.CloseHandle = ctypes.windll.kernel32.CloseHandle\n            cls.CloseHandle.argtypes = [HANDLE]\n            cls.CloseHandle.restype = BOOL\n\n            class FILETIME(ctypes.Structure):\n                _fields_ = [(\"dwLowDateTime\", DWORD),\n                            (\"dwHighDateTime\", DWORD)]\n\n            class BY_HANDLE_FILE_INFORMATION(ctypes.Structure):\n                _fields_ = [(\"dwFileAttributes\", DWORD),\n                            (\"ftCreationTime\", FILETIME),\n                            (\"ftLastAccessTime\", FILETIME),\n                            (\"ftLastWriteTime\", FILETIME),\n                            (\"dwVolumeSerialNumber\", DWORD),\n                            (\"nFileSizeHigh\", DWORD),\n                            (\"nFileSizeLow\", DWORD),\n                            (\"nNumberOfLinks\", DWORD),\n                            (\"nFileIndexHigh\", DWORD),\n                            (\"nFileIndexLow\", DWORD)]\n            cls.BY_HANDLE_FILE_INFORMATION = BY_HANDLE_FILE_INFORMATION\n\n            # http://msdn.microsoft.com/en-us/library/windows/desktop/aa364952\n            cls.GetFileInformationByHandle = ctypes.windll.kernel32.GetFileInformationByHandle\n            cls.GetFileInformationByHandle.argtypes = [HANDLE, POINTER(BY_HANDLE_FILE_INFORMATION)]\n            cls.GetFileInformationByHandle.restype = BOOL\n\n            cls._st_nlink = cls._windows_st_nlink\n", "path": "conda/common/compat.py"}]}