def launch_arrayeditor(data, title="", xlabels=None, ylabels=None): """Helper routine to launch an arrayeditor and return its result.""" dlg = ArrayEditor() assert dlg.setup_and_check(data, title, xlabels=xlabels, ylabels=ylabels) dlg.show() dlg.accept() # trigger slot connected to OK button return dlg.get_value()
def doubleClicked_callback(self, index: QModelIndex): import pandas as pd import numpy as np import numpy.ma if index.isValid() and index.column() == NodeCols.Value: item = index.internalPointer() obj = item.node['obj']['fullname'] args = str(item.node['args']) data, _ = self.shell.get_obj_value( 'analyze_getval', obj, args) if isinstance(data, (pd.DataFrame, pd.Index, pd.Series)): dialog = DataFrameEditor(self) dialog.setup_and_check(data) elif isinstance(data, (np.ndarray, np.ma.MaskedArray)): dialog = ArrayEditor(self) dialog.setup_and_check(data, title='', readonly=True) elif isinstance(data, (list, set, tuple, dict)): dialog = CollectionsEditor(self) dialog.setup(data, title='', readonly=True) else: return dialog.show()
def setup_arrayeditor(qbot, data, title="", xlabels=None, ylabels=None): """Setups an arrayeditor.""" dlg = ArrayEditor() dlg.setup_and_check(data, title, xlabels=xlabels, ylabels=ylabels) dlg.show() qbot.addWidget(dlg) return dlg
def setup_arrayeditor(qtbot, data): """Setups an arrayeditor.""" dlg = ArrayEditor() dlg.setup_and_check(data) dlg.show() qtbot.addWidget(dlg) return dlg
def test_arrayeditor_edit_overflow(qtbot, monkeypatch): """ Test that entry of an overflowing integer is caught and handled properly. Integration regression test for spyder-ide/spyder#6114. """ MockQMessageBox = Mock() attr_to_patch = 'spyder.plugins.variableexplorer.widgets.arrayeditor.QMessageBox' monkeypatch.setattr(attr_to_patch, MockQMessageBox) # Numpy doesn't raise the OverflowError for ints smaller than 64 bits if not os.name == 'nt': int32_bit_exponent = 66 else: int32_bit_exponent = 34 test_parameters = [(1, np.int32, int32_bit_exponent), (2, np.int64, 66)] expected_array = np.array([5, 6, 7, 3, 4]) for idx, int_type, bit_exponent in test_parameters: test_array = np.arange(0, 5).astype(int_type) dialog = ArrayEditor() assert dialog.setup_and_check(test_array, '1D array', xlabels=None, ylabels=None) dialog.show() qtbot.waitForWindowShown(dialog) view = dialog.arraywidget.view qtbot.keyClick(view, Qt.Key_Down) qtbot.keyClick(view, Qt.Key_Up) qtbot.keyClicks(view, '5') qtbot.keyClick(view, Qt.Key_Down) qtbot.keyClick(view, Qt.Key_Space) qtbot.keyClicks(view.focusWidget(), str(int(2**bit_exponent))) qtbot.keyClick(view.focusWidget(), Qt.Key_Down) MockQMessageBox.critical.assert_called_with(ANY, "Error", ANY) assert MockQMessageBox.critical.call_count == idx qtbot.keyClicks(view, '7') qtbot.keyClick(view, Qt.Key_Up) qtbot.keyClicks(view, '6') qtbot.keyClick(view, Qt.Key_Down) qtbot.wait(200) dialog.accept() qtbot.wait(500) assert np.sum( expected_array == dialog.get_value()) == len(expected_array)
def test_arrayeditor_edit_complex_array(qtbot): """See: spyder-ide/spyder#7848""" cnum = -1+0.5j arr = (np.random.random((10, 10)) - 0.50) * cnum dlg = ArrayEditor() assert dlg.setup_and_check(arr, '2D complex array', xlabels=None, ylabels=None) dlg.show() qtbot.waitForWindowShown(dlg) view = dlg.arraywidget.view qtbot.keyPress(view, Qt.Key_Down) # Prevent the test from failing qtbot.wait(300) # This is the actual editor widget on the cell cell_editor = view.viewport().focusWidget() qtbot.keyClicks(cell_editor, str(cnum)) qtbot.keyPress(cell_editor, Qt.Key_Return) dlg.accept()
def test_arrayeditor_edit_1d_array(qtbot): exp_arr = np.array([1, 0, 2, 3, 4]) arr = np.arange(0, 5) dlg = ArrayEditor() assert dlg.setup_and_check(arr, '1D array', xlabels=None, ylabels=None) dlg.show() qtbot.waitForWindowShown(dlg) view = dlg.arraywidget.view qtbot.keyPress(view, Qt.Key_Down) qtbot.keyPress(view, Qt.Key_Up) qtbot.keyClicks(view, '1') qtbot.keyPress(view, Qt.Key_Down) qtbot.keyClicks(view, '0') qtbot.keyPress(view, Qt.Key_Down) qtbot.keyPress(view, Qt.Key_Return) assert np.sum(exp_arr == dlg.get_value()) == 5
def test_arrayeditor_edit_2d_array(qtbot): arr = np.ones((3, 3)) diff_arr = arr.copy() dlg = ArrayEditor() assert dlg.setup_and_check(arr, '2D array', xlabels=None, ylabels=None) dlg.show() qtbot.waitForWindowShown(dlg) view = dlg.arraywidget.view qtbot.keyPress(view, Qt.Key_Down) qtbot.keyPress(view, Qt.Key_Right) qtbot.keyClicks(view, '3') qtbot.keyPress(view, Qt.Key_Down) qtbot.keyPress(view, Qt.Key_Right) qtbot.keyClicks(view, '0') qtbot.keyPress(view, Qt.Key_Left) qtbot.keyPress(view, Qt.Key_Return) assert np.sum(diff_arr != dlg.get_value()) == 2
def createEditor(self, parent, option, index, object_explorer=False): """Overriding method createEditor""" val_type = index.sibling(index.row(), 1).data() self.sig_open_editor.emit() if index.column() < 3: return None if self.show_warning(index): answer = QMessageBox.warning( self.parent(), _("Warning"), _("Opening this variable can be slow\n\n" "Do you want to continue anyway?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.No: return None try: value = self.get_value(index) if value is None: return None except ImportError as msg: self.sig_editor_shown.emit() module = str(msg).split("'")[1] if module in ['pandas', 'numpy']: if module == 'numpy': val_type = 'array' else: val_type = 'dataframe, series' QMessageBox.critical( self.parent(), _("Error"), _("Spyder is unable to show the {val_type} or object " "you're trying to view because <tt>{module}</tt> was " "not installed alongside Spyder. Please install " "this package in your Spyder environment." "<br>").format(val_type=val_type, module=module)) return else: QMessageBox.critical( self.parent(), _("Error"), _("Spyder is unable to show the variable you're " "trying to view because the module " "<tt>{module}</tt> was not found in your " "Spyder environment. Please install " "this package in your Spyder environment." "<br>").format(module=module)) return except Exception as msg: QMessageBox.critical( self.parent(), _("Error"), _("Spyder was unable to retrieve the value of " "this variable from the console.<br><br>" "The error message was:<br>" "%s") % to_text_string(msg)) return key = index.model().get_key(index) readonly = (isinstance(value, (tuple, set)) or self.parent().readonly or not is_known_type(value)) # CollectionsEditor for a list, tuple, dict, etc. if isinstance(value, (list, set, tuple, dict)) and not object_explorer: from spyder.widgets.collectionseditor import CollectionsEditor editor = CollectionsEditor(parent=parent) editor.setup(value, key, icon=self.parent().windowIcon(), readonly=readonly) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for a Numpy array elif (isinstance(value, (ndarray, MaskedArray)) and ndarray is not FakeObject and not object_explorer): editor = ArrayEditor(parent=parent) if not editor.setup_and_check(value, title=key, readonly=readonly): return self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for an images elif (isinstance(value, Image) and ndarray is not FakeObject and Image is not FakeObject and not object_explorer): arr = array(value) editor = ArrayEditor(parent=parent) if not editor.setup_and_check(arr, title=key, readonly=readonly): return conv_func = lambda arr: Image.fromarray(arr, mode=value.mode) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly, conv=conv_func)) return None # DataFrameEditor for a pandas dataframe, series or index elif (isinstance(value, (DataFrame, Index, Series)) and DataFrame is not FakeObject and not object_explorer): editor = DataFrameEditor(parent=parent) if not editor.setup_and_check(value, title=key): return editor.dataModel.set_format(index.model().dataframe_format) editor.sig_option_changed.connect(self.change_option) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QDateEdit and QDateTimeEdit for a dates or datetime respectively elif isinstance(value, datetime.date) and not object_explorer: # Needed to handle NaT values # See spyder-ide/spyder#8329 try: value.time() except ValueError: self.sig_editor_shown.emit() return None if readonly: self.sig_editor_shown.emit() return None else: if isinstance(value, datetime.datetime): editor = QDateTimeEdit(value, parent=parent) else: editor = QDateEdit(value, parent=parent) editor.setCalendarPopup(True) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) self.sig_editor_shown.emit() return editor # TextEditor for a long string elif is_text_string(value) and len(value) > 40 and not object_explorer: te = TextEditor(None, parent=parent) if te.setup_and_check(value): editor = TextEditor(value, key, readonly=readonly, parent=parent) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QLineEdit for an individual value (int, float, short string, etc) elif is_editable_type(value) and not object_explorer: if readonly: self.sig_editor_shown.emit() return None else: editor = QLineEdit(parent=parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignLeft) # This is making Spyder crash because the QLineEdit that it's # been modified is removed and a new one is created after # evaluation. So the object on which this method is trying to # act doesn't exist anymore. # editor.returnPressed.connect(self.commitAndCloseEditor) self.sig_editor_shown.emit() return editor # ObjectExplorer for an arbitrary Python object else: show_callable_attributes = index.model().show_callable_attributes show_special_attributes = index.model().show_special_attributes dataframe_format = index.model().dataframe_format if show_callable_attributes is None: show_callable_attributes = False if show_special_attributes is None: show_special_attributes = False from spyder.plugins.variableexplorer.widgets.objectexplorer \ import ObjectExplorer editor = ObjectExplorer( value, name=key, parent=parent, show_callable_attributes=show_callable_attributes, show_special_attributes=show_special_attributes, dataframe_format=dataframe_format, readonly=readonly) editor.sig_option_changed.connect(self.change_option) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None
def createEditor(self, parent, option, index): """Overriding method createEditor""" if self.show_warning(index): answer = QMessageBox.warning( self.parent(), _("Warning"), _("Opening this variable can be slow\n\n" "Do you want to continue anyway?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.No: return None try: value = self.get_value(index) try: self.old_obj = value.copy() except AttributeError: self.old_obj = copy.deepcopy(value) if value is None: return None except Exception as msg: QMessageBox.critical( self.parent(), _("Error"), _("Spyder was unable to retrieve the value of " "this variable from the console.<br><br>" "The error message was:<br>" "<i>%s</i>") % to_text_string(msg)) return self.current_index = index key = index.model().get_key(index).obj_name readonly = (isinstance(value, (tuple, set)) or self.parent().readonly or not is_known_type(value)) # CollectionsEditor for a list, tuple, dict, etc. if isinstance(value, (list, set, tuple, dict)): from spyder.widgets.collectionseditor import CollectionsEditor editor = CollectionsEditor(parent=parent) editor.setup(value, key, icon=self.parent().windowIcon(), readonly=readonly) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for a Numpy array elif (isinstance(value, (ndarray, MaskedArray)) and ndarray is not FakeObject): editor = ArrayEditor(parent=parent) if not editor.setup_and_check(value, title=key, readonly=readonly): return self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for an images elif (isinstance(value, Image) and ndarray is not FakeObject and Image is not FakeObject): arr = array(value) editor = ArrayEditor(parent=parent) if not editor.setup_and_check(arr, title=key, readonly=readonly): return conv_func = lambda arr: Image.fromarray(arr, mode=value.mode) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly, conv=conv_func)) return None # DataFrameEditor for a pandas dataframe, series or index elif (isinstance(value, (DataFrame, Index, Series)) and DataFrame is not FakeObject): editor = DataFrameEditor(parent=parent) if not editor.setup_and_check(value, title=key): return editor.dataModel.set_format(index.model().dataframe_format) editor.sig_option_changed.connect(self.change_option) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QDateEdit and QDateTimeEdit for a dates or datetime respectively elif isinstance(value, datetime.date): if readonly: return None else: if isinstance(value, datetime.datetime): editor = QDateTimeEdit(value, parent=parent) else: editor = QDateEdit(value, parent=parent) editor.setCalendarPopup(True) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return editor # TextEditor for a long string elif is_text_string(value) and len(value) > 40: te = TextEditor(None, parent=parent) if te.setup_and_check(value): editor = TextEditor(value, key, readonly=readonly, parent=parent) self.create_dialog( editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QLineEdit for an individual value (int, float, short string, etc) elif is_editable_type(value): if readonly: return None else: editor = QLineEdit(parent=parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignLeft) # This is making Spyder crash because the QLineEdit that it's # been modified is removed and a new one is created after # evaluation. So the object on which this method is trying to # act doesn't exist anymore. # editor.returnPressed.connect(self.commitAndCloseEditor) return editor # An arbitrary Python object. # Since we are already in the Object Explorer no editor is needed else: return None
def create_dialog(obj, obj_name): """Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that he can monkey patch oedit to show eMZed related data) """ # Local import from spyder_kernels.utils.nsview import (ndarray, FakeObject, Image, is_known_type, DataFrame, Series) from spyder.plugins.variableexplorer.widgets.texteditor import TextEditor from spyder.plugins.variableexplorer.widgets.arrayeditor import ( ArrayEditor) from spyder.widgets.collectionseditor import CollectionsEditor if DataFrame is not FakeObject: from spyder.plugins.variableexplorer.widgets.dataframeeditor import ( DataFrameEditor) conv_func = lambda data: data readonly = not is_known_type(obj) if isinstance(obj, ndarray) and ndarray is not FakeObject: dialog = ArrayEditor() if not dialog.setup_and_check(obj, title=obj_name, readonly=readonly): return elif isinstance(obj, Image) and Image is not FakeObject \ and ndarray is not FakeObject: dialog = ArrayEditor() import numpy as np data = np.array(obj) if not dialog.setup_and_check(data, title=obj_name, readonly=readonly): return from spyder.pil_patch import Image conv_func = lambda data: Image.fromarray(data, mode=obj.mode) elif isinstance(obj, (DataFrame, Series)) and DataFrame is not FakeObject: dialog = DataFrameEditor() if not dialog.setup_and_check(obj): return elif is_text_string(obj): dialog = TextEditor(obj, title=obj_name, readonly=readonly) else: dialog = CollectionsEditor() dialog.setup(obj, title=obj_name, readonly=readonly) def end_func(dialog): return conv_func(dialog.get_value()) return dialog, end_func
def createEditor(self, parent, option, index, object_explorer=False): """Overriding method createEditor""" val_type = index.sibling(index.row(), 1).data() self.sig_editor_creation_started.emit() if index.column() < 3: return None if self.show_warning(index): answer = QMessageBox.warning( self.parent(), _("Warning"), _("Opening this variable can be slow\n\n" "Do you want to continue anyway?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.No: self.sig_editor_shown.emit() return None try: value = self.get_value(index) if value is None: return None except ImportError as msg: self.sig_editor_shown.emit() module = str(msg).split("'")[1] if module in ['pandas', 'numpy']: if module == 'numpy': val_type = 'array' else: val_type = 'dataframe, series' message = _("Spyder is unable to show the {val_type} or object" " you're trying to view because <tt>{module}</tt>" " is not installed. ") if running_in_mac_app(): message += _("Please consider using the full version of " "the Spyder MacOS application.<br>") else: message += _("Please install this package in your Spyder " "environment.<br>") QMessageBox.critical( self.parent(), _("Error"), message.format(val_type=val_type, module=module)) return else: if running_in_mac_app() or is_pynsist(): message = _("Spyder is unable to show the variable you're" " trying to view because the module " "<tt>{module}</tt> is not supported in the " "Spyder Lite application.<br>") else: message = _("Spyder is unable to show the variable you're" " trying to view because the module " "<tt>{module}</tt> is not found in your " "Spyder environment. Please install this " "package in this environment.<br>") QMessageBox.critical(self.parent(), _("Error"), message.format(module=module)) return except Exception as msg: QMessageBox.critical( self.parent(), _("Error"), _("Spyder was unable to retrieve the value of " "this variable from the console.<br><br>" "The error message was:<br>" "%s") % to_text_string(msg)) return key = index.model().get_key(index) readonly = (isinstance(value, (tuple, set)) or self.parent().readonly or not is_known_type(value)) # We can't edit Numpy void objects because they could be anything, so # this might cause a crash. # Fixes spyder-ide/spyder#10603 if isinstance(value, np.void): self.sig_editor_shown.emit() return None # CollectionsEditor for a list, tuple, dict, etc. elif isinstance(value, (list, set, tuple, dict)) and not object_explorer: from spyder.widgets.collectionseditor import CollectionsEditor editor = CollectionsEditor(parent=parent) editor.setup(value, key, icon=self.parent().windowIcon(), readonly=readonly) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for a Numpy array elif (isinstance(value, (np.ndarray, np.ma.MaskedArray)) and np.ndarray is not FakeObject and not object_explorer): # We need to leave this import here for tests to pass. from .arrayeditor import ArrayEditor editor = ArrayEditor(parent=parent) if not editor.setup_and_check(value, title=key, readonly=readonly): return self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # ArrayEditor for an images elif (isinstance(value, PIL.Image.Image) and np.ndarray is not FakeObject and PIL.Image is not FakeObject and not object_explorer): # Sometimes the ArrayEditor import above is not seen (don't know # why), so we need to reimport it here. # Fixes spyder-ide/spyder#16731 from .arrayeditor import ArrayEditor arr = np.array(value) editor = ArrayEditor(parent=parent) if not editor.setup_and_check(arr, title=key, readonly=readonly): return conv_func = lambda arr: PIL.Image.fromarray(arr, mode=value.mode) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly, conv=conv_func)) return None # DataFrameEditor for a pandas dataframe, series or index elif (isinstance(value, (pd.DataFrame, pd.Index, pd.Series)) and pd.DataFrame is not FakeObject and not object_explorer): # We need to leave this import here for tests to pass. from .dataframeeditor import DataFrameEditor editor = DataFrameEditor(parent=parent) if not editor.setup_and_check(value, title=key): self.sig_editor_shown.emit() return self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QDateEdit and QDateTimeEdit for a dates or datetime respectively elif isinstance(value, datetime.date) and not object_explorer: if readonly: self.sig_editor_shown.emit() return None else: if isinstance(value, datetime.datetime): editor = QDateTimeEdit(value, parent=parent) # Needed to handle NaT values # See spyder-ide/spyder#8329 try: value.time() except ValueError: self.sig_editor_shown.emit() return None else: editor = QDateEdit(value, parent=parent) editor.setCalendarPopup(True) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) self.sig_editor_shown.emit() return editor # TextEditor for a long string elif is_text_string(value) and len(value) > 40 and not object_explorer: te = TextEditor(None, parent=parent) if te.setup_and_check(value): editor = TextEditor(value, key, readonly=readonly, parent=parent) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None # QLineEdit for an individual value (int, float, short string, etc) elif is_editable_type(value) and not object_explorer: if readonly: self.sig_editor_shown.emit() return None else: editor = QLineEdit(parent=parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignLeft) # This is making Spyder crash because the QLineEdit that it's # been modified is removed and a new one is created after # evaluation. So the object on which this method is trying to # act doesn't exist anymore. # editor.returnPressed.connect(self.commitAndCloseEditor) self.sig_editor_shown.emit() return editor # ObjectExplorer for an arbitrary Python object else: from spyder.plugins.variableexplorer.widgets.objectexplorer \ import ObjectExplorer editor = ObjectExplorer( value, name=key, parent=parent, readonly=readonly) self.create_dialog(editor, dict(model=index.model(), editor=editor, key=key, readonly=readonly)) return None
def create_dialog(obj, obj_name): """Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that he can monkey patch oedit to show eMZed related data) """ # Local import conv_func = lambda data: data readonly = not is_known_type(obj) if isinstance(obj, np.ndarray) and np.ndarray is not FakeObject: dialog = ArrayEditor() if not dialog.setup_and_check(obj, title=obj_name, readonly=readonly): return elif (isinstance(obj, PIL.Image.Image) and PIL.Image is not FakeObject and np.ndarray is not FakeObject): dialog = ArrayEditor() data = np.array(obj) if not dialog.setup_and_check(data, title=obj_name, readonly=readonly): return conv_func = lambda data: PIL.Image.fromarray(data, mode=obj.mode) elif (isinstance(obj, (pd.DataFrame, pd.Series)) and pd.DataFrame is not FakeObject): dialog = DataFrameEditor() if not dialog.setup_and_check(obj): return elif is_text_string(obj): dialog = TextEditor(obj, title=obj_name, readonly=readonly) else: dialog = CollectionsEditor() dialog.setup(obj, title=obj_name, readonly=readonly) def end_func(dialog): return conv_func(dialog.get_value()) return dialog, end_func