id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
30,900
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.change_last_focused_widget
def change_last_focused_widget(self, old, now): """To keep track of to the last focused widget""" if (now is None and QApplication.activeWindow() is not None): QApplication.activeWindow().setFocus() self.last_focused_widget = QApplication.focusWidget() elif now is not None: self.last_focused_widget = now self.previous_focused_widget = old
python
def change_last_focused_widget(self, old, now): """To keep track of to the last focused widget""" if (now is None and QApplication.activeWindow() is not None): QApplication.activeWindow().setFocus() self.last_focused_widget = QApplication.focusWidget() elif now is not None: self.last_focused_widget = now self.previous_focused_widget = old
[ "def", "change_last_focused_widget", "(", "self", ",", "old", ",", "now", ")", ":", "if", "(", "now", "is", "None", "and", "QApplication", ".", "activeWindow", "(", ")", "is", "not", "None", ")", ":", "QApplication", ".", "activeWindow", "(", ")", ".", ...
To keep track of to the last focused widget
[ "To", "keep", "track", "of", "to", "the", "last", "focused", "widget" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2301-L2309
30,901
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.add_dockwidget
def add_dockwidget(self, child): """Add QDockWidget and toggleViewAction""" dockwidget, location = child.create_dockwidget() if CONF.get('main', 'vertical_dockwidget_titlebars'): dockwidget.setFeatures(dockwidget.features()| QDockWidget.DockWidgetVerticalTitleBar) self.addDockWidget(location, dockwidget) self.widgetlist.append(child)
python
def add_dockwidget(self, child): """Add QDockWidget and toggleViewAction""" dockwidget, location = child.create_dockwidget() if CONF.get('main', 'vertical_dockwidget_titlebars'): dockwidget.setFeatures(dockwidget.features()| QDockWidget.DockWidgetVerticalTitleBar) self.addDockWidget(location, dockwidget) self.widgetlist.append(child)
[ "def", "add_dockwidget", "(", "self", ",", "child", ")", ":", "dockwidget", ",", "location", "=", "child", ".", "create_dockwidget", "(", ")", "if", "CONF", ".", "get", "(", "'main'", ",", "'vertical_dockwidget_titlebars'", ")", ":", "dockwidget", ".", "setF...
Add QDockWidget and toggleViewAction
[ "Add", "QDockWidget", "and", "toggleViewAction" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2336-L2343
30,902
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.add_to_toolbar
def add_to_toolbar(self, toolbar, widget): """Add widget actions to toolbar""" actions = widget.toolbar_actions if actions is not None: add_actions(toolbar, actions)
python
def add_to_toolbar(self, toolbar, widget): """Add widget actions to toolbar""" actions = widget.toolbar_actions if actions is not None: add_actions(toolbar, actions)
[ "def", "add_to_toolbar", "(", "self", ",", "toolbar", ",", "widget", ")", ":", "actions", "=", "widget", ".", "toolbar_actions", "if", "actions", "is", "not", "None", ":", "add_actions", "(", "toolbar", ",", "actions", ")" ]
Add widget actions to toolbar
[ "Add", "widget", "actions", "to", "toolbar" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2486-L2490
30,903
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.show_dependencies
def show_dependencies(self): """Show Spyder's Dependencies dialog box""" from spyder.widgets.dependencies import DependenciesDialog dlg = DependenciesDialog(self) dlg.set_data(dependencies.DEPENDENCIES) dlg.exec_()
python
def show_dependencies(self): """Show Spyder's Dependencies dialog box""" from spyder.widgets.dependencies import DependenciesDialog dlg = DependenciesDialog(self) dlg.set_data(dependencies.DEPENDENCIES) dlg.exec_()
[ "def", "show_dependencies", "(", "self", ")", ":", "from", "spyder", ".", "widgets", ".", "dependencies", "import", "DependenciesDialog", "dlg", "=", "DependenciesDialog", "(", "self", ")", "dlg", ".", "set_data", "(", "dependencies", ".", "DEPENDENCIES", ")", ...
Show Spyder's Dependencies dialog box
[ "Show", "Spyder", "s", "Dependencies", "dialog", "box" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2593-L2598
30,904
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.report_issue
def report_issue(self, body=None, title=None, open_webpage=False): """Report a Spyder issue to github, generating body text if needed.""" if body is None: from spyder.widgets.reporterror import SpyderErrorDialog report_dlg = SpyderErrorDialog(self, is_report=True) report_dlg.show() else: if open_webpage: if PY3: from urllib.parse import quote else: from urllib import quote # analysis:ignore from qtpy.QtCore import QUrlQuery url = QUrl(__project_url__ + '/issues/new') query = QUrlQuery() query.addQueryItem("body", quote(body)) if title: query.addQueryItem("title", quote(title)) url.setQuery(query) QDesktopServices.openUrl(url)
python
def report_issue(self, body=None, title=None, open_webpage=False): """Report a Spyder issue to github, generating body text if needed.""" if body is None: from spyder.widgets.reporterror import SpyderErrorDialog report_dlg = SpyderErrorDialog(self, is_report=True) report_dlg.show() else: if open_webpage: if PY3: from urllib.parse import quote else: from urllib import quote # analysis:ignore from qtpy.QtCore import QUrlQuery url = QUrl(__project_url__ + '/issues/new') query = QUrlQuery() query.addQueryItem("body", quote(body)) if title: query.addQueryItem("title", quote(title)) url.setQuery(query) QDesktopServices.openUrl(url)
[ "def", "report_issue", "(", "self", ",", "body", "=", "None", ",", "title", "=", "None", ",", "open_webpage", "=", "False", ")", ":", "if", "body", "is", "None", ":", "from", "spyder", ".", "widgets", ".", "reporterror", "import", "SpyderErrorDialog", "r...
Report a Spyder issue to github, generating body text if needed.
[ "Report", "a", "Spyder", "issue", "to", "github", "generating", "body", "text", "if", "needed", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2657-L2677
30,905
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.open_external_console
def open_external_console(self, fname, wdir, args, interact, debug, python, python_args, systerm, post_mortem=False): """Open external console""" if systerm: # Running script in an external system terminal try: if CONF.get('main_interpreter', 'default'): executable = get_python_executable() else: executable = CONF.get('main_interpreter', 'executable') programs.run_python_script_in_terminal( fname, wdir, args, interact, debug, python_args, executable) except NotImplementedError: QMessageBox.critical(self, _("Run"), _("Running an external system terminal " "is not supported on platform %s." ) % os.name)
python
def open_external_console(self, fname, wdir, args, interact, debug, python, python_args, systerm, post_mortem=False): """Open external console""" if systerm: # Running script in an external system terminal try: if CONF.get('main_interpreter', 'default'): executable = get_python_executable() else: executable = CONF.get('main_interpreter', 'executable') programs.run_python_script_in_terminal( fname, wdir, args, interact, debug, python_args, executable) except NotImplementedError: QMessageBox.critical(self, _("Run"), _("Running an external system terminal " "is not supported on platform %s." ) % os.name)
[ "def", "open_external_console", "(", "self", ",", "fname", ",", "wdir", ",", "args", ",", "interact", ",", "debug", ",", "python", ",", "python_args", ",", "systerm", ",", "post_mortem", "=", "False", ")", ":", "if", "systerm", ":", "# Running script in an e...
Open external console
[ "Open", "external", "console" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2711-L2728
30,906
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.execute_in_external_console
def execute_in_external_console(self, lines, focus_to_editor): """ Execute lines in IPython console and eventually set focus to the Editor. """ console = self.ipyconsole console.switch_to_plugin() console.execute_code(lines) if focus_to_editor: self.editor.switch_to_plugin()
python
def execute_in_external_console(self, lines, focus_to_editor): """ Execute lines in IPython console and eventually set focus to the Editor. """ console = self.ipyconsole console.switch_to_plugin() console.execute_code(lines) if focus_to_editor: self.editor.switch_to_plugin()
[ "def", "execute_in_external_console", "(", "self", ",", "lines", ",", "focus_to_editor", ")", ":", "console", "=", "self", ".", "ipyconsole", "console", ".", "switch_to_plugin", "(", ")", "console", ".", "execute_code", "(", "lines", ")", "if", "focus_to_editor"...
Execute lines in IPython console and eventually set focus to the Editor.
[ "Execute", "lines", "in", "IPython", "console", "and", "eventually", "set", "focus", "to", "the", "Editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2730-L2739
30,907
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.open_external_file
def open_external_file(self, fname): """ Open external files that can be handled either by the Editor or the variable explorer inside Spyder. """ fname = encoding.to_unicode_from_fs(fname) if osp.isfile(fname): self.open_file(fname, external=True) elif osp.isfile(osp.join(CWD, fname)): self.open_file(osp.join(CWD, fname), external=True)
python
def open_external_file(self, fname): """ Open external files that can be handled either by the Editor or the variable explorer inside Spyder. """ fname = encoding.to_unicode_from_fs(fname) if osp.isfile(fname): self.open_file(fname, external=True) elif osp.isfile(osp.join(CWD, fname)): self.open_file(osp.join(CWD, fname), external=True)
[ "def", "open_external_file", "(", "self", ",", "fname", ")", ":", "fname", "=", "encoding", ".", "to_unicode_from_fs", "(", "fname", ")", "if", "osp", ".", "isfile", "(", "fname", ")", ":", "self", ".", "open_file", "(", "fname", ",", "external", "=", ...
Open external files that can be handled either by the Editor or the variable explorer inside Spyder.
[ "Open", "external", "files", "that", "can", "be", "handled", "either", "by", "the", "Editor", "or", "the", "variable", "explorer", "inside", "Spyder", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2757-L2766
30,908
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.get_spyder_pythonpath
def get_spyder_pythonpath(self): """Return Spyder PYTHONPATH""" active_path = [p for p in self.path if p not in self.not_active_path] return active_path + self.project_path
python
def get_spyder_pythonpath(self): """Return Spyder PYTHONPATH""" active_path = [p for p in self.path if p not in self.not_active_path] return active_path + self.project_path
[ "def", "get_spyder_pythonpath", "(", "self", ")", ":", "active_path", "=", "[", "p", "for", "p", "in", "self", ".", "path", "if", "p", "not", "in", "self", ".", "not_active_path", "]", "return", "active_path", "+", "self", ".", "project_path" ]
Return Spyder PYTHONPATH
[ "Return", "Spyder", "PYTHONPATH" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2769-L2772
30,909
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.add_path_to_sys_path
def add_path_to_sys_path(self): """Add Spyder path to sys.path""" for path in reversed(self.get_spyder_pythonpath()): sys.path.insert(1, path)
python
def add_path_to_sys_path(self): """Add Spyder path to sys.path""" for path in reversed(self.get_spyder_pythonpath()): sys.path.insert(1, path)
[ "def", "add_path_to_sys_path", "(", "self", ")", ":", "for", "path", "in", "reversed", "(", "self", ".", "get_spyder_pythonpath", "(", ")", ")", ":", "sys", ".", "path", ".", "insert", "(", "1", ",", "path", ")" ]
Add Spyder path to sys.path
[ "Add", "Spyder", "path", "to", "sys", ".", "path" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2774-L2777
30,910
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.remove_path_from_sys_path
def remove_path_from_sys_path(self): """Remove Spyder path from sys.path""" for path in self.path + self.project_path: while path in sys.path: sys.path.remove(path)
python
def remove_path_from_sys_path(self): """Remove Spyder path from sys.path""" for path in self.path + self.project_path: while path in sys.path: sys.path.remove(path)
[ "def", "remove_path_from_sys_path", "(", "self", ")", ":", "for", "path", "in", "self", ".", "path", "+", "self", ".", "project_path", ":", "while", "path", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "remove", "(", "path", ")" ]
Remove Spyder path from sys.path
[ "Remove", "Spyder", "path", "from", "sys", ".", "path" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2779-L2783
30,911
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.path_manager_callback
def path_manager_callback(self): """Spyder path manager""" from spyder.widgets.pathmanager import PathManager self.remove_path_from_sys_path() project_path = self.projects.get_pythonpath() dialog = PathManager(self, self.path, project_path, self.not_active_path, sync=True) dialog.redirect_stdio.connect(self.redirect_internalshell_stdio) dialog.exec_() self.add_path_to_sys_path() try: encoding.writelines(self.path, self.SPYDER_PATH) # Saving path encoding.writelines(self.not_active_path, self.SPYDER_NOT_ACTIVE_PATH) except EnvironmentError: pass self.sig_pythonpath_changed.emit()
python
def path_manager_callback(self): """Spyder path manager""" from spyder.widgets.pathmanager import PathManager self.remove_path_from_sys_path() project_path = self.projects.get_pythonpath() dialog = PathManager(self, self.path, project_path, self.not_active_path, sync=True) dialog.redirect_stdio.connect(self.redirect_internalshell_stdio) dialog.exec_() self.add_path_to_sys_path() try: encoding.writelines(self.path, self.SPYDER_PATH) # Saving path encoding.writelines(self.not_active_path, self.SPYDER_NOT_ACTIVE_PATH) except EnvironmentError: pass self.sig_pythonpath_changed.emit()
[ "def", "path_manager_callback", "(", "self", ")", ":", "from", "spyder", ".", "widgets", ".", "pathmanager", "import", "PathManager", "self", ".", "remove_path_from_sys_path", "(", ")", "project_path", "=", "self", ".", "projects", ".", "get_pythonpath", "(", ")...
Spyder path manager
[ "Spyder", "path", "manager" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2786-L2802
30,912
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.pythonpath_changed
def pythonpath_changed(self): """Projects PYTHONPATH contribution has changed""" self.remove_path_from_sys_path() self.project_path = self.projects.get_pythonpath() self.add_path_to_sys_path() self.sig_pythonpath_changed.emit()
python
def pythonpath_changed(self): """Projects PYTHONPATH contribution has changed""" self.remove_path_from_sys_path() self.project_path = self.projects.get_pythonpath() self.add_path_to_sys_path() self.sig_pythonpath_changed.emit()
[ "def", "pythonpath_changed", "(", "self", ")", ":", "self", ".", "remove_path_from_sys_path", "(", ")", "self", ".", "project_path", "=", "self", ".", "projects", ".", "get_pythonpath", "(", ")", "self", ".", "add_path_to_sys_path", "(", ")", "self", ".", "s...
Projects PYTHONPATH contribution has changed
[ "Projects", "PYTHONPATH", "contribution", "has", "changed" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2804-L2809
30,913
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.apply_settings
def apply_settings(self): """Apply settings changed in 'Preferences' dialog box""" qapp = QApplication.instance() # Set 'gtk+' as the default theme in Gtk-based desktops # Fixes Issue 2036 if is_gtk_desktop() and ('GTK+' in QStyleFactory.keys()): try: qapp.setStyle('gtk+') except: pass else: style_name = CONF.get('appearance', 'windows_style', self.default_style) style = QStyleFactory.create(style_name) if style is not None: style.setProperty('name', style_name) qapp.setStyle(style) default = self.DOCKOPTIONS if CONF.get('main', 'vertical_tabs'): default = default|QMainWindow.VerticalTabs if CONF.get('main', 'animated_docks'): default = default|QMainWindow.AnimatedDocks self.setDockOptions(default) self.apply_panes_settings() self.apply_statusbar_settings() if CONF.get('main', 'use_custom_cursor_blinking'): qapp.setCursorFlashTime(CONF.get('main', 'custom_cursor_blinking')) else: qapp.setCursorFlashTime(self.CURSORBLINK_OSDEFAULT)
python
def apply_settings(self): """Apply settings changed in 'Preferences' dialog box""" qapp = QApplication.instance() # Set 'gtk+' as the default theme in Gtk-based desktops # Fixes Issue 2036 if is_gtk_desktop() and ('GTK+' in QStyleFactory.keys()): try: qapp.setStyle('gtk+') except: pass else: style_name = CONF.get('appearance', 'windows_style', self.default_style) style = QStyleFactory.create(style_name) if style is not None: style.setProperty('name', style_name) qapp.setStyle(style) default = self.DOCKOPTIONS if CONF.get('main', 'vertical_tabs'): default = default|QMainWindow.VerticalTabs if CONF.get('main', 'animated_docks'): default = default|QMainWindow.AnimatedDocks self.setDockOptions(default) self.apply_panes_settings() self.apply_statusbar_settings() if CONF.get('main', 'use_custom_cursor_blinking'): qapp.setCursorFlashTime(CONF.get('main', 'custom_cursor_blinking')) else: qapp.setCursorFlashTime(self.CURSORBLINK_OSDEFAULT)
[ "def", "apply_settings", "(", "self", ")", ":", "qapp", "=", "QApplication", ".", "instance", "(", ")", "# Set 'gtk+' as the default theme in Gtk-based desktops\r", "# Fixes Issue 2036\r", "if", "is_gtk_desktop", "(", ")", "and", "(", "'GTK+'", "in", "QStyleFactory", ...
Apply settings changed in 'Preferences' dialog box
[ "Apply", "settings", "changed", "in", "Preferences", "dialog", "box" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2817-L2848
30,914
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.apply_panes_settings
def apply_panes_settings(self): """Update dockwidgets features settings""" for plugin in (self.widgetlist + self.thirdparty_plugins): features = plugin.FEATURES if CONF.get('main', 'vertical_dockwidget_titlebars'): features = features | QDockWidget.DockWidgetVerticalTitleBar plugin.dockwidget.setFeatures(features) plugin.update_margins()
python
def apply_panes_settings(self): """Update dockwidgets features settings""" for plugin in (self.widgetlist + self.thirdparty_plugins): features = plugin.FEATURES if CONF.get('main', 'vertical_dockwidget_titlebars'): features = features | QDockWidget.DockWidgetVerticalTitleBar plugin.dockwidget.setFeatures(features) plugin.update_margins()
[ "def", "apply_panes_settings", "(", "self", ")", ":", "for", "plugin", "in", "(", "self", ".", "widgetlist", "+", "self", ".", "thirdparty_plugins", ")", ":", "features", "=", "plugin", ".", "FEATURES", "if", "CONF", ".", "get", "(", "'main'", ",", "'ver...
Update dockwidgets features settings
[ "Update", "dockwidgets", "features", "settings" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2850-L2857
30,915
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.apply_statusbar_settings
def apply_statusbar_settings(self): """Update status bar widgets settings""" show_status_bar = CONF.get('main', 'show_status_bar') self.statusBar().setVisible(show_status_bar) if show_status_bar: for widget, name in ((self.mem_status, 'memory_usage'), (self.cpu_status, 'cpu_usage')): if widget is not None: widget.setVisible(CONF.get('main', '%s/enable' % name)) widget.set_interval(CONF.get('main', '%s/timeout' % name)) else: return
python
def apply_statusbar_settings(self): """Update status bar widgets settings""" show_status_bar = CONF.get('main', 'show_status_bar') self.statusBar().setVisible(show_status_bar) if show_status_bar: for widget, name in ((self.mem_status, 'memory_usage'), (self.cpu_status, 'cpu_usage')): if widget is not None: widget.setVisible(CONF.get('main', '%s/enable' % name)) widget.set_interval(CONF.get('main', '%s/timeout' % name)) else: return
[ "def", "apply_statusbar_settings", "(", "self", ")", ":", "show_status_bar", "=", "CONF", ".", "get", "(", "'main'", ",", "'show_status_bar'", ")", "self", ".", "statusBar", "(", ")", ".", "setVisible", "(", "show_status_bar", ")", "if", "show_status_bar", ":"...
Update status bar widgets settings
[ "Update", "status", "bar", "widgets", "settings" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2859-L2871
30,916
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.edit_preferences
def edit_preferences(self): """Edit Spyder preferences""" from spyder.preferences.configdialog import ConfigDialog dlg = ConfigDialog(self) dlg.size_change.connect(self.set_prefs_size) if self.prefs_dialog_size is not None: dlg.resize(self.prefs_dialog_size) for PrefPageClass in self.general_prefs: widget = PrefPageClass(dlg, main=self) widget.initialize() dlg.add_page(widget) for plugin in [self.workingdirectory, self.editor, self.projects, self.ipyconsole, self.historylog, self.help, self.variableexplorer, self.onlinehelp, self.explorer, self.findinfiles ]+self.thirdparty_plugins: if plugin is not None: try: widget = plugin.create_configwidget(dlg) if widget is not None: dlg.add_page(widget) except Exception: traceback.print_exc(file=sys.stderr) if self.prefs_index is not None: dlg.set_current_index(self.prefs_index) dlg.show() dlg.check_all_settings() dlg.pages_widget.currentChanged.connect(self.__preference_page_changed) dlg.exec_()
python
def edit_preferences(self): """Edit Spyder preferences""" from spyder.preferences.configdialog import ConfigDialog dlg = ConfigDialog(self) dlg.size_change.connect(self.set_prefs_size) if self.prefs_dialog_size is not None: dlg.resize(self.prefs_dialog_size) for PrefPageClass in self.general_prefs: widget = PrefPageClass(dlg, main=self) widget.initialize() dlg.add_page(widget) for plugin in [self.workingdirectory, self.editor, self.projects, self.ipyconsole, self.historylog, self.help, self.variableexplorer, self.onlinehelp, self.explorer, self.findinfiles ]+self.thirdparty_plugins: if plugin is not None: try: widget = plugin.create_configwidget(dlg) if widget is not None: dlg.add_page(widget) except Exception: traceback.print_exc(file=sys.stderr) if self.prefs_index is not None: dlg.set_current_index(self.prefs_index) dlg.show() dlg.check_all_settings() dlg.pages_widget.currentChanged.connect(self.__preference_page_changed) dlg.exec_()
[ "def", "edit_preferences", "(", "self", ")", ":", "from", "spyder", ".", "preferences", ".", "configdialog", "import", "ConfigDialog", "dlg", "=", "ConfigDialog", "(", "self", ")", "dlg", ".", "size_change", ".", "connect", "(", "self", ".", "set_prefs_size", ...
Edit Spyder preferences
[ "Edit", "Spyder", "preferences" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2874-L2902
30,917
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.reset_spyder
def reset_spyder(self): """ Quit and reset Spyder and then Restart application. """ answer = QMessageBox.warning(self, _("Warning"), _("Spyder will restart and reset to default settings: <br><br>" "Do you want to continue?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: self.restart(reset=True)
python
def reset_spyder(self): """ Quit and reset Spyder and then Restart application. """ answer = QMessageBox.warning(self, _("Warning"), _("Spyder will restart and reset to default settings: <br><br>" "Do you want to continue?"), QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.Yes: self.restart(reset=True)
[ "def", "reset_spyder", "(", "self", ")", ":", "answer", "=", "QMessageBox", ".", "warning", "(", "self", ",", "_", "(", "\"Warning\"", ")", ",", "_", "(", "\"Spyder will restart and reset to default settings: <br><br>\"", "\"Do you want to continue?\"", ")", ",", "Q...
Quit and reset Spyder and then Restart application.
[ "Quit", "and", "reset", "Spyder", "and", "then", "Restart", "application", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2982-L2991
30,918
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.restart
def restart(self, reset=False): """ Quit and Restart Spyder application. If reset True it allows to reset spyder on restart. """ # Get start path to use in restart script spyder_start_directory = get_module_path('spyder') restart_script = osp.join(spyder_start_directory, 'app', 'restart.py') # Get any initial argument passed when spyder was started # Note: Variables defined in bootstrap.py and spyder/app/start.py env = os.environ.copy() bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None) spyder_args = env.pop('SPYDER_ARGS') # Get current process and python running spyder pid = os.getpid() python = sys.executable # Check if started with bootstrap.py if bootstrap_args is not None: spyder_args = bootstrap_args is_bootstrap = True else: is_bootstrap = False # Pass variables as environment variables (str) to restarter subprocess env['SPYDER_ARGS'] = spyder_args env['SPYDER_PID'] = str(pid) env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap) env['SPYDER_RESET'] = str(reset) if DEV: if os.name == 'nt': env['PYTHONPATH'] = ';'.join(sys.path) else: env['PYTHONPATH'] = ':'.join(sys.path) # Build the command and popen arguments depending on the OS if os.name == 'nt': # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW shell = False else: startupinfo = None shell = True command = '"{0}" "{1}"' command = command.format(python, restart_script) try: if self.closing(True): subprocess.Popen(command, shell=shell, env=env, startupinfo=startupinfo) self.console.quit() except Exception as error: # If there is an error with subprocess, Spyder should not quit and # the error can be inspected in the internal console print(error) # spyder: test-skip print(command)
python
def restart(self, reset=False): """ Quit and Restart Spyder application. If reset True it allows to reset spyder on restart. """ # Get start path to use in restart script spyder_start_directory = get_module_path('spyder') restart_script = osp.join(spyder_start_directory, 'app', 'restart.py') # Get any initial argument passed when spyder was started # Note: Variables defined in bootstrap.py and spyder/app/start.py env = os.environ.copy() bootstrap_args = env.pop('SPYDER_BOOTSTRAP_ARGS', None) spyder_args = env.pop('SPYDER_ARGS') # Get current process and python running spyder pid = os.getpid() python = sys.executable # Check if started with bootstrap.py if bootstrap_args is not None: spyder_args = bootstrap_args is_bootstrap = True else: is_bootstrap = False # Pass variables as environment variables (str) to restarter subprocess env['SPYDER_ARGS'] = spyder_args env['SPYDER_PID'] = str(pid) env['SPYDER_IS_BOOTSTRAP'] = str(is_bootstrap) env['SPYDER_RESET'] = str(reset) if DEV: if os.name == 'nt': env['PYTHONPATH'] = ';'.join(sys.path) else: env['PYTHONPATH'] = ':'.join(sys.path) # Build the command and popen arguments depending on the OS if os.name == 'nt': # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW shell = False else: startupinfo = None shell = True command = '"{0}" "{1}"' command = command.format(python, restart_script) try: if self.closing(True): subprocess.Popen(command, shell=shell, env=env, startupinfo=startupinfo) self.console.quit() except Exception as error: # If there is an error with subprocess, Spyder should not quit and # the error can be inspected in the internal console print(error) # spyder: test-skip print(command)
[ "def", "restart", "(", "self", ",", "reset", "=", "False", ")", ":", "# Get start path to use in restart script\r", "spyder_start_directory", "=", "get_module_path", "(", "'spyder'", ")", "restart_script", "=", "osp", ".", "join", "(", "spyder_start_directory", ",", ...
Quit and Restart Spyder application. If reset True it allows to reset spyder on restart.
[ "Quit", "and", "Restart", "Spyder", "application", ".", "If", "reset", "True", "it", "allows", "to", "reset", "spyder", "on", "restart", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2994-L3055
30,919
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.show_tour
def show_tour(self, index): """Show interactive tour.""" self.maximize_dockwidget(restore=True) frames = self.tours_available[index] self.tour.set_tour(index, frames, self) self.tour.start_tour()
python
def show_tour(self, index): """Show interactive tour.""" self.maximize_dockwidget(restore=True) frames = self.tours_available[index] self.tour.set_tour(index, frames, self) self.tour.start_tour()
[ "def", "show_tour", "(", "self", ",", "index", ")", ":", "self", ".", "maximize_dockwidget", "(", "restore", "=", "True", ")", "frames", "=", "self", ".", "tours_available", "[", "index", "]", "self", ".", "tour", ".", "set_tour", "(", "index", ",", "f...
Show interactive tour.
[ "Show", "interactive", "tour", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L3058-L3063
30,920
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.open_fileswitcher
def open_fileswitcher(self, symbol=False): """Open file list management dialog box.""" if self.fileswitcher is not None and \ self.fileswitcher.is_visible: self.fileswitcher.hide() self.fileswitcher.is_visible = False return if symbol: self.fileswitcher.plugin = self.editor self.fileswitcher.set_search_text('@') else: self.fileswitcher.set_search_text('') self.fileswitcher.show() self.fileswitcher.is_visible = True
python
def open_fileswitcher(self, symbol=False): """Open file list management dialog box.""" if self.fileswitcher is not None and \ self.fileswitcher.is_visible: self.fileswitcher.hide() self.fileswitcher.is_visible = False return if symbol: self.fileswitcher.plugin = self.editor self.fileswitcher.set_search_text('@') else: self.fileswitcher.set_search_text('') self.fileswitcher.show() self.fileswitcher.is_visible = True
[ "def", "open_fileswitcher", "(", "self", ",", "symbol", "=", "False", ")", ":", "if", "self", ".", "fileswitcher", "is", "not", "None", "and", "self", ".", "fileswitcher", ".", "is_visible", ":", "self", ".", "fileswitcher", ".", "hide", "(", ")", "self"...
Open file list management dialog box.
[ "Open", "file", "list", "management", "dialog", "box", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L3066-L3079
30,921
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.add_to_fileswitcher
def add_to_fileswitcher(self, plugin, tabs, data, icon): """Add a plugin to the File Switcher.""" if self.fileswitcher is None: from spyder.widgets.fileswitcher import FileSwitcher self.fileswitcher = FileSwitcher(self, plugin, tabs, data, icon) else: self.fileswitcher.add_plugin(plugin, tabs, data, icon) self.fileswitcher.sig_goto_file.connect( plugin.get_current_tab_manager().set_stack_index)
python
def add_to_fileswitcher(self, plugin, tabs, data, icon): """Add a plugin to the File Switcher.""" if self.fileswitcher is None: from spyder.widgets.fileswitcher import FileSwitcher self.fileswitcher = FileSwitcher(self, plugin, tabs, data, icon) else: self.fileswitcher.add_plugin(plugin, tabs, data, icon) self.fileswitcher.sig_goto_file.connect( plugin.get_current_tab_manager().set_stack_index)
[ "def", "add_to_fileswitcher", "(", "self", ",", "plugin", ",", "tabs", ",", "data", ",", "icon", ")", ":", "if", "self", ".", "fileswitcher", "is", "None", ":", "from", "spyder", ".", "widgets", ".", "fileswitcher", "import", "FileSwitcher", "self", ".", ...
Add a plugin to the File Switcher.
[ "Add", "a", "plugin", "to", "the", "File", "Switcher", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L3085-L3094
30,922
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow._check_updates_ready
def _check_updates_ready(self): """Called by WorkerUpdates when ready""" from spyder.widgets.helperwidgets import MessageCheckBox # feedback` = False is used on startup, so only positive feedback is # given. `feedback` = True is used when after startup (when using the # menu action, and gives feeback if updates are, or are not found. feedback = self.give_updates_feedback # Get results from worker update_available = self.worker_updates.update_available latest_release = self.worker_updates.latest_release error_msg = self.worker_updates.error url_r = __project_url__ + '/releases' url_i = 'https://docs.spyder-ide.org/installation.html' # Define the custom QMessageBox box = MessageCheckBox(icon=QMessageBox.Information, parent=self) box.setWindowTitle(_("Spyder updates")) box.set_checkbox_text(_("Check for updates on startup")) box.setStandardButtons(QMessageBox.Ok) box.setDefaultButton(QMessageBox.Ok) # Adjust the checkbox depending on the stored configuration section, option = 'main', 'check_updates_on_startup' check_updates = CONF.get(section, option) box.set_checked(check_updates) if error_msg is not None: msg = error_msg box.setText(msg) box.set_check_visible(False) box.exec_() check_updates = box.is_checked() else: if update_available: anaconda_msg = '' if 'Anaconda' in sys.version or 'conda-forge' in sys.version: anaconda_msg = _("<hr><b>IMPORTANT NOTE:</b> It seems " "that you are using Spyder with " "<b>Anaconda/Miniconda</b>. Please " "<b>don't</b> use <code>pip</code> to " "update it as that will probably break " "your installation.<br><br>" "Instead, please wait until new conda " "packages are available and use " "<code>conda</code> to perform the " "update.<hr>") msg = _("<b>Spyder %s is available!</b> <br><br>Please use " "your package manager to update Spyder or go to our " "<a href=\"%s\">Releases</a> page to download this " "new version. <br><br>If you are not sure how to " "proceed to update Spyder please refer to our " " <a href=\"%s\">Installation</a> instructions." "") % (latest_release, url_r, url_i) msg += '<br>' + anaconda_msg box.setText(msg) box.set_check_visible(True) box.exec_() check_updates = box.is_checked() elif feedback: msg = _("Spyder is up to date.") box.setText(msg) box.set_check_visible(False) box.exec_() check_updates = box.is_checked() # Update checkbox based on user interaction CONF.set(section, option, check_updates) # Enable check_updates_action after the thread has finished self.check_updates_action.setDisabled(False) # Provide feeback when clicking menu if check on startup is on self.give_updates_feedback = True
python
def _check_updates_ready(self): """Called by WorkerUpdates when ready""" from spyder.widgets.helperwidgets import MessageCheckBox # feedback` = False is used on startup, so only positive feedback is # given. `feedback` = True is used when after startup (when using the # menu action, and gives feeback if updates are, or are not found. feedback = self.give_updates_feedback # Get results from worker update_available = self.worker_updates.update_available latest_release = self.worker_updates.latest_release error_msg = self.worker_updates.error url_r = __project_url__ + '/releases' url_i = 'https://docs.spyder-ide.org/installation.html' # Define the custom QMessageBox box = MessageCheckBox(icon=QMessageBox.Information, parent=self) box.setWindowTitle(_("Spyder updates")) box.set_checkbox_text(_("Check for updates on startup")) box.setStandardButtons(QMessageBox.Ok) box.setDefaultButton(QMessageBox.Ok) # Adjust the checkbox depending on the stored configuration section, option = 'main', 'check_updates_on_startup' check_updates = CONF.get(section, option) box.set_checked(check_updates) if error_msg is not None: msg = error_msg box.setText(msg) box.set_check_visible(False) box.exec_() check_updates = box.is_checked() else: if update_available: anaconda_msg = '' if 'Anaconda' in sys.version or 'conda-forge' in sys.version: anaconda_msg = _("<hr><b>IMPORTANT NOTE:</b> It seems " "that you are using Spyder with " "<b>Anaconda/Miniconda</b>. Please " "<b>don't</b> use <code>pip</code> to " "update it as that will probably break " "your installation.<br><br>" "Instead, please wait until new conda " "packages are available and use " "<code>conda</code> to perform the " "update.<hr>") msg = _("<b>Spyder %s is available!</b> <br><br>Please use " "your package manager to update Spyder or go to our " "<a href=\"%s\">Releases</a> page to download this " "new version. <br><br>If you are not sure how to " "proceed to update Spyder please refer to our " " <a href=\"%s\">Installation</a> instructions." "") % (latest_release, url_r, url_i) msg += '<br>' + anaconda_msg box.setText(msg) box.set_check_visible(True) box.exec_() check_updates = box.is_checked() elif feedback: msg = _("Spyder is up to date.") box.setText(msg) box.set_check_visible(False) box.exec_() check_updates = box.is_checked() # Update checkbox based on user interaction CONF.set(section, option, check_updates) # Enable check_updates_action after the thread has finished self.check_updates_action.setDisabled(False) # Provide feeback when clicking menu if check on startup is on self.give_updates_feedback = True
[ "def", "_check_updates_ready", "(", "self", ")", ":", "from", "spyder", ".", "widgets", ".", "helperwidgets", "import", "MessageCheckBox", "# feedback` = False is used on startup, so only positive feedback is\r", "# given. `feedback` = True is used when after startup (when using the\r"...
Called by WorkerUpdates when ready
[ "Called", "by", "WorkerUpdates", "when", "ready" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L3097-L3173
30,923
spyder-ide/spyder
spyder/app/mainwindow.py
MainWindow.check_updates
def check_updates(self, startup=False): """ Check for spyder updates on github releases using a QThread. """ from spyder.workers.updates import WorkerUpdates # Disable check_updates_action while the thread is working self.check_updates_action.setDisabled(True) if self.thread_updates is not None: self.thread_updates.terminate() self.thread_updates = QThread(self) self.worker_updates = WorkerUpdates(self, startup=startup) self.worker_updates.sig_ready.connect(self._check_updates_ready) self.worker_updates.sig_ready.connect(self.thread_updates.quit) self.worker_updates.moveToThread(self.thread_updates) self.thread_updates.started.connect(self.worker_updates.start) self.thread_updates.start()
python
def check_updates(self, startup=False): """ Check for spyder updates on github releases using a QThread. """ from spyder.workers.updates import WorkerUpdates # Disable check_updates_action while the thread is working self.check_updates_action.setDisabled(True) if self.thread_updates is not None: self.thread_updates.terminate() self.thread_updates = QThread(self) self.worker_updates = WorkerUpdates(self, startup=startup) self.worker_updates.sig_ready.connect(self._check_updates_ready) self.worker_updates.sig_ready.connect(self.thread_updates.quit) self.worker_updates.moveToThread(self.thread_updates) self.thread_updates.started.connect(self.worker_updates.start) self.thread_updates.start()
[ "def", "check_updates", "(", "self", ",", "startup", "=", "False", ")", ":", "from", "spyder", ".", "workers", ".", "updates", "import", "WorkerUpdates", "# Disable check_updates_action while the thread is working\r", "self", ".", "check_updates_action", ".", "setDisabl...
Check for spyder updates on github releases using a QThread.
[ "Check", "for", "spyder", "updates", "on", "github", "releases", "using", "a", "QThread", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L3176-L3194
30,924
spyder-ide/spyder
spyder/config/user.py
DefaultsConfig._set
def _set(self, section, option, value, verbose): """ Private set method """ if not self.has_section(section): self.add_section( section ) if not is_text_string(value): value = repr( value ) if verbose: print('%s[ %s ] = %s' % (section, option, value)) # spyder: test-skip cp.ConfigParser.set(self, section, option, value)
python
def _set(self, section, option, value, verbose): """ Private set method """ if not self.has_section(section): self.add_section( section ) if not is_text_string(value): value = repr( value ) if verbose: print('%s[ %s ] = %s' % (section, option, value)) # spyder: test-skip cp.ConfigParser.set(self, section, option, value)
[ "def", "_set", "(", "self", ",", "section", ",", "option", ",", "value", ",", "verbose", ")", ":", "if", "not", "self", ".", "has_section", "(", "section", ")", ":", "self", ".", "add_section", "(", "section", ")", "if", "not", "is_text_string", "(", ...
Private set method
[ "Private", "set", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L79-L89
30,925
spyder-ide/spyder
spyder/config/user.py
DefaultsConfig._save
def _save(self): """ Save config into the associated .ini file """ # See Issue 1086 and 1242 for background on why this # method contains all the exception handling. fname = self.filename() def _write_file(fname): if PY2: # Python 2 with codecs.open(fname, 'w', encoding='utf-8') as configfile: self._write(configfile) else: # Python 3 with open(fname, 'w', encoding='utf-8') as configfile: self.write(configfile) try: # the "easy" way _write_file(fname) except EnvironmentError: try: # the "delete and sleep" way if osp.isfile(fname): os.remove(fname) time.sleep(0.05) _write_file(fname) except Exception as e: print("Failed to write user configuration file to disk, with " "the exception shown below") # spyder: test-skip print(e)
python
def _save(self): """ Save config into the associated .ini file """ # See Issue 1086 and 1242 for background on why this # method contains all the exception handling. fname = self.filename() def _write_file(fname): if PY2: # Python 2 with codecs.open(fname, 'w', encoding='utf-8') as configfile: self._write(configfile) else: # Python 3 with open(fname, 'w', encoding='utf-8') as configfile: self.write(configfile) try: # the "easy" way _write_file(fname) except EnvironmentError: try: # the "delete and sleep" way if osp.isfile(fname): os.remove(fname) time.sleep(0.05) _write_file(fname) except Exception as e: print("Failed to write user configuration file to disk, with " "the exception shown below") # spyder: test-skip print(e)
[ "def", "_save", "(", "self", ")", ":", "# See Issue 1086 and 1242 for background on why this\r", "# method contains all the exception handling.\r", "fname", "=", "self", ".", "filename", "(", ")", "def", "_write_file", "(", "fname", ")", ":", "if", "PY2", ":", "# Pyth...
Save config into the associated .ini file
[ "Save", "config", "into", "the", "associated", ".", "ini", "file" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L91-L120
30,926
spyder-ide/spyder
spyder/config/user.py
DefaultsConfig.filename
def filename(self): """Defines the name of the configuration file to use.""" # Needs to be done this way to be used by the project config. # To fix on a later PR self._filename = getattr(self, '_filename', None) self._root_path = getattr(self, '_root_path', None) if self._filename is None and self._root_path is None: return self._filename_global() else: return self._filename_projects()
python
def filename(self): """Defines the name of the configuration file to use.""" # Needs to be done this way to be used by the project config. # To fix on a later PR self._filename = getattr(self, '_filename', None) self._root_path = getattr(self, '_root_path', None) if self._filename is None and self._root_path is None: return self._filename_global() else: return self._filename_projects()
[ "def", "filename", "(", "self", ")", ":", "# Needs to be done this way to be used by the project config.\r", "# To fix on a later PR\r", "self", ".", "_filename", "=", "getattr", "(", "self", ",", "'_filename'", ",", "None", ")", "self", ".", "_root_path", "=", "getat...
Defines the name of the configuration file to use.
[ "Defines", "the", "name", "of", "the", "configuration", "file", "to", "use", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L122-L132
30,927
spyder-ide/spyder
spyder/config/user.py
DefaultsConfig._filename_global
def _filename_global(self): """Create a .ini filename located in user home directory. This .ini files stores the global spyder preferences. """ if self.subfolder is None: config_file = osp.join(get_home_dir(), '.%s.ini' % self.name) return config_file else: folder = get_conf_path() # Save defaults in a "defaults" dir of .spyder2 to not pollute it if 'defaults' in self.name: folder = osp.join(folder, 'defaults') if not osp.isdir(folder): os.mkdir(folder) config_file = osp.join(folder, '%s.ini' % self.name) return config_file
python
def _filename_global(self): """Create a .ini filename located in user home directory. This .ini files stores the global spyder preferences. """ if self.subfolder is None: config_file = osp.join(get_home_dir(), '.%s.ini' % self.name) return config_file else: folder = get_conf_path() # Save defaults in a "defaults" dir of .spyder2 to not pollute it if 'defaults' in self.name: folder = osp.join(folder, 'defaults') if not osp.isdir(folder): os.mkdir(folder) config_file = osp.join(folder, '%s.ini' % self.name) return config_file
[ "def", "_filename_global", "(", "self", ")", ":", "if", "self", ".", "subfolder", "is", "None", ":", "config_file", "=", "osp", ".", "join", "(", "get_home_dir", "(", ")", ",", "'.%s.ini'", "%", "self", ".", "name", ")", "return", "config_file", "else", ...
Create a .ini filename located in user home directory. This .ini files stores the global spyder preferences.
[ "Create", "a", ".", "ini", "filename", "located", "in", "user", "home", "directory", ".", "This", ".", "ini", "files", "stores", "the", "global", "spyder", "preferences", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L141-L156
30,928
spyder-ide/spyder
spyder/config/user.py
UserConfig.load_from_ini
def load_from_ini(self): """ Load config from the associated .ini file """ try: if PY2: # Python 2 fname = self.filename() if osp.isfile(fname): try: with codecs.open(fname, encoding='utf-8') as configfile: self.readfp(configfile) except IOError: print("Failed reading file", fname) # spyder: test-skip else: # Python 3 self.read(self.filename(), encoding='utf-8') except cp.MissingSectionHeaderError: print("Warning: File contains no section headers.")
python
def load_from_ini(self): """ Load config from the associated .ini file """ try: if PY2: # Python 2 fname = self.filename() if osp.isfile(fname): try: with codecs.open(fname, encoding='utf-8') as configfile: self.readfp(configfile) except IOError: print("Failed reading file", fname) # spyder: test-skip else: # Python 3 self.read(self.filename(), encoding='utf-8') except cp.MissingSectionHeaderError: print("Warning: File contains no section headers.")
[ "def", "load_from_ini", "(", "self", ")", ":", "try", ":", "if", "PY2", ":", "# Python 2\r", "fname", "=", "self", ".", "filename", "(", ")", "if", "osp", ".", "isfile", "(", "fname", ")", ":", "try", ":", "with", "codecs", ".", "open", "(", "fname...
Load config from the associated .ini file
[ "Load", "config", "from", "the", "associated", ".", "ini", "file" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L243-L261
30,929
spyder-ide/spyder
spyder/config/user.py
UserConfig._load_old_defaults
def _load_old_defaults(self, old_version): """Read old defaults""" old_defaults = cp.ConfigParser() if check_version(old_version, '3.0.0', '<='): path = get_module_source_path('spyder') else: path = osp.dirname(self.filename()) path = osp.join(path, 'defaults') old_defaults.read(osp.join(path, 'defaults-'+old_version+'.ini')) return old_defaults
python
def _load_old_defaults(self, old_version): """Read old defaults""" old_defaults = cp.ConfigParser() if check_version(old_version, '3.0.0', '<='): path = get_module_source_path('spyder') else: path = osp.dirname(self.filename()) path = osp.join(path, 'defaults') old_defaults.read(osp.join(path, 'defaults-'+old_version+'.ini')) return old_defaults
[ "def", "_load_old_defaults", "(", "self", ",", "old_version", ")", ":", "old_defaults", "=", "cp", ".", "ConfigParser", "(", ")", "if", "check_version", "(", "old_version", ",", "'3.0.0'", ",", "'<='", ")", ":", "path", "=", "get_module_source_path", "(", "'...
Read old defaults
[ "Read", "old", "defaults" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L263-L272
30,930
spyder-ide/spyder
spyder/config/user.py
UserConfig._save_new_defaults
def _save_new_defaults(self, defaults, new_version, subfolder): """Save new defaults""" new_defaults = DefaultsConfig(name='defaults-'+new_version, subfolder=subfolder) if not osp.isfile(new_defaults.filename()): new_defaults.set_defaults(defaults) new_defaults._save()
python
def _save_new_defaults(self, defaults, new_version, subfolder): """Save new defaults""" new_defaults = DefaultsConfig(name='defaults-'+new_version, subfolder=subfolder) if not osp.isfile(new_defaults.filename()): new_defaults.set_defaults(defaults) new_defaults._save()
[ "def", "_save_new_defaults", "(", "self", ",", "defaults", ",", "new_version", ",", "subfolder", ")", ":", "new_defaults", "=", "DefaultsConfig", "(", "name", "=", "'defaults-'", "+", "new_version", ",", "subfolder", "=", "subfolder", ")", "if", "not", "osp", ...
Save new defaults
[ "Save", "new", "defaults" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L274-L280
30,931
spyder-ide/spyder
spyder/config/user.py
UserConfig._update_defaults
def _update_defaults(self, defaults, old_version, verbose=False): """Update defaults after a change in version""" old_defaults = self._load_old_defaults(old_version) for section, options in defaults: for option in options: new_value = options[ option ] try: old_value = old_defaults.get(section, option) except (cp.NoSectionError, cp.NoOptionError): old_value = None if old_value is None or \ to_text_string(new_value) != old_value: self._set(section, option, new_value, verbose)
python
def _update_defaults(self, defaults, old_version, verbose=False): """Update defaults after a change in version""" old_defaults = self._load_old_defaults(old_version) for section, options in defaults: for option in options: new_value = options[ option ] try: old_value = old_defaults.get(section, option) except (cp.NoSectionError, cp.NoOptionError): old_value = None if old_value is None or \ to_text_string(new_value) != old_value: self._set(section, option, new_value, verbose)
[ "def", "_update_defaults", "(", "self", ",", "defaults", ",", "old_version", ",", "verbose", "=", "False", ")", ":", "old_defaults", "=", "self", ".", "_load_old_defaults", "(", "old_version", ")", "for", "section", ",", "options", "in", "defaults", ":", "fo...
Update defaults after a change in version
[ "Update", "defaults", "after", "a", "change", "in", "version" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L282-L294
30,932
spyder-ide/spyder
spyder/config/user.py
UserConfig._remove_deprecated_options
def _remove_deprecated_options(self, old_version): """ Remove options which are present in the .ini file but not in defaults """ old_defaults = self._load_old_defaults(old_version) for section in old_defaults.sections(): for option, _ in old_defaults.items(section, raw=self.raw): if self.get_default(section, option) is NoDefault: try: self.remove_option(section, option) if len(self.items(section, raw=self.raw)) == 0: self.remove_section(section) except cp.NoSectionError: self.remove_section(section)
python
def _remove_deprecated_options(self, old_version): """ Remove options which are present in the .ini file but not in defaults """ old_defaults = self._load_old_defaults(old_version) for section in old_defaults.sections(): for option, _ in old_defaults.items(section, raw=self.raw): if self.get_default(section, option) is NoDefault: try: self.remove_option(section, option) if len(self.items(section, raw=self.raw)) == 0: self.remove_section(section) except cp.NoSectionError: self.remove_section(section)
[ "def", "_remove_deprecated_options", "(", "self", ",", "old_version", ")", ":", "old_defaults", "=", "self", ".", "_load_old_defaults", "(", "old_version", ")", "for", "section", "in", "old_defaults", ".", "sections", "(", ")", ":", "for", "option", ",", "_", ...
Remove options which are present in the .ini file but not in defaults
[ "Remove", "options", "which", "are", "present", "in", "the", ".", "ini", "file", "but", "not", "in", "defaults" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L296-L309
30,933
spyder-ide/spyder
spyder/config/user.py
UserConfig.set_as_defaults
def set_as_defaults(self): """ Set defaults from the current config """ self.defaults = [] for section in self.sections(): secdict = {} for option, value in self.items(section, raw=self.raw): secdict[option] = value self.defaults.append( (section, secdict) )
python
def set_as_defaults(self): """ Set defaults from the current config """ self.defaults = [] for section in self.sections(): secdict = {} for option, value in self.items(section, raw=self.raw): secdict[option] = value self.defaults.append( (section, secdict) )
[ "def", "set_as_defaults", "(", "self", ")", ":", "self", ".", "defaults", "=", "[", "]", "for", "section", "in", "self", ".", "sections", "(", ")", ":", "secdict", "=", "{", "}", "for", "option", ",", "value", "in", "self", ".", "items", "(", "sect...
Set defaults from the current config
[ "Set", "defaults", "from", "the", "current", "config" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L317-L326
30,934
spyder-ide/spyder
spyder/config/user.py
UserConfig.reset_to_defaults
def reset_to_defaults(self, save=True, verbose=False, section=None): """ Reset config to Default values """ for sec, options in self.defaults: if section == None or section == sec: for option in options: value = options[ option ] self._set(sec, option, value, verbose) if save: self._save()
python
def reset_to_defaults(self, save=True, verbose=False, section=None): """ Reset config to Default values """ for sec, options in self.defaults: if section == None or section == sec: for option in options: value = options[ option ] self._set(sec, option, value, verbose) if save: self._save()
[ "def", "reset_to_defaults", "(", "self", ",", "save", "=", "True", ",", "verbose", "=", "False", ",", "section", "=", "None", ")", ":", "for", "sec", ",", "options", "in", "self", ".", "defaults", ":", "if", "section", "==", "None", "or", "section", ...
Reset config to Default values
[ "Reset", "config", "to", "Default", "values" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L328-L338
30,935
spyder-ide/spyder
spyder/config/user.py
UserConfig._check_section_option
def _check_section_option(self, section, option): """ Private method to check section and option types """ if section is None: section = self.DEFAULT_SECTION_NAME elif not is_text_string(section): raise RuntimeError("Argument 'section' must be a string") if not is_text_string(option): raise RuntimeError("Argument 'option' must be a string") return section
python
def _check_section_option(self, section, option): """ Private method to check section and option types """ if section is None: section = self.DEFAULT_SECTION_NAME elif not is_text_string(section): raise RuntimeError("Argument 'section' must be a string") if not is_text_string(option): raise RuntimeError("Argument 'option' must be a string") return section
[ "def", "_check_section_option", "(", "self", ",", "section", ",", "option", ")", ":", "if", "section", "is", "None", ":", "section", "=", "self", ".", "DEFAULT_SECTION_NAME", "elif", "not", "is_text_string", "(", "section", ")", ":", "raise", "RuntimeError", ...
Private method to check section and option types
[ "Private", "method", "to", "check", "section", "and", "option", "types" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/user.py#L340-L350
30,936
spyder-ide/spyder
spyder/utils/programs.py
get_temp_dir
def get_temp_dir(suffix=None): """ Return temporary Spyder directory, checking previously that it exists. """ to_join = [tempfile.gettempdir()] if os.name == 'nt': to_join.append('spyder') else: username = encoding.to_unicode_from_fs(getuser()) to_join.append('spyder-' + username) if suffix is not None: to_join.append(suffix) tempdir = osp.join(*to_join) if not osp.isdir(tempdir): os.mkdir(tempdir) return tempdir
python
def get_temp_dir(suffix=None): """ Return temporary Spyder directory, checking previously that it exists. """ to_join = [tempfile.gettempdir()] if os.name == 'nt': to_join.append('spyder') else: username = encoding.to_unicode_from_fs(getuser()) to_join.append('spyder-' + username) if suffix is not None: to_join.append(suffix) tempdir = osp.join(*to_join) if not osp.isdir(tempdir): os.mkdir(tempdir) return tempdir
[ "def", "get_temp_dir", "(", "suffix", "=", "None", ")", ":", "to_join", "=", "[", "tempfile", ".", "gettempdir", "(", ")", "]", "if", "os", ".", "name", "==", "'nt'", ":", "to_join", ".", "append", "(", "'spyder'", ")", "else", ":", "username", "=", ...
Return temporary Spyder directory, checking previously that it exists.
[ "Return", "temporary", "Spyder", "directory", "checking", "previously", "that", "it", "exists", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L34-L54
30,937
spyder-ide/spyder
spyder/utils/programs.py
is_program_installed
def is_program_installed(basename): """ Return program absolute path if installed in PATH. Otherwise, return None """ for path in os.environ["PATH"].split(os.pathsep): abspath = osp.join(path, basename) if osp.isfile(abspath): return abspath
python
def is_program_installed(basename): """ Return program absolute path if installed in PATH. Otherwise, return None """ for path in os.environ["PATH"].split(os.pathsep): abspath = osp.join(path, basename) if osp.isfile(abspath): return abspath
[ "def", "is_program_installed", "(", "basename", ")", ":", "for", "path", "in", "os", ".", "environ", "[", "\"PATH\"", "]", ".", "split", "(", "os", ".", "pathsep", ")", ":", "abspath", "=", "osp", ".", "join", "(", "path", ",", "basename", ")", "if",...
Return program absolute path if installed in PATH. Otherwise, return None
[ "Return", "program", "absolute", "path", "if", "installed", "in", "PATH", ".", "Otherwise", "return", "None" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L57-L66
30,938
spyder-ide/spyder
spyder/utils/programs.py
alter_subprocess_kwargs_by_platform
def alter_subprocess_kwargs_by_platform(**kwargs): """ Given a dict, populate kwargs to create a generally useful default setup for running subprocess processes on different platforms. For example, `close_fds` is set on posix and creation of a new console window is disabled on Windows. This function will alter the given kwargs and return the modified dict. """ kwargs.setdefault('close_fds', os.name == 'posix') if os.name == 'nt': CONSOLE_CREATION_FLAGS = 0 # Default value # See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863%28v=vs.85%29.aspx CREATE_NO_WINDOW = 0x08000000 # We "or" them together CONSOLE_CREATION_FLAGS |= CREATE_NO_WINDOW kwargs.setdefault('creationflags', CONSOLE_CREATION_FLAGS) return kwargs
python
def alter_subprocess_kwargs_by_platform(**kwargs): """ Given a dict, populate kwargs to create a generally useful default setup for running subprocess processes on different platforms. For example, `close_fds` is set on posix and creation of a new console window is disabled on Windows. This function will alter the given kwargs and return the modified dict. """ kwargs.setdefault('close_fds', os.name == 'posix') if os.name == 'nt': CONSOLE_CREATION_FLAGS = 0 # Default value # See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863%28v=vs.85%29.aspx CREATE_NO_WINDOW = 0x08000000 # We "or" them together CONSOLE_CREATION_FLAGS |= CREATE_NO_WINDOW kwargs.setdefault('creationflags', CONSOLE_CREATION_FLAGS) return kwargs
[ "def", "alter_subprocess_kwargs_by_platform", "(", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'close_fds'", ",", "os", ".", "name", "==", "'posix'", ")", "if", "os", ".", "name", "==", "'nt'", ":", "CONSOLE_CREATION_FLAGS", "=", "0", ...
Given a dict, populate kwargs to create a generally useful default setup for running subprocess processes on different platforms. For example, `close_fds` is set on posix and creation of a new console window is disabled on Windows. This function will alter the given kwargs and return the modified dict.
[ "Given", "a", "dict", "populate", "kwargs", "to", "create", "a", "generally", "useful", "default", "setup", "for", "running", "subprocess", "processes", "on", "different", "platforms", ".", "For", "example", "close_fds", "is", "set", "on", "posix", "and", "cre...
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L88-L107
30,939
spyder-ide/spyder
spyder/utils/programs.py
start_file
def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. """ from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices # We need to use setUrl instead of setPath because this is the only # cross-platform way to open external files. setPath fails completely on # Mac and doesn't open non-ascii files on Linux. # Fixes Issue 740 url = QUrl() url.setUrl(filename) return QDesktopServices.openUrl(url)
python
def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. """ from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices # We need to use setUrl instead of setPath because this is the only # cross-platform way to open external files. setPath fails completely on # Mac and doesn't open non-ascii files on Linux. # Fixes Issue 740 url = QUrl() url.setUrl(filename) return QDesktopServices.openUrl(url)
[ "def", "start_file", "(", "filename", ")", ":", "from", "qtpy", ".", "QtCore", "import", "QUrl", "from", "qtpy", ".", "QtGui", "import", "QDesktopServices", "# We need to use setUrl instead of setPath because this is the only\r", "# cross-platform way to open external files. se...
Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False.
[ "Generalized", "os", ".", "startfile", "for", "all", "platforms", "supported", "by", "Qt", "This", "function", "is", "simply", "wrapping", "QDesktopServices", ".", "openUrl", "Returns", "True", "if", "successfull", "otherwise", "returns", "False", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L183-L200
30,940
spyder-ide/spyder
spyder/utils/programs.py
get_python_args
def get_python_args(fname, python_args, interact, debug, end_args): """Construct Python interpreter arguments""" p_args = [] if python_args is not None: p_args += python_args.split() if interact: p_args.append('-i') if debug: p_args.extend(['-m', 'pdb']) if fname is not None: if os.name == 'nt' and debug: # When calling pdb on Windows, one has to replace backslashes by # slashes to avoid confusion with escape characters (otherwise, # for example, '\t' will be interpreted as a tabulation): p_args.append(osp.normpath(fname).replace(os.sep, '/')) else: p_args.append(fname) if end_args: p_args.extend(shell_split(end_args)) return p_args
python
def get_python_args(fname, python_args, interact, debug, end_args): """Construct Python interpreter arguments""" p_args = [] if python_args is not None: p_args += python_args.split() if interact: p_args.append('-i') if debug: p_args.extend(['-m', 'pdb']) if fname is not None: if os.name == 'nt' and debug: # When calling pdb on Windows, one has to replace backslashes by # slashes to avoid confusion with escape characters (otherwise, # for example, '\t' will be interpreted as a tabulation): p_args.append(osp.normpath(fname).replace(os.sep, '/')) else: p_args.append(fname) if end_args: p_args.extend(shell_split(end_args)) return p_args
[ "def", "get_python_args", "(", "fname", ",", "python_args", ",", "interact", ",", "debug", ",", "end_args", ")", ":", "p_args", "=", "[", "]", "if", "python_args", "is", "not", "None", ":", "p_args", "+=", "python_args", ".", "split", "(", ")", "if", "...
Construct Python interpreter arguments
[ "Construct", "Python", "interpreter", "arguments" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L251-L270
30,941
spyder-ide/spyder
spyder/utils/programs.py
is_python_interpreter_valid_name
def is_python_interpreter_valid_name(filename): """Check that the python interpreter file has a valid name.""" pattern = r'.*python(\d\.?\d*)?(w)?(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
python
def is_python_interpreter_valid_name(filename): """Check that the python interpreter file has a valid name.""" pattern = r'.*python(\d\.?\d*)?(w)?(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
[ "def", "is_python_interpreter_valid_name", "(", "filename", ")", ":", "pattern", "=", "r'.*python(\\d\\.?\\d*)?(w)?(.exe)?$'", "if", "re", ".", "match", "(", "pattern", ",", "filename", ",", "flags", "=", "re", ".", "I", ")", "is", "None", ":", "return", "Fals...
Check that the python interpreter file has a valid name.
[ "Check", "that", "the", "python", "interpreter", "file", "has", "a", "valid", "name", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L478-L484
30,942
spyder-ide/spyder
spyder/utils/programs.py
is_python_interpreter
def is_python_interpreter(filename): """Evaluate wether a file is a python interpreter or not.""" real_filename = os.path.realpath(filename) # To follow symlink if existent if (not osp.isfile(real_filename) or not is_python_interpreter_valid_name(filename)): return False elif is_pythonw(filename): if os.name == 'nt': # pythonw is a binary on Windows if not encoding.is_text_file(real_filename): return True else: return False elif sys.platform == 'darwin': # pythonw is a text file in Anaconda but a binary in # the system if is_anaconda() and encoding.is_text_file(real_filename): return True elif not encoding.is_text_file(real_filename): return True else: return False else: # There's no pythonw in other systems return False elif encoding.is_text_file(real_filename): # At this point we can't have a text file return False else: return check_python_help(filename)
python
def is_python_interpreter(filename): """Evaluate wether a file is a python interpreter or not.""" real_filename = os.path.realpath(filename) # To follow symlink if existent if (not osp.isfile(real_filename) or not is_python_interpreter_valid_name(filename)): return False elif is_pythonw(filename): if os.name == 'nt': # pythonw is a binary on Windows if not encoding.is_text_file(real_filename): return True else: return False elif sys.platform == 'darwin': # pythonw is a text file in Anaconda but a binary in # the system if is_anaconda() and encoding.is_text_file(real_filename): return True elif not encoding.is_text_file(real_filename): return True else: return False else: # There's no pythonw in other systems return False elif encoding.is_text_file(real_filename): # At this point we can't have a text file return False else: return check_python_help(filename)
[ "def", "is_python_interpreter", "(", "filename", ")", ":", "real_filename", "=", "os", ".", "path", ".", "realpath", "(", "filename", ")", "# To follow symlink if existent\r", "if", "(", "not", "osp", ".", "isfile", "(", "real_filename", ")", "or", "not", "is_...
Evaluate wether a file is a python interpreter or not.
[ "Evaluate", "wether", "a", "file", "is", "a", "python", "interpreter", "or", "not", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L486-L515
30,943
spyder-ide/spyder
spyder/utils/programs.py
is_pythonw
def is_pythonw(filename): """Check that the python interpreter has 'pythonw'.""" pattern = r'.*python(\d\.?\d*)?w(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
python
def is_pythonw(filename): """Check that the python interpreter has 'pythonw'.""" pattern = r'.*python(\d\.?\d*)?w(.exe)?$' if re.match(pattern, filename, flags=re.I) is None: return False else: return True
[ "def", "is_pythonw", "(", "filename", ")", ":", "pattern", "=", "r'.*python(\\d\\.?\\d*)?w(.exe)?$'", "if", "re", ".", "match", "(", "pattern", ",", "filename", ",", "flags", "=", "re", ".", "I", ")", "is", "None", ":", "return", "False", "else", ":", "r...
Check that the python interpreter has 'pythonw'.
[ "Check", "that", "the", "python", "interpreter", "has", "pythonw", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L518-L524
30,944
spyder-ide/spyder
spyder/utils/programs.py
check_python_help
def check_python_help(filename): """Check that the python interpreter can execute help.""" try: proc = run_program(filename, ["-h"]) output = to_text_string(proc.communicate()[0]) valid = ("Options and arguments (and corresponding environment " "variables)") if 'usage:' in output and valid in output: return True else: return False except: return False
python
def check_python_help(filename): """Check that the python interpreter can execute help.""" try: proc = run_program(filename, ["-h"]) output = to_text_string(proc.communicate()[0]) valid = ("Options and arguments (and corresponding environment " "variables)") if 'usage:' in output and valid in output: return True else: return False except: return False
[ "def", "check_python_help", "(", "filename", ")", ":", "try", ":", "proc", "=", "run_program", "(", "filename", ",", "[", "\"-h\"", "]", ")", "output", "=", "to_text_string", "(", "proc", ".", "communicate", "(", ")", "[", "0", "]", ")", "valid", "=", ...
Check that the python interpreter can execute help.
[ "Check", "that", "the", "python", "interpreter", "can", "execute", "help", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L527-L539
30,945
spyder-ide/spyder
spyder/plugins/editor/panels/debugger.py
DebuggerPanel._draw_breakpoint_icon
def _draw_breakpoint_icon(self, top, painter, icon_name): """Draw the given breakpoint pixmap. Args: top (int): top of the line to draw the breakpoint icon. painter (QPainter) icon_name (srt): key of icon to draw (see: self.icons) """ rect = QRect(0, top, self.sizeHint().width(), self.sizeHint().height()) try: icon = self.icons[icon_name] except KeyError as e: debug_print("Breakpoint icon doen't exist, {}".format(e)) else: icon.paint(painter, rect)
python
def _draw_breakpoint_icon(self, top, painter, icon_name): """Draw the given breakpoint pixmap. Args: top (int): top of the line to draw the breakpoint icon. painter (QPainter) icon_name (srt): key of icon to draw (see: self.icons) """ rect = QRect(0, top, self.sizeHint().width(), self.sizeHint().height()) try: icon = self.icons[icon_name] except KeyError as e: debug_print("Breakpoint icon doen't exist, {}".format(e)) else: icon.paint(painter, rect)
[ "def", "_draw_breakpoint_icon", "(", "self", ",", "top", ",", "painter", ",", "icon_name", ")", ":", "rect", "=", "QRect", "(", "0", ",", "top", ",", "self", ".", "sizeHint", "(", ")", ".", "width", "(", ")", ",", "self", ".", "sizeHint", "(", ")",...
Draw the given breakpoint pixmap. Args: top (int): top of the line to draw the breakpoint icon. painter (QPainter) icon_name (srt): key of icon to draw (see: self.icons)
[ "Draw", "the", "given", "breakpoint", "pixmap", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/debugger.py#L51-L66
30,946
spyder-ide/spyder
spyder/utils/workers.py
sleeping_func
def sleeping_func(arg, secs=10, result_queue=None): """This methods illustrates how the workers can be used.""" import time time.sleep(secs) if result_queue is not None: result_queue.put(arg) else: return arg
python
def sleeping_func(arg, secs=10, result_queue=None): """This methods illustrates how the workers can be used.""" import time time.sleep(secs) if result_queue is not None: result_queue.put(arg) else: return arg
[ "def", "sleeping_func", "(", "arg", ",", "secs", "=", "10", ",", "result_queue", "=", "None", ")", ":", "import", "time", "time", ".", "sleep", "(", "secs", ")", "if", "result_queue", "is", "not", "None", ":", "result_queue", ".", "put", "(", "arg", ...
This methods illustrates how the workers can be used.
[ "This", "methods", "illustrates", "how", "the", "workers", "can", "be", "used", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L328-L335
30,947
spyder-ide/spyder
spyder/utils/workers.py
PythonWorker._start
def _start(self): """Start process worker for given method args and kwargs.""" error = None output = None try: output = self.func(*self.args, **self.kwargs) except Exception as err: error = err if not self._is_finished: self.sig_finished.emit(self, output, error) self._is_finished = True
python
def _start(self): """Start process worker for given method args and kwargs.""" error = None output = None try: output = self.func(*self.args, **self.kwargs) except Exception as err: error = err if not self._is_finished: self.sig_finished.emit(self, output, error) self._is_finished = True
[ "def", "_start", "(", "self", ")", ":", "error", "=", "None", "output", "=", "None", "try", ":", "output", "=", "self", ".", "func", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "except", "Exception", "as", "err", ":"...
Start process worker for given method args and kwargs.
[ "Start", "process", "worker", "for", "given", "method", "args", "and", "kwargs", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L69-L81
30,948
spyder-ide/spyder
spyder/utils/workers.py
ProcessWorker._set_environment
def _set_environment(self, environ): """Set the environment on the QProcess.""" if environ: q_environ = self._process.processEnvironment() for k, v in environ.items(): q_environ.insert(k, v) self._process.setProcessEnvironment(q_environ)
python
def _set_environment(self, environ): """Set the environment on the QProcess.""" if environ: q_environ = self._process.processEnvironment() for k, v in environ.items(): q_environ.insert(k, v) self._process.setProcessEnvironment(q_environ)
[ "def", "_set_environment", "(", "self", ",", "environ", ")", ":", "if", "environ", ":", "q_environ", "=", "self", ".", "_process", ".", "processEnvironment", "(", ")", "for", "k", ",", "v", "in", "environ", ".", "items", "(", ")", ":", "q_environ", "."...
Set the environment on the QProcess.
[ "Set", "the", "environment", "on", "the", "QProcess", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L131-L137
30,949
spyder-ide/spyder
spyder/utils/workers.py
ProcessWorker._communicate
def _communicate(self): """Callback for communicate.""" if (not self._communicate_first and self._process.state() == QProcess.NotRunning): self.communicate() elif self._fired: self._timer.stop()
python
def _communicate(self): """Callback for communicate.""" if (not self._communicate_first and self._process.state() == QProcess.NotRunning): self.communicate() elif self._fired: self._timer.stop()
[ "def", "_communicate", "(", "self", ")", ":", "if", "(", "not", "self", ".", "_communicate_first", "and", "self", ".", "_process", ".", "state", "(", ")", "==", "QProcess", ".", "NotRunning", ")", ":", "self", ".", "communicate", "(", ")", "elif", "sel...
Callback for communicate.
[ "Callback", "for", "communicate", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L151-L157
30,950
spyder-ide/spyder
spyder/utils/workers.py
ProcessWorker.terminate
def terminate(self): """Terminate running processes.""" if self._process.state() == QProcess.Running: try: self._process.terminate() except Exception: pass self._fired = True
python
def terminate(self): """Terminate running processes.""" if self._process.state() == QProcess.Running: try: self._process.terminate() except Exception: pass self._fired = True
[ "def", "terminate", "(", "self", ")", ":", "if", "self", ".", "_process", ".", "state", "(", ")", "==", "QProcess", ".", "Running", ":", "try", ":", "self", ".", "_process", ".", "terminate", "(", ")", "except", "Exception", ":", "pass", "self", ".",...
Terminate running processes.
[ "Terminate", "running", "processes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L203-L210
30,951
spyder-ide/spyder
spyder/utils/workers.py
WorkerManager._clean_workers
def _clean_workers(self): """Delete periodically workers in workers bag.""" while self._bag_collector: self._bag_collector.popleft() self._timer_worker_delete.stop()
python
def _clean_workers(self): """Delete periodically workers in workers bag.""" while self._bag_collector: self._bag_collector.popleft() self._timer_worker_delete.stop()
[ "def", "_clean_workers", "(", "self", ")", ":", "while", "self", ".", "_bag_collector", ":", "self", ".", "_bag_collector", ".", "popleft", "(", ")", "self", ".", "_timer_worker_delete", ".", "stop", "(", ")" ]
Delete periodically workers in workers bag.
[ "Delete", "periodically", "workers", "in", "workers", "bag", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L243-L247
30,952
spyder-ide/spyder
spyder/utils/workers.py
WorkerManager._start
def _start(self, worker=None): """Start threads and check for inactive workers.""" if worker: self._queue_workers.append(worker) if self._queue_workers and self._running_threads < self._max_threads: #print('Queue: {0} Running: {1} Workers: {2} ' # 'Threads: {3}'.format(len(self._queue_workers), # self._running_threads, # len(self._workers), # len(self._threads))) self._running_threads += 1 worker = self._queue_workers.popleft() thread = QThread() if isinstance(worker, PythonWorker): worker.moveToThread(thread) worker.sig_finished.connect(thread.quit) thread.started.connect(worker._start) thread.start() elif isinstance(worker, ProcessWorker): thread.quit() worker._start() self._threads.append(thread) else: self._timer.start() if self._workers: for w in self._workers: if w.is_finished(): self._bag_collector.append(w) self._workers.remove(w) if self._threads: for t in self._threads: if t.isFinished(): self._threads.remove(t) self._running_threads -= 1 if len(self._threads) == 0 and len(self._workers) == 0: self._timer.stop() self._timer_worker_delete.start()
python
def _start(self, worker=None): """Start threads and check for inactive workers.""" if worker: self._queue_workers.append(worker) if self._queue_workers and self._running_threads < self._max_threads: #print('Queue: {0} Running: {1} Workers: {2} ' # 'Threads: {3}'.format(len(self._queue_workers), # self._running_threads, # len(self._workers), # len(self._threads))) self._running_threads += 1 worker = self._queue_workers.popleft() thread = QThread() if isinstance(worker, PythonWorker): worker.moveToThread(thread) worker.sig_finished.connect(thread.quit) thread.started.connect(worker._start) thread.start() elif isinstance(worker, ProcessWorker): thread.quit() worker._start() self._threads.append(thread) else: self._timer.start() if self._workers: for w in self._workers: if w.is_finished(): self._bag_collector.append(w) self._workers.remove(w) if self._threads: for t in self._threads: if t.isFinished(): self._threads.remove(t) self._running_threads -= 1 if len(self._threads) == 0 and len(self._workers) == 0: self._timer.stop() self._timer_worker_delete.start()
[ "def", "_start", "(", "self", ",", "worker", "=", "None", ")", ":", "if", "worker", ":", "self", ".", "_queue_workers", ".", "append", "(", "worker", ")", "if", "self", ".", "_queue_workers", "and", "self", ".", "_running_threads", "<", "self", ".", "_...
Start threads and check for inactive workers.
[ "Start", "threads", "and", "check", "for", "inactive", "workers", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L249-L289
30,953
spyder-ide/spyder
spyder/utils/workers.py
WorkerManager.create_python_worker
def create_python_worker(self, func, *args, **kwargs): """Create a new python worker instance.""" worker = PythonWorker(func, args, kwargs) self._create_worker(worker) return worker
python
def create_python_worker(self, func, *args, **kwargs): """Create a new python worker instance.""" worker = PythonWorker(func, args, kwargs) self._create_worker(worker) return worker
[ "def", "create_python_worker", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "worker", "=", "PythonWorker", "(", "func", ",", "args", ",", "kwargs", ")", "self", ".", "_create_worker", "(", "worker", ")", "return", "wor...
Create a new python worker instance.
[ "Create", "a", "new", "python", "worker", "instance", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L291-L295
30,954
spyder-ide/spyder
spyder/utils/workers.py
WorkerManager.create_process_worker
def create_process_worker(self, cmd_list, environ=None): """Create a new process worker instance.""" worker = ProcessWorker(cmd_list, environ=environ) self._create_worker(worker) return worker
python
def create_process_worker(self, cmd_list, environ=None): """Create a new process worker instance.""" worker = ProcessWorker(cmd_list, environ=environ) self._create_worker(worker) return worker
[ "def", "create_process_worker", "(", "self", ",", "cmd_list", ",", "environ", "=", "None", ")", ":", "worker", "=", "ProcessWorker", "(", "cmd_list", ",", "environ", "=", "environ", ")", "self", ".", "_create_worker", "(", "worker", ")", "return", "worker" ]
Create a new process worker instance.
[ "Create", "a", "new", "process", "worker", "instance", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L297-L301
30,955
spyder-ide/spyder
spyder/utils/workers.py
WorkerManager.terminate_all
def terminate_all(self): """Terminate all worker processes.""" for worker in self._workers: worker.terminate() # for thread in self._threads: # try: # thread.terminate() # thread.wait() # except Exception: # pass self._queue_workers = deque()
python
def terminate_all(self): """Terminate all worker processes.""" for worker in self._workers: worker.terminate() # for thread in self._threads: # try: # thread.terminate() # thread.wait() # except Exception: # pass self._queue_workers = deque()
[ "def", "terminate_all", "(", "self", ")", ":", "for", "worker", "in", "self", ".", "_workers", ":", "worker", ".", "terminate", "(", ")", "# for thread in self._threads:", "# try:", "# thread.terminate()", "# thread.wait()", "# except Exception:", ...
Terminate all worker processes.
[ "Terminate", "all", "worker", "processes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L303-L314
30,956
spyder-ide/spyder
spyder/utils/workers.py
WorkerManager._create_worker
def _create_worker(self, worker): """Common worker setup.""" worker.sig_started.connect(self._start) self._workers.append(worker)
python
def _create_worker(self, worker): """Common worker setup.""" worker.sig_started.connect(self._start) self._workers.append(worker)
[ "def", "_create_worker", "(", "self", ",", "worker", ")", ":", "worker", ".", "sig_started", ".", "connect", "(", "self", ".", "_start", ")", "self", ".", "_workers", ".", "append", "(", "worker", ")" ]
Common worker setup.
[ "Common", "worker", "setup", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L316-L319
30,957
spyder-ide/spyder
spyder/plugins/editor/widgets/recover.py
gather_file_data
def gather_file_data(name): """ Gather data about a given file. Returns a dict with fields name, mtime and size, containing the relevant data for the fiel. """ res = {'name': name} try: res['mtime'] = osp.getmtime(name) res['size'] = osp.getsize(name) except OSError: pass return res
python
def gather_file_data(name): """ Gather data about a given file. Returns a dict with fields name, mtime and size, containing the relevant data for the fiel. """ res = {'name': name} try: res['mtime'] = osp.getmtime(name) res['size'] = osp.getsize(name) except OSError: pass return res
[ "def", "gather_file_data", "(", "name", ")", ":", "res", "=", "{", "'name'", ":", "name", "}", "try", ":", "res", "[", "'mtime'", "]", "=", "osp", ".", "getmtime", "(", "name", ")", "res", "[", "'size'", "]", "=", "osp", ".", "getsize", "(", "nam...
Gather data about a given file. Returns a dict with fields name, mtime and size, containing the relevant data for the fiel.
[ "Gather", "data", "about", "a", "given", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/recover.py#L26-L39
30,958
spyder-ide/spyder
spyder/plugins/editor/widgets/recover.py
file_data_to_str
def file_data_to_str(data): """ Convert file data to a string for display. This function takes the file data produced by gather_file_data(). """ if not data: return _('<i>File name not recorded</i>') res = data['name'] try: mtime_as_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['mtime'])) res += '<br><i>{}</i>: {}'.format(_('Last modified'), mtime_as_str) res += '<br><i>{}</i>: {} {}'.format( _('Size'), data['size'], _('bytes')) except KeyError: res += '<br>' + _('<i>File no longer exists</i>') return res
python
def file_data_to_str(data): """ Convert file data to a string for display. This function takes the file data produced by gather_file_data(). """ if not data: return _('<i>File name not recorded</i>') res = data['name'] try: mtime_as_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['mtime'])) res += '<br><i>{}</i>: {}'.format(_('Last modified'), mtime_as_str) res += '<br><i>{}</i>: {} {}'.format( _('Size'), data['size'], _('bytes')) except KeyError: res += '<br>' + _('<i>File no longer exists</i>') return res
[ "def", "file_data_to_str", "(", "data", ")", ":", "if", "not", "data", ":", "return", "_", "(", "'<i>File name not recorded</i>'", ")", "res", "=", "data", "[", "'name'", "]", "try", ":", "mtime_as_str", "=", "time", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S...
Convert file data to a string for display. This function takes the file data produced by gather_file_data().
[ "Convert", "file", "data", "to", "a", "string", "for", "display", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/recover.py#L42-L59
30,959
spyder-ide/spyder
spyder/plugins/editor/widgets/recover.py
make_temporary_files
def make_temporary_files(tempdir): """ Make temporary files to simulate a recovery use case. Create a directory under tempdir containing some original files and another directory with autosave files. Return a tuple with the name of the directory with the original files, the name of the directory with the autosave files, and the autosave mapping. """ orig_dir = osp.join(tempdir, 'orig') os.mkdir(orig_dir) autosave_dir = osp.join(tempdir, 'autosave') os.mkdir(autosave_dir) autosave_mapping = {} # ham.py: Both original and autosave files exist, mentioned in mapping orig_file = osp.join(orig_dir, 'ham.py') with open(orig_file, 'w') as f: f.write('ham = "original"\n') autosave_file = osp.join(autosave_dir, 'ham.py') with open(autosave_file, 'w') as f: f.write('ham = "autosave"\n') autosave_mapping[orig_file] = autosave_file # spam.py: Only autosave file exists, mentioned in mapping orig_file = osp.join(orig_dir, 'spam.py') autosave_file = osp.join(autosave_dir, 'spam.py') with open(autosave_file, 'w') as f: f.write('spam = "autosave"\n') autosave_mapping[orig_file] = autosave_file # eggs.py: Only original files exists, mentioned in mapping orig_file = osp.join(orig_dir, 'eggs.py') with open(orig_file, 'w') as f: f.write('eggs = "original"\n') autosave_file = osp.join(autosave_dir, 'eggs.py') autosave_mapping[orig_file] = autosave_file # cheese.py: Only autosave file exists, not mentioned in mapping autosave_file = osp.join(autosave_dir, 'cheese.py') with open(autosave_file, 'w') as f: f.write('cheese = "autosave"\n') return orig_dir, autosave_dir, autosave_mapping
python
def make_temporary_files(tempdir): """ Make temporary files to simulate a recovery use case. Create a directory under tempdir containing some original files and another directory with autosave files. Return a tuple with the name of the directory with the original files, the name of the directory with the autosave files, and the autosave mapping. """ orig_dir = osp.join(tempdir, 'orig') os.mkdir(orig_dir) autosave_dir = osp.join(tempdir, 'autosave') os.mkdir(autosave_dir) autosave_mapping = {} # ham.py: Both original and autosave files exist, mentioned in mapping orig_file = osp.join(orig_dir, 'ham.py') with open(orig_file, 'w') as f: f.write('ham = "original"\n') autosave_file = osp.join(autosave_dir, 'ham.py') with open(autosave_file, 'w') as f: f.write('ham = "autosave"\n') autosave_mapping[orig_file] = autosave_file # spam.py: Only autosave file exists, mentioned in mapping orig_file = osp.join(orig_dir, 'spam.py') autosave_file = osp.join(autosave_dir, 'spam.py') with open(autosave_file, 'w') as f: f.write('spam = "autosave"\n') autosave_mapping[orig_file] = autosave_file # eggs.py: Only original files exists, mentioned in mapping orig_file = osp.join(orig_dir, 'eggs.py') with open(orig_file, 'w') as f: f.write('eggs = "original"\n') autosave_file = osp.join(autosave_dir, 'eggs.py') autosave_mapping[orig_file] = autosave_file # cheese.py: Only autosave file exists, not mentioned in mapping autosave_file = osp.join(autosave_dir, 'cheese.py') with open(autosave_file, 'w') as f: f.write('cheese = "autosave"\n') return orig_dir, autosave_dir, autosave_mapping
[ "def", "make_temporary_files", "(", "tempdir", ")", ":", "orig_dir", "=", "osp", ".", "join", "(", "tempdir", ",", "'orig'", ")", "os", ".", "mkdir", "(", "orig_dir", ")", "autosave_dir", "=", "osp", ".", "join", "(", "tempdir", ",", "'autosave'", ")", ...
Make temporary files to simulate a recovery use case. Create a directory under tempdir containing some original files and another directory with autosave files. Return a tuple with the name of the directory with the original files, the name of the directory with the autosave files, and the autosave mapping.
[ "Make", "temporary", "files", "to", "simulate", "a", "recovery", "use", "case", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/recover.py#L278-L321
30,960
spyder-ide/spyder
spyder/plugins/editor/widgets/recover.py
RecoveryDialog.gather_data
def gather_data(self): """ Gather data about files which may be recovered. The data is stored in self.data as a list of tuples with the data pertaining to the original file and the autosave file. Each element of the tuple is a dict as returned by gather_file_data(). """ self.data = [] try: FileNotFoundError except NameError: # Python 2 FileNotFoundError = OSError # In Python 3, easier to use os.scandir() try: for name in os.listdir(self.autosave_dir): full_name = osp.join(self.autosave_dir, name) if osp.isdir(full_name): continue for orig, autosave in self.autosave_mapping.items(): if autosave == full_name: orig_dict = gather_file_data(orig) break else: orig_dict = None autosave_dict = gather_file_data(full_name) self.data.append((orig_dict, autosave_dict)) except FileNotFoundError: # autosave dir does not exist pass self.data.sort(key=recovery_data_key_function) self.num_enabled = len(self.data)
python
def gather_data(self): """ Gather data about files which may be recovered. The data is stored in self.data as a list of tuples with the data pertaining to the original file and the autosave file. Each element of the tuple is a dict as returned by gather_file_data(). """ self.data = [] try: FileNotFoundError except NameError: # Python 2 FileNotFoundError = OSError # In Python 3, easier to use os.scandir() try: for name in os.listdir(self.autosave_dir): full_name = osp.join(self.autosave_dir, name) if osp.isdir(full_name): continue for orig, autosave in self.autosave_mapping.items(): if autosave == full_name: orig_dict = gather_file_data(orig) break else: orig_dict = None autosave_dict = gather_file_data(full_name) self.data.append((orig_dict, autosave_dict)) except FileNotFoundError: # autosave dir does not exist pass self.data.sort(key=recovery_data_key_function) self.num_enabled = len(self.data)
[ "def", "gather_data", "(", "self", ")", ":", "self", ".", "data", "=", "[", "]", "try", ":", "FileNotFoundError", "except", "NameError", ":", "# Python 2", "FileNotFoundError", "=", "OSError", "# In Python 3, easier to use os.scandir()", "try", ":", "for", "name",...
Gather data about files which may be recovered. The data is stored in self.data as a list of tuples with the data pertaining to the original file and the autosave file. Each element of the tuple is a dict as returned by gather_file_data().
[ "Gather", "data", "about", "files", "which", "may", "be", "recovered", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/recover.py#L93-L123
30,961
spyder-ide/spyder
spyder/plugins/editor/widgets/recover.py
RecoveryDialog.add_label
def add_label(self): """Add label with explanation at top of dialog window.""" txt = _('Autosave files found. What would you like to do?\n\n' 'This dialog will be shown again on next startup if any ' 'autosave files are not restored, moved or deleted.') label = QLabel(txt, self) label.setWordWrap(True) self.layout.addWidget(label)
python
def add_label(self): """Add label with explanation at top of dialog window.""" txt = _('Autosave files found. What would you like to do?\n\n' 'This dialog will be shown again on next startup if any ' 'autosave files are not restored, moved or deleted.') label = QLabel(txt, self) label.setWordWrap(True) self.layout.addWidget(label)
[ "def", "add_label", "(", "self", ")", ":", "txt", "=", "_", "(", "'Autosave files found. What would you like to do?\\n\\n'", "'This dialog will be shown again on next startup if any '", "'autosave files are not restored, moved or deleted.'", ")", "label", "=", "QLabel", "(", "txt...
Add label with explanation at top of dialog window.
[ "Add", "label", "with", "explanation", "at", "top", "of", "dialog", "window", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/recover.py#L125-L132
30,962
spyder-ide/spyder
spyder/plugins/editor/widgets/recover.py
RecoveryDialog.add_label_to_table
def add_label_to_table(self, row, col, txt): """Add a label to specified cell in table.""" label = QLabel(txt) label.setMargin(5) label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.table.setCellWidget(row, col, label)
python
def add_label_to_table(self, row, col, txt): """Add a label to specified cell in table.""" label = QLabel(txt) label.setMargin(5) label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.table.setCellWidget(row, col, label)
[ "def", "add_label_to_table", "(", "self", ",", "row", ",", "col", ",", "txt", ")", ":", "label", "=", "QLabel", "(", "txt", ")", "label", ".", "setMargin", "(", "5", ")", "label", ".", "setAlignment", "(", "Qt", ".", "AlignLeft", "|", "Qt", ".", "A...
Add a label to specified cell in table.
[ "Add", "a", "label", "to", "specified", "cell", "in", "table", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/recover.py#L134-L139
30,963
spyder-ide/spyder
spyder/plugins/editor/widgets/recover.py
RecoveryDialog.add_table
def add_table(self): """Add table with info about files to be recovered.""" table = QTableWidget(len(self.data), 3, self) self.table = table labels = [_('Original file'), _('Autosave file'), _('Actions')] table.setHorizontalHeaderLabels(labels) table.verticalHeader().hide() table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setSelectionMode(QTableWidget.NoSelection) # Show horizontal grid lines table.setShowGrid(False) table.setStyleSheet('::item { border-bottom: 1px solid gray }') for idx, (original, autosave) in enumerate(self.data): self.add_label_to_table(idx, 0, file_data_to_str(original)) self.add_label_to_table(idx, 1, file_data_to_str(autosave)) widget = QWidget() layout = QHBoxLayout() tooltip = _('Recover the autosave file to its original location, ' 'replacing the original if it exists.') button = QPushButton(_('Restore')) button.setToolTip(tooltip) button.clicked.connect( lambda checked, my_idx=idx: self.restore(my_idx)) layout.addWidget(button) tooltip = _('Delete the autosave file.') button = QPushButton(_('Discard')) button.setToolTip(tooltip) button.clicked.connect( lambda checked, my_idx=idx: self.discard(my_idx)) layout.addWidget(button) tooltip = _('Display the autosave file (and the original, if it ' 'exists) in Spyder\'s Editor. You will have to move ' 'or delete it manually.') button = QPushButton(_('Open')) button.setToolTip(tooltip) button.clicked.connect( lambda checked, my_idx=idx: self.open_files(my_idx)) layout.addWidget(button) widget.setLayout(layout) self.table.setCellWidget(idx, 2, widget) table.resizeRowsToContents() table.resizeColumnsToContents() # Need to add the "+ 2" because otherwise the table scrolls a tiny # amount; no idea why width = table.horizontalHeader().length() + 2 height = (table.verticalHeader().length() + table.horizontalHeader().height() + 2) table.setFixedSize(width, height) self.layout.addWidget(table)
python
def add_table(self): """Add table with info about files to be recovered.""" table = QTableWidget(len(self.data), 3, self) self.table = table labels = [_('Original file'), _('Autosave file'), _('Actions')] table.setHorizontalHeaderLabels(labels) table.verticalHeader().hide() table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setSelectionMode(QTableWidget.NoSelection) # Show horizontal grid lines table.setShowGrid(False) table.setStyleSheet('::item { border-bottom: 1px solid gray }') for idx, (original, autosave) in enumerate(self.data): self.add_label_to_table(idx, 0, file_data_to_str(original)) self.add_label_to_table(idx, 1, file_data_to_str(autosave)) widget = QWidget() layout = QHBoxLayout() tooltip = _('Recover the autosave file to its original location, ' 'replacing the original if it exists.') button = QPushButton(_('Restore')) button.setToolTip(tooltip) button.clicked.connect( lambda checked, my_idx=idx: self.restore(my_idx)) layout.addWidget(button) tooltip = _('Delete the autosave file.') button = QPushButton(_('Discard')) button.setToolTip(tooltip) button.clicked.connect( lambda checked, my_idx=idx: self.discard(my_idx)) layout.addWidget(button) tooltip = _('Display the autosave file (and the original, if it ' 'exists) in Spyder\'s Editor. You will have to move ' 'or delete it manually.') button = QPushButton(_('Open')) button.setToolTip(tooltip) button.clicked.connect( lambda checked, my_idx=idx: self.open_files(my_idx)) layout.addWidget(button) widget.setLayout(layout) self.table.setCellWidget(idx, 2, widget) table.resizeRowsToContents() table.resizeColumnsToContents() # Need to add the "+ 2" because otherwise the table scrolls a tiny # amount; no idea why width = table.horizontalHeader().length() + 2 height = (table.verticalHeader().length() + table.horizontalHeader().height() + 2) table.setFixedSize(width, height) self.layout.addWidget(table)
[ "def", "add_table", "(", "self", ")", ":", "table", "=", "QTableWidget", "(", "len", "(", "self", ".", "data", ")", ",", "3", ",", "self", ")", "self", ".", "table", "=", "table", "labels", "=", "[", "_", "(", "'Original file'", ")", ",", "_", "(...
Add table with info about files to be recovered.
[ "Add", "table", "with", "info", "about", "files", "to", "be", "recovered", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/recover.py#L141-L201
30,964
spyder-ide/spyder
spyder/plugins/editor/widgets/recover.py
RecoveryDialog.add_cancel_button
def add_cancel_button(self): """Add a cancel button at the bottom of the dialog window.""" button_box = QDialogButtonBox(QDialogButtonBox.Cancel, self) button_box.rejected.connect(self.reject) self.layout.addWidget(button_box)
python
def add_cancel_button(self): """Add a cancel button at the bottom of the dialog window.""" button_box = QDialogButtonBox(QDialogButtonBox.Cancel, self) button_box.rejected.connect(self.reject) self.layout.addWidget(button_box)
[ "def", "add_cancel_button", "(", "self", ")", ":", "button_box", "=", "QDialogButtonBox", "(", "QDialogButtonBox", ".", "Cancel", ",", "self", ")", "button_box", ".", "rejected", ".", "connect", "(", "self", ".", "reject", ")", "self", ".", "layout", ".", ...
Add a cancel button at the bottom of the dialog window.
[ "Add", "a", "cancel", "button", "at", "the", "bottom", "of", "the", "dialog", "window", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/recover.py#L203-L207
30,965
spyder-ide/spyder
spyder/plugins/workingdirectory/plugin.py
WorkingDirectory.parent_directory
def parent_directory(self): """Change working directory to parent directory""" self.chdir(os.path.join(getcwd_or_home(), os.path.pardir))
python
def parent_directory(self): """Change working directory to parent directory""" self.chdir(os.path.join(getcwd_or_home(), os.path.pardir))
[ "def", "parent_directory", "(", "self", ")", ":", "self", ".", "chdir", "(", "os", ".", "path", ".", "join", "(", "getcwd_or_home", "(", ")", ",", "os", ".", "path", ".", "pardir", ")", ")" ]
Change working directory to parent directory
[ "Change", "working", "directory", "to", "parent", "directory" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L203-L205
30,966
spyder-ide/spyder
spyder/plugins/editor/utils/debugger.py
DebuggerManager.breakpoints_changed
def breakpoints_changed(self): """Breakpoint list has changed""" breakpoints = self.get_breakpoints() if self.breakpoints != breakpoints: self.breakpoints = breakpoints self.save_breakpoints()
python
def breakpoints_changed(self): """Breakpoint list has changed""" breakpoints = self.get_breakpoints() if self.breakpoints != breakpoints: self.breakpoints = breakpoints self.save_breakpoints()
[ "def", "breakpoints_changed", "(", "self", ")", ":", "breakpoints", "=", "self", ".", "get_breakpoints", "(", ")", "if", "self", ".", "breakpoints", "!=", "breakpoints", ":", "self", ".", "breakpoints", "=", "breakpoints", "self", ".", "save_breakpoints", "(",...
Breakpoint list has changed
[ "Breakpoint", "list", "has", "changed" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/debugger.py#L150-L155
30,967
spyder-ide/spyder
spyder/plugins/editor/extensions/closequotes.py
unmatched_quotes_in_line
def unmatched_quotes_in_line(text): """Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Take from the IPython project (in IPython/core/completer.py in v0.13) Spyder team: Add some changes to deal with escaped quotes - Copyright (C) 2008-2011 IPython Development Team - Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> - Copyright (C) 2001 Python Software Foundation, www.python.org Distributed under the terms of the BSD License. """ # We check " first, then ', so complex cases with nested quotes will # get the " to take precedence. text = text.replace("\\'", "") text = text.replace('\\"', '') if text.count('"') % 2: return '"' elif text.count("'") % 2: return "'" else: return ''
python
def unmatched_quotes_in_line(text): """Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Take from the IPython project (in IPython/core/completer.py in v0.13) Spyder team: Add some changes to deal with escaped quotes - Copyright (C) 2008-2011 IPython Development Team - Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> - Copyright (C) 2001 Python Software Foundation, www.python.org Distributed under the terms of the BSD License. """ # We check " first, then ', so complex cases with nested quotes will # get the " to take precedence. text = text.replace("\\'", "") text = text.replace('\\"', '') if text.count('"') % 2: return '"' elif text.count("'") % 2: return "'" else: return ''
[ "def", "unmatched_quotes_in_line", "(", "text", ")", ":", "# We check \" first, then ', so complex cases with nested quotes will", "# get the \" to take precedence.", "text", "=", "text", ".", "replace", "(", "\"\\\\'\"", ",", "\"\"", ")", "text", "=", "text", ".", "repla...
Return whether a string has open quotes. This simply counts whether the number of quote characters of either type in the string is odd. Take from the IPython project (in IPython/core/completer.py in v0.13) Spyder team: Add some changes to deal with escaped quotes - Copyright (C) 2008-2011 IPython Development Team - Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> - Copyright (C) 2001 Python Software Foundation, www.python.org Distributed under the terms of the BSD License.
[ "Return", "whether", "a", "string", "has", "open", "quotes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/closequotes.py#L14-L38
30,968
spyder-ide/spyder
spyder/plugins/editor/extensions/closequotes.py
CloseQuotesExtension._autoinsert_quotes
def _autoinsert_quotes(self, key): """Control how to automatically insert quotes in various situations.""" char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: '\''}[key] line_text = self.editor.get_text('sol', 'eol') line_to_cursor = self.editor.get_text('sol', 'cursor') cursor = self.editor.textCursor() last_three = self.editor.get_text('sol', 'cursor')[-3:] last_two = self.editor.get_text('sol', 'cursor')[-2:] trailing_text = self.editor.get_text('cursor', 'eol').strip() if self.editor.has_selected_text(): text = self.editor.get_selected_text() self.editor.insert_text("{0}{1}{0}".format(char, text)) # keep text selected, for inserting multiple quotes cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, 1) cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, len(text)) self.editor.setTextCursor(cursor) elif self.editor.in_comment(): self.editor.insert_text(char) elif (len(trailing_text) > 0 and not unmatched_quotes_in_line(line_to_cursor) == char and not trailing_text[0] in (',', ':', ';', ')', ']', '}')): self.editor.insert_text(char) elif (unmatched_quotes_in_line(line_text) and (not last_three == 3*char)): self.editor.insert_text(char) # Move to the right if we are before a quote elif self.editor.next_char() == char: cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, 1) cursor.clearSelection() self.editor.setTextCursor(cursor) # Automatic insertion of triple double quotes (for docstrings) elif last_three == 3*char: self.editor.insert_text(3*char) cursor = self.editor.textCursor() cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor, 3) cursor.clearSelection() self.editor.setTextCursor(cursor) # If last two chars are quotes, just insert one more because most # probably the user wants to write a docstring elif last_two == 2*char: self.editor.insert_text(char) self.editor.delayed_popup_docstring() # Automatic insertion of quotes else: self.editor.insert_text(2*char) cursor = self.editor.textCursor() cursor.movePosition(QTextCursor.PreviousCharacter) self.editor.setTextCursor(cursor)
python
def _autoinsert_quotes(self, key): """Control how to automatically insert quotes in various situations.""" char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: '\''}[key] line_text = self.editor.get_text('sol', 'eol') line_to_cursor = self.editor.get_text('sol', 'cursor') cursor = self.editor.textCursor() last_three = self.editor.get_text('sol', 'cursor')[-3:] last_two = self.editor.get_text('sol', 'cursor')[-2:] trailing_text = self.editor.get_text('cursor', 'eol').strip() if self.editor.has_selected_text(): text = self.editor.get_selected_text() self.editor.insert_text("{0}{1}{0}".format(char, text)) # keep text selected, for inserting multiple quotes cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, 1) cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, len(text)) self.editor.setTextCursor(cursor) elif self.editor.in_comment(): self.editor.insert_text(char) elif (len(trailing_text) > 0 and not unmatched_quotes_in_line(line_to_cursor) == char and not trailing_text[0] in (',', ':', ';', ')', ']', '}')): self.editor.insert_text(char) elif (unmatched_quotes_in_line(line_text) and (not last_three == 3*char)): self.editor.insert_text(char) # Move to the right if we are before a quote elif self.editor.next_char() == char: cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, 1) cursor.clearSelection() self.editor.setTextCursor(cursor) # Automatic insertion of triple double quotes (for docstrings) elif last_three == 3*char: self.editor.insert_text(3*char) cursor = self.editor.textCursor() cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor, 3) cursor.clearSelection() self.editor.setTextCursor(cursor) # If last two chars are quotes, just insert one more because most # probably the user wants to write a docstring elif last_two == 2*char: self.editor.insert_text(char) self.editor.delayed_popup_docstring() # Automatic insertion of quotes else: self.editor.insert_text(2*char) cursor = self.editor.textCursor() cursor.movePosition(QTextCursor.PreviousCharacter) self.editor.setTextCursor(cursor)
[ "def", "_autoinsert_quotes", "(", "self", ",", "key", ")", ":", "char", "=", "{", "Qt", ".", "Key_QuoteDbl", ":", "'\"'", ",", "Qt", ".", "Key_Apostrophe", ":", "'\\''", "}", "[", "key", "]", "line_text", "=", "self", ".", "editor", ".", "get_text", ...
Control how to automatically insert quotes in various situations.
[ "Control", "how", "to", "automatically", "insert", "quotes", "in", "various", "situations", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/closequotes.py#L61-L113
30,969
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
populate
def populate(combobox, data): """ Populate the given ``combobox`` with the class or function names. Parameters ---------- combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate data : list of :class:`FoldScopeHelper` The data to populate with. There should be one list element per class or function defintion in the file. Returns ------- None """ combobox.clear() combobox.addItem("<None>", 0) # First create a list of fully-qualified names. cb_data = [] for item in data: fqn = item.name for parent in reversed(item.parents): fqn = parent.name + "." + fqn cb_data.append((fqn, item)) for fqn, item in sorted(cb_data, key=operator.itemgetter(0)): # Set the icon. Just threw this in here, streight from editortools.py icon = None if item.def_type == OED.FUNCTION_TOKEN: if item.name.startswith('__'): icon = ima.icon('private2') elif item.name.startswith('_'): icon = ima.icon('private1') else: icon = ima.icon('method') else: icon = ima.icon('class') # Add the combobox item if icon is not None: combobox.addItem(icon, fqn, item) else: combobox.addItem(fqn, item)
python
def populate(combobox, data): """ Populate the given ``combobox`` with the class or function names. Parameters ---------- combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate data : list of :class:`FoldScopeHelper` The data to populate with. There should be one list element per class or function defintion in the file. Returns ------- None """ combobox.clear() combobox.addItem("<None>", 0) # First create a list of fully-qualified names. cb_data = [] for item in data: fqn = item.name for parent in reversed(item.parents): fqn = parent.name + "." + fqn cb_data.append((fqn, item)) for fqn, item in sorted(cb_data, key=operator.itemgetter(0)): # Set the icon. Just threw this in here, streight from editortools.py icon = None if item.def_type == OED.FUNCTION_TOKEN: if item.name.startswith('__'): icon = ima.icon('private2') elif item.name.startswith('_'): icon = ima.icon('private1') else: icon = ima.icon('method') else: icon = ima.icon('class') # Add the combobox item if icon is not None: combobox.addItem(icon, fqn, item) else: combobox.addItem(fqn, item)
[ "def", "populate", "(", "combobox", ",", "data", ")", ":", "combobox", ".", "clear", "(", ")", "combobox", ".", "addItem", "(", "\"<None>\"", ",", "0", ")", "# First create a list of fully-qualified names.", "cb_data", "=", "[", "]", "for", "item", "in", "da...
Populate the given ``combobox`` with the class or function names. Parameters ---------- combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate data : list of :class:`FoldScopeHelper` The data to populate with. There should be one list element per class or function defintion in the file. Returns ------- None
[ "Populate", "the", "given", "combobox", "with", "the", "class", "or", "function", "names", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L32-L77
30,970
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
_adjust_parent_stack
def _adjust_parent_stack(fsh, prev, parents): """ Adjust the parent stack in-place as the trigger level changes. Parameters ---------- fsh : :class:`FoldScopeHelper` The :class:`FoldScopeHelper` object to act on. prev : :class:`FoldScopeHelper` The previous :class:`FoldScopeHelper` object. parents : list of :class:`FoldScopeHelper` The current list of parent objects. Returns ------- None """ if prev is None: return if fsh.fold_scope.trigger_level < prev.fold_scope.trigger_level: diff = prev.fold_scope.trigger_level - fsh.fold_scope.trigger_level del parents[-diff:] elif fsh.fold_scope.trigger_level > prev.fold_scope.trigger_level: parents.append(prev) elif fsh.fold_scope.trigger_level == prev.fold_scope.trigger_level: pass
python
def _adjust_parent_stack(fsh, prev, parents): """ Adjust the parent stack in-place as the trigger level changes. Parameters ---------- fsh : :class:`FoldScopeHelper` The :class:`FoldScopeHelper` object to act on. prev : :class:`FoldScopeHelper` The previous :class:`FoldScopeHelper` object. parents : list of :class:`FoldScopeHelper` The current list of parent objects. Returns ------- None """ if prev is None: return if fsh.fold_scope.trigger_level < prev.fold_scope.trigger_level: diff = prev.fold_scope.trigger_level - fsh.fold_scope.trigger_level del parents[-diff:] elif fsh.fold_scope.trigger_level > prev.fold_scope.trigger_level: parents.append(prev) elif fsh.fold_scope.trigger_level == prev.fold_scope.trigger_level: pass
[ "def", "_adjust_parent_stack", "(", "fsh", ",", "prev", ",", "parents", ")", ":", "if", "prev", "is", "None", ":", "return", "if", "fsh", ".", "fold_scope", ".", "trigger_level", "<", "prev", ".", "fold_scope", ".", "trigger_level", ":", "diff", "=", "pr...
Adjust the parent stack in-place as the trigger level changes. Parameters ---------- fsh : :class:`FoldScopeHelper` The :class:`FoldScopeHelper` object to act on. prev : :class:`FoldScopeHelper` The previous :class:`FoldScopeHelper` object. parents : list of :class:`FoldScopeHelper` The current list of parent objects. Returns ------- None
[ "Adjust", "the", "parent", "stack", "in", "-", "place", "as", "the", "trigger", "level", "changes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L123-L149
30,971
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
_split_classes_and_methods
def _split_classes_and_methods(folds): """ Split out classes and methods into two separate lists. Parameters ---------- folds : list of :class:`FoldScopeHelper` The result of :func:`_get_fold_levels`. Returns ------- classes, functions: list of :class:`FoldScopeHelper` Two separate lists of :class:`FoldScopeHelper` objects. The former contains only class definitions while the latter contains only function/method definitions. """ classes = [] functions = [] for fold in folds: if fold.def_type == OED.FUNCTION_TOKEN: functions.append(fold) elif fold.def_type == OED.CLASS_TOKEN: classes.append(fold) return classes, functions
python
def _split_classes_and_methods(folds): """ Split out classes and methods into two separate lists. Parameters ---------- folds : list of :class:`FoldScopeHelper` The result of :func:`_get_fold_levels`. Returns ------- classes, functions: list of :class:`FoldScopeHelper` Two separate lists of :class:`FoldScopeHelper` objects. The former contains only class definitions while the latter contains only function/method definitions. """ classes = [] functions = [] for fold in folds: if fold.def_type == OED.FUNCTION_TOKEN: functions.append(fold) elif fold.def_type == OED.CLASS_TOKEN: classes.append(fold) return classes, functions
[ "def", "_split_classes_and_methods", "(", "folds", ")", ":", "classes", "=", "[", "]", "functions", "=", "[", "]", "for", "fold", "in", "folds", ":", "if", "fold", ".", "def_type", "==", "OED", ".", "FUNCTION_TOKEN", ":", "functions", ".", "append", "(",...
Split out classes and methods into two separate lists. Parameters ---------- folds : list of :class:`FoldScopeHelper` The result of :func:`_get_fold_levels`. Returns ------- classes, functions: list of :class:`FoldScopeHelper` Two separate lists of :class:`FoldScopeHelper` objects. The former contains only class definitions while the latter contains only function/method definitions.
[ "Split", "out", "classes", "and", "methods", "into", "two", "separate", "lists", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L152-L176
30,972
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
_get_parents
def _get_parents(folds, linenum): """ Get the parents at a given linenum. If parents is empty, then the linenum belongs to the module. Parameters ---------- folds : list of :class:`FoldScopeHelper` linenum : int The line number to get parents for. Typically this would be the cursor position. Returns ------- parents : list of :class:`FoldScopeHelper` A list of :class:`FoldScopeHelper` objects that describe the defintion heirarcy for the given ``linenum``. The 1st index will be the top-level parent defined at the module level while the last index will be the class or funtion that contains ``linenum``. """ # Note: this might be able to be sped up by finding some kind of # abort-early condition. parents = [] for fold in folds: start, end = fold.range if linenum >= start and linenum <= end: parents.append(fold) else: continue return parents
python
def _get_parents(folds, linenum): """ Get the parents at a given linenum. If parents is empty, then the linenum belongs to the module. Parameters ---------- folds : list of :class:`FoldScopeHelper` linenum : int The line number to get parents for. Typically this would be the cursor position. Returns ------- parents : list of :class:`FoldScopeHelper` A list of :class:`FoldScopeHelper` objects that describe the defintion heirarcy for the given ``linenum``. The 1st index will be the top-level parent defined at the module level while the last index will be the class or funtion that contains ``linenum``. """ # Note: this might be able to be sped up by finding some kind of # abort-early condition. parents = [] for fold in folds: start, end = fold.range if linenum >= start and linenum <= end: parents.append(fold) else: continue return parents
[ "def", "_get_parents", "(", "folds", ",", "linenum", ")", ":", "# Note: this might be able to be sped up by finding some kind of", "# abort-early condition.", "parents", "=", "[", "]", "for", "fold", "in", "folds", ":", "start", ",", "end", "=", "fold", ".", "range"...
Get the parents at a given linenum. If parents is empty, then the linenum belongs to the module. Parameters ---------- folds : list of :class:`FoldScopeHelper` linenum : int The line number to get parents for. Typically this would be the cursor position. Returns ------- parents : list of :class:`FoldScopeHelper` A list of :class:`FoldScopeHelper` objects that describe the defintion heirarcy for the given ``linenum``. The 1st index will be the top-level parent defined at the module level while the last index will be the class or funtion that contains ``linenum``.
[ "Get", "the", "parents", "at", "a", "given", "linenum", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L179-L210
30,973
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
update_selected_cb
def update_selected_cb(parents, combobox): """ Update the combobox with the selected item based on the parents. Parameters ---------- parents : list of :class:`FoldScopeHelper` combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate Returns ------- None """ if parents is not None and len(parents) == 0: combobox.setCurrentIndex(0) else: item = parents[-1] for i in range(combobox.count()): if combobox.itemData(i) == item: combobox.setCurrentIndex(i) break
python
def update_selected_cb(parents, combobox): """ Update the combobox with the selected item based on the parents. Parameters ---------- parents : list of :class:`FoldScopeHelper` combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate Returns ------- None """ if parents is not None and len(parents) == 0: combobox.setCurrentIndex(0) else: item = parents[-1] for i in range(combobox.count()): if combobox.itemData(i) == item: combobox.setCurrentIndex(i) break
[ "def", "update_selected_cb", "(", "parents", ",", "combobox", ")", ":", "if", "parents", "is", "not", "None", "and", "len", "(", "parents", ")", "==", "0", ":", "combobox", ".", "setCurrentIndex", "(", "0", ")", "else", ":", "item", "=", "parents", "["...
Update the combobox with the selected item based on the parents. Parameters ---------- parents : list of :class:`FoldScopeHelper` combobox : :class:`qtpy.QtWidets.QComboBox` The combobox to populate Returns ------- None
[ "Update", "the", "combobox", "with", "the", "selected", "item", "based", "on", "the", "parents", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L213-L234
30,974
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
ClassFunctionDropdown._update_data
def _update_data(self): """Update the internal data values.""" _old = self.folds self.folds = _get_fold_levels(self.editor) # only update our dropdown lists if the folds have changed. if self.folds != _old: self.classes, self.funcs = _split_classes_and_methods(self.folds) self.populate_dropdowns()
python
def _update_data(self): """Update the internal data values.""" _old = self.folds self.folds = _get_fold_levels(self.editor) # only update our dropdown lists if the folds have changed. if self.folds != _old: self.classes, self.funcs = _split_classes_and_methods(self.folds) self.populate_dropdowns()
[ "def", "_update_data", "(", "self", ")", ":", "_old", "=", "self", ".", "folds", "self", ".", "folds", "=", "_get_fold_levels", "(", "self", ".", "editor", ")", "# only update our dropdown lists if the folds have changed.", "if", "self", ".", "folds", "!=", "_ol...
Update the internal data values.
[ "Update", "the", "internal", "data", "values", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L378-L386
30,975
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
ClassFunctionDropdown.combobox_activated
def combobox_activated(self): """Move the cursor to the selected definition.""" sender = self.sender() data = sender.itemData(sender.currentIndex()) if isinstance(data, FoldScopeHelper): self.editor.go_to_line(data.line + 1)
python
def combobox_activated(self): """Move the cursor to the selected definition.""" sender = self.sender() data = sender.itemData(sender.currentIndex()) if isinstance(data, FoldScopeHelper): self.editor.go_to_line(data.line + 1)
[ "def", "combobox_activated", "(", "self", ")", ":", "sender", "=", "self", ".", "sender", "(", ")", "data", "=", "sender", ".", "itemData", "(", "sender", ".", "currentIndex", "(", ")", ")", "if", "isinstance", "(", "data", ",", "FoldScopeHelper", ")", ...
Move the cursor to the selected definition.
[ "Move", "the", "cursor", "to", "the", "selected", "definition", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L395-L401
30,976
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
ClassFunctionDropdown.update_selected
def update_selected(self, linenum): """Updates the dropdowns to reflect the current class and function.""" self.parents = _get_parents(self.funcs, linenum) update_selected_cb(self.parents, self.method_cb) self.parents = _get_parents(self.classes, linenum) update_selected_cb(self.parents, self.class_cb)
python
def update_selected(self, linenum): """Updates the dropdowns to reflect the current class and function.""" self.parents = _get_parents(self.funcs, linenum) update_selected_cb(self.parents, self.method_cb) self.parents = _get_parents(self.classes, linenum) update_selected_cb(self.parents, self.class_cb)
[ "def", "update_selected", "(", "self", ",", "linenum", ")", ":", "self", ".", "parents", "=", "_get_parents", "(", "self", ".", "funcs", ",", "linenum", ")", "update_selected_cb", "(", "self", ".", "parents", ",", "self", ".", "method_cb", ")", "self", "...
Updates the dropdowns to reflect the current class and function.
[ "Updates", "the", "dropdowns", "to", "reflect", "the", "current", "class", "and", "function", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L403-L409
30,977
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.highlight_current_cell
def highlight_current_cell(self): """Highlight current cell""" if self.cell_separators is None or \ not self.highlight_current_cell_enabled: return cursor, whole_file_selected, whole_screen_selected =\ self.select_current_cell_in_visible_portion() selection = TextDecoration(cursor) selection.format.setProperty(QTextFormat.FullWidthSelection, to_qvariant(True)) selection.format.setBackground(self.currentcell_color) if whole_file_selected: self.clear_extra_selections('current_cell') elif whole_screen_selected: if self.has_cell_separators: self.set_extra_selections('current_cell', [selection]) self.update_extra_selections() else: self.clear_extra_selections('current_cell') else: self.set_extra_selections('current_cell', [selection]) self.update_extra_selections()
python
def highlight_current_cell(self): """Highlight current cell""" if self.cell_separators is None or \ not self.highlight_current_cell_enabled: return cursor, whole_file_selected, whole_screen_selected =\ self.select_current_cell_in_visible_portion() selection = TextDecoration(cursor) selection.format.setProperty(QTextFormat.FullWidthSelection, to_qvariant(True)) selection.format.setBackground(self.currentcell_color) if whole_file_selected: self.clear_extra_selections('current_cell') elif whole_screen_selected: if self.has_cell_separators: self.set_extra_selections('current_cell', [selection]) self.update_extra_selections() else: self.clear_extra_selections('current_cell') else: self.set_extra_selections('current_cell', [selection]) self.update_extra_selections()
[ "def", "highlight_current_cell", "(", "self", ")", ":", "if", "self", ".", "cell_separators", "is", "None", "or", "not", "self", ".", "highlight_current_cell_enabled", ":", "return", "cursor", ",", "whole_file_selected", ",", "whole_screen_selected", "=", "self", ...
Highlight current cell
[ "Highlight", "current", "cell" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L433-L455
30,978
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.select_current_cell
def select_current_cell(self): """Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating if the entire file is selected""" cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cur_pos = prev_pos = cursor.position() # Moving to the next line that is not a separator, if we are # exactly at one of them while self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.NextBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: return cursor, False prev_pos = cur_pos # If not, move backwards to find the previous separator while not self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.PreviousBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: if self.is_cell_separator(cursor): return cursor, False else: break cursor.setPosition(prev_pos) cell_at_file_start = cursor.atStart() # Once we find it (or reach the beginning of the file) # move to the next separator (or the end of the file) # so we can grab the cell contents while not self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) cur_pos = cursor.position() if cur_pos == prev_pos: cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) break prev_pos = cur_pos cell_at_file_end = cursor.atEnd() return cursor, cell_at_file_start and cell_at_file_end
python
def select_current_cell(self): """Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating if the entire file is selected""" cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cur_pos = prev_pos = cursor.position() # Moving to the next line that is not a separator, if we are # exactly at one of them while self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.NextBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: return cursor, False prev_pos = cur_pos # If not, move backwards to find the previous separator while not self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.PreviousBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: if self.is_cell_separator(cursor): return cursor, False else: break cursor.setPosition(prev_pos) cell_at_file_start = cursor.atStart() # Once we find it (or reach the beginning of the file) # move to the next separator (or the end of the file) # so we can grab the cell contents while not self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) cur_pos = cursor.position() if cur_pos == prev_pos: cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) break prev_pos = cur_pos cell_at_file_end = cursor.atEnd() return cursor, cell_at_file_start and cell_at_file_end
[ "def", "select_current_cell", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "StartOfBlock", ")", "cur_pos", "=", "prev_pos", "=", "cursor", ".", "position", "(", ")", "# M...
Select cell under cursor cell = group of lines separated by CELL_SEPARATORS returns the textCursor and a boolean indicating if the entire file is selected
[ "Select", "cell", "under", "cursor", "cell", "=", "group", "of", "lines", "separated", "by", "CELL_SEPARATORS", "returns", "the", "textCursor", "and", "a", "boolean", "indicating", "if", "the", "entire", "file", "is", "selected" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L700-L743
30,979
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.select_current_cell_in_visible_portion
def select_current_cell_in_visible_portion(self): """Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns -the textCursor -a boolean indicating if the entire file is selected -a boolean indicating if the entire visible portion of the file is selected""" cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cur_pos = prev_pos = cursor.position() beg_pos = self.cursorForPosition(QPoint(0, 0)).position() bottom_right = QPoint(self.viewport().width() - 1, self.viewport().height() - 1) end_pos = self.cursorForPosition(bottom_right).position() # Moving to the next line that is not a separator, if we are # exactly at one of them while self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.NextBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: return cursor, False, False prev_pos = cur_pos # If not, move backwards to find the previous separator while not self.is_cell_separator(cursor)\ and cursor.position() >= beg_pos: cursor.movePosition(QTextCursor.PreviousBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: if self.is_cell_separator(cursor): return cursor, False, False else: break cell_at_screen_start = cursor.position() <= beg_pos cursor.setPosition(prev_pos) cell_at_file_start = cursor.atStart() # Selecting cell header if not cell_at_file_start: cursor.movePosition(QTextCursor.PreviousBlock) cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) # Once we find it (or reach the beginning of the file) # move to the next separator (or the end of the file) # so we can grab the cell contents while not self.is_cell_separator(cursor)\ and cursor.position() <= end_pos: cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) cur_pos = cursor.position() if cur_pos == prev_pos: cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) break prev_pos = cur_pos cell_at_file_end = cursor.atEnd() cell_at_screen_end = cursor.position() >= end_pos return cursor,\ cell_at_file_start and cell_at_file_end,\ cell_at_screen_start and cell_at_screen_end
python
def select_current_cell_in_visible_portion(self): """Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns -the textCursor -a boolean indicating if the entire file is selected -a boolean indicating if the entire visible portion of the file is selected""" cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) cur_pos = prev_pos = cursor.position() beg_pos = self.cursorForPosition(QPoint(0, 0)).position() bottom_right = QPoint(self.viewport().width() - 1, self.viewport().height() - 1) end_pos = self.cursorForPosition(bottom_right).position() # Moving to the next line that is not a separator, if we are # exactly at one of them while self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.NextBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: return cursor, False, False prev_pos = cur_pos # If not, move backwards to find the previous separator while not self.is_cell_separator(cursor)\ and cursor.position() >= beg_pos: cursor.movePosition(QTextCursor.PreviousBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: if self.is_cell_separator(cursor): return cursor, False, False else: break cell_at_screen_start = cursor.position() <= beg_pos cursor.setPosition(prev_pos) cell_at_file_start = cursor.atStart() # Selecting cell header if not cell_at_file_start: cursor.movePosition(QTextCursor.PreviousBlock) cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) # Once we find it (or reach the beginning of the file) # move to the next separator (or the end of the file) # so we can grab the cell contents while not self.is_cell_separator(cursor)\ and cursor.position() <= end_pos: cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) cur_pos = cursor.position() if cur_pos == prev_pos: cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) break prev_pos = cur_pos cell_at_file_end = cursor.atEnd() cell_at_screen_end = cursor.position() >= end_pos return cursor,\ cell_at_file_start and cell_at_file_end,\ cell_at_screen_start and cell_at_screen_end
[ "def", "select_current_cell_in_visible_portion", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "StartOfBlock", ")", "cur_pos", "=", "prev_pos", "=", "cursor", ".", "position", ...
Select cell under cursor in the visible portion of the file cell = group of lines separated by CELL_SEPARATORS returns -the textCursor -a boolean indicating if the entire file is selected -a boolean indicating if the entire visible portion of the file is selected
[ "Select", "cell", "under", "cursor", "in", "the", "visible", "portion", "of", "the", "file", "cell", "=", "group", "of", "lines", "separated", "by", "CELL_SEPARATORS", "returns", "-", "the", "textCursor", "-", "a", "boolean", "indicating", "if", "the", "enti...
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L745-L806
30,980
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.go_to_next_cell
def go_to_next_cell(self): """Go to the next cell of lines""" cursor = self.textCursor() cursor.movePosition(QTextCursor.NextBlock) cur_pos = prev_pos = cursor.position() while not self.is_cell_separator(cursor): # Moving to the next code cell cursor.movePosition(QTextCursor.NextBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: return self.setTextCursor(cursor)
python
def go_to_next_cell(self): """Go to the next cell of lines""" cursor = self.textCursor() cursor.movePosition(QTextCursor.NextBlock) cur_pos = prev_pos = cursor.position() while not self.is_cell_separator(cursor): # Moving to the next code cell cursor.movePosition(QTextCursor.NextBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: return self.setTextCursor(cursor)
[ "def", "go_to_next_cell", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "NextBlock", ")", "cur_pos", "=", "prev_pos", "=", "cursor", ".", "position", "(", ")", "while", ...
Go to the next cell of lines
[ "Go", "to", "the", "next", "cell", "of", "lines" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L808-L820
30,981
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.go_to_previous_cell
def go_to_previous_cell(self): """Go to the previous cell of lines""" cursor = self.textCursor() cur_pos = prev_pos = cursor.position() if self.is_cell_separator(cursor): # Move to the previous cell cursor.movePosition(QTextCursor.PreviousBlock) cur_pos = prev_pos = cursor.position() while not self.is_cell_separator(cursor): # Move to the previous cell or the beginning of the current cell cursor.movePosition(QTextCursor.PreviousBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: return self.setTextCursor(cursor)
python
def go_to_previous_cell(self): """Go to the previous cell of lines""" cursor = self.textCursor() cur_pos = prev_pos = cursor.position() if self.is_cell_separator(cursor): # Move to the previous cell cursor.movePosition(QTextCursor.PreviousBlock) cur_pos = prev_pos = cursor.position() while not self.is_cell_separator(cursor): # Move to the previous cell or the beginning of the current cell cursor.movePosition(QTextCursor.PreviousBlock) prev_pos = cur_pos cur_pos = cursor.position() if cur_pos == prev_pos: return self.setTextCursor(cursor)
[ "def", "go_to_previous_cell", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cur_pos", "=", "prev_pos", "=", "cursor", ".", "position", "(", ")", "if", "self", ".", "is_cell_separator", "(", "cursor", ")", ":", "# Move to the p...
Go to the previous cell of lines
[ "Go", "to", "the", "previous", "cell", "of", "lines" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L822-L840
30,982
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.__restore_selection
def __restore_selection(self, start_pos, end_pos): """Restore cursor selection from position bounds""" cursor = self.textCursor() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) self.setTextCursor(cursor)
python
def __restore_selection(self, start_pos, end_pos): """Restore cursor selection from position bounds""" cursor = self.textCursor() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) self.setTextCursor(cursor)
[ "def", "__restore_selection", "(", "self", ",", "start_pos", ",", "end_pos", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "setPosition", "(", "start_pos", ")", "cursor", ".", "setPosition", "(", "end_pos", ",", "QTextCursor", ...
Restore cursor selection from position bounds
[ "Restore", "cursor", "selection", "from", "position", "bounds" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L851-L856
30,983
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.__duplicate_line_or_selection
def __duplicate_line_or_selection(self, after_current_line=True): """Duplicate current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() if to_text_string(cursor.selectedText()): cursor.setPosition(end_pos) # Check if end_pos is at the start of a block: if so, starting # changes from the previous block cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.KeepAnchor) if not to_text_string(cursor.selectedText()): cursor.movePosition(QTextCursor.PreviousBlock) end_pos = cursor.position() cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) while cursor.position() <= end_pos: cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) if cursor.atEnd(): cursor_temp = QTextCursor(cursor) cursor_temp.clearSelection() cursor_temp.insertText(self.get_line_separator()) break cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) text = cursor.selectedText() cursor.clearSelection() if not after_current_line: # Moving cursor before current line/selected text cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) start_pos += len(text) end_pos += len(text) cursor.insertText(text) cursor.endEditBlock() self.setTextCursor(cursor) self.__restore_selection(start_pos, end_pos)
python
def __duplicate_line_or_selection(self, after_current_line=True): """Duplicate current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() if to_text_string(cursor.selectedText()): cursor.setPosition(end_pos) # Check if end_pos is at the start of a block: if so, starting # changes from the previous block cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.KeepAnchor) if not to_text_string(cursor.selectedText()): cursor.movePosition(QTextCursor.PreviousBlock) end_pos = cursor.position() cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) while cursor.position() <= end_pos: cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) if cursor.atEnd(): cursor_temp = QTextCursor(cursor) cursor_temp.clearSelection() cursor_temp.insertText(self.get_line_separator()) break cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) text = cursor.selectedText() cursor.clearSelection() if not after_current_line: # Moving cursor before current line/selected text cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) start_pos += len(text) end_pos += len(text) cursor.insertText(text) cursor.endEditBlock() self.setTextCursor(cursor) self.__restore_selection(start_pos, end_pos)
[ "def", "__duplicate_line_or_selection", "(", "self", ",", "after_current_line", "=", "True", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "beginEditBlock", "(", ")", "start_pos", ",", "end_pos", "=", "self", ".", "__save_selecti...
Duplicate current line or selected text
[ "Duplicate", "current", "line", "or", "selected", "text" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L858-L896
30,984
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.__move_line_or_selection
def __move_line_or_selection(self, after_current_line=True): """Move current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() last_line = False # ------ Select text # Get selection start location cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) start_pos = cursor.position() # Get selection end location cursor.setPosition(end_pos) if not cursor.atBlockStart() or end_pos == start_pos: cursor.movePosition(QTextCursor.EndOfBlock) cursor.movePosition(QTextCursor.NextBlock) end_pos = cursor.position() # Check if selection ends on the last line of the document if cursor.atEnd(): if not cursor.atBlockStart() or end_pos == start_pos: last_line = True # ------ Stop if at document boundary cursor.setPosition(start_pos) if cursor.atStart() and not after_current_line: # Stop if selection is already at top of the file while moving up cursor.endEditBlock() self.setTextCursor(cursor) self.__restore_selection(start_pos, end_pos) return cursor.setPosition(end_pos, QTextCursor.KeepAnchor) if last_line and after_current_line: # Stop if selection is already at end of the file while moving down cursor.endEditBlock() self.setTextCursor(cursor) self.__restore_selection(start_pos, end_pos) return # ------ Move text sel_text = to_text_string(cursor.selectedText()) cursor.removeSelectedText() if after_current_line: # Shift selection down text = to_text_string(cursor.block().text()) sel_text = os.linesep + sel_text[0:-1] # Move linesep at the start cursor.movePosition(QTextCursor.EndOfBlock) start_pos += len(text)+1 end_pos += len(text) if not cursor.atEnd(): end_pos += 1 else: # Shift selection up if last_line: # Remove the last linesep and add it to the selected text cursor.deletePreviousChar() sel_text = sel_text + os.linesep cursor.movePosition(QTextCursor.StartOfBlock) end_pos += 1 else: cursor.movePosition(QTextCursor.PreviousBlock) text = to_text_string(cursor.block().text()) start_pos -= len(text)+1 end_pos -= len(text)+1 cursor.insertText(sel_text) cursor.endEditBlock() self.setTextCursor(cursor) self.__restore_selection(start_pos, end_pos)
python
def __move_line_or_selection(self, after_current_line=True): """Move current line or selected text""" cursor = self.textCursor() cursor.beginEditBlock() start_pos, end_pos = self.__save_selection() last_line = False # ------ Select text # Get selection start location cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) start_pos = cursor.position() # Get selection end location cursor.setPosition(end_pos) if not cursor.atBlockStart() or end_pos == start_pos: cursor.movePosition(QTextCursor.EndOfBlock) cursor.movePosition(QTextCursor.NextBlock) end_pos = cursor.position() # Check if selection ends on the last line of the document if cursor.atEnd(): if not cursor.atBlockStart() or end_pos == start_pos: last_line = True # ------ Stop if at document boundary cursor.setPosition(start_pos) if cursor.atStart() and not after_current_line: # Stop if selection is already at top of the file while moving up cursor.endEditBlock() self.setTextCursor(cursor) self.__restore_selection(start_pos, end_pos) return cursor.setPosition(end_pos, QTextCursor.KeepAnchor) if last_line and after_current_line: # Stop if selection is already at end of the file while moving down cursor.endEditBlock() self.setTextCursor(cursor) self.__restore_selection(start_pos, end_pos) return # ------ Move text sel_text = to_text_string(cursor.selectedText()) cursor.removeSelectedText() if after_current_line: # Shift selection down text = to_text_string(cursor.block().text()) sel_text = os.linesep + sel_text[0:-1] # Move linesep at the start cursor.movePosition(QTextCursor.EndOfBlock) start_pos += len(text)+1 end_pos += len(text) if not cursor.atEnd(): end_pos += 1 else: # Shift selection up if last_line: # Remove the last linesep and add it to the selected text cursor.deletePreviousChar() sel_text = sel_text + os.linesep cursor.movePosition(QTextCursor.StartOfBlock) end_pos += 1 else: cursor.movePosition(QTextCursor.PreviousBlock) text = to_text_string(cursor.block().text()) start_pos -= len(text)+1 end_pos -= len(text)+1 cursor.insertText(sel_text) cursor.endEditBlock() self.setTextCursor(cursor) self.__restore_selection(start_pos, end_pos)
[ "def", "__move_line_or_selection", "(", "self", ",", "after_current_line", "=", "True", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "beginEditBlock", "(", ")", "start_pos", ",", "end_pos", "=", "self", ".", "__save_selection", ...
Move current line or selected text
[ "Move", "current", "line", "or", "selected", "text" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L912-L989
30,985
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.go_to_new_line
def go_to_new_line(self): """Go to the end of the current line and create a new line""" self.stdkey_end(False, False) self.insert_text(self.get_line_separator())
python
def go_to_new_line(self): """Go to the end of the current line and create a new line""" self.stdkey_end(False, False) self.insert_text(self.get_line_separator())
[ "def", "go_to_new_line", "(", "self", ")", ":", "self", ".", "stdkey_end", "(", "False", ",", "False", ")", "self", ".", "insert_text", "(", "self", ".", "get_line_separator", "(", ")", ")" ]
Go to the end of the current line and create a new line
[ "Go", "to", "the", "end", "of", "the", "current", "line", "and", "create", "a", "new", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L999-L1002
30,986
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.extend_selection_to_complete_lines
def extend_selection_to_complete_lines(self): """Extend current selection to complete lines""" cursor = self.textCursor() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) if cursor.atBlockStart(): cursor.movePosition(QTextCursor.PreviousBlock, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) self.setTextCursor(cursor)
python
def extend_selection_to_complete_lines(self): """Extend current selection to complete lines""" cursor = self.textCursor() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) cursor.setPosition(end_pos, QTextCursor.KeepAnchor) if cursor.atBlockStart(): cursor.movePosition(QTextCursor.PreviousBlock, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) self.setTextCursor(cursor)
[ "def", "extend_selection_to_complete_lines", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "start_pos", ",", "end_pos", "=", "cursor", ".", "selectionStart", "(", ")", ",", "cursor", ".", "selectionEnd", "(", ")", "cursor", ".", ...
Extend current selection to complete lines
[ "Extend", "current", "selection", "to", "complete", "lines" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1004-L1015
30,987
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.delete_line
def delete_line(self): """Delete current line""" cursor = self.textCursor() if self.has_selected_text(): self.extend_selection_to_complete_lines() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) else: start_pos = end_pos = cursor.position() cursor.beginEditBlock() cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) while cursor.position() <= end_pos: cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) if cursor.atEnd(): break cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor.endEditBlock() self.ensureCursorVisible()
python
def delete_line(self): """Delete current line""" cursor = self.textCursor() if self.has_selected_text(): self.extend_selection_to_complete_lines() start_pos, end_pos = cursor.selectionStart(), cursor.selectionEnd() cursor.setPosition(start_pos) else: start_pos = end_pos = cursor.position() cursor.beginEditBlock() cursor.setPosition(start_pos) cursor.movePosition(QTextCursor.StartOfBlock) while cursor.position() <= end_pos: cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) if cursor.atEnd(): break cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor.endEditBlock() self.ensureCursorVisible()
[ "def", "delete_line", "(", "self", ")", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "if", "self", ".", "has_selected_text", "(", ")", ":", "self", ".", "extend_selection_to_complete_lines", "(", ")", "start_pos", ",", "end_pos", "=", "cursor", ...
Delete current line
[ "Delete", "current", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1017-L1036
30,988
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.truncate_selection
def truncate_selection(self, position_from): """Unselect read-only parts in shell, like prompt""" position_from = self.get_position(position_from) cursor = self.textCursor() start, end = cursor.selectionStart(), cursor.selectionEnd() if start < end: start = max([position_from, start]) else: end = max([position_from, end]) self.set_selection(start, end)
python
def truncate_selection(self, position_from): """Unselect read-only parts in shell, like prompt""" position_from = self.get_position(position_from) cursor = self.textCursor() start, end = cursor.selectionStart(), cursor.selectionEnd() if start < end: start = max([position_from, start]) else: end = max([position_from, end]) self.set_selection(start, end)
[ "def", "truncate_selection", "(", "self", ",", "position_from", ")", ":", "position_from", "=", "self", ".", "get_position", "(", "position_from", ")", "cursor", "=", "self", ".", "textCursor", "(", ")", "start", ",", "end", "=", "cursor", ".", "selectionSta...
Unselect read-only parts in shell, like prompt
[ "Unselect", "read", "-", "only", "parts", "in", "shell", "like", "prompt" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1044-L1053
30,989
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.restrict_cursor_position
def restrict_cursor_position(self, position_from, position_to): """In shell, avoid editing text except between prompt and EOF""" position_from = self.get_position(position_from) position_to = self.get_position(position_to) cursor = self.textCursor() cursor_position = cursor.position() if cursor_position < position_from or cursor_position > position_to: self.set_cursor_position(position_to)
python
def restrict_cursor_position(self, position_from, position_to): """In shell, avoid editing text except between prompt and EOF""" position_from = self.get_position(position_from) position_to = self.get_position(position_to) cursor = self.textCursor() cursor_position = cursor.position() if cursor_position < position_from or cursor_position > position_to: self.set_cursor_position(position_to)
[ "def", "restrict_cursor_position", "(", "self", ",", "position_from", ",", "position_to", ")", ":", "position_from", "=", "self", ".", "get_position", "(", "position_from", ")", "position_to", "=", "self", ".", "get_position", "(", "position_to", ")", "cursor", ...
In shell, avoid editing text except between prompt and EOF
[ "In", "shell", "avoid", "editing", "text", "except", "between", "prompt", "and", "EOF" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1055-L1062
30,990
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.hide_tooltip_if_necessary
def hide_tooltip_if_necessary(self, key): """Hide calltip when necessary""" try: calltip_char = self.get_character(self.calltip_position) before = self.is_cursor_before(self.calltip_position, char_offset=1) other = key in (Qt.Key_ParenRight, Qt.Key_Period, Qt.Key_Tab) if calltip_char not in ('?', '(') or before or other: QToolTip.hideText() except (IndexError, TypeError): QToolTip.hideText()
python
def hide_tooltip_if_necessary(self, key): """Hide calltip when necessary""" try: calltip_char = self.get_character(self.calltip_position) before = self.is_cursor_before(self.calltip_position, char_offset=1) other = key in (Qt.Key_ParenRight, Qt.Key_Period, Qt.Key_Tab) if calltip_char not in ('?', '(') or before or other: QToolTip.hideText() except (IndexError, TypeError): QToolTip.hideText()
[ "def", "hide_tooltip_if_necessary", "(", "self", ",", "key", ")", ":", "try", ":", "calltip_char", "=", "self", ".", "get_character", "(", "self", ".", "calltip_position", ")", "before", "=", "self", ".", "is_cursor_before", "(", "self", ".", "calltip_position...
Hide calltip when necessary
[ "Hide", "calltip", "when", "necessary" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1065-L1075
30,991
spyder-ide/spyder
spyder/app/cli_options.py
get_options
def get_options(argv=None): """ Convert options into commands return commands, message """ parser = argparse.ArgumentParser(usage="spyder [options] files") parser.add_argument('--new-instance', action='store_true', default=False, help="Run a new instance of Spyder, even if the single " "instance mode has been turned on (default)") parser.add_argument('--defaults', dest="reset_to_defaults", action='store_true', default=False, help="Reset configuration settings to defaults") parser.add_argument('--reset', dest="reset_config_files", action='store_true', default=False, help="Remove all configuration files!") parser.add_argument('--optimize', action='store_true', default=False, help="Optimize Spyder bytecode (this may require " "administrative privileges)") parser.add_argument('-w', '--workdir', dest="working_directory", default=None, help="Default working directory") parser.add_argument('--hide-console', action='store_true', default=False, help="Hide parent console window (Windows)") parser.add_argument('--show-console', action='store_true', default=False, help="(Deprecated) Does nothing, now the default behavior " "is to show the console") parser.add_argument('--multithread', dest="multithreaded", action='store_true', default=False, help="Internal console is executed in another thread " "(separate from main application thread)") parser.add_argument('--profile', action='store_true', default=False, help="Profile mode (internal test, " "not related with Python profiling)") parser.add_argument('--window-title', type=str, default=None, help="String to show in the main window title") parser.add_argument('-p', '--project', default=None, type=str, dest="project", help="Path that contains an Spyder project") parser.add_argument('--opengl', default=None, dest="opengl_implementation", choices=['software', 'desktop', 'gles'], help=("OpenGL implementation to pass to Qt") ) parser.add_argument('--debug-info', default=None, dest="debug_info", choices=['minimal', 'verbose'], help=("Level of internal debugging info to give. " "'minimal' only logs a small amount of " "confirmation messages and 'verbose' logs a " "lot of detailed information.") ) parser.add_argument('--debug-output', default='terminal', dest="debug_output", choices=['terminal', 'file'], help=("Print internal debugging info either to the " "terminal or to a file called spyder-debug.log " "in your current working directory. Default is " "'terminal'.") ) parser.add_argument('files', nargs='*') options = parser.parse_args(argv) args = options.files return options, args
python
def get_options(argv=None): """ Convert options into commands return commands, message """ parser = argparse.ArgumentParser(usage="spyder [options] files") parser.add_argument('--new-instance', action='store_true', default=False, help="Run a new instance of Spyder, even if the single " "instance mode has been turned on (default)") parser.add_argument('--defaults', dest="reset_to_defaults", action='store_true', default=False, help="Reset configuration settings to defaults") parser.add_argument('--reset', dest="reset_config_files", action='store_true', default=False, help="Remove all configuration files!") parser.add_argument('--optimize', action='store_true', default=False, help="Optimize Spyder bytecode (this may require " "administrative privileges)") parser.add_argument('-w', '--workdir', dest="working_directory", default=None, help="Default working directory") parser.add_argument('--hide-console', action='store_true', default=False, help="Hide parent console window (Windows)") parser.add_argument('--show-console', action='store_true', default=False, help="(Deprecated) Does nothing, now the default behavior " "is to show the console") parser.add_argument('--multithread', dest="multithreaded", action='store_true', default=False, help="Internal console is executed in another thread " "(separate from main application thread)") parser.add_argument('--profile', action='store_true', default=False, help="Profile mode (internal test, " "not related with Python profiling)") parser.add_argument('--window-title', type=str, default=None, help="String to show in the main window title") parser.add_argument('-p', '--project', default=None, type=str, dest="project", help="Path that contains an Spyder project") parser.add_argument('--opengl', default=None, dest="opengl_implementation", choices=['software', 'desktop', 'gles'], help=("OpenGL implementation to pass to Qt") ) parser.add_argument('--debug-info', default=None, dest="debug_info", choices=['minimal', 'verbose'], help=("Level of internal debugging info to give. " "'minimal' only logs a small amount of " "confirmation messages and 'verbose' logs a " "lot of detailed information.") ) parser.add_argument('--debug-output', default='terminal', dest="debug_output", choices=['terminal', 'file'], help=("Print internal debugging info either to the " "terminal or to a file called spyder-debug.log " "in your current working directory. Default is " "'terminal'.") ) parser.add_argument('files', nargs='*') options = parser.parse_args(argv) args = options.files return options, args
[ "def", "get_options", "(", "argv", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "usage", "=", "\"spyder [options] files\"", ")", "parser", ".", "add_argument", "(", "'--new-instance'", ",", "action", "=", "'store_true'", ",", "...
Convert options into commands return commands, message
[ "Convert", "options", "into", "commands", "return", "commands", "message" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/cli_options.py#L9-L70
30,992
spyder-ide/spyder
spyder/plugins/projects/api.py
BaseProject.set_recent_files
def set_recent_files(self, recent_files): """Set a list of files opened by the project.""" for recent_file in recent_files[:]: if not os.path.isfile(recent_file): recent_files.remove(recent_file) try: self.CONF[WORKSPACE].set('main', 'recent_files', list(OrderedDict.fromkeys(recent_files))) except EnvironmentError: pass
python
def set_recent_files(self, recent_files): """Set a list of files opened by the project.""" for recent_file in recent_files[:]: if not os.path.isfile(recent_file): recent_files.remove(recent_file) try: self.CONF[WORKSPACE].set('main', 'recent_files', list(OrderedDict.fromkeys(recent_files))) except EnvironmentError: pass
[ "def", "set_recent_files", "(", "self", ",", "recent_files", ")", ":", "for", "recent_file", "in", "recent_files", "[", ":", "]", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "recent_file", ")", ":", "recent_files", ".", "remove", "(", "recen...
Set a list of files opened by the project.
[ "Set", "a", "list", "of", "files", "opened", "by", "the", "project", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/api.py#L68-L77
30,993
spyder-ide/spyder
spyder/plugins/projects/api.py
BaseProject.get_recent_files
def get_recent_files(self): """Return a list of files opened by the project.""" try: recent_files = self.CONF[WORKSPACE].get('main', 'recent_files', default=[]) except EnvironmentError: return [] for recent_file in recent_files[:]: if not os.path.isfile(recent_file): recent_files.remove(recent_file) return list(OrderedDict.fromkeys(recent_files))
python
def get_recent_files(self): """Return a list of files opened by the project.""" try: recent_files = self.CONF[WORKSPACE].get('main', 'recent_files', default=[]) except EnvironmentError: return [] for recent_file in recent_files[:]: if not os.path.isfile(recent_file): recent_files.remove(recent_file) return list(OrderedDict.fromkeys(recent_files))
[ "def", "get_recent_files", "(", "self", ")", ":", "try", ":", "recent_files", "=", "self", ".", "CONF", "[", "WORKSPACE", "]", ".", "get", "(", "'main'", ",", "'recent_files'", ",", "default", "=", "[", "]", ")", "except", "EnvironmentError", ":", "retur...
Return a list of files opened by the project.
[ "Return", "a", "list", "of", "files", "opened", "by", "the", "project", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/api.py#L79-L90
30,994
spyder-ide/spyder
spyder/plugins/projects/api.py
BaseProject.set_root_path
def set_root_path(self, root_path): """Set project root path.""" if self.name is None: self.name = osp.basename(root_path) self.root_path = to_text_string(root_path) config_path = self.__get_project_config_path() if osp.exists(config_path): self.load() else: if not osp.isdir(self.root_path): os.mkdir(self.root_path) self.save()
python
def set_root_path(self, root_path): """Set project root path.""" if self.name is None: self.name = osp.basename(root_path) self.root_path = to_text_string(root_path) config_path = self.__get_project_config_path() if osp.exists(config_path): self.load() else: if not osp.isdir(self.root_path): os.mkdir(self.root_path) self.save()
[ "def", "set_root_path", "(", "self", ",", "root_path", ")", ":", "if", "self", ".", "name", "is", "None", ":", "self", ".", "name", "=", "osp", ".", "basename", "(", "root_path", ")", "self", ".", "root_path", "=", "to_text_string", "(", "root_path", "...
Set project root path.
[ "Set", "project", "root", "path", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/api.py#L115-L126
30,995
spyder-ide/spyder
spyder/plugins/projects/api.py
BaseProject.rename
def rename(self, new_name): """Rename project and rename its root path accordingly.""" old_name = self.name self.name = new_name pypath = self.relative_pythonpath # ?? self.root_path = self.root_path[:-len(old_name)]+new_name self.relative_pythonpath = pypath # ?? self.save()
python
def rename(self, new_name): """Rename project and rename its root path accordingly.""" old_name = self.name self.name = new_name pypath = self.relative_pythonpath # ?? self.root_path = self.root_path[:-len(old_name)]+new_name self.relative_pythonpath = pypath # ?? self.save()
[ "def", "rename", "(", "self", ",", "new_name", ")", ":", "old_name", "=", "self", ".", "name", "self", ".", "name", "=", "new_name", "pypath", "=", "self", ".", "relative_pythonpath", "# ??\r", "self", ".", "root_path", "=", "self", ".", "root_path", "["...
Rename project and rename its root path accordingly.
[ "Rename", "project", "and", "rename", "its", "root", "path", "accordingly", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/api.py#L128-L135
30,996
spyder-ide/spyder
spyder/plugins/onlinehelp/widgets.py
PydocBrowser.text_to_url
def text_to_url(self, text): """Convert text address into QUrl object""" if text.startswith('/'): text = text[1:] return QUrl(self.home_url.toString()+text+'.html')
python
def text_to_url(self, text): """Convert text address into QUrl object""" if text.startswith('/'): text = text[1:] return QUrl(self.home_url.toString()+text+'.html')
[ "def", "text_to_url", "(", "self", ",", "text", ")", ":", "if", "text", ".", "startswith", "(", "'/'", ")", ":", "text", "=", "text", "[", "1", ":", "]", "return", "QUrl", "(", "self", ".", "home_url", ".", "toString", "(", ")", "+", "text", "+",...
Convert text address into QUrl object
[ "Convert", "text", "address", "into", "QUrl", "object" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/widgets.py#L126-L130
30,997
spyder-ide/spyder
spyder/plugins/editor/utils/autosave.py
AutosaveForPlugin.do_autosave
def do_autosave(self): """Instruct current editorstack to autosave files where necessary.""" logger.debug('Autosave triggered') stack = self.editor.get_current_editorstack() stack.autosave.autosave_all() self.start_autosave_timer()
python
def do_autosave(self): """Instruct current editorstack to autosave files where necessary.""" logger.debug('Autosave triggered') stack = self.editor.get_current_editorstack() stack.autosave.autosave_all() self.start_autosave_timer()
[ "def", "do_autosave", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Autosave triggered'", ")", "stack", "=", "self", ".", "editor", ".", "get_current_editorstack", "(", ")", "stack", ".", "autosave", ".", "autosave_all", "(", ")", "self", ".", "sta...
Instruct current editorstack to autosave files where necessary.
[ "Instruct", "current", "editorstack", "to", "autosave", "files", "where", "necessary", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L99-L104
30,998
spyder-ide/spyder
spyder/plugins/editor/utils/autosave.py
AutosaveForPlugin.try_recover_from_autosave
def try_recover_from_autosave(self): """Offer to recover files from autosave.""" autosave_dir = get_conf_path('autosave') autosave_mapping = CONF.get('editor', 'autosave_mapping', {}) dialog = RecoveryDialog(autosave_dir, autosave_mapping, parent=self.editor) dialog.exec_if_nonempty() self.recover_files_to_open = dialog.files_to_open[:]
python
def try_recover_from_autosave(self): """Offer to recover files from autosave.""" autosave_dir = get_conf_path('autosave') autosave_mapping = CONF.get('editor', 'autosave_mapping', {}) dialog = RecoveryDialog(autosave_dir, autosave_mapping, parent=self.editor) dialog.exec_if_nonempty() self.recover_files_to_open = dialog.files_to_open[:]
[ "def", "try_recover_from_autosave", "(", "self", ")", ":", "autosave_dir", "=", "get_conf_path", "(", "'autosave'", ")", "autosave_mapping", "=", "CONF", ".", "get", "(", "'editor'", ",", "'autosave_mapping'", ",", "{", "}", ")", "dialog", "=", "RecoveryDialog",...
Offer to recover files from autosave.
[ "Offer", "to", "recover", "files", "from", "autosave", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L106-L113
30,999
spyder-ide/spyder
spyder/plugins/editor/utils/autosave.py
AutosaveForStack.create_unique_autosave_filename
def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored """ basename = osp.basename(filename) autosave_filename = osp.join(autosave_dir, basename) if autosave_filename in self.name_mapping.values(): counter = 0 root, ext = osp.splitext(basename) while autosave_filename in self.name_mapping.values(): counter += 1 autosave_basename = '{}-{}{}'.format(root, counter, ext) autosave_filename = osp.join(autosave_dir, autosave_basename) return autosave_filename
python
def create_unique_autosave_filename(self, filename, autosave_dir): """ Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored """ basename = osp.basename(filename) autosave_filename = osp.join(autosave_dir, basename) if autosave_filename in self.name_mapping.values(): counter = 0 root, ext = osp.splitext(basename) while autosave_filename in self.name_mapping.values(): counter += 1 autosave_basename = '{}-{}{}'.format(root, counter, ext) autosave_filename = osp.join(autosave_dir, autosave_basename) return autosave_filename
[ "def", "create_unique_autosave_filename", "(", "self", ",", "filename", ",", "autosave_dir", ")", ":", "basename", "=", "osp", ".", "basename", "(", "filename", ")", "autosave_filename", "=", "osp", ".", "join", "(", "autosave_dir", ",", "basename", ")", "if",...
Create unique autosave file name for specified file name. Args: filename (str): original file name autosave_dir (str): directory in which autosave files are stored
[ "Create", "unique", "autosave", "file", "name", "for", "specified", "file", "name", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L135-L152