Patch spyder to make it work with sos files and sos kernel
558384
def patch_spyder2(verbose=False):
    ''' '''
    try:
        # patch spyderlib/config.py for file extension
        from spyderlib import config
        src_file = config.__file__
        spyderlib_dir = os.path.dirname(src_file)
        if verbose:
            print('Patching {}'.format(src_file))
        with open(src_file, encoding='utf-8') as src:
            content = src.read()
        with open(src_file, 'w', encoding='utf-8') as src:
            src.write(content.replace('''
    (_("Cython/Pyrex files"), ('.pyx', '.pxd', '.pxi')),
    (_("C files"), ('.c', '.h')),''', '''
    (_("Cython/Pyrex files"), ('.pyx', '.pxd', '.pxi')),
    (_("SoS files"), ('.sos', )),
    (_("C files"), ('.c', '.h')),'''))
        #
        # patch spyderlib/cli_options.py to add command line option --kernel
        src_file = os.path.join(spyderlib_dir, 'cli_options.py')
        if verbose:
            print('Patching {}'.format(src_file))
        with open(src_file, encoding='utf-8') as src:
            content = src.read()
        with open(src_file, 'w', encoding='utf-8') as src:
            src.write(content.replace('''with Python profiling)")
    options, args = parser.parse_args()''',
            '''with Python profiling)")
    parser.add_option('--kernel', help="Jupyter kernel to start.")
    options, args = parser.parse_args()'''))
        #
        # patch spyderlib.utils.sourcecode.py,
        src_file = os.path.join(spyderlib_dir, 'utils', 'sourcecode.py')
        if verbose:
            print('Patching {}'.format(src_file))
        with open(src_file, encoding='utf-8') as src:
            content = src.read()
        with open(src_file, 'w', encoding='utf-8') as src:
            src.write(content.replace(
                "'Python': ('py', 'pyw', 'python', 'ipy')",
                "'Python': ('py', 'pyw', 'python', 'ipy', 'sos')")
                .replace(
                '''CELL_LANGUAGES = {'Python': ('#%%', '# %%', '# <codecell>', '# In[')}''',
                '''CELL_LANGUAGES = {'Python': ('#%%', '# %%', '# <codecell>', '# In[', '%cell')}''')
            )
        #
        # patch spyderlib/spyder.py
        src_file = os.path.join(spyderlib_dir, 'spyder.py')
        if verbose:
            print('Patching {}'.format(src_file))
        with open(src_file, encoding='utf-8') as src:
            content = src.read()
        with open(src_file, 'w', encoding='utf-8') as src:
            src.write(content.replace(
            '''
    app.exec_()
''',
            r'''
    try:
        if options.kernel == 'sos':
            cfg_file = os.path.expanduser('~/.ipython/profile_default/ipython_config.py')
            has_cfg = os.path.isfile(cfg_file)
            if has_cfg and not os.path.isfile(cfg_file + '.sos_bak'):
                os.rename(cfg_file, cfg_file + '.sos_bak')
            with open(cfg_file, 'w') as cfg:
                cfg.write("c.IPKernelApp.kernel_class =  'sos_notebook.kernel.SoS_Kernel'\n")
        app.exec_()
    finally:
        if options.kernel == 'sos':
            os.remove(cfg_file)
            if os.path.isfile(cfg_file + '.sos_bak'):
                os.rename(cfg_file + '.sos_bak', cfg_file)
'''))
        #
        print('\nSpyder is successfully patched to accept .sos format and sos kernel.')
        print('Use ')
        print()
        print('    $ spyder --kernel sos')
        print()
        print('to start spyder with sos kernel')
    except Exception as e:
        sys.exit('Failed to patch spyder: {}'.format(e))
738452
async def restart(self):
        '''
        
        '''
        params = {}
        if self.owner_access_key:
            params['owner_access_key'] = self.owner_access_key
        rqst = Request(self.session,
                       'PATCH', '/kernel/{}'.format(self.kernel_id),
                       params=params)
        async with rqst.fetch():
            pass
325186
function patch(fs) {
    if (fs[NS])
        return;

    const virtualFS = {
        files: {},
        add(options) {
            const file = path.resolve(options.path);
            if (virtualFS.files[file] && virtualFS.files[file].content.equals(options.content)) {
                return;
            }
            virtualFS.files[file] = {
                path: file,
                content: options.content,
            };
        },
    };
    fs[NS] = virtualFS;

    createPatchFn(fs, 'readFile', function (orig, args, file, encoding, cb) {
        const rfile = path.resolve(file);
        const vfile = virtualFS.files[rfile];
        if (vfile) {
            if (typeof encoding === 'function') {
                cb = encoding;
                encoding = null;
            }

            let content = vfile.content;
            if (encoding !== null)
                content = content.toString(encoding);

            cb(null, content);
            return;
        }
        return orig.apply(this, args);
    });
    createPatchFn(fs, 'readFileSync', function (orig, args, file, encoding) {
        const rfile = path.resolve(file);
        const vfile = virtualFS.files[rfile];
        if (vfile) {
            let content = vfile.content;
            if (encoding !== null)
                content = content.toString(encoding);
            return content;
        }
        return orig.apply(this, args);
    });

    createPatchFn(fs, 'stat', function (orig, args, p, cb) {
        const rp = path.resolve(p);
        const vfile = virtualFS.files[rp];
        if (vfile) {
            const vstat = {
                dev: 8675309,
                nlink: 1,
                uid: 501,
                gid: 20,
                rdev: 0,
                blksize: 4096,
                ino: 44700000,
                mode: 33188,
                size: vfile.content.length,
                isFile: function isFile() {
                    return true;
                },
                isDirectory: function isDirectory() {
                    return false;
                },
                isBlockDevice: function isBlockDevice() {
                    return false;
                },
                isCharacterDevice: function isCharacterDevice() {
                    return false;
                },
                isSymbolicLink: function isSymbolicLink() {
                    return false;
                },
                isFIFO: function isFIFO() {
                    return false;
                },
                isSocket: function isSocket() {
                    return false;
                },
            };
            cb(null, vstat);
            return;
        }
        return orig.apply(this, args);
    });
    createPatchFn(fs, 'statSync', function (orig, args, p) {
        const rp = path.resolve(p);
        const vfile = virtualFS.files[rp];
        if (vfile) {
            const vstat = {
                dev: 8675309,
                nlink: 1,
                uid: 501,
                gid: 20,
                rdev: 0,
                blksize: 4096,
                ino: 44700000,
                mode: 33188,
                size: vfile.content.length,
                isFile: function isFile() {
                    return true;
                },
                isDirectory: function isDirectory() {
                    return false;
                },
                isBlockDevice: function isBlockDevice() {
                    return false;
                },
                isCharacterDevice: function isCharacterDevice() {
                    return false;
                },
                isSymbolicLink: function isSymbolicLink() {
                    return false;
                },
                isFIFO: function isFIFO() {
                    return false;
                },
                isSocket: function isSocket() {
                    return false;
                },
            };
            return vstat;
        }
        return orig.apply(this, args);
    });
}
993688
def singledispatch(*, nargs=None, nouts=None, ndefs=None):
    

    def wrapper(f):
        return wraps(f)(SingleDispatchFunction(f, nargs=nargs, nouts=nouts, ndefs=ndefs))

    return wrapper
825682
def patchCurses(self):
        
        if (sys.version_info)[:3] == (3, 4, 0):
            self.addchar = lambda y, x, *args: self.win.addch(x, y, *args)
        else:
            self.addchar = self.win.addch
118817
def prepare_env(gdef='', gvars={}, extra_vars={}, host='localhost'):
    ''''''
    env.sos_dict.clear()

    if not gdef and not gvars:
        # SoS Notebook calls prepare_env without global statement from a
        # particular
        gdef, gvars = analyze_global_statements('')

    if gdef:
        exec(compile(gdef, filename="<ast>", mode="exec"), env.sos_dict._dict)

    env.sos_dict.quick_update(gvars)
    env.sos_dict.quick_update(extra_vars)
    if 'CONFIG' not in env.sos_dict:
        # if this is in sos notebook
        load_config_files()
    if 'hosts' not in env.sos_dict[
            'CONFIG'] and 'localhost' not in env.sos_dict['CONFIG']:
        env.sos_dict['CONFIG']['localhost'] = 'localhost'
        env.sos_dict['CONFIG']['hosts'] = {
            'localhost': {
                'paths': {},
                'address': 'localhost'
            }
        }
    # expose `paths` of localhost
    if host == 'localhost':
        if 'localhost' in env.sos_dict['CONFIG']:
            if 'hosts' not in env.sos_dict['CONFIG'] or env.sos_dict['CONFIG'][
                    'localhost'] not in env.sos_dict['CONFIG']['hosts']:
                env.logger.warning(
                    f"Localhost {env.sos_dict['CONFIG']['localhost']} is not defined in CONFIG['hosts']"
                )
                env.sos_dict['CONFIG']['hosts'][env.sos_dict['CONFIG']
                                                ['localhost']] = {
                                                    'paths': {},
                                                    'address': 'localhost'
                                                }
            env.sos_dict.set('__host__', env.sos_dict['CONFIG']['localhost'])
        else:
            if 'hosts' in env.sos_dict['CONFIG']:
                if 'localhost' not in env.sos_dict['CONFIG']['hosts']:
                    env.logger.warning('locahost is not defined in "hosts".')
                    env.sos_dict['CONFIG']['hosts']['localhost'] = {
                        'paths': {},
                        'address': 'localhost'
                    }
            elif 'paths' not in env.sos_dict['CONFIG']['hosts']['localhost']:
                env.sos_dict['CONFIG']['hosts']['localhost']['paths'] = {}
            env.sos_dict.set('__host__', 'localhost')
    else:
        if 'hosts' not in env.sos_dict['CONFIG'] or host not in env.sos_dict[
                'CONFIG']['hosts']:
            raise RuntimeError(
                f"Remote host {host} is not defined in CONFIG['hosts']. Available ones are {env.sos_dict['CONFIG']['hosts'].keys()}"
            )
        env.sos_dict.set('__host__', host)
218180
def fix_builtins(override_debug=False):
    """"""
    override_dict = {}
    orig_print = None
    used_print = None

    if(__builtins__.__class__ is dict):
        builtins_dict = __builtins__
    else:
        try:
            import builtins
        except ImportError:
            import __builtin__ as builtins
        builtins_dict = builtins.__dict__

    def _deprecated(*args, **kwargs):
        """Report the fact that the called function is deprecated."""
        import traceback
        raise DeprecationWarning("the called function is deprecated => " +
                                 traceback.extract_stack(None, 2)[0][3])

    def _print_wrapper(*args, **kwargs):
        flush = kwargs.get("flush", False)
        if "flush" in kwargs:
            del kwargs["flush"]
        orig_print(*args, **kwargs)
        if flush:
            kwargs.get("file", sys.stdout).flush()

    def _print_full(*args, **kwargs):
        opt = {"sep": " ", "end": "\n", "file": sys.stdout, "flush": False}
        for key in kwargs:
            if(key in opt):
                opt[key] = kwargs[key]
            else:
                raise TypeError("'"+key+"' is an invalid keyword argument "
                                "for this function")
        opt["file"].write(opt["sep"].join(str(val) for val in args)+opt["end"])
        if opt["flush"]:
            opt["file"].flush()

    def _sorted(my_list):
        my_list = list(my_list)
        my_list.sort()
        return my_list

    def _format(value, format_spec):
        return value.__format__(format_spec)

    if builtins_dict.get(__name__, False):
        raise RuntimeError(__name__+" already loaded")

    # Exceptions
    if builtins_dict.get("BaseException") is None:
        override_dict["BaseException"] = Exception

    # basestring
    if builtins_dict.get("basestring") is None:
        if builtins_dict.get("bytes") is None:
            import types
            override_dict["basestring"] = types.StringType
        else:
            override_dict["basestring"] = (str, bytes)  # It works only when used in isinstance
    # IntType
    if getattr(int, "__str__", None) is None:
        import types
        override_dict["IntType"] = types.IntType
    else:
        override_dict["IntType"] = int  # Python >= 2.2

    if 'format' not in str.__dict__:
        override_dict["str"] = _Internal.ExtStr
    # Function 'input'
    if builtins_dict.get("raw_input") is not None:
        override_dict["input"] = builtins_dict.get("raw_input")
    override_dict["raw_input"] = _deprecated
    # Function 'print' (also aliased as print_)
    if sys.version_info >= (3, 3):
        used_print = builtins_dict.get("print")
    else:
        orig_print = builtins_dict.get("print")
        if orig_print is not None:
            used_print = _print_wrapper
        else:
            used_print = _print_full
        override_dict["print"] = used_print
    override_dict["print_"] = used_print
    # Function 'sorted'
    if builtins_dict.get("sorted") is None:
        override_dict["sorted"] = _sorted
    # Function 'format'
    if builtins_dict.get("format") is None:
        override_dict["format"] = _format

    override_dict[__name__] = True
    builtins_dict.update(override_dict)
    del override_dict
656149
def monkey_patch_bson(bson=None):
  ''''''
  if not bson:
    import bson

  if not hasattr(bson, 'loads'):
    bson.loads = lambda bsondoc: bson.BSON(bsondoc).decode()

  if not hasattr(bson, 'dumps'):
    bson.dumps = lambda document: bson.BSON.encode(document)
1143243
def monkey_patch(cls):
        """"""
        on_read_the_docs = os.environ.get('READTHEDOCS', False)
        if on_read_the_docs:
            sys.modules['zbarlight._zbarlight'] = cls
1328413
def _patched_pep257():
    """"""
    import pep257

    if getattr(pep257, "log", None):
        def _dummy(*args, **kwargs):
            del args
            del kwargs

        old_log_info = pep257.log.info
        pep257.log.info = _dummy  # suppress(unused-attribute)
    try:
        yield
    finally:
        if getattr(pep257, "log", None):
            pep257.log.info = old_log_info
125413
def open_with_external_spyder(self, text):
        """"""
        match = get_error_match(to_text_string(text))
        if match:
            fname, lnb = match.groups()
            builtins.open_in_spyder(fname, int(lnb))
900785
def add_patchs_to_build_without_pkg_config(self, lib_dir, include_dir):
        
        additional_patches = [
            {
                'src': r"pkgconfig\('--libs-only-L'\)",
                'dest': "['{0}']".format(lib_dir),
            },
            # Considering -libs-only-l and -libs-only-L
            # https://github.com/rpm-software-management/rpm/pull/327
            {
                'src': r"pkgconfig\('--libs(-only-l)?'\)",
                'dest': "['rpm', 'rpmio']",
                'required': True,
            },
            {
                'src': r"pkgconfig\('--cflags'\)",
                'dest': "['{0}']".format(include_dir),
                'required': True,
            },
        ]
        self.patches.extend(additional_patches)
874487
def patch_lustre_path(f_path):
    """"""

    if CHECK_LUSTRE_PATH_LEN and len(f_path) == 60:
        if os.path.isabs(f_path):
            f_path = '/.' + f_path
        else:
            f_path = './' + f_path

    return f_path
1210836
def get_spyderplugins_mods(io=False):
    """"""
    # Create user directory
    user_plugin_path = osp.join(get_conf_path(), USER_PLUGIN_DIR)
    if not osp.isdir(user_plugin_path):
        os.makedirs(user_plugin_path)

    modlist, modnames = [], []

    # The user plugins directory is given the priority when looking for modules
    for plugin_path in [user_plugin_path] + sys.path:
        _get_spyderplugins(plugin_path, io, modnames, modlist)
    return modlist
957550
def connect_client_to_kernel(self, client, is_cython=False,
                                 is_pylab=False, is_sympy=False):
        """"""
        connection_file = client.connection_file
        stderr_handle = None if self.test_no_stderr else client.stderr_handle
        km, kc = self.create_kernel_manager_and_kernel_client(
                     connection_file,
                     stderr_handle,
                     is_cython=is_cython,
                     is_pylab=is_pylab,
                     is_sympy=is_sympy)

        # An error occurred if this is True
        if is_string(km) and kc is None:
            client.shellwidget.kernel_manager = None
            client.show_kernel_error(km)
            return

        # This avoids a recurrent, spurious NameError when running our
        # tests in our CIs
        if not self.testing:
            kc.started_channels.connect(
                lambda c=client: self.process_started(c))
            kc.stopped_channels.connect(
                lambda c=client: self.process_finished(c))
        kc.start_channels(shell=True, iopub=True)

        shellwidget = client.shellwidget
        shellwidget.kernel_manager = km
        shellwidget.kernel_client = kc
761486
def synchronize(self):
        
        answer = QMessageBox.question(self, _("Synchronize"),
            _("This will synchronize Spyder's path list with "
                    "<b>PYTHONPATH</b> environment variable for current user, "
                    "allowing you to run your Python modules outside Spyder "
                    "without having to configure sys.path. "
                    "<br>Do you want to clear contents of PYTHONPATH before "
                    "adding Spyder's path list?"),
            QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
        if answer == QMessageBox.Cancel:
            return
        elif answer == QMessageBox.Yes:
            remove = True
        else:
            remove = False
        from spyder.utils.environ import (get_user_env, set_user_env,
                                          listdict2envdict)
        env = get_user_env()
        if remove:
            ppath = self.active_pathlist+self.ro_pathlist
        else:
            ppath = env.get('PYTHONPATH', [])
            if not isinstance(ppath, list):
                ppath = [ppath]
            ppath = [path for path in ppath
                     if path not in (self.active_pathlist+self.ro_pathlist)]
            ppath.extend(self.active_pathlist+self.ro_pathlist)
        env['PYTHONPATH'] = ppath
        set_user_env(listdict2envdict(env), parent=self)
617425
def patch(patch_inspect=True):
    
    PATCHED['collections.abc.Generator'] = _collections_abc.Generator = Generator
    PATCHED['collections.abc.Coroutine'] = _collections_abc.Coroutine = Coroutine
    PATCHED['collections.abc.Awaitable'] = _collections_abc.Awaitable = Awaitable

    if patch_inspect:
        import inspect
        PATCHED['inspect.isawaitable'] = inspect.isawaitable = isawaitable