INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Set color scheme of the shell.
def set_color_scheme(self, color_scheme, reset=True): """Set color scheme of the shell.""" self.set_bracket_matcher_color_scheme(color_scheme) self.style_sheet, dark_color = create_qss_style(color_scheme) self.syntax_style = color_scheme self._style_sheet_changed() self._...
Banner for IPython widgets with pylab message
def long_banner(self): """Banner for IPython widgets with pylab message""" # Default banner try: from IPython.core.usage import quick_guide except Exception: quick_guide = '' banner_parts = [ 'Python %s\n' % self.interpreter_versions['python_ve...
Reset the namespace by removing all names defined by the user.
def reset_namespace(self, warning=False, message=False): """Reset the namespace by removing all names defined by the user.""" reset_str = _("Remove all variables") warn_str = _("All user-defined variables will be removed. " "Are you sure you want to proceed?") kernel...
Create shortcuts for ipyconsole.
def create_shortcuts(self): """Create shortcuts for ipyconsole.""" inspect = config_shortcut(self._control.inspect_current_object, context='Console', name='Inspect current object', parent=self) clear_console = config_shortcut(se...
Execute code in the kernel without increasing the prompt
def silent_execute(self, code): """Execute code in the kernel without increasing the prompt""" try: self.kernel_client.execute(to_text_string(code), silent=True) except AttributeError: pass
Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string ...
def silent_exec_method(self, code): """Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ...
Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD.
def handle_exec_method(self, msg): """ Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD. """ user_exp = msg['content'].get('user_expressions') if not user_e...
Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends
def set_backend_for_mayavi(self, command): """ Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends """ calling_mayavi = False lines = command.splitlines() for l in lines: if not l.startswith('#'): ...
If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002
def change_mpl_backend(self, command): """ If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002 """ if command.startswith('%matplotlib') and \ len(comman...
Reimplement the IPython context menu
def _context_menu_make(self, pos): """Reimplement the IPython context menu""" menu = super(ShellWidget, self)._context_menu_make(pos) return self.ipyclient.add_actions_to_context_menu(menu)
Reimplement banner creation to let the user decide if he wants a banner or not
def _banner_default(self): """ Reimplement banner creation to let the user decide if he wants a banner or not """ # Don't change banner for external kernels if self.external_kernel: return '' show_banner_o = self.additional_options['show_banner'] ...
Refresh the highlighting with the current syntax style by class.
def _syntax_style_changed(self): """Refresh the highlighting with the current syntax style by class.""" if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter._style = create_style_class(self.syntax_style) ...
Emit a signal when the prompt is ready.
def _prompt_started_hook(self): """Emit a signal when the prompt is ready.""" if not self._reading: self._highlighter.highlighting_on = True self.sig_prompt_ready.emit()
Reimplement Qt method to send focus change notification
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ShellWidget, self).focusInEvent(event)
Reimplement Qt method to send focus change notification
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ShellWidget, self).focusOutEvent(event)
Installs a panel on the editor. :param panel: Panel to install :param position: Position where the panel must be installed. :return: The installed panel
def register(self, panel, position=Panel.Position.LEFT): """ Installs a panel on the editor. :param panel: Panel to install :param position: Position where the panel must be installed. :return: The installed panel """ assert panel is not None pos_to_strin...
Removes the specified panel. :param name_or_klass: Name or class of the panel to remove. :return: The removed panel
def remove(self, name_or_klass): """ Removes the specified panel. :param name_or_klass: Name or class of the panel to remove. :return: The removed panel """ logger.debug('removing panel %s' % name_or_klass) panel = self.get(name_or_klass) panel.on_uninsta...
Removes all panel from the CodeEditor.
def clear(self): """Removes all panel from the CodeEditor.""" for i in range(4): while len(self._panels[i]): key = sorted(list(self._panels[i].keys()))[0] panel = self.remove(key) panel.setParent(None) panel.deleteLater()
Gets a specific panel instance. :param name_or_klass: Name or class of the panel to retrieve. :return: The specified panel instance.
def get(self, name_or_klass): """ Gets a specific panel instance. :param name_or_klass: Name or class of the panel to retrieve. :return: The specified panel instance. """ if not is_text_string(name_or_klass): name_or_klass = name_or_klass.__name__ for...
Refreshes the editor panels (resize and update margins).
def refresh(self): """Refreshes the editor panels (resize and update margins).""" logger.debug('Refresh panels') self.resize() self._update(self.editor.contentsRect(), 0, force_update_margins=True)
Resizes panels.
def resize(self): """Resizes panels.""" crect = self.editor.contentsRect() view_crect = self.editor.viewport().contentsRect() s_bottom, s_left, s_right, s_top = self._compute_zones_sizes() tw = s_left + s_right th = s_bottom + s_top w_offset = crect.width() - (vie...
Update foating panels.
def update_floating_panels(self): """Update foating panels.""" crect = self.editor.contentsRect() panels = self.panels_for_zone(Panel.Position.FLOATING) for panel in panels: if not panel.isVisible(): continue panel.set_geometry(crect)
Update viewport margins.
def _update_viewport_margins(self): """Update viewport margins.""" top = 0 left = 0 right = 0 bottom = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if panel.isVisible(): width = panel.sizeHint().width() left += widt...
Compute panel zone sizes.
def _compute_zones_sizes(self): """Compute panel zone sizes.""" # Left panels left = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if not panel.isVisible(): continue size_hint = panel.sizeHint() left += size_hint.width() ...
Locate a module path based on an import line in an python-like file import_line is the line of source code containing the import alt_path specifies an alternate base path for the module stop_token specifies the desired name to stop on This is used to a find the path to python-like modules (...
def python_like_mod_finder(import_line, alt_path=None, stop_token=None): """ Locate a module path based on an import line in an python-like file import_line is the line of source code containing the import alt_path specifies an alternate base path for the module st...
Find the definition of an object within a source closest to a given line
def get_definition_with_regex(source, token, start_line=-1): """ Find the definition of an object within a source closest to a given line """ if not token: return None if DEBUG_EDITOR: t0 = time.time() patterns = [ # python / cython keyword definitions r...
Return a list of all python-like extensions
def python_like_exts(): """Return a list of all python-like extensions""" exts = [] for lang in languages.PYTHON_LIKE_LANGUAGES: exts.extend(list(languages.ALL_LANGUAGES[lang])) return ['.' + ext for ext in exts]
Return a list of all editable extensions
def all_editable_exts(): """Return a list of all editable extensions""" exts = [] for (language, extensions) in languages.ALL_LANGUAGES.items(): exts.extend(list(extensions)) return ['.' + ext for ext in exts]
Perform completion of filesystem path. https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input
def _complete_path(path=None): """Perform completion of filesystem path. https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input """ if not path: return _listdir('.') dirname, rest = os.path.split(path) tmp = dirname if dirname else '.' res = [p for p ...
Return a list of (completion, type) tuples Simple completion based on python-like identifiers and whitespace
def get_completions(self, info): """Return a list of (completion, type) tuples Simple completion based on python-like identifiers and whitespace """ if not info['obj']: return items = [] obj = info['obj'] if info['context']: lexe...
Find the definition for an object within a set of source code This is used to find the path of python-like modules (e.g. cython and enaml) for a goto definition
def get_definition(self, info): """ Find the definition for an object within a set of source code This is used to find the path of python-like modules (e.g. cython and enaml) for a goto definition """ if not info['is_python_like']: return tok...
Get a formatted calltip and docstring from Fallback
def get_info(self, info): """Get a formatted calltip and docstring from Fallback""" if info['docstring']: if info['filename']: filename = os.path.basename(info['filename']) filename = os.path.splitext(filename)[0] else: filen...
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 h...
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...
Edit the object 'obj' in a GUI-based editor and return the edited copy (if Cancel is pressed, return None) The object 'obj' is a container Supported container types: dict, list, set, tuple, str/unicode or numpy.array (instantiate a new QApplication if necessary, so it can be ...
def oedit(obj, modal=True, namespace=None): """Edit the object 'obj' in a GUI-based editor and return the edited copy (if Cancel is pressed, return None) The object 'obj' is a container Supported container types: dict, list, set, tuple, str/unicode or numpy.array (instantiate...
Return a sorted list of all the children items of 'item'.
def get_item_children(item): """Return a sorted list of all the children items of 'item'.""" children = [item.child(index) for index in range(item.childCount())] for child in children[:]: others = get_item_children(child) if others is not None: children += others retur...
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 item = root_item for item in get_item_children(root_item): if item.line > line: return...
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'), triggered=self.go_to_cursor_position) ...
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 """ for _it in self.get_top_level_items(): _it.setHidden(_it is not item and not self.show_all_files)
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) self...
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 issue 8813 return editor_id = ed...
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_editor_ids != ordered_editor_ids: self.ordered_editor_ids = ordered_editor_ids i...
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' is True, else order the items as specified in the 'self.ordered_editor_ids' list. """ if self.show_all_files is False: return c...
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: tree_cache = {} # Removing cached items for which line is > total line...
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: self.expandItem(root_item) else: ...
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.isHidden(): if item.parent(): ...
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 = item.line se...
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.treewidget.go_to_cursor_position) buttons = [self.fro...
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, show_comments=self.tree...
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 script requires guidata 1.5+") for _modname in ('spyder', 'spyderplugins'): dis...
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, branch = vcs.get_git_revision(os.path.dirname(__dir__)) ...
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') except: ...
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 if dtype == "b...
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_qvariant(int(section))...
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)) return elif v...
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.commitData.emit(editor) ...
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.restoreOverrideCursor()
Setup context menu
def setup_menu(self): """Setup context menu""" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, ...
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-1): # we've selected a whole ...
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: format = str(format) ...
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 """ self.data = data readonly = readonly or not self.data.flags.writeable ...
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 """ string_index = [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label....
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] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + '...
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]) else: try: le...
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 = [] for vals in lexer.tokens.value...
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 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. """ if (file_path is None and (content ...
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 'numpy.core' """ dirname = osp.dirname(path) try: mod = osp.basename(path) mod = osp.splitext(mod)[0] imp.find_mo...
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 = self.position while right < le...
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", "") is_remote = existing_kernel.get("is_remote", False) ...
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.text(), "is_remote": self.rm_...
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: return to_qvariant(get_co...
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()] = \ datestr_to_datetime(self._data[in...
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:] for row in text_rows: str...
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) self._model = PreviewTableMo...
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, skiprows=skiprows, commen...
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)
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(alist[-1], 1) return [self._simpl...
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.open_data(self._get_plain_t...