Example #1
0
 def process_data(self, text, colsep=u("\t"), rowsep=u("\n"),
                  transpose=False, skiprows=0, comments='#'):
     """Put data into table model"""
     data = self._shape_text(text, colsep, rowsep, transpose, skiprows,
                             comments)
     self._model = PreviewTableModel(data)
     self.setModel(self._model)
Example #2
0
 def process_data(self, text, colsep=u("\t"), rowsep=u("\n"),
                  transpose=False, skiprows=0, comments='#'):
     """Put data into table model"""
     data = self._shape_text(text, colsep, rowsep, transpose, skiprows,
                             comments)
     self._model = PreviewTableModel(data)
     self.setModel(self._model)
Example #3
0
    def text(self, encoding=None, errors='strict'):
        r""" Open this file, read it in, return the content as a string.

        This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
        are automatically translated to '\n'.

        Optional arguments:

        encoding - The Unicode encoding (or character set) of
            the file.  If present, the content of the file is
            decoded and returned as a unicode object; otherwise
            it is returned as an 8-bit str.
        errors - How to handle Unicode errors; see help(str.decode)
            for the options.  Default is 'strict'.
        """
        if encoding is None:
            # 8-bit
            f = self.open(_textmode)
            try:
                return f.read()
            finally:
                f.close()
        else:
            # Unicode
            f = codecs.open(self, 'r', encoding, errors)
            # (Note - Can't use 'U' mode here, since codecs.open
            # doesn't support 'U' mode, even in Python 2.3.)
            try:
                t = f.read()
            finally:
                f.close()
            return (t.replace(u('\r\n'), u('\n')).replace(
                u('\r\x85'), u('\n')).replace(u('\r'), u('\n')).replace(
                    u('\x85'), u('\n')).replace(u('\u2028'), u('\n')))
Example #4
0
 def _shape_text(self,
                 text,
                 colsep=u("\t"),
                 rowsep=u("\n"),
                 transpose=False,
                 skiprows=0,
                 comments='#'):
     """Decode the shape of the given text"""
     assert colsep != rowsep
     out = []
     text_rows = text.split(rowsep)[skiprows:]
     for row in text_rows:
         stripped = to_text_string(row).strip()
         if len(stripped) == 0 or stripped.startswith(comments):
             continue
         line = to_text_string(row).split(colsep)
         line = [try_to_parse(to_text_string(x)) for x in line]
         out.append(line)
     # Replace missing elements with np.nan's or None's
     if programs.is_module_installed('numpy'):
         from numpy import nan
         out = list(zip_longest(*out, fillvalue=nan))
     else:
         out = list(zip_longest(*out, fillvalue=None))
     # Tranpose the last result to get the expected one
     out = [[r[col] for r in out] for col in range(len(out[0]))]
     if transpose:
         return [[r[col] for r in out] for col in range(len(out[0]))]
     return out
Example #5
0
 def open_data(self, text, colsep=u("\t"), rowsep=u("\n"),
               transpose=False, skiprows=0, comments='#'):
     """Open clipboard text as table"""
     if pd:
         self.pd_text = text
         self.pd_info = dict(sep=colsep, lineterminator=rowsep,
             skiprows=skiprows,comment=comments)
     self._table_view.process_data(text, colsep, rowsep, transpose,
                                   skiprows, comments)
Example #6
0
 def open_data(self, text, colsep=u("\t"), rowsep=u("\n"),
               transpose=False, skiprows=0, comments='#'):
     """Open clipboard text as table"""
     if pd:
         self.pd_text = text
         self.pd_info = dict(sep=colsep, lineterminator=rowsep,
             skiprows=skiprows,comment=comments)
     self._table_view.process_data(text, colsep, rowsep, transpose,
                                   skiprows, comments)
Example #7
0
def test():
    """Array editor test"""
    _app = qapplication()
    
    arr = np.array(["kjrekrjkejr"])
    print("out:", test_edit(arr, "string array"))
    from spyderlib.py3compat import u
    arr = np.array([u("kjrekrjkejr")])
    print("out:", test_edit(arr, "unicode array"))
    arr = np.ma.array([[1, 0], [1, 0]], mask=[[True, False], [False, False]])
    print("out:", test_edit(arr, "masked array"))
    arr = np.zeros((2, 2), {'names': ('red', 'green', 'blue'),
                           'formats': (np.float32, np.float32, np.float32)})
    print("out:", test_edit(arr, "record array"))
    arr = np.array([(0, 0.0), (0, 0.0), (0, 0.0)],
                   dtype=[(('title 1', 'x'), '|i1'),
                          (('title 2', 'y'), '>f4')])
    print("out:", test_edit(arr, "record array with titles"))
    arr = np.random.rand(5, 5)
    print("out:", test_edit(arr, "float array",
                            xlabels=['a', 'b', 'c', 'd', 'e']))
    arr = np.round(np.random.rand(5, 5)*10)+\
                   np.round(np.random.rand(5, 5)*10)*1j
    print("out:", test_edit(arr, "complex array",
                            xlabels=np.linspace(-12, 12, 5),
                            ylabels=np.linspace(-12, 12, 5)))
    arr_in = np.array([True, False, True])
    print("in:", arr_in)
    arr_out = test_edit(arr_in, "bool array")
    print("out:", arr_out)
    print(arr_in is arr_out)
    arr = np.array([1, 2, 3], dtype="int8")
    print("out:", test_edit(arr, "int array"))
Example #8
0
 def get_selected_text(self):
     """
     Return text selected by current text cursor, converted in unicode
     
     Replace the unicode line separator character \u2029 by 
     the line separator characters returned by get_line_separator
     """
     return to_text_string(self.textCursor().selectedText()).replace(u("\u2029"),
                                                  self.get_line_separator())
Example #9
0
 def get_selected_text(self):
     """
     Return text selected by current text cursor, converted in unicode
     
     Replace the unicode line separator character \u2029 by 
     the line separator characters returned by get_line_separator
     """
     return to_text_string(self.textCursor().selectedText()).replace(
         u("\u2029"), self.get_line_separator())
Example #10
0
 def kernel_and_frontend_match(self, connection_file):
     # Determine kernel version
     ci = get_connection_info(connection_file, unpack=True,
                              profile='default')
     if u('control_port') in ci:
         kernel_ver = '>=1.0'
     else:
         kernel_ver = '<1.0'
     # is_module_installed checks if frontend version agrees with the
     # kernel one
     return programs.is_module_installed('IPython', version=kernel_ver)
Example #11
0
 def kernel_and_frontend_match(self, connection_file):
     # Determine kernel version
     ci = get_connection_info(connection_file,
                              unpack=True,
                              profile='default')
     if u('control_port') in ci:
         kernel_ver = '>=1.0'
     else:
         kernel_ver = '<1.0'
     # is_module_installed checks if frontend version agrees with the
     # kernel one
     return programs.is_module_installed('IPython', version=kernel_ver)
Example #12
0
 def on_enter(self, command):
     """on_enter"""
     if self.profile:
         # Simple profiling test
         t0 = time()
         for _ in range(10):
             self.execute_command(command)
         self.insert_text(u("\n<Δt>=%dms\n") % (1e2*(time()-t0)))
         self.new_prompt(self.interpreter.p1)
     else:
         self.execute_command(command)
     self.__flush_eventqueue()
Example #13
0
 def on_enter(self, command):
     """on_enter"""
     if self.profile:
         # Simple profiling test
         t0 = time()
         for _ in range(10):
             self.execute_command(command)
         self.insert_text(u("\n<Δt>=%dms\n") % (1e2 * (time() - t0)))
         self.new_prompt(self.interpreter.p1)
     else:
         self.execute_command(command)
     self.__flush_eventqueue()
Example #14
0
 def get_text(self, position_from, position_to):
     """
     Return text between *position_from* and *position_to*
     Positions may be positions or 'sol', 'eol', 'sof', 'eof' or 'cursor'
     """
     cursor = self.__select_text(position_from, position_to)
     text = to_text_string(cursor.selectedText())
     if text:
         while text.endswith("\n"):
             text = text[:-1]
         while text.endswith(u("\u2029")):
             text = text[:-1]
     return text
Example #15
0
 def get_text(self, position_from, position_to):
     """
     Return text between *position_from* and *position_to*
     Positions may be positions or 'sol', 'eol', 'sof', 'eof' or 'cursor'
     """
     cursor = self.__select_text(position_from, position_to)
     text = to_text_string(cursor.selectedText())
     if text:
         while text.endswith("\n"):
             text = text[:-1]
         while text.endswith(u("\u2029")):
             text = text[:-1]
     return text
Example #16
0
    def text(self, encoding=None, errors='strict'):
        r""" Open this file, read it in, return the content as a string.

        This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
        are automatically translated to '\n'.

        Optional arguments:

        encoding - The Unicode encoding (or character set) of
            the file.  If present, the content of the file is
            decoded and returned as a unicode object; otherwise
            it is returned as an 8-bit str.
        errors - How to handle Unicode errors; see help(str.decode)
            for the options.  Default is 'strict'.
        """
        if encoding is None:
            # 8-bit
            f = self.open(_textmode)
            try:
                return f.read()
            finally:
                f.close()
        else:
            # Unicode
            f = codecs.open(self, 'r', encoding, errors)
            # (Note - Can't use 'U' mode here, since codecs.open
            # doesn't support 'U' mode, even in Python 2.3.)
            try:
                t = f.read()
            finally:
                f.close()
            return (t.replace(u('\r\n'), u('\n'))
                     .replace(u('\r\x85'), u('\n'))
                     .replace(u('\r'), u('\n'))
                     .replace(u('\x85'), u('\n'))
                     .replace(u('\u2028'), u('\n')))
Example #17
0
 def _shape_text(self, text, colsep=u("\t"), rowsep=u("\n"),
                 transpose=False, skiprows=0, comments='#'):
     """Decode the shape of the given text"""
     assert colsep != rowsep
     out = []
     text_rows = text.split(rowsep)[skiprows:]
     for row in text_rows:
         stripped = to_text_string(row).strip()
         if len(stripped) == 0 or stripped.startswith(comments):
             continue
         line = to_text_string(row).split(colsep)
         line = [try_to_parse(to_text_string(x)) for x in line]
         out.append(line)
     # Replace missing elements with np.nan's or None's
     if programs.is_module_installed('numpy'):
         from numpy import nan
         out = list(zip_longest(*out, fillvalue=nan))
     else:
         out = list(zip_longest(*out, fillvalue=None))
     # Tranpose the last result to get the expected one
     out = [[r[col] for r in out] for col in range(len(out[0]))]
     if transpose:
         return [[r[col] for r in out] for col in range(len(out[0]))]
     return out
Example #18
0
 def get(self):
     valuelist = []
     for index, (label, value) in enumerate(self.data):
         field = self.widgets[index]
         if label is None:
             # Separator / Comment
             continue
         elif tuple_to_qfont(value) is not None:
             value = field.get_font()
         elif is_text_string(value):
             if isinstance(field, QTextEdit):
                 value = to_text_string(field.toPlainText()
                                        ).replace(u("\u2029"), os.linesep)
             else:
                 value = to_text_string(field.text())
         elif isinstance(value, (list, tuple)):
             index = int(field.currentIndex())
             if isinstance(value[0], int):
                 # Return an int index, if initialization was an int
                 value = index
             else:
                 value = value[index+1]
                 if isinstance(value, (list, tuple)):
                     value = value[0]
         elif isinstance(value, bool):
             value = field.checkState() == Qt.Checked
         elif isinstance(value, float):
             value = float(field.text())
         elif isinstance(value, int):
             value = int(field.value())
         elif isinstance(value, datetime.datetime):
             value = field.dateTime()
             try:
                 value = value.toPyDateTime()  # PyQt
             except AttributeError:
                 value = value.toPython()  # PySide
         elif isinstance(value, datetime.date):
             value = field.date()
             try:
                 value = value.toPyDate()  # PyQt
             except AttributeError:
                 value = value.toPython()  # PySide
         else:
             value = eval(str(field.text()))
         valuelist.append(value)
     return valuelist
Example #19
0
def test():
    """Array editor test"""
    _app = qapplication()

    arr = np.array(["kjrekrjkejr"])
    print("out:", test_edit(arr, "string array"))
    from spyderlib.py3compat import u
    arr = np.array([u("kjrekrjkejr")])
    print("out:", test_edit(arr, "unicode array"))
    arr = np.ma.array([[1, 0], [1, 0]], mask=[[True, False], [False, False]])
    print("out:", test_edit(arr, "masked array"))
    arr = np.zeros(
        (2, 2), {
            'names': ('red', 'green', 'blue'),
            'formats': (np.float32, np.float32, np.float32)
        })
    print("out:", test_edit(arr, "record array"))
    arr = np.array([(0, 0.0), (0, 0.0), (0, 0.0)],
                   dtype=[(('title 1', 'x'), '|i1'),
                          (('title 2', 'y'), '>f4')])
    print("out:", test_edit(arr, "record array with titles"))
    arr = np.random.rand(5, 5)
    print("out:",
          test_edit(arr, "float array", xlabels=['a', 'b', 'c', 'd', 'e']))
    arr = np.round(np.random.rand(5, 5)*10)+\
                   np.round(np.random.rand(5, 5)*10)*1j
    print(
        "out:",
        test_edit(arr,
                  "complex array",
                  xlabels=np.linspace(-12, 12, 5),
                  ylabels=np.linspace(-12, 12, 5)))
    arr_in = np.array([True, False, True])
    print("in:", arr_in)
    arr_out = test_edit(arr_in, "bool array")
    print("out:", arr_out)
    print(arr_in is arr_out)
    arr = np.array([1, 2, 3], dtype="int8")
    print("out:", test_edit(arr, "int array"))
    arr = np.zeros((3, 3, 4))
    arr[0, 0, 0] = 1
    arr[0, 0, 1] = 2
    arr[0, 0, 2] = 3
    print("out:", test_edit(arr))
Example #20
0
    def get_owner(self):
        r""" Return the name of the owner of this file or directory.

        This follows symbolic links.

        On Windows, this returns a name of the form ur'DOMAIN\User Name'.
        On Windows, a group can own a file or directory.
        """
        if os.name == 'nt':
            if win32security is None:
                raise Exception("path.owner requires win32all to be installed")
            desc = win32security.GetFileSecurity(
                self, win32security.OWNER_SECURITY_INFORMATION)
            sid = desc.GetSecurityDescriptorOwner()
            account, domain, typecode = win32security.LookupAccountSid(None, sid)
            return domain + u('\\') + account
        else:
            if pwd is None:
                raise NotImplementedError("path.owner is not implemented on this platform.")
            st = self.stat()
            return pwd.getpwuid(st.st_uid).pw_name
Example #21
0
    def get_owner(self):
        r""" Return the name of the owner of this file or directory.

        This follows symbolic links.

        On Windows, this returns a name of the form ur'DOMAIN\User Name'.
        On Windows, a group can own a file or directory.
        """
        if os.name == 'nt':
            if win32security is None:
                raise Exception("path.owner requires win32all to be installed")
            desc = win32security.GetFileSecurity(
                self, win32security.OWNER_SECURITY_INFORMATION)
            sid = desc.GetSecurityDescriptorOwner()
            account, domain, typecode = win32security.LookupAccountSid(
                None, sid)
            return domain + u('\\') + account
        else:
            if pwd is None:
                raise NotImplementedError(
                    "path.owner is not implemented on this platform.")
            st = self.stat()
            return pwd.getpwuid(st.st_uid).pw_name
Example #22
0

def save_auto(data, filename):
    """Save data into filename, depending on file extension"""
    pass


if __name__ == "__main__":
    from spyderlib.py3compat import u
    import datetime

    testdict = {"d": 1, "a": np.random.rand(10, 10), "b": [1, 2]}
    testdate = datetime.date(1945, 5, 8)
    example = {
        "str": "kjkj kj k j j kj k jkj",
        "unicode": u("éù"),
        "list": [1, 3, [4, 5, 6], "kjkj", None],
        "tuple": ([1, testdate, testdict], "kjkj", None),
        "dict": testdict,
        "float": 1.2233,
        "array": np.random.rand(4000, 400),
        "empty_array": np.array([]),
        "date": testdate,
        "datetime": datetime.datetime(1945, 5, 8),
    }
    import time

    t0 = time.time()
    save_dictionary(example, "test.spydata")
    print(" Data saved in %.3f seconds" % (time.time() - t0))
    t0 = time.time()
Example #23
0
iofunctions = IOFunctions()
iofunctions.setup()


def save_auto(data, filename):
    """Save data into filename, depending on file extension"""
    pass


if __name__ == "__main__":
    from spyderlib.py3compat import u
    import datetime
    testdict = {'d': 1, 'a': np.random.rand(10, 10), 'b': [1, 2]}
    testdate = datetime.date(1945, 5, 8)
    example = {'str': 'kjkj kj k j j kj k jkj',
               'unicode': u('éù'),
               'list': [1, 3, [4, 5, 6], 'kjkj', None],
               'tuple': ([1, testdate, testdict], 'kjkj', None),
               'dict': testdict,
               'float': 1.2233,
               'array': np.random.rand(4000, 400),
               'empty_array': np.array([]),
               'date': testdate,
               'datetime': datetime.datetime(1945, 5, 8),
               }
    import time
    t0 = time.time()
    save_dictionary(example, "test.spydata")
    print(" Data saved in %.3f seconds" % (time.time()-t0))
    t0 = time.time()
    example2, ok = load_dictionary("test.spydata")
Example #24
0
 def get_row_sep(self):
     """Return the row separator"""
     if self.eol_btn.isChecked():
         return u("\n")
     return to_text_string(self.line_edt_row.text())
Example #25
0
 def get_col_sep(self):
     """Return the column separator"""
     if self.tab_btn.isChecked():
         return u("\t")
     return to_text_string(self.line_edt.text())
Example #26
0
    @Slot()
    def process(self):
        """Process the data from clipboard"""
        var_name = self.name_edt.text()
        try:
            self.var_name = str(var_name)
        except UnicodeEncodeError:
            self.var_name = to_text_string(var_name)
        if self.text_widget.get_as_data():
            self.clip_data = self._get_table_data()
        elif self.text_widget.get_as_code():
            self.clip_data = try_to_eval(to_text_string(
                self._get_plain_text()))
        else:
            self.clip_data = to_text_string(self._get_plain_text())
        self.accept()


def test(text):
    """Test"""
    from spyderlib.utils.qthelpers import qapplication
    _app = qapplication()  # analysis:ignore
    dialog = ImportWizard(None, text)
    if dialog.exec_():
        print(dialog.get_data())


if __name__ == "__main__":
    test(u("17/11/1976\t1.34\n14/05/09\t3.14"))
Example #27
0
templates_path = ['templates']

# MathJax load path (doesn't have effect for sphinx 1.0-)
mathjax_path = 'MathJax/MathJax.js'

# JsMath load path (doesn't have effect for sphinx 1.1+)
jsmath_path = 'easy/load.js'

# The suffix of source filenames.
source_suffix = '.rst'

# The master toctree document.
master_doc = 'docstring'

# General information about the project.
project = u("Object Inspector")
copyright = u('2009--2013, The Spyder Development Team')

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['.build']

# The reST default role (used for this markup: `text`) to use for all documents.
#
# TODO: This role has to be set on a per project basis, i.e. numpy, sympy,
# mpmath, etc, use different default_role's which give different rendered
# docstrings. Setting this to None until it's solved.
default_role = 'None'

# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
Example #28
0
 def get_line_at(self, coordinates):
     """Return line at *coordinates* (QPoint)"""
     cursor = self.cursorForPosition(coordinates)
     cursor.select(QTextCursor.BlockUnderCursor)
     return to_text_string(cursor.selectedText()).replace(u('\u2029'), '')
Example #29
0
iofunctions.setup()


def save_auto(data, filename):
    """Save data into filename, depending on file extension"""
    pass


if __name__ == "__main__":
    from spyderlib.py3compat import u
    import datetime
    testdict = {'d': 1, 'a': np.random.rand(10, 10), 'b': [1, 2]}
    testdate = datetime.date(1945, 5, 8)
    example = {
        'str': 'kjkj kj k j j kj k jkj',
        'unicode': u('éù'),
        'list': [1, 3, [4, 5, 6], 'kjkj', None],
        'tuple': ([1, testdate, testdict], 'kjkj', None),
        'dict': testdict,
        'float': 1.2233,
        'array': np.random.rand(4000, 400),
        'empty_array': np.array([]),
        'date': testdate,
        'datetime': datetime.datetime(1945, 5, 8),
    }
    import time
    t0 = time.time()
    save_dictionary(example, "test.spydata")
    print(" Data saved in %.3f seconds" % (time.time() - t0))
    t0 = time.time()
    example2, ok = load_dictionary("test.spydata")
Example #30
0
 def get_line_at(self, coordinates):
     """Return line at *coordinates* (QPoint)"""
     cursor = self.cursorForPosition(coordinates)
     cursor.select(QTextCursor.BlockUnderCursor)
     return to_text_string(cursor.selectedText()).replace(u('\u2029'), '')
Example #31
0
templates_path = ['templates']

# MathJax load path (doesn't have effect for sphinx 1.0-)
mathjax_path = 'MathJax/MathJax.js'

# JsMath load path (doesn't have effect for sphinx 1.1+)
jsmath_path = 'easy/load.js'

# The suffix of source filenames.
source_suffix = '.rst'

# The master toctree document.
master_doc = 'docstring'

# General information about the project.
project = u("Object Inspector")
copyright = u('2009--2013, The Spyder Development Team')

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['.build']

# The reST default role (used for this markup: `text`) to use for all documents.
#
# TODO: This role has to be set on a per project basis, i.e. numpy, sympy,
# mpmath, etc, use different default_role's which give different rendered
# docstrings. Setting this to None until it's solved.
default_role = 'None'

# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
Example #32
0
 def get_col_sep(self):
     """Return the column separator"""
     if self.tab_btn.isChecked():
         return u("\t")
     return to_text_string(self.line_edt.text())
Example #33
0
templates_path = ['templates']

# MathJax load path (doesn't have effect for sphinx 1.0-)
mathjax_path = 'MathJax/MathJax.js'

# JsMath load path (doesn't have effect for sphinx 1.1+)
jsmath_path = 'easy/load.js'

# The suffix of source filenames.
source_suffix = '.rst'

# The master toctree document.
master_doc = 'docstring'

# General information about the project.
project = u("Spyder Help plugin")
copyright = u('2009--2013, The Spyder Development Team')

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['.build']

# The reST default role (used for this markup: `text`) to use for all documents.
#
# TODO: This role has to be set on a per project basis, i.e. numpy, sympy,
# mpmath, etc, use different default_role's which give different rendered
# docstrings. Setting this to None until it's solved.
default_role = 'None'

# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
Example #34
0
    @Slot()
    def process(self):
        """Process the data from clipboard"""
        var_name = self.name_edt.text()
        try:
            self.var_name = str(var_name)
        except UnicodeEncodeError:
            self.var_name = to_text_string(var_name)
        if self.text_widget.get_as_data():
            self.clip_data = self._get_table_data()
        elif self.text_widget.get_as_code():
            self.clip_data = try_to_eval(
                to_text_string(self._get_plain_text()))
        elif self.text_widget.get_as_df():
            self.clip_data = pd.read_csv(self._get_plain_text())
        else:
            self.clip_data = to_text_string(self._get_plain_text())
        self.accept()


def test(text):
    """Test"""
    from spyderlib.utils.qthelpers import qapplication
    _app = qapplication()  # analysis:ignore
    dialog = ImportWizard(None, text)
    if dialog.exec_():
        print(dialog.get_data())

if __name__ == "__main__":
    test(u("17/11/1976\t1.34\n14/05/09\t3.14"))
Example #35
0
    def write_lines(self,
                    lines,
                    encoding=None,
                    errors='strict',
                    linesep=os.linesep,
                    append=False):
        r""" Write the given lines of text to this file.

        By default this overwrites any existing file at this path.

        This puts a platform-specific newline sequence on every line.
        See 'linesep' below.

        lines - A list of strings.

        encoding - A Unicode encoding to use.  This applies only if
            'lines' contains any Unicode strings.

        errors - How to handle errors in Unicode encoding.  This
            also applies only to Unicode strings.

        linesep - The desired line-ending.  This line-ending is
            applied to every line.  If a line already has any
            standard line ending ('\r', '\n', '\r\n', u'\x85',
            u'\r\x85', u'\u2028'), that will be stripped off and
            this will be used instead.  The default is os.linesep,
            which is platform-dependent ('\r\n' on Windows, '\n' on
            Unix, etc.)  Specify None to write the lines as-is,
            like file.writelines().

        Use the keyword argument append=True to append lines to the
        file.  The default is to overwrite the file.  Warning:
        When you use this with Unicode data, if the encoding of the
        existing data in the file is different from the encoding
        you specify with the encoding= parameter, the result is
        mixed-encoding data, which can really confuse someone trying
        to read the file later.
        """
        if append:
            mode = 'ab'
        else:
            mode = 'wb'
        f = self.open(mode)
        try:
            for line in lines:
                isUnicode = is_unicode(line)
                if linesep is not None:
                    # Strip off any existing line-end and add the
                    # specified linesep string.
                    if isUnicode:
                        if line[-2:] in (u('\r\n'), u('\x0d\x85')):
                            line = line[:-2]
                        elif line[-1:] in (u('\r'), u('\n'), u('\x85'),
                                           u('\u2028')):
                            line = line[:-1]
                    else:
                        if line[-2:] == '\r\n':
                            line = line[:-2]
                        elif line[-1:] in ('\r', '\n'):
                            line = line[:-1]
                    line += linesep
                if isUnicode:
                    if encoding is None:
                        encoding = sys.getdefaultencoding()
                    line = line.encode(encoding, errors)
                f.write(line)
        finally:
            f.close()
Example #36
0
 def get_row_sep(self):
     """Return the row separator"""
     if self.eol_btn.isChecked():
         return u("\n")
     return to_text_string(self.line_edt_row.text())
Example #37
0
    def write_lines(self, lines, encoding=None, errors='strict',
                    linesep=os.linesep, append=False):
        r""" Write the given lines of text to this file.

        By default this overwrites any existing file at this path.

        This puts a platform-specific newline sequence on every line.
        See 'linesep' below.

        lines - A list of strings.

        encoding - A Unicode encoding to use.  This applies only if
            'lines' contains any Unicode strings.

        errors - How to handle errors in Unicode encoding.  This
            also applies only to Unicode strings.

        linesep - The desired line-ending.  This line-ending is
            applied to every line.  If a line already has any
            standard line ending ('\r', '\n', '\r\n', u'\x85',
            u'\r\x85', u'\u2028'), that will be stripped off and
            this will be used instead.  The default is os.linesep,
            which is platform-dependent ('\r\n' on Windows, '\n' on
            Unix, etc.)  Specify None to write the lines as-is,
            like file.writelines().

        Use the keyword argument append=True to append lines to the
        file.  The default is to overwrite the file.  Warning:
        When you use this with Unicode data, if the encoding of the
        existing data in the file is different from the encoding
        you specify with the encoding= parameter, the result is
        mixed-encoding data, which can really confuse someone trying
        to read the file later.
        """
        if append:
            mode = 'ab'
        else:
            mode = 'wb'
        f = self.open(mode)
        try:
            for line in lines:
                isUnicode = is_unicode(line)
                if linesep is not None:
                    # Strip off any existing line-end and add the
                    # specified linesep string.
                    if isUnicode:
                        if line[-2:] in (u('\r\n'), u('\x0d\x85')):
                            line = line[:-2]
                        elif line[-1:] in (u('\r'), u('\n'),
                                           u('\x85'), u('\u2028')):
                            line = line[:-1]
                    else:
                        if line[-2:] == '\r\n':
                            line = line[:-2]
                        elif line[-1:] in ('\r', '\n'):
                            line = line[:-1]
                    line += linesep
                if isUnicode:
                    if encoding is None:
                        encoding = sys.getdefaultencoding()
                    line = line.encode(encoding, errors)
                f.write(line)
        finally:
            f.close()
Example #38
0
    def write_text(self,
                   text,
                   encoding=None,
                   errors='strict',
                   linesep=os.linesep,
                   append=False):
        r""" Write the given text to this file.

        The default behavior is to overwrite any existing file;
        to append instead, use the 'append=True' keyword argument.

        There are two differences between path.write_text() and
        path.write_bytes(): newline handling and Unicode handling.
        See below.

        Parameters:

          - text - str/unicode - The text to be written.

          - encoding - str - The Unicode encoding that will be used.
            This is ignored if 'text' isn't a Unicode string.

          - errors - str - How to handle Unicode encoding errors.
            Default is 'strict'.  See help(unicode.encode) for the
            options.  This is ignored if 'text' isn't a Unicode
            string.

          - linesep - keyword argument - str/unicode - The sequence of
            characters to be used to mark end-of-line.  The default is
            os.linesep.  You can also specify None; this means to
            leave all newlines as they are in 'text'.

          - append - keyword argument - bool - Specifies what to do if
            the file already exists (True: append to the end of it;
            False: overwrite it.)  The default is False.


        --- Newline handling.

        write_text() converts all standard end-of-line sequences
        ('\n', '\r', and '\r\n') to your platform's default end-of-line
        sequence (see os.linesep; on Windows, for example, the
        end-of-line marker is '\r\n').

        If you don't like your platform's default, you can override it
        using the 'linesep=' keyword argument.  If you specifically want
        write_text() to preserve the newlines as-is, use 'linesep=None'.

        This applies to Unicode text the same as to 8-bit text, except
        there are three additional standard Unicode end-of-line sequences:
        u'\x85', u'\r\x85', and u'\u2028'.

        (This is slightly different from when you open a file for
        writing with fopen(filename, "w") in C or open(filename, 'w')
        in Python.)


        --- Unicode

        If 'text' isn't Unicode, then apart from newline handling, the
        bytes are written verbatim to the file.  The 'encoding' and
        'errors' arguments are not used and must be omitted.

        If 'text' is Unicode, it is first converted to bytes using the
        specified 'encoding' (or the default encoding if 'encoding'
        isn't specified).  The 'errors' argument applies only to this
        conversion.

        """
        if is_unicode(text):
            if linesep is not None:
                # Convert all standard end-of-line sequences to
                # ordinary newline characters.
                text = (text.replace(u('\r\n'), u('\n')).replace(
                    u('\r\x85'), u('\n')).replace(u('\r'), u('\n')).replace(
                        u('\x85'), u('\n')).replace(u('\u2028'), u('\n')))
                text = text.replace(u('\n'), linesep)
            if encoding is None:
                encoding = sys.getdefaultencoding()
            bytes = text.encode(encoding, errors)
        else:
            # It is an error to specify an encoding if 'text' is
            # an 8-bit string.
            assert encoding is None

            if linesep is not None:
                text = (text.replace('\r\n', '\n').replace('\r', '\n'))
                bytes = text.replace('\n', linesep)

        self.write_bytes(bytes, append)
Example #39
0
    def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False):
        r""" Write the given text to this file.

        The default behavior is to overwrite any existing file;
        to append instead, use the 'append=True' keyword argument.

        There are two differences between path.write_text() and
        path.write_bytes(): newline handling and Unicode handling.
        See below.

        Parameters:

          - text - str/unicode - The text to be written.

          - encoding - str - The Unicode encoding that will be used.
            This is ignored if 'text' isn't a Unicode string.

          - errors - str - How to handle Unicode encoding errors.
            Default is 'strict'.  See help(unicode.encode) for the
            options.  This is ignored if 'text' isn't a Unicode
            string.

          - linesep - keyword argument - str/unicode - The sequence of
            characters to be used to mark end-of-line.  The default is
            os.linesep.  You can also specify None; this means to
            leave all newlines as they are in 'text'.

          - append - keyword argument - bool - Specifies what to do if
            the file already exists (True: append to the end of it;
            False: overwrite it.)  The default is False.


        --- Newline handling.

        write_text() converts all standard end-of-line sequences
        ('\n', '\r', and '\r\n') to your platform's default end-of-line
        sequence (see os.linesep; on Windows, for example, the
        end-of-line marker is '\r\n').

        If you don't like your platform's default, you can override it
        using the 'linesep=' keyword argument.  If you specifically want
        write_text() to preserve the newlines as-is, use 'linesep=None'.

        This applies to Unicode text the same as to 8-bit text, except
        there are three additional standard Unicode end-of-line sequences:
        u'\x85', u'\r\x85', and u'\u2028'.

        (This is slightly different from when you open a file for
        writing with fopen(filename, "w") in C or open(filename, 'w')
        in Python.)


        --- Unicode

        If 'text' isn't Unicode, then apart from newline handling, the
        bytes are written verbatim to the file.  The 'encoding' and
        'errors' arguments are not used and must be omitted.

        If 'text' is Unicode, it is first converted to bytes using the
        specified 'encoding' (or the default encoding if 'encoding'
        isn't specified).  The 'errors' argument applies only to this
        conversion.

        """
        if is_unicode(text):
            if linesep is not None:
                # Convert all standard end-of-line sequences to
                # ordinary newline characters.
                text = (text.replace(u('\r\n'), u('\n'))
                            .replace(u('\r\x85'), u('\n'))
                            .replace(u('\r'), u('\n'))
                            .replace(u('\x85'), u('\n'))
                            .replace(u('\u2028'), u('\n')))
                text = text.replace(u('\n'), linesep)
            if encoding is None:
                encoding = sys.getdefaultencoding()
            bytes = text.encode(encoding, errors)
        else:
            # It is an error to specify an encoding if 'text' is
            # an 8-bit string.
            assert encoding is None

            if linesep is not None:
                text = (text.replace('\r\n', '\n')
                            .replace('\r', '\n'))
                bytes = text.replace('\n', linesep)

        self.write_bytes(bytes, append)
Example #40
0
 def setup(self):
     for label, value in self.data:
         if DEBUG_FORMLAYOUT:
             print("value:", value)
         if label is None and value is None:
             # Separator: (None, None)
             self.formlayout.addRow(QLabel(" "), QLabel(" "))
             self.widgets.append(None)
             continue
         elif label is None:
             # Comment
             self.formlayout.addRow(QLabel(value))
             self.widgets.append(None)
             continue
         elif tuple_to_qfont(value) is not None:
             field = FontLayout(value, self)
         elif text_to_qcolor(value).isValid():
             field = ColorLayout(QColor(value), self)
         elif is_text_string(value):
             if '\n' in value:
                 for linesep in (os.linesep, '\n'):
                     if linesep in value:
                         value = value.replace(linesep, u("\u2029"))
                 field = QTextEdit(value, self)
             else:
                 field = QLineEdit(value, self)
         elif isinstance(value, (list, tuple)):
             value = list(value)  # in case this is a tuple
             selindex = value.pop(0)
             field = QComboBox(self)
             if isinstance(value[0], (list, tuple)):
                 keys = [ key for key, _val in value ]
                 value = [ val for _key, val in value ]
             else:
                 keys = value
             field.addItems(value)
             if selindex in value:
                 selindex = value.index(selindex)
             elif selindex in keys:
                 selindex = keys.index(selindex)
             elif not isinstance(selindex, int):
                 print("Warning: '%s' index is invalid (label: "\
                       "%s, value: %s)" % (selindex, label, value),
                       file=STDERR)
                 selindex = 0
             field.setCurrentIndex(selindex)
         elif isinstance(value, bool):
             field = QCheckBox(self)
             field.setCheckState(Qt.Checked if value else Qt.Unchecked)
         elif isinstance(value, float):
             field = QLineEdit(repr(value), self)
             field.setValidator(QDoubleValidator(field))
             dialog = self.get_dialog()
             dialog.register_float_field(field)
             field.textChanged.connect(lambda text: dialog.update_buttons())
         elif isinstance(value, int):
             field = QSpinBox(self)
             field.setRange(-1e9, 1e9)
             field.setValue(value)
         elif isinstance(value, datetime.datetime):
             field = QDateTimeEdit(self)
             field.setDateTime(value)
         elif isinstance(value, datetime.date):
             field = QDateEdit(self)
             field.setDate(value)
         else:
             field = QLineEdit(repr(value), self)
         self.formlayout.addRow(label, field)
         self.widgets.append(field)
Example #41
0
 def open_data(self, text, colsep=u("\t"), rowsep=u("\n"),
               transpose=False, skiprows=0, comments='#'):
     """Open clipboard text as table"""
     self._table_view.process_data(text, colsep, rowsep, transpose,
                                   skiprows, comments)
Example #42
0
templates_path = ['templates']

# MathJax load path (doesn't have effect for sphinx 1.0-)
mathjax_path = 'MathJax/MathJax.js'

# JsMath load path (doesn't have effect for sphinx 1.1+)
jsmath_path = 'easy/load.js'

# The suffix of source filenames.
source_suffix = '.rst'

# The master toctree document.
master_doc = 'docstring'

# General information about the project.
project = u("Spyder Help plugin")
copyright = u('2009--2013, The Spyder Development Team')

# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['.build']

# The reST default role (used for this markup: `text`) to use for all documents.
#
# TODO: This role has to be set on a per project basis, i.e. numpy, sympy,
# mpmath, etc, use different default_role's which give different rendered
# docstrings. Setting this to None until it's solved.
default_role = 'None'

# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True