~ubuntu-branches/debian/experimental/spyder/experimental

« back to all changes in this revision

Viewing changes to spyderlib/widgets/arrayeditor.py

  • Committer: Package Import Robot
  • Author(s): Picca Frédéric-Emmanuel
  • Date: 2014-05-29 09:06:26 UTC
  • mfrom: (1.1.21) (18.1.6 sid)
  • Revision ID: package-import@ubuntu.com-20140529090626-f58t82g0n5iewaxu
Tags: 2.3.0~rc+dfsg-1~experimental2
* Add spyder-common binary package for all the python2,3 common files
* debian/path
  - 0001-fix-documentation-installation.patch (deleted)
  + 0001-fix-spyderlib-path.patch (new)

Show diffs side-by-side

added added

removed removed

Lines of Context:
13
13
# pylint: disable=R0911
14
14
# pylint: disable=R0201
15
15
 
 
16
from __future__ import print_function
 
17
 
16
18
from spyderlib.qt.QtGui import (QHBoxLayout, QColor, QTableView, QItemDelegate,
17
19
                                QLineEdit, QCheckBox, QGridLayout,
18
20
                                QDoubleValidator, QDialog, QDialogButtonBox,
24
26
from spyderlib.qt.compat import to_qvariant, from_qvariant
25
27
 
26
28
import numpy as np
27
 
import StringIO
28
29
 
29
30
# Local imports
30
31
from spyderlib.baseconfig import _
31
32
from spyderlib.guiconfig import get_font
32
33
from spyderlib.utils.qthelpers import (add_actions, create_action, keybinding,
33
34
                                       qapplication, get_icon)
 
35
from spyderlib.py3compat import io, to_text_string, is_text_string
34
36
 
35
37
# Note: string and unicode data types will be formatted with '%s' (see below)
36
38
SUPPORTED_FORMATS = {
85
87
 
86
88
def get_idx_rect(index_list):
87
89
    """Extract the boundaries from a list of indexes"""
88
 
    rows, cols = zip(*[(i.row(), i.column()) for i in index_list])
 
90
    rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))
89
91
    return ( min(rows), max(rows), min(cols), max(cols) )
90
92
 
91
93
 
205
207
        elif self._data.dtype.name.startswith("string"):
206
208
            val = str(value)
207
209
        elif self._data.dtype.name.startswith("unicode"):
208
 
            val = unicode(value)
 
210
            val = to_text_string(value)
209
211
        else:
210
212
            if value.lower().startswith('e') or value.lower().endswith('e'):
211
213
                return False
213
215
                val = complex(value)
214
216
                if not val.imag:
215
217
                    val = val.real
216
 
            except ValueError, e:
 
218
            except ValueError as e:
217
219
                QMessageBox.critical(self.dialog, "Error",
218
220
                                     "Value error: %s" % str(e))
219
221
                return False
220
222
        try:
221
223
            self.test_array[0] = val # will raise an Exception eventually
222
 
        except OverflowError, e:
223
 
            print type(e.message)
 
224
        except OverflowError as e:
 
225
            print(type(e.message))
224
226
            QMessageBox.critical(self.dialog, "Error",
225
227
                                 "Overflow error: %s" % e.message)
226
228
            return False
298
300
        self.setModel(model)
299
301
        self.setItemDelegate(ArrayDelegate(dtype, self))
300
302
        total_width = 0
301
 
        for k in xrange(shape[1]):
 
303
        for k in range(shape[1]):
302
304
            total_width += self.columnWidth(k)
303
305
        self.viewport().resize(min(total_width, 1024), self.height())
304
306
        self.shape = shape
347
349
        """Copy an array portion to a unicode string"""
348
350
        row_min, row_max, col_min, col_max = get_idx_rect(cell_range)
349
351
        _data = self.model().get_data()
350
 
        output = StringIO.StringIO()
 
352
        output = io.StringIO()
351
353
        np.savetxt(output,
352
354
                  _data[row_min:row_max+1, col_min:col_max+1],
353
355
                  delimiter='\t')
403
405
        
404
406
    def accept_changes(self):
405
407
        """Accept changes"""
406
 
        for (i, j), value in self.model.changes.iteritems():
 
408
        for (i, j), value in list(self.model.changes.items()):
407
409
            self.data[i, j] = value
408
410
        if self.old_data_shape is not None:
409
411
            self.data.shape = self.old_data_shape
481
483
        self.setLayout(self.layout)
482
484
        self.setWindowIcon(get_icon('arredit.png'))
483
485
        if title:
484
 
            title = unicode(title) # in case title is not a string
 
486
            title = to_text_string(title) # in case title is not a string
485
487
        else:
486
488
            title = _("Array editor")
487
489
        if readonly:
521
523
                    text = name
522
524
                    if len(field) >= 3:
523
525
                        title = field[2]
524
 
                        if not isinstance(title, basestring):
 
526
                        if not is_text_string(title):
525
527
                            title = repr(title)
526
528
                        text += ' - '+title
527
529
                    names.append(text)
598
600
    _app = qapplication()
599
601
    
600
602
    arr = np.array(["kjrekrjkejr"])
601
 
    print "out:", test_edit(arr, "string array")
602
 
    arr = np.array([u"kjrekrjkejr"])
603
 
    print "out:", test_edit(arr, "unicode array")
 
603
    print("out:", test_edit(arr, "string array"))
 
604
    from spyderlib.py3compat import u
 
605
    arr = np.array([u("kjrekrjkejr")])
 
606
    print("out:", test_edit(arr, "unicode array"))
604
607
    arr = np.ma.array([[1, 0], [1, 0]], mask=[[True, False], [False, False]])
605
 
    print "out:", test_edit(arr, "masked array")
606
 
    arr = np.zeros((2,2), {'names': ('red', 'green', 'blue'),
 
608
    print("out:", test_edit(arr, "masked array"))
 
609
    arr = np.zeros((2, 2), {'names': ('red', 'green', 'blue'),
607
610
                           'formats': (np.float32, np.float32, np.float32)})
608
 
    print "out:", test_edit(arr, "record array")
 
611
    print("out:", test_edit(arr, "record array"))
609
612
    arr = np.array([(0, 0.0), (0, 0.0), (0, 0.0)],
610
613
                   dtype=[(('title 1', 'x'), '|i1'),
611
614
                          (('title 2', 'y'), '>f4')])
612
 
    print "out:", test_edit(arr, "record array with titles")
 
615
    print("out:", test_edit(arr, "record array with titles"))
613
616
    arr = np.random.rand(5, 5)
614
 
    print "out:", test_edit(arr, "float array",
615
 
                            xlabels=['a', 'b', 'c', 'd', 'e'])
 
617
    print("out:", test_edit(arr, "float array",
 
618
                            xlabels=['a', 'b', 'c', 'd', 'e']))
616
619
    arr = np.round(np.random.rand(5, 5)*10)+\
617
620
                   np.round(np.random.rand(5, 5)*10)*1j
618
 
    print "out:", test_edit(arr, "complex array",
 
621
    print("out:", test_edit(arr, "complex array",
619
622
                            xlabels=np.linspace(-12, 12, 5),
620
 
                            ylabels=np.linspace(-12, 12, 5))
 
623
                            ylabels=np.linspace(-12, 12, 5)))
621
624
    arr_in = np.array([True, False, True])
622
 
    print "in:", arr_in
 
625
    print("in:", arr_in)
623
626
    arr_out = test_edit(arr_in, "bool array")
624
 
    print "out:", arr_out
625
 
    print arr_in is arr_out
 
627
    print("out:", arr_out)
 
628
    print(arr_in is arr_out)
626
629
    arr = np.array([1, 2, 3], dtype="int8")
627
 
    print "out:", test_edit(arr, "int array")
 
630
    print("out:", test_edit(arr, "int array"))
628
631
 
629
632
 
630
633
if __name__ == "__main__":