INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Ctrl+Tab
def tab_navigate(self, delta=1): """Ctrl+Tab""" if delta > 0 and self.currentIndex() == self.count()-1: index = delta-1 elif delta < 0 and self.currentIndex() == 0: index = self.count()+delta else: index = self.currentIndex()+delta self...
Setting Tabs close function None -> tabs are not closable
def set_close_function(self, func): """Setting Tabs close function None -> tabs are not closable""" state = func is not None if state: self.sig_close_tab.connect(func) try: # Assuming Qt >= 4.5 QTabWidget.setTabsClosable(self, state) ...
Move tab inside a tabwidget
def move_tab(self, index_from, index_to): """Move tab inside a tabwidget""" self.move_data.emit(index_from, index_to) tip, text = self.tabToolTip(index_from), self.tabText(index_from) icon, widget = self.tabIcon(index_from), self.widget(index_from) current_widget = self.cu...
Move tab from a tabwidget to another
def move_tab_from_another_tabwidget(self, tabwidget_from, index_from, index_to): """Move tab from a tabwidget to another""" # We pass self object IDs as QString objs, because otherwise it would # depend on the platform: long for 64bit, i...
Return script *fname* run configuration
def get_run_configuration(fname): """Return script *fname* run configuration""" configurations = _get_run_configurations() for filename, options in configurations: if fname == filename: runconf = RunConfiguration() runconf.set(options) return runconf
Select directory
def select_directory(self): """Select directory""" basedir = to_text_string(self.wd_edit.text()) if not osp.isdir(basedir): basedir = getcwd_or_home() directory = getexistingdirectory(self, _("Select directory"), basedir) if directory: self.wd_edit....
Add widgets/spacing to dialog vertical layout
def add_widgets(self, *widgets_or_spacings): """Add widgets/spacing to dialog vertical layout""" layout = self.layout() for widget_or_spacing in widgets_or_spacings: if isinstance(widget_or_spacing, int): layout.addSpacing(widget_or_spacing) else: ...
Create dialog button box and add it to the dialog layout
def add_button_box(self, stdbtns): """Create dialog button box and add it to the dialog layout""" bbox = QDialogButtonBox(stdbtns) run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole) run_btn.clicked.connect(self.run_btn_clicked) bbox.accepted.connect(self.accept)...
Setup Run Configuration dialog with filename *fname*
def setup(self, fname): """Setup Run Configuration dialog with filename *fname*""" self.filename = fname self.runconfigoptions = RunConfigOptions(self) self.runconfigoptions.set(RunConfiguration(fname).get()) self.add_widgets(self.runconfigoptions) self.add_button_b...
Reimplement Qt method
def accept(self): """Reimplement Qt method""" if not self.runconfigoptions.is_valid(): return configurations = _get_run_configurations() configurations.insert(0, (self.filename, self.runconfigoptions.get())) _set_run_configurations(configurations) QDial...
Setup Run Configuration dialog with filename *fname*
def setup(self, fname): """Setup Run Configuration dialog with filename *fname*""" combo_label = QLabel(_("Select a run configuration:")) self.combo = QComboBox() self.combo.setMaxVisibleItems(20) self.combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength) ...
Reimplement Qt method
def accept(self): """Reimplement Qt method""" configurations = [] for index in range(self.stack.count()): filename = to_text_string(self.combo.itemText(index)) runconfigoptions = self.stack.widget(index) if index == self.stack.currentIndex() and\ ...
Override Qt method. Painting line number area
def paintEvent(self, event): """Override Qt method. Painting line number area """ painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) # This is needed to make that the font size of line numbers # be the same as the text one when z...
Override Qt method. Show code analisis, if left button pressed select lines.
def mouseMoveEvent(self, event): """Override Qt method. Show code analisis, if left button pressed select lines. """ line_number = self.editor.get_linenumber_from_mouse_event(event) block = self.editor.document().findBlockByNumber(line_number-1) data = block.userData() ...
Override Qt method Select line, and starts selection
def mousePressEvent(self, event): """Override Qt method Select line, and starts selection """ line_number = self.editor.get_linenumber_from_mouse_event(event) self._pressed = line_number self._released = line_number self.editor.select_lines(self._pressed, ...
Compute and return line number area width
def compute_width(self): """Compute and return line number area width""" if not self._enabled: return 0 digits = 1 maxb = max(1, self.editor.blockCount()) while maxb >= 10: maxb /= 10 digits += 1 if self._margin: margin = 3+...
Setup margin settings (except font, now set in editor.set_font)
def setup_margins(self, linenumbers=True, markers=True): """ Setup margin settings (except font, now set in editor.set_font) """ self._margin = linenumbers self._markers_margin = markers self.set_enabled(linenumbers or markers)
Returns a list with line number, definition name, fold and token.
def process_python_symbol_data(oedata): """Returns a list with line number, definition name, fold and token.""" symbol_list = [] for key in oedata: val = oedata[key] if val and key != 'found_cell_separators': if val.is_class_or_function(): symbol_list.append((key,...
Return a list of icons for oedata of a python file.
def get_python_symbol_icons(oedata): """Return a list of icons for oedata of a python file.""" class_icon = ima.icon('class') method_icon = ima.icon('method') function_icon = ima.icon('function') private_icon = ima.icon('private1') super_private_icon = ima.icon('private2') symbols = process...
Takes a list of paths and tries to "intelligently" shorten them all. The aim is to make it clear to the user where the paths differ, as that is likely what they care about. Note that this operates on a list of paths not on individual paths. If the path ends in an actual file name, it will be trimmed of...
def shorten_paths(path_list, is_unsaved): """ Takes a list of paths and tries to "intelligently" shorten them all. The aim is to make it clear to the user where the paths differ, as that is likely what they care about. Note that this operates on a list of paths not on individual paths. If the p...
Detect when the focus goes out of this widget. This is used to make the file switcher leave focus on the last selected file by the user.
def focusOutEvent(self, event): """ Detect when the focus goes out of this widget. This is used to make the file switcher leave focus on the last selected file by the user. """ self.clicked_outside = True return super(QLineEdit, self).focusOutEvent(event)
Save initial cursors and initial active widget.
def save_initial_state(self): """Save initial cursors and initial active widget.""" paths = self.paths self.initial_widget = self.get_widget() self.initial_cursors = {} for i, editor in enumerate(self.widgets): if editor is self.initial_widget: self.i...
Restores initial cursors and initial active editor.
def restore_initial_state(self): """Restores initial cursors and initial active editor.""" self.list.clear() self.is_visible = False widgets = self.widgets_by_path if not self.edit.clicked_outside: for path in self.initial_cursors: cursor = self.initi...
Get the max size (width and height) for the elements of a list of strings as a QLabel.
def get_item_size(self, content): """ Get the max size (width and height) for the elements of a list of strings as a QLabel. """ strings = [] if content: for rich_text in content: label = QLabel(rich_text) label.setTextFormat(Qt...
Positions the file switcher dialog.
def set_dialog_position(self): """Positions the file switcher dialog.""" parent = self.parent() geo = parent.geometry() width = self.list.width() # This has been set in setup left = parent.geometry().width()/2 - width/2 # Note: the +1 pixel on the top makes it look bette...
Adjusts the width and height of the file switcher based on the relative size of the parent and content.
def fix_size(self, content): """ Adjusts the width and height of the file switcher based on the relative size of the parent and content. """ # Update size of dialog based on relative size of the parent if content: width, height = self.get_item_size(content) ...
Select row in list widget based on a number of steps with direction. Steps can be positive (next rows) or negative (previous rows).
def select_row(self, steps): """Select row in list widget based on a number of steps with direction. Steps can be positive (next rows) or negative (previous rows). """ row = self.current_row() + steps if 0 <= row < self.count(): self.set_current_row(row)
Select previous row in list widget.
def previous_row(self): """Select previous row in list widget.""" if self.mode == self.SYMBOL_MODE: self.select_row(-1) return prev_row = self.current_row() - 1 if prev_row >= 0: title = self.list.item(prev_row).text() else: title =...
Select next row in list widget.
def next_row(self): """Select next row in list widget.""" if self.mode == self.SYMBOL_MODE: self.select_row(+1) return next_row = self.current_row() + 1 if next_row < self.count(): if '</b></big><br>' in self.list.item(next_row).text(): ...
Get the real index of the selected item.
def get_stack_index(self, stack_index, plugin_index): """Get the real index of the selected item.""" other_plugins_count = sum([other_tabs[0].count() \ for other_tabs in \ self.plugins_tabs[:plugin_index]]) real_index = stack_...
Get the data object of the plugin's current tab manager.
def get_plugin_data(self, plugin): """Get the data object of the plugin's current tab manager.""" # The data object is named "data" in the editor plugin while it is # named "clients" in the notebook plugin. try: data = plugin.get_current_tab_manager().data except Attr...
Get the tabwidget of the plugin's current tab manager.
def get_plugin_tabwidget(self, plugin): """Get the tabwidget of the plugin's current tab manager.""" # The tab widget is named "tabs" in the editor plugin while it is # named "tabwidget" in the notebook plugin. try: tabwidget = plugin.get_current_tab_manager().tabs ex...
Get widget by index. If no tabs and index specified the current active widget is returned.
def get_widget(self, index=None, path=None, tabs=None): """Get widget by index. If no tabs and index specified the current active widget is returned. """ if (index and tabs) or (path and tabs): return tabs.widget(index) elif self.plugin: return self.get_p...
Set the cursor of an editor.
def set_editor_cursor(self, editor, cursor): """Set the cursor of an editor.""" pos = cursor.position() anchor = cursor.anchor() new_cursor = QTextCursor() if pos == anchor: new_cursor.movePosition(pos) else: new_cursor.movePosition(anchor) ...
Go to specified line number in current active editor.
def goto_line(self, line_number): """Go to specified line number in current active editor.""" if line_number: line_number = int(line_number) try: self.plugin.go_to_line(line_number) except AttributeError: pass
List widget item selection change handler.
def item_selection_changed(self): """List widget item selection change handler.""" row = self.current_row() if self.count() and row >= 0: if '</b></big><br>' in self.list.currentItem().text() and row == 0: self.next_row() if self.mode == self.FILE_MODE: ...
Setup list widget content for file list display.
def setup_file_list(self, filter_text, current_path): """Setup list widget content for file list display.""" short_paths = shorten_paths(self.paths, self.save_status) paths = self.paths icons = self.icons results = [] trying_for_line_number = ':' in filter_text #...
Setup list widget content for symbol list display.
def setup_symbol_list(self, filter_text, current_path): """Setup list widget content for symbol list display.""" # Get optional symbol name filter_text, symbol_text = filter_text.split('@') # Fetch the Outline explorer data, get the icons and values oedata = self.get_symbol_list...
Setup list widget content.
def setup(self): """Setup list widget content.""" if len(self.plugins_tabs) == 0: self.close() return self.list.clear() current_path = self.current_path filter_text = self.filter_text # Get optional line or symbol to define mode and method handle...
Add a plugin to display its files.
def add_plugin(self, plugin, tabs, data, icon): """Add a plugin to display its files.""" self.plugins_tabs.append((tabs, plugin)) self.plugins_data.append((data, icon)) self.plugins_instances.append(plugin)
:param filename: File to check. :returns: True if it's a binary file, otherwise False.
def is_binary(filename): """ :param filename: File to check. :returns: True if it's a binary file, otherwise False. """ logger.debug('is_binary: %(filename)r', locals()) # Check if the file extension is in a list of known binary types binary_extensions = ['pyc', 'iso', 'zip', 'pdf'] for...
Return support status dict if path is under VCS root
def get_vcs_info(path): """Return support status dict if path is under VCS root""" for info in SUPPORTED: vcs_path = osp.join(path, info['rootdir']) if osp.isdir(vcs_path): return info
Return VCS root directory path Return None if path is not within a supported VCS repository
def get_vcs_root(path): """Return VCS root directory path Return None if path is not within a supported VCS repository""" previous_path = path while get_vcs_info(path) is None: path = abspardir(path) if path == previous_path: return else: previous...
If path is a valid VCS repository, run the corresponding VCS tool Supported VCS actions: 'commit', 'browse' Return False if the VCS tool is not installed
def run_vcs_tool(path, action): """If path is a valid VCS repository, run the corresponding VCS tool Supported VCS actions: 'commit', 'browse' Return False if the VCS tool is not installed""" info = get_vcs_info(get_vcs_root(path)) tools = info['actions'][action] for tool, args in tools: ...
Return Mercurial revision for the repository located at repopath Result is a tuple (global, local, branch), with None values on error For example: >>> get_hg_revision(".") ('eba7273c69df+', '2015+', 'default')
def get_hg_revision(repopath): """Return Mercurial revision for the repository located at repopath Result is a tuple (global, local, branch), with None values on error For example: >>> get_hg_revision(".") ('eba7273c69df+', '2015+', 'default') """ try: ass...
Return Git revision for the repository located at repopath Result is a tuple (latest commit hash, branch), with None values on error
def get_git_revision(repopath): """ Return Git revision for the repository located at repopath Result is a tuple (latest commit hash, branch), with None values on error """ try: git = programs.find_program('git') assert git is not None and osp.isdir(osp.join(repopat...
Return Git active branch, state, branches (plus tags).
def get_git_refs(repopath): """ Return Git active branch, state, branches (plus tags). """ tags = [] branches = [] branch = '' files_modifed = [] if os.path.isfile(repopath): repopath = os.path.dirname(repopath) try: git = programs.find_program('git')...
Return True if path is a Python module/package
def is_module_or_package(path): """Return True if path is a Python module/package""" is_module = osp.isfile(path) and osp.splitext(path)[1] in ('.py', '.pyw') is_package = osp.isdir(path) and osp.isfile(osp.join(path, '__init__.py')) return is_module or is_package
Qt Override. Filter tab keys and process double tab keys.
def event(self, event): """Qt Override. Filter tab keys and process double tab keys. """ if (event.type() == QEvent.KeyPress) and (event.key() == Qt.Key_Tab): self.sig_tab_pressed.emit(True) self.numpress += 1 if self.numpress == 1: ...
Qt Override. Handle key press events.
def keyPressEvent(self, event): """Qt Override. Handle key press events. """ if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: if self.add_current_text_if_valid(): self.selected() self.hide_completer() elif event...
When hitting tab, it handles if single or double tab
def handle_keypress(self): """When hitting tab, it handles if single or double tab""" if self.numpress == 2: self.sig_double_tab_pressed.emit(True) self.numpress = 0
Add text to combo box: add a new item if text is not found in combo box items.
def add_text(self, text): """Add text to combo box: add a new item if text is not found in combo box items.""" index = self.findText(text) while index != -1: self.removeItem(index) index = self.findText(text) self.insertItem(0, text) index ...
Add current text to combo box history if valid
def add_current_text_if_valid(self): """Add current text to combo box history if valid""" valid = self.is_valid(self.currentText()) if valid or valid is None: self.add_current_text() return True else: self.set_current_text(self.selected_text)
Show tip
def show_tip(self, tip=""): """Show tip""" QToolTip.showText(self.mapToGlobal(self.pos()), tip, self)
Validate entered path
def validate(self, qstr, editing=True): """Validate entered path""" if self.selected_text == qstr and qstr != '': self.valid.emit(True, True) return valid = self.is_valid(qstr) if editing: if valid: self.valid.emit(True, False...
Handle focus in event restoring to display the status icon.
def focusInEvent(self, event): """Handle focus in event restoring to display the status icon.""" show_status = getattr(self.lineEdit(), 'show_status_icon', None) if show_status: show_status() QComboBox.focusInEvent(self, event)
Handle focus out event restoring the last valid selected path.
def focusOutEvent(self, event): """Handle focus out event restoring the last valid selected path.""" # Calling asynchronously the 'add_current_text' to avoid crash # https://groups.google.com/group/spyderlib/browse_thread/thread/2257abf530e210bd if not self.is_valid(): l...
Find available completion options.
def _complete_options(self): """Find available completion options.""" text = to_text_string(self.currentText()) opts = glob.glob(text + "*") opts = sorted([opt for opt in opts if osp.isdir(opt)]) self.setCompleter(QCompleter(opts, self)) return opts
If several options available a double tab displays options.
def double_tab_complete(self): """If several options available a double tab displays options.""" opts = self._complete_options() if len(opts) > 1: self.completer().complete()
If there is a single option available one tab completes the option.
def tab_complete(self): """ If there is a single option available one tab completes the option. """ opts = self._complete_options() if len(opts) == 1: self.set_current_text(opts[0] + os.sep) self.hide_completer()
Return True if string is valid
def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return osp.isdir(to_text_string(qstr))
Action to be executed when a valid item has been selected
def selected(self): """Action to be executed when a valid item has been selected""" self.selected_text = self.currentText() self.valid.emit(True, True) self.open_dir.emit(self.selected_text)
Add current text to combo box history (convenient method). If path ends in os separator ("\" windows, "/" unix) remove it.
def add_current_text(self): """ Add current text to combo box history (convenient method). If path ends in os separator ("\" windows, "/" unix) remove it. """ text = self.currentText() if osp.isdir(text) and text: if text[-1] == os.sep: ...
Add a tooltip showing the full path of the currently highlighted item of the PathComboBox.
def add_tooltip_to_highlighted_item(self, index): """ Add a tooltip showing the full path of the currently highlighted item of the PathComboBox. """ self.setItemData(index, self.itemText(index), Qt.ToolTipRole)
Return True if string is valid
def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return QUrl(qstr).isValid()
Return True if string is valid
def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return osp.isfile(to_text_string(qstr))
Return True if string is valid
def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return is_module_or_package(to_text_string(qstr))
Action to be executed when a valid item has been selected
def selected(self): """Action to be executed when a valid item has been selected""" EditableComboBox.selected(self) self.open_dir.emit(self.currentText())
Bind historylog instance to this console Not used anymore since v2.0
def set_historylog(self, historylog): """Bind historylog instance to this console Not used anymore since v2.0""" historylog.add_history(self.shell.history_filename) self.shell.append_to_history.connect(historylog.append_to_history)
Perform actions before parent main window is closed
def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" self.dialog_manager.close_all() self.shell.exit_interpreter() return True
Return a list of actions related to plugin
def get_plugin_actions(self): """Return a list of actions related to plugin""" quit_action = create_action(self, _("&Quit"), icon=ima.icon('exit'), tip=_("Quit"), triggered=self.quit) ...
Register plugin in Spyder's main window
def register_plugin(self): """Register plugin in Spyder's main window""" self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) # Connecting the following signal once the dockwidget has been created: self.shell.exception_occurred.connect(se...
Exception ocurred in the internal console. Show a QDialog or the internal console to warn the user.
def exception_occurred(self, text, is_traceback): """ Exception ocurred in the internal console. Show a QDialog or the internal console to warn the user. """ # Skip errors without traceback or dismiss if (not is_traceback and self.error_dlg is None) or self.dismis...
Close error dialog.
def close_error_dlg(self): """Close error dialog.""" if self.error_dlg.dismiss_box.isChecked(): self.dismiss_error = True self.error_dlg.reject()
Show sys.path
def show_syspath(self): """Show sys.path""" editor = CollectionsEditor(parent=self) editor.setup(sys.path, title="sys.path", readonly=True, width=600, icon=ima.icon('syspath')) self.dialog_manager.show(editor)
Run a Python script
def run_script(self, filename=None, silent=False, set_focus=False, args=None): """Run a Python script""" if filename is None: self.shell.interpreter.restore_stds() filename, _selfilter = getopenfilename( self, _("Run Python script"), g...
Go to error if relevant
def go_to_error(self, text): """Go to error if relevant""" match = get_error_match(to_text_string(text)) if match: fname, lnb = match.groups() self.edit_script(fname, int(lnb))
Edit script
def edit_script(self, filename=None, goto=-1): """Edit script""" # Called from InternalShell if not hasattr(self, 'main') \ or not hasattr(self.main, 'editor'): self.shell.external_editor(filename, goto) return if filename is not None: ...
Execute lines and give focus to shell
def execute_lines(self, lines): """Execute lines and give focus to shell""" self.shell.execute_lines(to_text_string(lines)) self.shell.setFocus()
Change external editor path
def change_exteditor(self): """Change external editor path""" path, valid = QInputDialog.getText(self, _('External editor'), _('External editor executable path:'), QLineEdit.Normal, self.get_option('external_editor/path')...
Toggle wrap mode
def toggle_wrap_mode(self, checked): """Toggle wrap mode""" self.shell.toggle_wrap_mode(checked) self.set_option('wrap', checked)
Toggle automatic code completion
def toggle_codecompletion(self, checked): """Toggle automatic code completion""" self.shell.set_codecompletion_auto(checked) self.set_option('codecompletion/auto', checked)
Reimplement Qt method Inform Qt about the types of data that the widget accepts
def dragEnterEvent(self, event): """Reimplement Qt method Inform Qt about the types of data that the widget accepts""" source = event.mimeData() if source.hasUrls(): if mimedata2url(source): event.acceptProposedAction() else: ...
Reimplement Qt method Unpack dropped data and handle it
def dropEvent(self, event): """Reimplement Qt method Unpack dropped data and handle it""" source = event.mimeData() if source.hasUrls(): pathlist = mimedata2url(source) self.shell.drop_pathlist(pathlist) elif source.hasText(): lines = t...
Function executed when running the script with the -install switch
def install(): """Function executed when running the script with the -install switch""" # Create Spyder start menu folder # Don't use CSIDL_COMMON_PROGRAMS because it requres admin rights # This is consistent with use of CSIDL_DESKTOPDIRECTORY below # CSIDL_COMMON_PROGRAMS = # C:\ProgramDa...
Function executed when running the script with the -remove switch
def remove(): """Function executed when running the script with the -remove switch""" current = True # only affects current user root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE for key in (KEY_C1 % ("", EWS), KEY_C1 % ("NoCon", EWS), KEY_C0 % ("", EWS), KE...
This function generates a list of tours. The index argument is used to retrieve a particular tour. If None is passed, it will return the full list of tours. If instead -1 is given, this function will return a test tour To add more tours a new variable needs to be created to hold the list of ...
def get_tour(index): """ This function generates a list of tours. The index argument is used to retrieve a particular tour. If None is passed, it will return the full list of tours. If instead -1 is given, this function will return a test tour To add more tours a new variable needs...
Override Qt method
def paintEvent(self, event): """Override Qt method""" painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # Decoration painter.fillPath(self.path_current, QBrush(self.color)) painter.strokePath(self.path_decoration, QPen(self.color_decoration, ...
Override Qt method
def reject(self): """Override Qt method""" if not self.is_fade_running(): key = Qt.Key_Escape self.key_pressed = key self.sig_key_pressed.emit()
override Qt method
def mousePressEvent(self, event): """override Qt method""" # Raise the main application window on click self.parent.raise_() self.raise_() if event.button() == Qt.RightButton: pass
Set data that is displayed in each step of the tour.
def _set_data(self): """Set data that is displayed in each step of the tour.""" self.setting_data = True step, steps, frames = self.step_current, self.steps, self.frames current = '{0}/{1}'.format(step + 1, steps) frame = frames[step] combobox_frames = [u"{0}. {1}...
Confirm if the tour loses focus and hides the tips.
def lost_focus(self): """Confirm if the tour loses focus and hides the tips.""" if (self.is_running and not self.any_has_focus() and not self.setting_data and not self.hidden): self.hide_tips()
Confirm if the tour regains focus and unhides the tips.
def gain_focus(self): """Confirm if the tour regains focus and unhides the tips.""" if (self.is_running and self.any_has_focus() and not self.setting_data and self.hidden): self.unhide_tips()
Returns if tour or any of its components has focus.
def any_has_focus(self): """Returns if tour or any of its components has focus.""" f = (self.hasFocus() or self.parent.hasFocus() or self.tips.hasFocus() or self.canvas.hasFocus()) return f
Reimplemented to handle communications between the figure explorer and the kernel.
def _handle_display_data(self, msg): """ Reimplemented to handle communications between the figure explorer and the kernel. """ img = None data = msg['content']['data'] if 'image/svg+xml' in data: fmt = 'image/svg+xml' img = data['image/svg...
Get file language from filename
def get_file_language(filename, text=None): """Get file language from filename""" ext = osp.splitext(filename)[1] if ext.startswith('.'): ext = ext[1:] # file extension with leading dot language = ext if not ext: if text is None: text, _enc = encoding.read(filenam...
Save fig to fname in the format specified by fmt.
def save_figure_tofile(fig, fmt, fname): """Save fig to fname in the format specified by fmt.""" root, ext = osp.splitext(fname) if ext == '.png' and fmt == 'image/svg+xml': qimg = svg_to_image(fig) qimg.save(fname) else: if fmt == 'image/svg+xml' and is_unicode(fig): ...
Line edit's text has changed
def text_has_changed(self, text): """Line edit's text has changed""" text = to_text_string(text) if text: self.lineno = int(text) else: self.lineno = None
Append a number to "root" to form a filename that does not already exist in "dirname".
def get_unique_figname(dirname, root, ext): """ Append a number to "root" to form a filename that does not already exist in "dirname". """ i = 1 figname = root + '_%d' % i + ext while True: if osp.exists(osp.join(dirname, figname)): i += 1 figname = root + '_%...
Setup the figure browser with provided settings.
def setup(self, mute_inline_plotting=None, show_plot_outline=None): """Setup the figure browser with provided settings.""" assert self.shellwidget is not None self.mute_inline_plotting = mute_inline_plotting self.show_plot_outline = show_plot_outline if self.figviewer is not No...