How to use the spyder.utils.encoding function in spyder

To help you get started, we’ve selected a few spyder examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sys-bio / tellurium / spyder_mod / Spyder 3.2.2 / spyder / plugins / editor.py View on Github external
'Tellurium oscillation', '"""',
                       '', 'import tellurium as te', 'import roadrunner',
                       'import antimony', '',
                       "r = te.loada ('''", 'model feedback()', '  // Reactions:',
  '  J0: $X0 -> S1; (VM1 * (X0 - S1/Keq1))/(1 + X0 + S1 + S4^h);',
  '  J1: S1 -> S2; (10 * S1 - 2 * S2) / (1 + S1 + S2);',
  '  J2: S2 -> S3; (10 * S2 - 2 * S3) / (1 + S2 + S3);',
  '  J3: S3 -> S4; (10 * S3 - 2 * S4) / (1 + S3 + S4);',
  '  J4: S4 -> $X1; (V4 * S4) / (KS4 + S4);','',
  '  // Species initializations:', '  S1 = 0; S2 = 0; S3 = 0;',
  '  S4 = 0; X0 = 10; X1 = 0;','', '  // Variable initialization:',
  '  VM1 = 10; Keq1 = 10; h = 10; V4 = 2.5; KS4 = 0.5;',
"end''')", '', 'result = r.simulate(0, 40, 500)', 'r.plot(result)', '']
            text = os.linesep.join([encoding.to_unicode(qstr)
                                    for qstr in default])
            encoding.write(to_text_string(text), self.TEMPFILE_PATH, 'utf-8')
        self.load(self.TEMPFILE_PATH)
github spyder-ide / spyder / spyder / plugins / history / plugin.py View on Github external
if osp.splitext(filename)[1] == '.py':
            language = 'py'
        else:
            language = 'bat'
        editor.setup_editor(linenumbers=self.get_option('line_numbers'),
                            language=language,
                            scrollflagarea=False)
        editor.focus_changed.connect(lambda: self.focus_changed.emit())
        editor.setReadOnly(True)
        color_scheme = self.get_color_scheme()
        editor.set_font(self.get_font(), color_scheme)
        editor.toggle_wrap_mode(self.get_option('wrap'))

        # Avoid a possible error when reading the history file
        try:
            text, _ = encoding.read(filename)
        except (IOError, OSError):
            text = "# Previous history could not be read from disk, sorry\n\n"
        text = normalize_eols(text)
        linebreaks = [m.start() for m in re.finditer('\n', text)]
        maxNline = self.get_option('max_entries')
        if len(linebreaks) > maxNline:
            text = text[linebreaks[-maxNline - 1] + 1:]
            # Avoid an error when trying to write the trimmed text to
            # disk.
            # See spyder-ide/spyder#9093.
            try:
                encoding.write(text, filename)
            except (IOError, OSError):
                pass
        editor.set_text(text)
        editor.set_cursor_position('eof')
github spyder-ide / spyder / spyder / plugins / console / utils / interpreter.py View on Github external
self.stderr_write.write(
                                "No such file or directory: %s\n" % filename)
        # remove reference (equivalent to MATLAB's clear command)
        elif clear_match:
            varnames = clear_match.groups()[0].replace(' ', '').split(',')
            for varname in varnames:
                try:
                    self.namespace.pop(varname)
                except KeyError:
                    pass
        # Execute command
        elif cmd.startswith('!'):
            # System ! command
            pipe = programs.run_shell_command(cmd[1:])
            txt_out = encoding.transcode( pipe.stdout.read().decode() )
            txt_err = encoding.transcode( pipe.stderr.read().decode().rstrip() )
            if txt_err:
                self.stderr_write.write(txt_err)
            if txt_out:
                self.stdout_write.write(txt_out)
            self.stdout_write.write('\n')
            self.more = False
        # -- End of Special commands type II
        else:
            # Command executed in the interpreter
#            self.widget_proxy.set_readonly(True)
            self.more = self.push(cmd)
#            self.widget_proxy.set_readonly(False)
        
        if new_prompt:
            self.widget_proxy.new_prompt(self.p2 if self.more else self.p1)
        if not self.more:
github spyder-ide / spyder / spyder / widgets / mixins.py View on Github external
def create_history_filename(self):
        """Create history_filename with INITHISTORY if it doesn't exist."""
        if self.history_filename and not osp.isfile(self.history_filename):
            try:
                encoding.writelines(self.INITHISTORY, self.history_filename)
            except EnvironmentError:
                pass
github spyder-ide / spyder / spyder / widgets / mixins.py View on Github external
def create_history_filename(self):
        """Create history_filename with INITHISTORY if it doesn't exist."""
        if self.history_filename and not osp.isfile(self.history_filename):
            try:
                encoding.writelines(self.INITHISTORY, self.history_filename)
            except EnvironmentError:
                pass
github spyder-ide / spyder / spyder / plugins / variableexplorer / widgets / namespacebrowser.py View on Github external
item, ok = QInputDialog.getItem(self, title,
                                                _('Open file as:'),
                                                formats, 0, False)
                if ok:
                    ext = iofunctions.load_extensions[to_text_string(item)]
                else:
                    return

            load_func = iofunctions.load_funcs[ext]
                
            # 'import_wizard' (self.setup_io)
            if is_text_string(load_func):
                # Import data with import wizard
                error_message = None
                try:
                    text, _encoding = encoding.read(self.filename)
                    base_name = osp.basename(self.filename)
                    editor = ImportWizard(self, text, title=base_name,
                                  varname=fix_reference_name(base_name))
                    if editor.exec_():
                        var_name, clip_data = editor.get_data()
                        self.editor.new_value(var_name, clip_data)
                except Exception as error:
                    error_message = str(error)
            else:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.processEvents()
                error_message = self.shellwidget.load_data(self.filename, ext)
                QApplication.restoreOverrideCursor()
                QApplication.processEvents()
    
            if error_message is not None:
github spyder-ide / spyder / spyder / plugins / editor / plugin.py View on Github external
os.environ.get('USERNAME', ''))
                # Linux, Mac OS X
                if not username:
                    username = encoding.to_unicode_from_fs(
                                   os.environ.get('USER', '-'))
                VARS = {
                    'date': time.ctime(),
                    'username': username,
                }
                try:
                    text = text % VARS
                except Exception:
                    pass
            else:
                default_content = False
                enc = encoding.read(self.TEMPLATE_PATH)[1]
        except (IOError, OSError):
            text = ''
            enc = 'utf-8'
            default_content = True
            empty = True

        create_fname = lambda n: to_text_string(_("untitled")) + ("%d.py" % n)
        # Creating editor widget
        if editorstack is None:
            current_es = self.get_current_editorstack()
        else:
            current_es = editorstack
        created_from_here = fname is None
        if created_from_here:
            while True:
                fname = create_fname(self.untitled_num)
github spyder-ide / spyder / spyder / plugins / editor / plugin.py View on Github external
def __load_temp_file(self):
        """Load temporary file from a text file in user home directory"""
        if not osp.isfile(self.TEMPFILE_PATH):
            # Creating temporary file
            default = ['# -*- coding: utf-8 -*-',
                       '"""', _("Spyder Editor"), '',
                       _("This is a temporary script file."),
                       '"""', '', '']
            text = os.linesep.join([encoding.to_unicode(qstr)
                                    for qstr in default])
            try:
                encoding.write(to_text_string(text), self.TEMPFILE_PATH,
                               'utf-8')
            except EnvironmentError:
                self.new()
                return

        self.load(self.TEMPFILE_PATH)
github sys-bio / tellurium / spyder_mod / Spyder 3.1.3 / spyder / app / mainwindow.py View on Github external
def open_external_file(self, fname):
        """
        Open external files that can be handled either by the Editor or the
        variable explorer inside Spyder.
        """
        fname = encoding.to_unicode_from_fs(fname)
        if osp.isfile(fname):
            self.open_file(fname, external=True)
        elif osp.isfile(osp.join(CWD, fname)):
            self.open_file(osp.join(CWD, fname), external=True)