text
stringlengths
81
112k
Find and return the item of the outline explorer under which is located the specified 'line' of the editor. def item_at_line(root_item, line): """ Find and return the item of the outline explorer under which is located the specified 'line' of the editor. """ previous_item = root_item ...
Reimplemented OneColumnTree method def get_actions_from_items(self, items): """Reimplemented OneColumnTree method""" fromcursor_act = create_action(self, text=_('Go to cursor position'), icon=ima.icon('fromcursor'), trigg...
show_all_files option is disabled: hide all root items except *item* show_all_files option is enabled: do nothing def __hide_or_show_root_items(self, item): """ show_all_files option is disabled: hide all root items except *item* show_all_files option is enabled: do nothing ...
Bind editor instance def set_current_editor(self, editor, update): """Bind editor instance""" editor_id = editor.get_id() if editor_id in list(self.editor_ids.values()): item = self.editor_items[editor_id] if not self.freeze: self.scrollToItem(item)...
File was renamed, updating outline explorer tree def file_renamed(self, editor, new_filename): """File was renamed, updating outline explorer tree""" if editor is None: # This is needed when we can't find an editor to attach # the outline explorer to. # Fix issu...
Order the root file items in the Outline Explorer following the provided list of editor ids. def set_editor_ids_order(self, ordered_editor_ids): """ Order the root file items in the Outline Explorer following the provided list of editor ids. """ if self.ordered_edi...
Sort the root file items in alphabetical order if 'sort_files_alphabetically' is True, else order the items as specified in the 'self.ordered_editor_ids' list. def __sort_toplevel_items(self): """ Sort the root file items in alphabetical order if 'sort_files_alphabetically'...
Generates an outline of the editor's content and stores the result in a cache. def populate_branch(self, editor, root_item, tree_cache=None): """ Generates an outline of the editor's content and stores the result in a cache. """ if tree_cache is None: ...
Root item has been selected: expanding it and collapsing others def root_item_selected(self, item): """Root item has been selected: expanding it and collapsing others""" if self.show_all_files: return for root_item in self.get_top_level_items(): if root_item is item...
Reimplemented OneColumnTree method def restore(self): """Reimplemented OneColumnTree method""" if self.current_editor is not None: self.collapseAll() editor_id = self.editor_ids[self.current_editor] self.root_item_selected(self.editor_items[editor_id])
Return the root item of the specified item. def get_root_item(self, item): """Return the root item of the specified item.""" root_item = item while isinstance(root_item.parent(), QTreeWidgetItem): root_item = root_item.parent() return root_item
Return a list of all visible items in the treewidget. def get_visible_items(self): """Return a list of all visible items in the treewidget.""" items = [] iterator = QTreeWidgetItemIterator(self) while iterator.value(): item = iterator.value() if not item.is...
Double-click event def activated(self, item): """Double-click event""" editor_item = self.editor_items.get( self.editor_ids.get(self.current_editor)) line = 0 if item == editor_item: line = 1 elif isinstance(item, TreeItem): line = ite...
Click event def clicked(self, item): """Click event""" if isinstance(item, FileRootItem): self.root_item_selected(item) self.activated(item)
Setup the buttons of the outline explorer widget toolbar. def setup_buttons(self): """Setup the buttons of the outline explorer widget toolbar.""" self.fromcursor_btn = create_toolbutton( self, icon=ima.icon('fromcursor'), tip=_('Go to cursor position'), triggered=self.treew...
Return outline explorer options def get_options(self): """ Return outline explorer options """ return dict( show_fullpath=self.treewidget.show_fullpath, show_all_files=self.treewidget.show_all_files, group_cells=self.treewidget.group_cells, ...
Uninstalls the editor extension from the editor. def on_uninstall(self): """Uninstalls the editor extension from the editor.""" self._on_close = True self.enabled = False self._editor = None
Add package to py2exe/cx_Freeze distribution object Extension to guidata.disthelpers def add_to_distribution(dist): """Add package to py2exe/cx_Freeze distribution object Extension to guidata.disthelpers""" try: dist.add_qt_bindings() except AttributeError: raise ImportError("This s...
Get version information for components used by Spyder def get_versions(reporev=True): """Get version information for components used by Spyder""" import sys import platform import qtpy import qtpy.QtCore revision = None if reporev: from spyder.utils import vcs revision, br...
Return True is datatype dtype is a number kind def is_number(dtype): """Return True is datatype dtype is a number kind""" return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \ or ('short' in dtype.name)
Extract the boundaries from a list of indexes def get_idx_rect(index_list): """Extract the boundaries from a list of indexes""" rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list])) return ( min(rows), max(rows), min(cols), max(cols) )
Array column number def columnCount(self, qindex=QModelIndex()): """Array column number""" if self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded
Array row number def rowCount(self, qindex=QModelIndex()): """Array row number""" if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded
Cell content def data(self, index, role=Qt.DisplayRole): """Cell content""" if not index.isValid(): return to_qvariant() value = self.get_value(index) if is_binary_string(value): try: value = to_text_string(value, 'utf8') excep...
Cell content change def setData(self, index, value, role=Qt.EditRole): """Cell content change""" if not index.isValid() or self.readonly: return False i = index.row() j = index.column() value = from_qvariant(value, str) dtype = self._data.dtype.name ...
Set header data def headerData(self, section, orientation, role=Qt.DisplayRole): """Set header data""" if role != Qt.DisplayRole: return to_qvariant() labels = self.xlabels if orientation == Qt.Horizontal else self.ylabels if labels is None: return to_qvari...
Create editor widget def createEditor(self, parent, option, index): """Create editor widget""" model = index.model() value = model.get_value(index) if model._data.dtype.name == "bool": value = not value model.setData(index, to_qvariant(value)) ...
Commit and close editor def commitAndCloseEditor(self): """Commit and close editor""" editor = self.sender() # Avoid a segfault with PyQt5. Variable value won't be changed # but at least Spyder won't crash. It seems generated by a bug in sip. try: self.commitDa...
Set editor widget's data def setEditorData(self, editor, index): """Set editor widget's data""" text = from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text)
Resize cells to contents def resize_to_contents(self): """Resize cells to contents""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOver...
Setup context menu def setup_menu(self): """Setup context menu""" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), tri...
Reimplement Qt method def contextMenuEvent(self, event): """Reimplement Qt method""" self.menu.popup(event.globalPos()) event.accept()
Reimplement Qt method def keyPressEvent(self, event): """Reimplement Qt method""" if event == QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self, event)
Copy an array portion to a unicode string def _sel_to_text(self, cell_range): """Copy an array portion to a unicode string""" if not cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min == 0 and col_max == (self.model().cols_loaded...
Copy text to clipboard def copy(self): """Copy text to clipboard""" cliptxt = self._sel_to_text( self.selectedIndexes() ) clipboard = QApplication.clipboard() clipboard.setText(cliptxt)
Accept changes def accept_changes(self): """Accept changes""" for (i, j), value in list(self.model.changes.items()): self.data[i, j] = value if self.old_data_shape is not None: self.data.shape = self.old_data_shape
Change display format def change_format(self): """Change display format""" format, valid = QInputDialog.getText(self, _( 'Format'), _( "Float formatting"), QLineEdit.Normal, self.model.get_format()) if valid: fo...
Setup ArrayEditor: return False if data is not supported, True otherwise def setup_and_check(self, data, title='', readonly=False, xlabels=None, ylabels=None): """ Setup ArrayEditor: return False if data is not supported, True otherwise """ ...
This is implemented for handling negative values in index for 3d arrays, to give the same behavior as slicing def change_active_widget(self, index): """ This is implemented for handling negative values in index for 3d arrays, to give the same behavior as slicing """ ...
This change the active axis the array editor is plotting over in 3D def current_dim_changed(self, index): """ This change the active axis the array editor is plotting over in 3D """ self.last_dim = index string_size = ['%i']*3 string_size[index] =...
Reimplement Qt method def accept(self): """Reimplement Qt method""" for index in range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self)
An error occured, closing the dialog box def error(self, message): """An error occured, closing the dialog box""" QMessageBox.critical(self, _("Array editor"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject()
Reimplement Qt method def reject(self): """Reimplement Qt method""" if self.arraywidget is not None: for index in range(self.stack.count()): self.stack.widget(index).reject_changes() QDialog.reject(self)
Get a Pygments Lexer given a filename. def find_lexer_for_filename(filename): """Get a Pygments Lexer given a filename. """ filename = filename or '' root, ext = os.path.splitext(filename) if ext in custom_extension_lexer_mapping: lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext...
Get the keywords for a given lexer. def get_keywords(lexer): """Get the keywords for a given lexer. """ if not hasattr(lexer, 'tokens'): return [] if 'keywords' in lexer.tokens: try: return lexer.tokens['keywords'][0][0].words except: pass keywords = ...
Extract all words from a source code file to be used in code completion. Extract the list of words that contains the file in the editor, to carry out the inline completion similar to VSCode. def get_words(file_path=None, content=None, extension=None): """ Extract all words from a source code file to b...
Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'numpy.core' def get_parent_until(path): """ Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'num...
Find the docstring we are currently in. def _get_docstring(self): """Find the docstring we are currently in.""" left = self.position while left: if self.source_code[left: left + 3] in ['"""', "'''"]: left += 3 break left -= 1 right...
Load the user's previously-saved kernel connection settings. def load_connection_settings(self): """Load the user's previously-saved kernel connection settings.""" existing_kernel = CONF.get("existing-kernel", "settings", {}) connection_file_path = existing_kernel.get("json_file_path", "") ...
Save user's kernel connection settings. def save_connection_settings(self): """Save user's kernel connection settings.""" if not self.save_layout.isChecked(): return is_ssh_key = bool(self.kf_radio.isChecked()) connection_settings = { "json_file_path": self.cf....
Return color depending on value type def get_color(value, alpha): """Return color depending on value type""" color = QColor() for typ in COLORS: if isinstance(value, typ): color = QColor(COLORS[typ]) color.setAlphaF(alpha) return color
Return the column separator def get_col_sep(self): """Return the column separator""" if self.tab_btn.isChecked(): return u"\t" elif self.ws_btn.isChecked(): return None return to_text_string(self.line_edt.text())
Return the row separator 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())
Set if data type conversion def set_as_data(self, as_data): """Set if data type conversion""" self._as_data = as_data self.asDataChanged.emit(as_data)
Return a data element def _display_data(self, index): """Return a data element""" return to_qvariant(self._data[index.row()][index.column()])
Return a model data element def data(self, index, role=Qt.DisplayRole): """Return a model data element""" if not index.isValid(): return to_qvariant() if role == Qt.DisplayRole: return self._display_data(index) elif role == Qt.BackgroundColorRole: ...
Parse a type to an other type def parse_data_type(self, index, **kwargs): """Parse a type to an other type""" if not index.isValid(): return False try: if kwargs['atype'] == "date": self._data[index.row()][index.column()] = \ da...
Decode the shape of the given text 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:] fo...
Put data into table model 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) s...
Parse to a given type def parse_to_type(self,**kwargs): """Parse to a given type""" indexes = self.selectedIndexes() if not indexes: return for index in indexes: self.model().parse_data_type(index, **kwargs)
Reimplement Qt method def contextMenuEvent(self, event): """Reimplement Qt method""" self.opt_menu.popup(event.globalPos()) event.accept()
Open clipboard text as table 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, ...
Change tab focus def _focus_tab(self, tab_idx): """Change tab focus""" for i in range(self.tab_widget.count()): self.tab_widget.setTabEnabled(i, False) self.tab_widget.setTabEnabled(tab_idx, True) self.tab_widget.setCurrentIndex(tab_idx)
Proceed to a given step def _set_step(self, step): """Proceed to a given step""" new_tab = self.tab_widget.currentIndex() + step assert new_tab < self.tab_widget.count() and new_tab >= 0 if new_tab == self.tab_widget.count()-1: try: self.table_widget.op...
Reduce the alist dimension if needed def _simplify_shape(self, alist, rec=0): """Reduce the alist dimension if needed""" if rec != 0: if len(alist) == 1: return alist[-1] return alist if len(alist) == 1: return self._simplify_shape(alis...
Return clipboard processed as data def _get_table_data(self): """Return clipboard processed as data""" data = self._simplify_shape( self.table_widget.get_data()) if self.table_widget.array_btn.isChecked(): return array(data) elif pd and self.table_widge...
Process the data from clipboard 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_...
Set Spyder breakpoints into a debugging session def set_spyder_breakpoints(self, force=False): """Set Spyder breakpoints into a debugging session""" if self._reading or force: breakpoints_dict = CONF.get('run', 'breakpoints', {}) # We need to enclose pickled values in a list to...
Run an IPython magic while debugging. def dbg_exec_magic(self, magic, args=''): """Run an IPython magic while debugging.""" code = "!get_ipython().kernel.shell.run_line_magic('{}', '{}')".format( magic, args) self.kernel_client.input(code)
Refresh Variable Explorer and Editor from a Pdb session, after running any pdb command. See publish_pdb_state and notify_spyder in spyder_kernels def refresh_from_pdb(self, pdb_state): """ Refresh Variable Explorer and Editor from a Pdb session, after running any pdb command. ...
Save history and add a %plot magic. def _handle_input_request(self, msg): """Save history and add a %plot magic.""" if self._hidden: raise RuntimeError('Request for raw input during hidden execution.') # Make sure that all output from the SUB channel has been processed # be...
Handle Key_Up/Key_Down while debugging. def _event_filter_console_keypress(self, event): """Handle Key_Up/Key_Down while debugging.""" key = event.key() if self._reading: self._control.current_prompt_pos = self._prompt_pos if key == Qt.Key_Up: self._contr...
Returns the global maximum and minimum. def global_max(col_vals, index): """Returns the global maximum and minimum.""" col_vals_without_None = [x for x in col_vals if x is not None] max_col, min_col = zip(*col_vals_without_None) return max(max_col), min(min_col)
Return the corresponding labels taking into account the axis. The axis could be horizontal (0) or vertical (1). def _axis(self, axis): """ Return the corresponding labels taking into account the axis. The axis could be horizontal (0) or vertical (1). """ return...
Return the number of levels in the labels taking into account the axis. Get the number of levels for the columns (0) or rows (1). def _axis_levels(self, axis): """ Return the number of levels in the labels taking into account the axis. Get the number of levels for the columns (0...
Return the values of the labels for the header of columns or rows. The value corresponds to the header of column or row x in the given level. def header(self, axis, x, level=0): """ Return the values of the labels for the header of columns or rows. The value corresponds...
Determines the maximum and minimum number in each column. The result is a list whose k-th entry is [vmax, vmin], where vmax and vmin denote the maximum and minimum of the k-th column (ignoring NaN). This list is stored in self.max_min_col. If the k-th column has a non-numerical ...
Toggle backgroundcolor def colum_avg(self, state): """Toggle backgroundcolor""" self.colum_avg_enabled = state > 0 if self.colum_avg_enabled: self.return_max = lambda col_vals, index: col_vals[index] else: self.return_max = global_max self.reset()
Background color depending on value. def get_bgcolor(self, index): """Background color depending on value.""" column = index.column() if not self.bgcolor_enabled: return value = self.get_value(index.row(), column) if self.max_min_col[column] is None or isna(val...
Return the value of the DataFrame. def get_value(self, row, column): """Return the value of the DataFrame.""" # To increase the performance iat is used but that requires error # handling, so fallback uses iloc try: value = self.df.iat[row, column] except OutOfB...
Cell content def data(self, index, role=Qt.DisplayRole): """Cell content""" if not index.isValid(): return to_qvariant() if role == Qt.DisplayRole or role == Qt.EditRole: column = index.column() row = index.row() value = self.get_value(row,...
Overriding sort method def sort(self, column, order=Qt.AscendingOrder): """Overriding sort method""" if self.complex_intran is not None: if self.complex_intran.any(axis=0).iloc[column]: QMessageBox.critical(self.dialog, "Error", "Typ...
Set flags def flags(self, index): """Set flags""" return Qt.ItemFlags(QAbstractTableModel.flags(self, index) | Qt.ItemIsEditable)
Cell content change def setData(self, index, value, role=Qt.EditRole, change_type=None): """Cell content change""" column = index.column() row = index.row() if index in self.display_error_idxs: return False if change_type is not None: try: ...
DataFrame column number def columnCount(self, index=QModelIndex()): """DataFrame column number""" # Avoid a "Qt exception in virtual methods" generated in our # tests on Windows/Python 3.7 # See PR 8910 try: # This is done to implement series if le...
Load more rows and columns to display. def load_more_data(self, value, rows=False, columns=False): """Load more rows and columns to display.""" try: if rows and value == self.verticalScrollBar().maximum(): self.model().fetch_more(rows=rows) self.sig_fetc...
Implement a column sort. def sortByColumn(self, index): """Implement a column sort.""" if self.sort_old == [None]: self.header_class.setSortIndicatorShown(True) sort_order = self.header_class.sortIndicatorOrder() self.sig_sort_by_column.emit() if not self.model...
Setup context menu. def setup_menu(self): """Setup context menu.""" copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, ...
A function that changes types of cells. def change_type(self, func): """A function that changes types of cells.""" model = self.model() index_list = self.selectedIndexes() [model.setData(i, '', change_type=func) for i in index_list]
Copy text to clipboard def copy(self): """Copy text to clipboard""" if not self.selectedIndexes(): return (row_min, row_max, col_min, col_max) = get_idx_rect(self.selectedIndexes()) index = header = False df = self.model().df obj = df.iloc[sl...
Get number of rows in the header. def rowCount(self, index=None): """Get number of rows in the header.""" if self.axis == 0: return max(1, self._shape[0]) else: if self.total_rows <= self.rows_loaded: return self.total_rows else: ...
DataFrame column number def columnCount(self, index=QModelIndex()): """DataFrame column number""" if self.axis == 0: if self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded else: ret...
Get more columns or rows (based on axis). def fetch_more(self, rows=False, columns=False): """Get more columns or rows (based on axis).""" if self.axis == 1 and self.total_rows > self.rows_loaded: reminder = self.total_rows - self.rows_loaded items_to_fetch = min(reminder, ...
Overriding sort method. def sort(self, column, order=Qt.AscendingOrder): """Overriding sort method.""" ascending = order == Qt.AscendingOrder self.model.sort(self.COLUMN_INDEX, order=ascending) return True
Get the information to put in the header. def headerData(self, section, orientation, role): """Get the information to put in the header.""" if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: return Qt.AlignCenter | Qt.AlignBottom else: ...
Get the data for the header. This is used when a header has levels. def data(self, index, role): """ Get the data for the header. This is used when a header has levels. """ if not index.isValid() or \ index.row() >= self._shape[0] or \ i...
Get the text to put in the header of the levels of the indexes. By default it returns 'Index i', where i is the section in the index def headerData(self, section, orientation, role): """ Get the text to put in the header of the levels of the indexes. By default it returns 'Index...
Get the information of the levels. def data(self, index, role): """Get the information of the levels.""" if not index.isValid(): return None if role == Qt.FontRole: return self._font label = '' if index.column() == self.model.header_shape[1] - 1: ...
Setup DataFrameEditor: return False if data is not supported, True otherwise. Supported types for data are DataFrame, Series and Index. def setup_and_check(self, data, title=''): """ Setup DataFrameEditor: return False if data is not supported, True otherwise. Supp...
Handle the data change event to enable the save and close button. def save_and_close_enable(self, top_left, bottom_right): """Handle the data change event to enable the save and close button.""" self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) se...