repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
spyder-ide/spyder
spyder/utils/programs.py
is_module_installed
def is_module_installed(module_name, version=None, installed_version=None, interpreter=None): """ Return True if module *module_name* is installed If version is not None, checking module version (module must have an attribute named '__version__') version may starts with =, >=, > or < to specify the exact requirement ; multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0') interpreter: check if a module is installed with a given version in a determined interpreter """ if interpreter: if osp.isfile(interpreter) and ('python' in interpreter): checkver = inspect.getsource(check_version) get_modver = inspect.getsource(get_module_version) stable_ver = inspect.getsource(is_stable_version) ismod_inst = inspect.getsource(is_module_installed) f = tempfile.NamedTemporaryFile('wt', suffix='.py', dir=get_temp_dir(), delete=False) try: script = f.name f.write("# -*- coding: utf-8 -*-" + "\n\n") f.write("from distutils.version import LooseVersion" + "\n") f.write("import re" + "\n\n") f.write(stable_ver + "\n") f.write(checkver + "\n") f.write(get_modver + "\n") f.write(ismod_inst + "\n") if version: f.write("print(is_module_installed('%s','%s'))"\ % (module_name, version)) else: f.write("print(is_module_installed('%s'))" % module_name) # We need to flush and sync changes to ensure that the content # of the file is in disk before running the script f.flush() os.fsync(f) f.close() try: proc = run_program(interpreter, [script]) output, _err = proc.communicate() except subprocess.CalledProcessError: return True return eval(output.decode()) finally: if not f.closed: f.close() os.remove(script) else: # Try to not take a wrong decision if there is no interpreter # available (needed for the change_pystartup method of ExtConsole # config page) return True else: if installed_version is None: try: actver = get_module_version(module_name) except: # Module is not installed return False else: actver = installed_version if actver is None and version is not None: return False elif version is None: return True else: if ';' in version: output = True for ver in version.split(';'): output = output and is_module_installed(module_name, ver) return output match = re.search(r'[0-9]', version) assert match is not None, "Invalid version number" symb = version[:match.start()] if not symb: symb = '=' assert symb in ('>=', '>', '=', '<', '<='),\ "Invalid version condition '%s'" % symb version = version[match.start():] return check_version(actver, version, symb)
python
def is_module_installed(module_name, version=None, installed_version=None, interpreter=None): """ Return True if module *module_name* is installed If version is not None, checking module version (module must have an attribute named '__version__') version may starts with =, >=, > or < to specify the exact requirement ; multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0') interpreter: check if a module is installed with a given version in a determined interpreter """ if interpreter: if osp.isfile(interpreter) and ('python' in interpreter): checkver = inspect.getsource(check_version) get_modver = inspect.getsource(get_module_version) stable_ver = inspect.getsource(is_stable_version) ismod_inst = inspect.getsource(is_module_installed) f = tempfile.NamedTemporaryFile('wt', suffix='.py', dir=get_temp_dir(), delete=False) try: script = f.name f.write("# -*- coding: utf-8 -*-" + "\n\n") f.write("from distutils.version import LooseVersion" + "\n") f.write("import re" + "\n\n") f.write(stable_ver + "\n") f.write(checkver + "\n") f.write(get_modver + "\n") f.write(ismod_inst + "\n") if version: f.write("print(is_module_installed('%s','%s'))"\ % (module_name, version)) else: f.write("print(is_module_installed('%s'))" % module_name) # We need to flush and sync changes to ensure that the content # of the file is in disk before running the script f.flush() os.fsync(f) f.close() try: proc = run_program(interpreter, [script]) output, _err = proc.communicate() except subprocess.CalledProcessError: return True return eval(output.decode()) finally: if not f.closed: f.close() os.remove(script) else: # Try to not take a wrong decision if there is no interpreter # available (needed for the change_pystartup method of ExtConsole # config page) return True else: if installed_version is None: try: actver = get_module_version(module_name) except: # Module is not installed return False else: actver = installed_version if actver is None and version is not None: return False elif version is None: return True else: if ';' in version: output = True for ver in version.split(';'): output = output and is_module_installed(module_name, ver) return output match = re.search(r'[0-9]', version) assert match is not None, "Invalid version number" symb = version[:match.start()] if not symb: symb = '=' assert symb in ('>=', '>', '=', '<', '<='),\ "Invalid version condition '%s'" % symb version = version[match.start():] return check_version(actver, version, symb)
[ "def", "is_module_installed", "(", "module_name", ",", "version", "=", "None", ",", "installed_version", "=", "None", ",", "interpreter", "=", "None", ")", ":", "if", "interpreter", ":", "if", "osp", ".", "isfile", "(", "interpreter", ")", "and", "(", "'python'", "in", "interpreter", ")", ":", "checkver", "=", "inspect", ".", "getsource", "(", "check_version", ")", "get_modver", "=", "inspect", ".", "getsource", "(", "get_module_version", ")", "stable_ver", "=", "inspect", ".", "getsource", "(", "is_stable_version", ")", "ismod_inst", "=", "inspect", ".", "getsource", "(", "is_module_installed", ")", "f", "=", "tempfile", ".", "NamedTemporaryFile", "(", "'wt'", ",", "suffix", "=", "'.py'", ",", "dir", "=", "get_temp_dir", "(", ")", ",", "delete", "=", "False", ")", "try", ":", "script", "=", "f", ".", "name", "f", ".", "write", "(", "\"# -*- coding: utf-8 -*-\"", "+", "\"\\n\\n\"", ")", "f", ".", "write", "(", "\"from distutils.version import LooseVersion\"", "+", "\"\\n\"", ")", "f", ".", "write", "(", "\"import re\"", "+", "\"\\n\\n\"", ")", "f", ".", "write", "(", "stable_ver", "+", "\"\\n\"", ")", "f", ".", "write", "(", "checkver", "+", "\"\\n\"", ")", "f", ".", "write", "(", "get_modver", "+", "\"\\n\"", ")", "f", ".", "write", "(", "ismod_inst", "+", "\"\\n\"", ")", "if", "version", ":", "f", ".", "write", "(", "\"print(is_module_installed('%s','%s'))\"", "%", "(", "module_name", ",", "version", ")", ")", "else", ":", "f", ".", "write", "(", "\"print(is_module_installed('%s'))\"", "%", "module_name", ")", "# We need to flush and sync changes to ensure that the content\r", "# of the file is in disk before running the script\r", "f", ".", "flush", "(", ")", "os", ".", "fsync", "(", "f", ")", "f", ".", "close", "(", ")", "try", ":", "proc", "=", "run_program", "(", "interpreter", ",", "[", "script", "]", ")", "output", ",", "_err", "=", "proc", ".", "communicate", "(", ")", "except", "subprocess", ".", "CalledProcessError", ":", "return", "True", "return", "eval", "(", "output", ".", "decode", "(", ")", ")", "finally", ":", "if", "not", "f", ".", "closed", ":", "f", ".", "close", "(", ")", "os", ".", "remove", "(", "script", ")", "else", ":", "# Try to not take a wrong decision if there is no interpreter\r", "# available (needed for the change_pystartup method of ExtConsole\r", "# config page)\r", "return", "True", "else", ":", "if", "installed_version", "is", "None", ":", "try", ":", "actver", "=", "get_module_version", "(", "module_name", ")", "except", ":", "# Module is not installed\r", "return", "False", "else", ":", "actver", "=", "installed_version", "if", "actver", "is", "None", "and", "version", "is", "not", "None", ":", "return", "False", "elif", "version", "is", "None", ":", "return", "True", "else", ":", "if", "';'", "in", "version", ":", "output", "=", "True", "for", "ver", "in", "version", ".", "split", "(", "';'", ")", ":", "output", "=", "output", "and", "is_module_installed", "(", "module_name", ",", "ver", ")", "return", "output", "match", "=", "re", ".", "search", "(", "r'[0-9]'", ",", "version", ")", "assert", "match", "is", "not", "None", ",", "\"Invalid version number\"", "symb", "=", "version", "[", ":", "match", ".", "start", "(", ")", "]", "if", "not", "symb", ":", "symb", "=", "'='", "assert", "symb", "in", "(", "'>='", ",", "'>'", ",", "'='", ",", "'<'", ",", "'<='", ")", ",", "\"Invalid version condition '%s'\"", "%", "symb", "version", "=", "version", "[", "match", ".", "start", "(", ")", ":", "]", "return", "check_version", "(", "actver", ",", "version", ",", "symb", ")" ]
Return True if module *module_name* is installed If version is not None, checking module version (module must have an attribute named '__version__') version may starts with =, >=, > or < to specify the exact requirement ; multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0') interpreter: check if a module is installed with a given version in a determined interpreter
[ "Return", "True", "if", "module", "*", "module_name", "*", "is", "installed", "If", "version", "is", "not", "None", "checking", "module", "version", "(", "module", "must", "have", "an", "attribute", "named", "__version__", ")", "version", "may", "starts", "with", "=", ">", "=", ">", "or", "<", "to", "specify", "the", "exact", "requirement", ";", "multiple", "conditions", "may", "be", "separated", "by", ";", "(", "e", ".", "g", ".", ">", "=", "0", ".", "13", ";", "<1", ".", "0", ")", "interpreter", ":", "check", "if", "a", "module", "is", "installed", "with", "a", "given", "version", "in", "a", "determined", "interpreter" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/programs.py#L390-L476
train
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", "False", "else", ":", "return", "True" ]
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
train
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_python_interpreter_valid_name", "(", "filename", ")", ")", ":", "return", "False", "elif", "is_pythonw", "(", "filename", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "# pythonw is a binary on Windows\r", "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\r", "# the system\r", "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\r", "return", "False", "elif", "encoding", ".", "is_text_file", "(", "real_filename", ")", ":", "# At this point we can't have a text file\r", "return", "False", "else", ":", "return", "check_python_help", "(", "filename", ")" ]
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
train
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", ":", "return", "True" ]
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
train
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", "=", "(", "\"Options and arguments (and corresponding environment \"", "\"variables)\"", ")", "if", "'usage:'", "in", "output", "and", "valid", "in", "output", ":", "return", "True", "else", ":", "return", "False", "except", ":", "return", "False" ]
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
train
spyder-ide/spyder
spyder/plugins/editor/panels/debugger.py
DebuggerPanel.sizeHint
def sizeHint(self): """Override Qt method. Returns the widget size hint (based on the editor font size). """ fm = QFontMetrics(self.editor.font()) size_hint = QSize(fm.height(), fm.height()) if size_hint.width() > 16: size_hint.setWidth(16) return size_hint
python
def sizeHint(self): """Override Qt method. Returns the widget size hint (based on the editor font size). """ fm = QFontMetrics(self.editor.font()) size_hint = QSize(fm.height(), fm.height()) if size_hint.width() > 16: size_hint.setWidth(16) return size_hint
[ "def", "sizeHint", "(", "self", ")", ":", "fm", "=", "QFontMetrics", "(", "self", ".", "editor", ".", "font", "(", ")", ")", "size_hint", "=", "QSize", "(", "fm", ".", "height", "(", ")", ",", "fm", ".", "height", "(", ")", ")", "if", "size_hint", ".", "width", "(", ")", ">", "16", ":", "size_hint", ".", "setWidth", "(", "16", ")", "return", "size_hint" ]
Override Qt method. Returns the widget size hint (based on the editor font size).
[ "Override", "Qt", "method", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/debugger.py#L40-L49
train
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", "(", ")", ".", "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", ")" ]
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
train
spyder-ide/spyder
spyder/plugins/editor/panels/debugger.py
DebuggerPanel.paintEvent
def paintEvent(self, event): """Override Qt method. Paint breakpoints icons. """ super(DebuggerPanel, self).paintEvent(event) painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) for top, line_number, block in self.editor.visible_blocks: if self.line_number_hint == line_number: self._draw_breakpoint_icon(top, painter, 'transparent') if self._current_line_arrow == line_number and not self.stop: self._draw_breakpoint_icon(top, painter, 'arrow') data = block.userData() if data is None or not data.breakpoint: continue if data.breakpoint_condition is None: self._draw_breakpoint_icon(top, painter, 'breakpoint') else: self._draw_breakpoint_icon(top, painter, 'condition')
python
def paintEvent(self, event): """Override Qt method. Paint breakpoints icons. """ super(DebuggerPanel, self).paintEvent(event) painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) for top, line_number, block in self.editor.visible_blocks: if self.line_number_hint == line_number: self._draw_breakpoint_icon(top, painter, 'transparent') if self._current_line_arrow == line_number and not self.stop: self._draw_breakpoint_icon(top, painter, 'arrow') data = block.userData() if data is None or not data.breakpoint: continue if data.breakpoint_condition is None: self._draw_breakpoint_icon(top, painter, 'breakpoint') else: self._draw_breakpoint_icon(top, painter, 'condition')
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "super", "(", "DebuggerPanel", ",", "self", ")", ".", "paintEvent", "(", "event", ")", "painter", "=", "QPainter", "(", "self", ")", "painter", ".", "fillRect", "(", "event", ".", "rect", "(", ")", ",", "self", ".", "editor", ".", "sideareas_color", ")", "for", "top", ",", "line_number", ",", "block", "in", "self", ".", "editor", ".", "visible_blocks", ":", "if", "self", ".", "line_number_hint", "==", "line_number", ":", "self", ".", "_draw_breakpoint_icon", "(", "top", ",", "painter", ",", "'transparent'", ")", "if", "self", ".", "_current_line_arrow", "==", "line_number", "and", "not", "self", ".", "stop", ":", "self", ".", "_draw_breakpoint_icon", "(", "top", ",", "painter", ",", "'arrow'", ")", "data", "=", "block", ".", "userData", "(", ")", "if", "data", "is", "None", "or", "not", "data", ".", "breakpoint", ":", "continue", "if", "data", ".", "breakpoint_condition", "is", "None", ":", "self", ".", "_draw_breakpoint_icon", "(", "top", ",", "painter", ",", "'breakpoint'", ")", "else", ":", "self", ".", "_draw_breakpoint_icon", "(", "top", ",", "painter", ",", "'condition'", ")" ]
Override Qt method. Paint breakpoints icons.
[ "Override", "Qt", "method", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/debugger.py#L80-L102
train
spyder-ide/spyder
spyder/plugins/editor/panels/debugger.py
DebuggerPanel.mousePressEvent
def mousePressEvent(self, event): """Override Qt method Add/remove breakpoints by single click. """ line_number = self.editor.get_linenumber_from_mouse_event(event) shift = event.modifiers() & Qt.ShiftModifier self.editor.debugger.toogle_breakpoint(line_number, edit_condition=shift)
python
def mousePressEvent(self, event): """Override Qt method Add/remove breakpoints by single click. """ line_number = self.editor.get_linenumber_from_mouse_event(event) shift = event.modifiers() & Qt.ShiftModifier self.editor.debugger.toogle_breakpoint(line_number, edit_condition=shift)
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "line_number", "=", "self", ".", "editor", ".", "get_linenumber_from_mouse_event", "(", "event", ")", "shift", "=", "event", ".", "modifiers", "(", ")", "&", "Qt", ".", "ShiftModifier", "self", ".", "editor", ".", "debugger", ".", "toogle_breakpoint", "(", "line_number", ",", "edit_condition", "=", "shift", ")" ]
Override Qt method Add/remove breakpoints by single click.
[ "Override", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/debugger.py#L104-L112
train
spyder-ide/spyder
spyder/plugins/editor/panels/debugger.py
DebuggerPanel.mouseMoveEvent
def mouseMoveEvent(self, event): """Override Qt method. Draw semitransparent breakpoint hint. """ self.line_number_hint = self.editor.get_linenumber_from_mouse_event( event) self.update()
python
def mouseMoveEvent(self, event): """Override Qt method. Draw semitransparent breakpoint hint. """ self.line_number_hint = self.editor.get_linenumber_from_mouse_event( event) self.update()
[ "def", "mouseMoveEvent", "(", "self", ",", "event", ")", ":", "self", ".", "line_number_hint", "=", "self", ".", "editor", ".", "get_linenumber_from_mouse_event", "(", "event", ")", "self", ".", "update", "(", ")" ]
Override Qt method. Draw semitransparent breakpoint hint.
[ "Override", "Qt", "method", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/debugger.py#L114-L121
train
spyder-ide/spyder
spyder/plugins/editor/panels/debugger.py
DebuggerPanel.on_state_changed
def on_state_changed(self, state): """Change visibility and connect/disconnect signal. Args: state (bool): Activate/deactivate. """ if state: self.editor.sig_breakpoints_changed.connect(self.repaint) self.editor.sig_debug_stop.connect(self.set_current_line_arrow) self.editor.sig_debug_stop[()].connect(self.stop_clean) self.editor.sig_debug_start.connect(self.start_clean) else: self.editor.sig_breakpoints_changed.disconnect(self.repaint) self.editor.sig_debug_stop.disconnect(self.set_current_line_arrow) self.editor.sig_debug_stop[()].disconnect(self.stop_clean) self.editor.sig_debug_start.disconnect(self.start_clean)
python
def on_state_changed(self, state): """Change visibility and connect/disconnect signal. Args: state (bool): Activate/deactivate. """ if state: self.editor.sig_breakpoints_changed.connect(self.repaint) self.editor.sig_debug_stop.connect(self.set_current_line_arrow) self.editor.sig_debug_stop[()].connect(self.stop_clean) self.editor.sig_debug_start.connect(self.start_clean) else: self.editor.sig_breakpoints_changed.disconnect(self.repaint) self.editor.sig_debug_stop.disconnect(self.set_current_line_arrow) self.editor.sig_debug_stop[()].disconnect(self.stop_clean) self.editor.sig_debug_start.disconnect(self.start_clean)
[ "def", "on_state_changed", "(", "self", ",", "state", ")", ":", "if", "state", ":", "self", ".", "editor", ".", "sig_breakpoints_changed", ".", "connect", "(", "self", ".", "repaint", ")", "self", ".", "editor", ".", "sig_debug_stop", ".", "connect", "(", "self", ".", "set_current_line_arrow", ")", "self", ".", "editor", ".", "sig_debug_stop", "[", "(", ")", "]", ".", "connect", "(", "self", ".", "stop_clean", ")", "self", ".", "editor", ".", "sig_debug_start", ".", "connect", "(", "self", ".", "start_clean", ")", "else", ":", "self", ".", "editor", ".", "sig_breakpoints_changed", ".", "disconnect", "(", "self", ".", "repaint", ")", "self", ".", "editor", ".", "sig_debug_stop", ".", "disconnect", "(", "self", ".", "set_current_line_arrow", ")", "self", ".", "editor", ".", "sig_debug_stop", "[", "(", ")", "]", ".", "disconnect", "(", "self", ".", "stop_clean", ")", "self", ".", "editor", ".", "sig_debug_start", ".", "disconnect", "(", "self", ".", "start_clean", ")" ]
Change visibility and connect/disconnect signal. Args: state (bool): Activate/deactivate.
[ "Change", "visibility", "and", "connect", "/", "disconnect", "signal", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/debugger.py#L138-L153
train
spyder-ide/spyder
spyder/utils/workers.py
handle_qbytearray
def handle_qbytearray(obj, encoding): """Qt/Python2/3 compatibility helper.""" if isinstance(obj, QByteArray): obj = obj.data() return to_text_string(obj, encoding=encoding)
python
def handle_qbytearray(obj, encoding): """Qt/Python2/3 compatibility helper.""" if isinstance(obj, QByteArray): obj = obj.data() return to_text_string(obj, encoding=encoding)
[ "def", "handle_qbytearray", "(", "obj", ",", "encoding", ")", ":", "if", "isinstance", "(", "obj", ",", "QByteArray", ")", ":", "obj", "=", "obj", ".", "data", "(", ")", "return", "to_text_string", "(", "obj", ",", "encoding", "=", "encoding", ")" ]
Qt/Python2/3 compatibility helper.
[ "Qt", "/", "Python2", "/", "3", "compatibility", "helper", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L29-L34
train
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", ")", "else", ":", "return", "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
train
spyder-ide/spyder
spyder/utils/workers.py
PythonWorker.start
def start(self): """Start the worker (emits sig_started signal with worker as arg).""" if not self._started: self.sig_started.emit(self) self._started = True
python
def start(self): """Start the worker (emits sig_started signal with worker as arg).""" if not self._started: self.sig_started.emit(self) self._started = True
[ "def", "start", "(", "self", ")", ":", "if", "not", "self", ".", "_started", ":", "self", ".", "sig_started", ".", "emit", "(", "self", ")", "self", ".", "_started", "=", "True" ]
Start the worker (emits sig_started signal with worker as arg).
[ "Start", "the", "worker", "(", "emits", "sig_started", "signal", "with", "worker", "as", "arg", ")", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L59-L63
train
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", ":", "error", "=", "err", "if", "not", "self", ".", "_is_finished", ":", "self", ".", "sig_finished", ".", "emit", "(", "self", ",", "output", ",", "error", ")", "self", ".", "_is_finished", "=", "True" ]
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
train
spyder-ide/spyder
spyder/utils/workers.py
ProcessWorker._get_encoding
def _get_encoding(self): """Return the encoding/codepage to use.""" enco = 'utf-8' # Currently only cp1252 is allowed? if WIN: import ctypes codepage = to_text_string(ctypes.cdll.kernel32.GetACP()) # import locale # locale.getpreferredencoding() # Differences? enco = 'cp' + codepage return enco
python
def _get_encoding(self): """Return the encoding/codepage to use.""" enco = 'utf-8' # Currently only cp1252 is allowed? if WIN: import ctypes codepage = to_text_string(ctypes.cdll.kernel32.GetACP()) # import locale # locale.getpreferredencoding() # Differences? enco = 'cp' + codepage return enco
[ "def", "_get_encoding", "(", "self", ")", ":", "enco", "=", "'utf-8'", "# Currently only cp1252 is allowed?", "if", "WIN", ":", "import", "ctypes", "codepage", "=", "to_text_string", "(", "ctypes", ".", "cdll", ".", "kernel32", ".", "GetACP", "(", ")", ")", "# import locale", "# locale.getpreferredencoding() # Differences?", "enco", "=", "'cp'", "+", "codepage", "return", "enco" ]
Return the encoding/codepage to use.
[ "Return", "the", "encoding", "/", "codepage", "to", "use", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L118-L129
train
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", ".", "insert", "(", "k", ",", "v", ")", "self", ".", "_process", ".", "setProcessEnvironment", "(", "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
train
spyder-ide/spyder
spyder/utils/workers.py
ProcessWorker._partial
def _partial(self): """Callback for partial output.""" raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(raw_stdout, self._get_encoding()) if self._partial_stdout is None: self._partial_stdout = stdout else: self._partial_stdout += stdout self.sig_partial.emit(self, stdout, None)
python
def _partial(self): """Callback for partial output.""" raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(raw_stdout, self._get_encoding()) if self._partial_stdout is None: self._partial_stdout = stdout else: self._partial_stdout += stdout self.sig_partial.emit(self, stdout, None)
[ "def", "_partial", "(", "self", ")", ":", "raw_stdout", "=", "self", ".", "_process", ".", "readAllStandardOutput", "(", ")", "stdout", "=", "handle_qbytearray", "(", "raw_stdout", ",", "self", ".", "_get_encoding", "(", ")", ")", "if", "self", ".", "_partial_stdout", "is", "None", ":", "self", ".", "_partial_stdout", "=", "stdout", "else", ":", "self", ".", "_partial_stdout", "+=", "stdout", "self", ".", "sig_partial", ".", "emit", "(", "self", ",", "stdout", ",", "None", ")" ]
Callback for partial output.
[ "Callback", "for", "partial", "output", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L139-L149
train
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", "self", ".", "_fired", ":", "self", ".", "_timer", ".", "stop", "(", ")" ]
Callback for communicate.
[ "Callback", "for", "communicate", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L151-L157
train
spyder-ide/spyder
spyder/utils/workers.py
ProcessWorker.communicate
def communicate(self): """Retrieve information.""" self._communicate_first = True self._process.waitForFinished() enco = self._get_encoding() if self._partial_stdout is None: raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(raw_stdout, enco) else: stdout = self._partial_stdout raw_stderr = self._process.readAllStandardError() stderr = handle_qbytearray(raw_stderr, enco) result = [stdout.encode(enco), stderr.encode(enco)] if PY2: stderr = stderr.decode() result[-1] = '' self._result = result if not self._fired: self.sig_finished.emit(self, result[0], result[-1]) self._fired = True return result
python
def communicate(self): """Retrieve information.""" self._communicate_first = True self._process.waitForFinished() enco = self._get_encoding() if self._partial_stdout is None: raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(raw_stdout, enco) else: stdout = self._partial_stdout raw_stderr = self._process.readAllStandardError() stderr = handle_qbytearray(raw_stderr, enco) result = [stdout.encode(enco), stderr.encode(enco)] if PY2: stderr = stderr.decode() result[-1] = '' self._result = result if not self._fired: self.sig_finished.emit(self, result[0], result[-1]) self._fired = True return result
[ "def", "communicate", "(", "self", ")", ":", "self", ".", "_communicate_first", "=", "True", "self", ".", "_process", ".", "waitForFinished", "(", ")", "enco", "=", "self", ".", "_get_encoding", "(", ")", "if", "self", ".", "_partial_stdout", "is", "None", ":", "raw_stdout", "=", "self", ".", "_process", ".", "readAllStandardOutput", "(", ")", "stdout", "=", "handle_qbytearray", "(", "raw_stdout", ",", "enco", ")", "else", ":", "stdout", "=", "self", ".", "_partial_stdout", "raw_stderr", "=", "self", ".", "_process", ".", "readAllStandardError", "(", ")", "stderr", "=", "handle_qbytearray", "(", "raw_stderr", ",", "enco", ")", "result", "=", "[", "stdout", ".", "encode", "(", "enco", ")", ",", "stderr", ".", "encode", "(", "enco", ")", "]", "if", "PY2", ":", "stderr", "=", "stderr", ".", "decode", "(", ")", "result", "[", "-", "1", "]", "=", "''", "self", ".", "_result", "=", "result", "if", "not", "self", ".", "_fired", ":", "self", ".", "sig_finished", ".", "emit", "(", "self", ",", "result", "[", "0", "]", ",", "result", "[", "-", "1", "]", ")", "self", ".", "_fired", "=", "True", "return", "result" ]
Retrieve information.
[ "Retrieve", "information", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L159-L186
train
spyder-ide/spyder
spyder/utils/workers.py
ProcessWorker._start
def _start(self): """Start process.""" if not self._fired: self._partial_ouput = None self._process.start(self._cmd_list[0], self._cmd_list[1:]) self._timer.start()
python
def _start(self): """Start process.""" if not self._fired: self._partial_ouput = None self._process.start(self._cmd_list[0], self._cmd_list[1:]) self._timer.start()
[ "def", "_start", "(", "self", ")", ":", "if", "not", "self", ".", "_fired", ":", "self", ".", "_partial_ouput", "=", "None", "self", ".", "_process", ".", "start", "(", "self", ".", "_cmd_list", "[", "0", "]", ",", "self", ".", "_cmd_list", "[", "1", ":", "]", ")", "self", ".", "_timer", ".", "start", "(", ")" ]
Start process.
[ "Start", "process", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L196-L201
train
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", ".", "_fired", "=", "True" ]
Terminate running processes.
[ "Terminate", "running", "processes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L203-L210
train
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
train
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", ".", "_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", "(", ")" ]
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
train
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", "worker" ]
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
train
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
train
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:", "# pass", "self", ".", "_queue_workers", "=", "deque", "(", ")" ]
Terminate all worker processes.
[ "Terminate", "all", "worker", "processes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L303-L314
train
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
train
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", "(", "name", ")", "except", "OSError", ":", "pass", "return", "res" ]
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
train
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'", ",", "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" ]
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
train
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'", ")", "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" ]
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
train
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", "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", ")" ]
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
train
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", ",", "self", ")", "label", ".", "setWordWrap", "(", "True", ")", "self", ".", "layout", ".", "addWidget", "(", "label", ")" ]
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
train
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", ".", "AlignVCenter", ")", "self", ".", "table", ".", "setCellWidget", "(", "row", ",", "col", ",", "label", ")" ]
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
train
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'", ")", ",", "_", "(", "'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", ")" ]
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
train
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", ".", "addWidget", "(", "button_box", ")" ]
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
train
spyder-ide/spyder
spyder/plugins/workingdirectory/plugin.py
WorkingDirectory.register_plugin
def register_plugin(self): """Register plugin in Spyder's main window""" self.redirect_stdio.connect(self.main.redirect_internalshell_stdio) self.main.console.shell.refresh.connect(self.refresh_plugin) iconsize = 24 self.toolbar.setIconSize(QSize(iconsize, iconsize)) self.main.addToolBar(self.toolbar)
python
def register_plugin(self): """Register plugin in Spyder's main window""" self.redirect_stdio.connect(self.main.redirect_internalshell_stdio) self.main.console.shell.refresh.connect(self.refresh_plugin) iconsize = 24 self.toolbar.setIconSize(QSize(iconsize, iconsize)) self.main.addToolBar(self.toolbar)
[ "def", "register_plugin", "(", "self", ")", ":", "self", ".", "redirect_stdio", ".", "connect", "(", "self", ".", "main", ".", "redirect_internalshell_stdio", ")", "self", ".", "main", ".", "console", ".", "shell", ".", "refresh", ".", "connect", "(", "self", ".", "refresh_plugin", ")", "iconsize", "=", "24", "self", ".", "toolbar", ".", "setIconSize", "(", "QSize", "(", "iconsize", ",", "iconsize", ")", ")", "self", ".", "main", ".", "addToolBar", "(", "self", ".", "toolbar", ")" ]
Register plugin in Spyder's main window
[ "Register", "plugin", "in", "Spyder", "s", "main", "window" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L133-L139
train
spyder-ide/spyder
spyder/plugins/workingdirectory/plugin.py
WorkingDirectory.refresh_plugin
def refresh_plugin(self): """Refresh widget""" curdir = getcwd_or_home() self.pathedit.add_text(curdir) self.save_wdhistory() self.set_previous_enabled.emit( self.histindex is not None and self.histindex > 0) self.set_next_enabled.emit(self.histindex is not None and \ self.histindex < len(self.history)-1)
python
def refresh_plugin(self): """Refresh widget""" curdir = getcwd_or_home() self.pathedit.add_text(curdir) self.save_wdhistory() self.set_previous_enabled.emit( self.histindex is not None and self.histindex > 0) self.set_next_enabled.emit(self.histindex is not None and \ self.histindex < len(self.history)-1)
[ "def", "refresh_plugin", "(", "self", ")", ":", "curdir", "=", "getcwd_or_home", "(", ")", "self", ".", "pathedit", ".", "add_text", "(", "curdir", ")", "self", ".", "save_wdhistory", "(", ")", "self", ".", "set_previous_enabled", ".", "emit", "(", "self", ".", "histindex", "is", "not", "None", "and", "self", ".", "histindex", ">", "0", ")", "self", ".", "set_next_enabled", ".", "emit", "(", "self", ".", "histindex", "is", "not", "None", "and", "self", ".", "histindex", "<", "len", "(", "self", ".", "history", ")", "-", "1", ")" ]
Refresh widget
[ "Refresh", "widget" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L141-L149
train
spyder-ide/spyder
spyder/plugins/workingdirectory/plugin.py
WorkingDirectory.load_wdhistory
def load_wdhistory(self, workdir=None): """Load history from a text file in user home directory""" if osp.isfile(self.LOG_PATH): wdhistory, _ = encoding.readlines(self.LOG_PATH) wdhistory = [name for name in wdhistory if os.path.isdir(name)] else: if workdir is None: workdir = get_home_dir() wdhistory = [ workdir ] return wdhistory
python
def load_wdhistory(self, workdir=None): """Load history from a text file in user home directory""" if osp.isfile(self.LOG_PATH): wdhistory, _ = encoding.readlines(self.LOG_PATH) wdhistory = [name for name in wdhistory if os.path.isdir(name)] else: if workdir is None: workdir = get_home_dir() wdhistory = [ workdir ] return wdhistory
[ "def", "load_wdhistory", "(", "self", ",", "workdir", "=", "None", ")", ":", "if", "osp", ".", "isfile", "(", "self", ".", "LOG_PATH", ")", ":", "wdhistory", ",", "_", "=", "encoding", ".", "readlines", "(", "self", ".", "LOG_PATH", ")", "wdhistory", "=", "[", "name", "for", "name", "in", "wdhistory", "if", "os", ".", "path", ".", "isdir", "(", "name", ")", "]", "else", ":", "if", "workdir", "is", "None", ":", "workdir", "=", "get_home_dir", "(", ")", "wdhistory", "=", "[", "workdir", "]", "return", "wdhistory" ]
Load history from a text file in user home directory
[ "Load", "history", "from", "a", "text", "file", "in", "user", "home", "directory" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L160-L169
train
spyder-ide/spyder
spyder/plugins/workingdirectory/plugin.py
WorkingDirectory.save_wdhistory
def save_wdhistory(self): """Save history to a text file in user home directory""" text = [ to_text_string( self.pathedit.itemText(index) ) \ for index in range(self.pathedit.count()) ] try: encoding.writelines(text, self.LOG_PATH) except EnvironmentError: pass
python
def save_wdhistory(self): """Save history to a text file in user home directory""" text = [ to_text_string( self.pathedit.itemText(index) ) \ for index in range(self.pathedit.count()) ] try: encoding.writelines(text, self.LOG_PATH) except EnvironmentError: pass
[ "def", "save_wdhistory", "(", "self", ")", ":", "text", "=", "[", "to_text_string", "(", "self", ".", "pathedit", ".", "itemText", "(", "index", ")", ")", "for", "index", "in", "range", "(", "self", ".", "pathedit", ".", "count", "(", ")", ")", "]", "try", ":", "encoding", ".", "writelines", "(", "text", ",", "self", ".", "LOG_PATH", ")", "except", "EnvironmentError", ":", "pass" ]
Save history to a text file in user home directory
[ "Save", "history", "to", "a", "text", "file", "in", "user", "home", "directory" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L171-L178
train
spyder-ide/spyder
spyder/plugins/workingdirectory/plugin.py
WorkingDirectory.select_directory
def select_directory(self): """Select directory""" self.redirect_stdio.emit(False) directory = getexistingdirectory(self.main, _("Select directory"), getcwd_or_home()) if directory: self.chdir(directory) self.redirect_stdio.emit(True)
python
def select_directory(self): """Select directory""" self.redirect_stdio.emit(False) directory = getexistingdirectory(self.main, _("Select directory"), getcwd_or_home()) if directory: self.chdir(directory) self.redirect_stdio.emit(True)
[ "def", "select_directory", "(", "self", ")", ":", "self", ".", "redirect_stdio", ".", "emit", "(", "False", ")", "directory", "=", "getexistingdirectory", "(", "self", ".", "main", ",", "_", "(", "\"Select directory\"", ")", ",", "getcwd_or_home", "(", ")", ")", "if", "directory", ":", "self", ".", "chdir", "(", "directory", ")", "self", ".", "redirect_stdio", ".", "emit", "(", "True", ")" ]
Select directory
[ "Select", "directory" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L181-L188
train
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
train
spyder-ide/spyder
spyder/plugins/workingdirectory/plugin.py
WorkingDirectory.chdir
def chdir(self, directory, browsing_history=False, refresh_explorer=True, refresh_console=True): """Set directory as working directory""" if directory: directory = osp.abspath(to_text_string(directory)) # Working directory history management if browsing_history: directory = self.history[self.histindex] elif directory in self.history: self.histindex = self.history.index(directory) else: if self.histindex is None: self.history = [] else: self.history = self.history[:self.histindex+1] self.history.append(directory) self.histindex = len(self.history)-1 # Changing working directory try: os.chdir(directory) if refresh_explorer: self.set_explorer_cwd.emit(directory) if refresh_console: self.set_current_console_wd.emit(directory) self.refresh_findinfiles.emit() except OSError: self.history.pop(self.histindex) self.refresh_plugin()
python
def chdir(self, directory, browsing_history=False, refresh_explorer=True, refresh_console=True): """Set directory as working directory""" if directory: directory = osp.abspath(to_text_string(directory)) # Working directory history management if browsing_history: directory = self.history[self.histindex] elif directory in self.history: self.histindex = self.history.index(directory) else: if self.histindex is None: self.history = [] else: self.history = self.history[:self.histindex+1] self.history.append(directory) self.histindex = len(self.history)-1 # Changing working directory try: os.chdir(directory) if refresh_explorer: self.set_explorer_cwd.emit(directory) if refresh_console: self.set_current_console_wd.emit(directory) self.refresh_findinfiles.emit() except OSError: self.history.pop(self.histindex) self.refresh_plugin()
[ "def", "chdir", "(", "self", ",", "directory", ",", "browsing_history", "=", "False", ",", "refresh_explorer", "=", "True", ",", "refresh_console", "=", "True", ")", ":", "if", "directory", ":", "directory", "=", "osp", ".", "abspath", "(", "to_text_string", "(", "directory", ")", ")", "# Working directory history management\r", "if", "browsing_history", ":", "directory", "=", "self", ".", "history", "[", "self", ".", "histindex", "]", "elif", "directory", "in", "self", ".", "history", ":", "self", ".", "histindex", "=", "self", ".", "history", ".", "index", "(", "directory", ")", "else", ":", "if", "self", ".", "histindex", "is", "None", ":", "self", ".", "history", "=", "[", "]", "else", ":", "self", ".", "history", "=", "self", ".", "history", "[", ":", "self", ".", "histindex", "+", "1", "]", "self", ".", "history", ".", "append", "(", "directory", ")", "self", ".", "histindex", "=", "len", "(", "self", ".", "history", ")", "-", "1", "# Changing working directory\r", "try", ":", "os", ".", "chdir", "(", "directory", ")", "if", "refresh_explorer", ":", "self", ".", "set_explorer_cwd", ".", "emit", "(", "directory", ")", "if", "refresh_console", ":", "self", ".", "set_current_console_wd", ".", "emit", "(", "directory", ")", "self", ".", "refresh_findinfiles", ".", "emit", "(", ")", "except", "OSError", ":", "self", ".", "history", ".", "pop", "(", "self", ".", "histindex", ")", "self", ".", "refresh_plugin", "(", ")" ]
Set directory as working directory
[ "Set", "directory", "as", "working", "directory" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L211-L240
train
spyder-ide/spyder
spyder/plugins/editor/utils/debugger.py
DebuggerManager.toogle_breakpoint
def toogle_breakpoint(self, line_number=None, condition=None, edit_condition=False): """Add/remove breakpoint.""" if not self.editor.is_python_like(): return if line_number is None: block = self.editor.textCursor().block() else: block = self.editor.document().findBlockByNumber(line_number-1) data = block.userData() if not data: data = BlockUserData(self.editor) data.breakpoint = True elif not edit_condition: data.breakpoint = not data.breakpoint data.breakpoint_condition = None if condition is not None: data.breakpoint_condition = condition if edit_condition: condition = data.breakpoint_condition condition, valid = QInputDialog.getText(self.editor, _('Breakpoint'), _("Condition:"), QLineEdit.Normal, condition) if not valid: return data.breakpoint = True data.breakpoint_condition = str(condition) if condition else None if data.breakpoint: text = to_text_string(block.text()).strip() if len(text) == 0 or text.startswith(('#', '"', "'")): data.breakpoint = False block.setUserData(data) self.editor.sig_flags_changed.emit() self.editor.sig_breakpoints_changed.emit()
python
def toogle_breakpoint(self, line_number=None, condition=None, edit_condition=False): """Add/remove breakpoint.""" if not self.editor.is_python_like(): return if line_number is None: block = self.editor.textCursor().block() else: block = self.editor.document().findBlockByNumber(line_number-1) data = block.userData() if not data: data = BlockUserData(self.editor) data.breakpoint = True elif not edit_condition: data.breakpoint = not data.breakpoint data.breakpoint_condition = None if condition is not None: data.breakpoint_condition = condition if edit_condition: condition = data.breakpoint_condition condition, valid = QInputDialog.getText(self.editor, _('Breakpoint'), _("Condition:"), QLineEdit.Normal, condition) if not valid: return data.breakpoint = True data.breakpoint_condition = str(condition) if condition else None if data.breakpoint: text = to_text_string(block.text()).strip() if len(text) == 0 or text.startswith(('#', '"', "'")): data.breakpoint = False block.setUserData(data) self.editor.sig_flags_changed.emit() self.editor.sig_breakpoints_changed.emit()
[ "def", "toogle_breakpoint", "(", "self", ",", "line_number", "=", "None", ",", "condition", "=", "None", ",", "edit_condition", "=", "False", ")", ":", "if", "not", "self", ".", "editor", ".", "is_python_like", "(", ")", ":", "return", "if", "line_number", "is", "None", ":", "block", "=", "self", ".", "editor", ".", "textCursor", "(", ")", ".", "block", "(", ")", "else", ":", "block", "=", "self", ".", "editor", ".", "document", "(", ")", ".", "findBlockByNumber", "(", "line_number", "-", "1", ")", "data", "=", "block", ".", "userData", "(", ")", "if", "not", "data", ":", "data", "=", "BlockUserData", "(", "self", ".", "editor", ")", "data", ".", "breakpoint", "=", "True", "elif", "not", "edit_condition", ":", "data", ".", "breakpoint", "=", "not", "data", ".", "breakpoint", "data", ".", "breakpoint_condition", "=", "None", "if", "condition", "is", "not", "None", ":", "data", ".", "breakpoint_condition", "=", "condition", "if", "edit_condition", ":", "condition", "=", "data", ".", "breakpoint_condition", "condition", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ".", "editor", ",", "_", "(", "'Breakpoint'", ")", ",", "_", "(", "\"Condition:\"", ")", ",", "QLineEdit", ".", "Normal", ",", "condition", ")", "if", "not", "valid", ":", "return", "data", ".", "breakpoint", "=", "True", "data", ".", "breakpoint_condition", "=", "str", "(", "condition", ")", "if", "condition", "else", "None", "if", "data", ".", "breakpoint", ":", "text", "=", "to_text_string", "(", "block", ".", "text", "(", ")", ")", ".", "strip", "(", ")", "if", "len", "(", "text", ")", "==", "0", "or", "text", ".", "startswith", "(", "(", "'#'", ",", "'\"'", ",", "\"'\"", ")", ")", ":", "data", ".", "breakpoint", "=", "False", "block", ".", "setUserData", "(", "data", ")", "self", ".", "editor", ".", "sig_flags_changed", ".", "emit", "(", ")", "self", ".", "editor", ".", "sig_breakpoints_changed", ".", "emit", "(", ")" ]
Add/remove breakpoint.
[ "Add", "/", "remove", "breakpoint", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/debugger.py#L79-L114
train
spyder-ide/spyder
spyder/plugins/editor/utils/debugger.py
DebuggerManager.get_breakpoints
def get_breakpoints(self): """Get breakpoints""" breakpoints = [] block = self.editor.document().firstBlock() for line_number in range(1, self.editor.document().blockCount()+1): data = block.userData() if data and data.breakpoint: breakpoints.append((line_number, data.breakpoint_condition)) block = block.next() return breakpoints
python
def get_breakpoints(self): """Get breakpoints""" breakpoints = [] block = self.editor.document().firstBlock() for line_number in range(1, self.editor.document().blockCount()+1): data = block.userData() if data and data.breakpoint: breakpoints.append((line_number, data.breakpoint_condition)) block = block.next() return breakpoints
[ "def", "get_breakpoints", "(", "self", ")", ":", "breakpoints", "=", "[", "]", "block", "=", "self", ".", "editor", ".", "document", "(", ")", ".", "firstBlock", "(", ")", "for", "line_number", "in", "range", "(", "1", ",", "self", ".", "editor", ".", "document", "(", ")", ".", "blockCount", "(", ")", "+", "1", ")", ":", "data", "=", "block", ".", "userData", "(", ")", "if", "data", "and", "data", ".", "breakpoint", ":", "breakpoints", ".", "append", "(", "(", "line_number", ",", "data", ".", "breakpoint_condition", ")", ")", "block", "=", "block", ".", "next", "(", ")", "return", "breakpoints" ]
Get breakpoints
[ "Get", "breakpoints" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/debugger.py#L116-L125
train
spyder-ide/spyder
spyder/plugins/editor/utils/debugger.py
DebuggerManager.clear_breakpoints
def clear_breakpoints(self): """Clear breakpoints""" self.breakpoints = [] for data in self.editor.blockuserdata_list[:]: data.breakpoint = False # data.breakpoint_condition = None # not necessary, but logical if data.is_empty(): # This is not calling the __del__ in BlockUserData. Not # sure if it's supposed to or not, but that seems to be the # intent. del data
python
def clear_breakpoints(self): """Clear breakpoints""" self.breakpoints = [] for data in self.editor.blockuserdata_list[:]: data.breakpoint = False # data.breakpoint_condition = None # not necessary, but logical if data.is_empty(): # This is not calling the __del__ in BlockUserData. Not # sure if it's supposed to or not, but that seems to be the # intent. del data
[ "def", "clear_breakpoints", "(", "self", ")", ":", "self", ".", "breakpoints", "=", "[", "]", "for", "data", "in", "self", ".", "editor", ".", "blockuserdata_list", "[", ":", "]", ":", "data", ".", "breakpoint", "=", "False", "# data.breakpoint_condition = None # not necessary, but logical", "if", "data", ".", "is_empty", "(", ")", ":", "# This is not calling the __del__ in BlockUserData. Not", "# sure if it's supposed to or not, but that seems to be the", "# intent.", "del", "data" ]
Clear breakpoints
[ "Clear", "breakpoints" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/debugger.py#L127-L137
train
spyder-ide/spyder
spyder/plugins/editor/utils/debugger.py
DebuggerManager.set_breakpoints
def set_breakpoints(self, breakpoints): """Set breakpoints""" self.clear_breakpoints() for line_number, condition in breakpoints: self.toogle_breakpoint(line_number, condition) self.breakpoints = self.get_breakpoints()
python
def set_breakpoints(self, breakpoints): """Set breakpoints""" self.clear_breakpoints() for line_number, condition in breakpoints: self.toogle_breakpoint(line_number, condition) self.breakpoints = self.get_breakpoints()
[ "def", "set_breakpoints", "(", "self", ",", "breakpoints", ")", ":", "self", ".", "clear_breakpoints", "(", ")", "for", "line_number", ",", "condition", "in", "breakpoints", ":", "self", ".", "toogle_breakpoint", "(", "line_number", ",", "condition", ")", "self", ".", "breakpoints", "=", "self", ".", "get_breakpoints", "(", ")" ]
Set breakpoints
[ "Set", "breakpoints" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/debugger.py#L139-L144
train
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
train
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", ".", "replace", "(", "'\\\\\"'", ",", "''", ")", "if", "text", ".", "count", "(", "'\"'", ")", "%", "2", ":", "return", "'\"'", "elif", "text", ".", "count", "(", "\"'\"", ")", "%", "2", ":", "return", "\"'\"", "else", ":", "return", "''" ]
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
train
spyder-ide/spyder
spyder/plugins/editor/extensions/closequotes.py
CloseQuotesExtension.on_state_changed
def on_state_changed(self, state): """Connect/disconnect sig_key_pressed signal.""" if state: self.editor.sig_key_pressed.connect(self._on_key_pressed) else: self.editor.sig_key_pressed.disconnect(self._on_key_pressed)
python
def on_state_changed(self, state): """Connect/disconnect sig_key_pressed signal.""" if state: self.editor.sig_key_pressed.connect(self._on_key_pressed) else: self.editor.sig_key_pressed.disconnect(self._on_key_pressed)
[ "def", "on_state_changed", "(", "self", ",", "state", ")", ":", "if", "state", ":", "self", ".", "editor", ".", "sig_key_pressed", ".", "connect", "(", "self", ".", "_on_key_pressed", ")", "else", ":", "self", ".", "editor", ".", "sig_key_pressed", ".", "disconnect", "(", "self", ".", "_on_key_pressed", ")" ]
Connect/disconnect sig_key_pressed signal.
[ "Connect", "/", "disconnect", "sig_key_pressed", "signal", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/closequotes.py#L44-L49
train
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", "(", "'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", ")" ]
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
train
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", "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", ")" ]
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
train
spyder-ide/spyder
spyder/plugins/editor/panels/classfunctiondropdown.py
_get_fold_levels
def _get_fold_levels(editor): """ Return a list of all the class/function definition ranges. Parameters ---------- editor : :class:`spyder.plugins.editor.widgets.codeeditor.CodeEditor` Returns ------- folds : list of :class:`FoldScopeHelper` A list of all the class or function defintion fold points. """ block = editor.document().firstBlock() oed = editor.get_outlineexplorer_data() folds = [] parents = [] prev = None while block.isValid(): if TextBlockHelper.is_fold_trigger(block): try: data = oed[block.firstLineNumber()] if data.def_type in (OED.CLASS, OED.FUNCTION): fsh = FoldScopeHelper(FoldScope(block), data) # Determine the parents of the item using a stack. _adjust_parent_stack(fsh, prev, parents) # Update the parents of this FoldScopeHelper item fsh.parents = copy.copy(parents) folds.append(fsh) prev = fsh except KeyError: pass block = block.next() return folds
python
def _get_fold_levels(editor): """ Return a list of all the class/function definition ranges. Parameters ---------- editor : :class:`spyder.plugins.editor.widgets.codeeditor.CodeEditor` Returns ------- folds : list of :class:`FoldScopeHelper` A list of all the class or function defintion fold points. """ block = editor.document().firstBlock() oed = editor.get_outlineexplorer_data() folds = [] parents = [] prev = None while block.isValid(): if TextBlockHelper.is_fold_trigger(block): try: data = oed[block.firstLineNumber()] if data.def_type in (OED.CLASS, OED.FUNCTION): fsh = FoldScopeHelper(FoldScope(block), data) # Determine the parents of the item using a stack. _adjust_parent_stack(fsh, prev, parents) # Update the parents of this FoldScopeHelper item fsh.parents = copy.copy(parents) folds.append(fsh) prev = fsh except KeyError: pass block = block.next() return folds
[ "def", "_get_fold_levels", "(", "editor", ")", ":", "block", "=", "editor", ".", "document", "(", ")", ".", "firstBlock", "(", ")", "oed", "=", "editor", ".", "get_outlineexplorer_data", "(", ")", "folds", "=", "[", "]", "parents", "=", "[", "]", "prev", "=", "None", "while", "block", ".", "isValid", "(", ")", ":", "if", "TextBlockHelper", ".", "is_fold_trigger", "(", "block", ")", ":", "try", ":", "data", "=", "oed", "[", "block", ".", "firstLineNumber", "(", ")", "]", "if", "data", ".", "def_type", "in", "(", "OED", ".", "CLASS", ",", "OED", ".", "FUNCTION", ")", ":", "fsh", "=", "FoldScopeHelper", "(", "FoldScope", "(", "block", ")", ",", "data", ")", "# Determine the parents of the item using a stack.", "_adjust_parent_stack", "(", "fsh", ",", "prev", ",", "parents", ")", "# Update the parents of this FoldScopeHelper item", "fsh", ".", "parents", "=", "copy", ".", "copy", "(", "parents", ")", "folds", ".", "append", "(", "fsh", ")", "prev", "=", "fsh", "except", "KeyError", ":", "pass", "block", "=", "block", ".", "next", "(", ")", "return", "folds" ]
Return a list of all the class/function definition ranges. Parameters ---------- editor : :class:`spyder.plugins.editor.widgets.codeeditor.CodeEditor` Returns ------- folds : list of :class:`FoldScopeHelper` A list of all the class or function defintion fold points.
[ "Return", "a", "list", "of", "all", "the", "class", "/", "function", "definition", "ranges", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/classfunctiondropdown.py#L80-L120
train
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", "=", "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" ]
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
train
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", "(", "fold", ")", "elif", "fold", ".", "def_type", "==", "OED", ".", "CLASS_TOKEN", ":", "classes", ".", "append", "(", "fold", ")", "return", "classes", ",", "functions" ]
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
train
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", "if", "linenum", ">=", "start", "and", "linenum", "<=", "end", ":", "parents", ".", "append", "(", "fold", ")", "else", ":", "continue", "return", "parents" ]
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
train
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", "[", "-", "1", "]", "for", "i", "in", "range", "(", "combobox", ".", "count", "(", ")", ")", ":", "if", "combobox", ".", "itemData", "(", "i", ")", "==", "item", ":", "combobox", ".", "setCurrentIndex", "(", "i", ")", "break" ]
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
train
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", "!=", "_old", ":", "self", ".", "classes", ",", "self", ".", "funcs", "=", "_split_classes_and_methods", "(", "self", ".", "folds", ")", "self", ".", "populate_dropdowns", "(", ")" ]
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
train
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", ")", ":", "self", ".", "editor", ".", "go_to_line", "(", "data", ".", "line", "+", "1", ")" ]
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
train
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", ".", "parents", "=", "_get_parents", "(", "self", ".", "classes", ",", "linenum", ")", "update_selected_cb", "(", "self", ".", "parents", ",", "self", ".", "class_cb", ")" ]
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
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.set_palette
def set_palette(self, background, foreground): """ Set text editor palette colors: background color and caret (text cursor) color """ palette = QPalette() palette.setColor(QPalette.Base, background) palette.setColor(QPalette.Text, foreground) self.setPalette(palette) # Set the right background color when changing color schemes # or creating new Editor windows. This seems to be a Qt bug. # Fixes Issue 2028 and 8069 if self.objectName(): style = "QPlainTextEdit#%s {background: %s; color: %s;}" % \ (self.objectName(), background.name(), foreground.name()) self.setStyleSheet(style)
python
def set_palette(self, background, foreground): """ Set text editor palette colors: background color and caret (text cursor) color """ palette = QPalette() palette.setColor(QPalette.Base, background) palette.setColor(QPalette.Text, foreground) self.setPalette(palette) # Set the right background color when changing color schemes # or creating new Editor windows. This seems to be a Qt bug. # Fixes Issue 2028 and 8069 if self.objectName(): style = "QPlainTextEdit#%s {background: %s; color: %s;}" % \ (self.objectName(), background.name(), foreground.name()) self.setStyleSheet(style)
[ "def", "set_palette", "(", "self", ",", "background", ",", "foreground", ")", ":", "palette", "=", "QPalette", "(", ")", "palette", ".", "setColor", "(", "QPalette", ".", "Base", ",", "background", ")", "palette", ".", "setColor", "(", "QPalette", ".", "Text", ",", "foreground", ")", "self", ".", "setPalette", "(", "palette", ")", "# Set the right background color when changing color schemes\r", "# or creating new Editor windows. This seems to be a Qt bug.\r", "# Fixes Issue 2028 and 8069\r", "if", "self", ".", "objectName", "(", ")", ":", "style", "=", "\"QPlainTextEdit#%s {background: %s; color: %s;}\"", "%", "(", "self", ".", "objectName", "(", ")", ",", "background", ".", "name", "(", ")", ",", "foreground", ".", "name", "(", ")", ")", "self", ".", "setStyleSheet", "(", "style", ")" ]
Set text editor palette colors: background color and caret (text cursor) color
[ "Set", "text", "editor", "palette", "colors", ":", "background", "color", "and", "caret", "(", "text", "cursor", ")", "color" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L336-L352
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.set_extra_selections
def set_extra_selections(self, key, extra_selections): """Set extra selections for a key. Also assign draw orders to leave current_cell and current_line in the backgrund (and avoid them to cover other decorations) NOTE: This will remove previous decorations added to the same key. Args: key (str) name of the extra selections group. extra_selections (list of sourcecode.api.TextDecoration). """ # use draw orders to highlight current_cell and current_line first draw_order = DRAW_ORDERS.get(key) if draw_order is None: draw_order = DRAW_ORDERS.get('on_top') for selection in extra_selections: selection.draw_order = draw_order self.clear_extra_selections(key) self.extra_selections_dict[key] = extra_selections
python
def set_extra_selections(self, key, extra_selections): """Set extra selections for a key. Also assign draw orders to leave current_cell and current_line in the backgrund (and avoid them to cover other decorations) NOTE: This will remove previous decorations added to the same key. Args: key (str) name of the extra selections group. extra_selections (list of sourcecode.api.TextDecoration). """ # use draw orders to highlight current_cell and current_line first draw_order = DRAW_ORDERS.get(key) if draw_order is None: draw_order = DRAW_ORDERS.get('on_top') for selection in extra_selections: selection.draw_order = draw_order self.clear_extra_selections(key) self.extra_selections_dict[key] = extra_selections
[ "def", "set_extra_selections", "(", "self", ",", "key", ",", "extra_selections", ")", ":", "# use draw orders to highlight current_cell and current_line first\r", "draw_order", "=", "DRAW_ORDERS", ".", "get", "(", "key", ")", "if", "draw_order", "is", "None", ":", "draw_order", "=", "DRAW_ORDERS", ".", "get", "(", "'on_top'", ")", "for", "selection", "in", "extra_selections", ":", "selection", ".", "draw_order", "=", "draw_order", "self", ".", "clear_extra_selections", "(", "key", ")", "self", ".", "extra_selections_dict", "[", "key", "]", "=", "extra_selections" ]
Set extra selections for a key. Also assign draw orders to leave current_cell and current_line in the backgrund (and avoid them to cover other decorations) NOTE: This will remove previous decorations added to the same key. Args: key (str) name of the extra selections group. extra_selections (list of sourcecode.api.TextDecoration).
[ "Set", "extra", "selections", "for", "a", "key", ".", "Also", "assign", "draw", "orders", "to", "leave", "current_cell", "and", "current_line", "in", "the", "backgrund", "(", "and", "avoid", "them", "to", "cover", "other", "decorations", ")", "NOTE", ":", "This", "will", "remove", "previous", "decorations", "added", "to", "the", "same", "key", ".", "Args", ":", "key", "(", "str", ")", "name", "of", "the", "extra", "selections", "group", ".", "extra_selections", "(", "list", "of", "sourcecode", ".", "api", ".", "TextDecoration", ")", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L367-L388
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.update_extra_selections
def update_extra_selections(self): """Add extra selections to DecorationsManager. TODO: This method could be remove it and decorations could be added/removed in set_extra_selections/clear_extra_selections. """ extra_selections = [] for key, extra in list(self.extra_selections_dict.items()): extra_selections.extend(extra) self.decorations.add(extra_selections)
python
def update_extra_selections(self): """Add extra selections to DecorationsManager. TODO: This method could be remove it and decorations could be added/removed in set_extra_selections/clear_extra_selections. """ extra_selections = [] for key, extra in list(self.extra_selections_dict.items()): extra_selections.extend(extra) self.decorations.add(extra_selections)
[ "def", "update_extra_selections", "(", "self", ")", ":", "extra_selections", "=", "[", "]", "for", "key", ",", "extra", "in", "list", "(", "self", ".", "extra_selections_dict", ".", "items", "(", ")", ")", ":", "extra_selections", ".", "extend", "(", "extra", ")", "self", ".", "decorations", ".", "add", "(", "extra_selections", ")" ]
Add extra selections to DecorationsManager. TODO: This method could be remove it and decorations could be added/removed in set_extra_selections/clear_extra_selections.
[ "Add", "extra", "selections", "to", "DecorationsManager", ".", "TODO", ":", "This", "method", "could", "be", "remove", "it", "and", "decorations", "could", "be", "added", "/", "removed", "in", "set_extra_selections", "/", "clear_extra_selections", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L390-L400
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.clear_extra_selections
def clear_extra_selections(self, key): """Remove decorations added through set_extra_selections. Args: key (str) name of the extra selections group. """ for decoration in self.extra_selections_dict.get(key, []): self.decorations.remove(decoration) self.extra_selections_dict[key] = []
python
def clear_extra_selections(self, key): """Remove decorations added through set_extra_selections. Args: key (str) name of the extra selections group. """ for decoration in self.extra_selections_dict.get(key, []): self.decorations.remove(decoration) self.extra_selections_dict[key] = []
[ "def", "clear_extra_selections", "(", "self", ",", "key", ")", ":", "for", "decoration", "in", "self", ".", "extra_selections_dict", ".", "get", "(", "key", ",", "[", "]", ")", ":", "self", ".", "decorations", ".", "remove", "(", "decoration", ")", "self", ".", "extra_selections_dict", "[", "key", "]", "=", "[", "]" ]
Remove decorations added through set_extra_selections. Args: key (str) name of the extra selections group.
[ "Remove", "decorations", "added", "through", "set_extra_selections", ".", "Args", ":", "key", "(", "str", ")", "name", "of", "the", "extra", "selections", "group", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L402-L410
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.highlight_current_line
def highlight_current_line(self): """Highlight current line""" selection = TextDecoration(self.textCursor()) selection.format.setProperty(QTextFormat.FullWidthSelection, to_qvariant(True)) selection.format.setBackground(self.currentline_color) selection.cursor.clearSelection() self.set_extra_selections('current_line', [selection]) self.update_extra_selections()
python
def highlight_current_line(self): """Highlight current line""" selection = TextDecoration(self.textCursor()) selection.format.setProperty(QTextFormat.FullWidthSelection, to_qvariant(True)) selection.format.setBackground(self.currentline_color) selection.cursor.clearSelection() self.set_extra_selections('current_line', [selection]) self.update_extra_selections()
[ "def", "highlight_current_line", "(", "self", ")", ":", "selection", "=", "TextDecoration", "(", "self", ".", "textCursor", "(", ")", ")", "selection", ".", "format", ".", "setProperty", "(", "QTextFormat", ".", "FullWidthSelection", ",", "to_qvariant", "(", "True", ")", ")", "selection", ".", "format", ".", "setBackground", "(", "self", ".", "currentline_color", ")", "selection", ".", "cursor", ".", "clearSelection", "(", ")", "self", ".", "set_extra_selections", "(", "'current_line'", ",", "[", "selection", "]", ")", "self", ".", "update_extra_selections", "(", ")" ]
Highlight current line
[ "Highlight", "current", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L418-L426
train
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", ".", "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", "(", ")" ]
Highlight current cell
[ "Highlight", "current", "cell" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L433-L455
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.cursor_position_changed
def cursor_position_changed(self): """Brace matching""" if self.bracepos is not None: self.__highlight(self.bracepos, cancel=True) self.bracepos = None cursor = self.textCursor() if cursor.position() == 0: return cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor) text = to_text_string(cursor.selectedText()) pos1 = cursor.position() if text in (')', ']', '}'): pos2 = self.find_brace_match(pos1, text, forward=False) elif text in ('(', '[', '{'): pos2 = self.find_brace_match(pos1, text, forward=True) else: return if pos2 is not None: self.bracepos = (pos1, pos2) self.__highlight(self.bracepos, color=self.matched_p_color) else: self.bracepos = (pos1,) self.__highlight(self.bracepos, color=self.unmatched_p_color)
python
def cursor_position_changed(self): """Brace matching""" if self.bracepos is not None: self.__highlight(self.bracepos, cancel=True) self.bracepos = None cursor = self.textCursor() if cursor.position() == 0: return cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor) text = to_text_string(cursor.selectedText()) pos1 = cursor.position() if text in (')', ']', '}'): pos2 = self.find_brace_match(pos1, text, forward=False) elif text in ('(', '[', '{'): pos2 = self.find_brace_match(pos1, text, forward=True) else: return if pos2 is not None: self.bracepos = (pos1, pos2) self.__highlight(self.bracepos, color=self.matched_p_color) else: self.bracepos = (pos1,) self.__highlight(self.bracepos, color=self.unmatched_p_color)
[ "def", "cursor_position_changed", "(", "self", ")", ":", "if", "self", ".", "bracepos", "is", "not", "None", ":", "self", ".", "__highlight", "(", "self", ".", "bracepos", ",", "cancel", "=", "True", ")", "self", ".", "bracepos", "=", "None", "cursor", "=", "self", ".", "textCursor", "(", ")", "if", "cursor", ".", "position", "(", ")", "==", "0", ":", "return", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "PreviousCharacter", ",", "QTextCursor", ".", "KeepAnchor", ")", "text", "=", "to_text_string", "(", "cursor", ".", "selectedText", "(", ")", ")", "pos1", "=", "cursor", ".", "position", "(", ")", "if", "text", "in", "(", "')'", ",", "']'", ",", "'}'", ")", ":", "pos2", "=", "self", ".", "find_brace_match", "(", "pos1", ",", "text", ",", "forward", "=", "False", ")", "elif", "text", "in", "(", "'('", ",", "'['", ",", "'{'", ")", ":", "pos2", "=", "self", ".", "find_brace_match", "(", "pos1", ",", "text", ",", "forward", "=", "True", ")", "else", ":", "return", "if", "pos2", "is", "not", "None", ":", "self", ".", "bracepos", "=", "(", "pos1", ",", "pos2", ")", "self", ".", "__highlight", "(", "self", ".", "bracepos", ",", "color", "=", "self", ".", "matched_p_color", ")", "else", ":", "self", ".", "bracepos", "=", "(", "pos1", ",", ")", "self", ".", "__highlight", "(", "self", ".", "bracepos", ",", "color", "=", "self", ".", "unmatched_p_color", ")" ]
Brace matching
[ "Brace", "matching" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L520-L543
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.set_wrap_mode
def set_wrap_mode(self, mode=None): """ Set wrap mode Valid *mode* values: None, 'word', 'character' """ if mode == 'word': wrap_mode = QTextOption.WrapAtWordBoundaryOrAnywhere elif mode == 'character': wrap_mode = QTextOption.WrapAnywhere else: wrap_mode = QTextOption.NoWrap self.setWordWrapMode(wrap_mode)
python
def set_wrap_mode(self, mode=None): """ Set wrap mode Valid *mode* values: None, 'word', 'character' """ if mode == 'word': wrap_mode = QTextOption.WrapAtWordBoundaryOrAnywhere elif mode == 'character': wrap_mode = QTextOption.WrapAnywhere else: wrap_mode = QTextOption.NoWrap self.setWordWrapMode(wrap_mode)
[ "def", "set_wrap_mode", "(", "self", ",", "mode", "=", "None", ")", ":", "if", "mode", "==", "'word'", ":", "wrap_mode", "=", "QTextOption", ".", "WrapAtWordBoundaryOrAnywhere", "elif", "mode", "==", "'character'", ":", "wrap_mode", "=", "QTextOption", ".", "WrapAnywhere", "else", ":", "wrap_mode", "=", "QTextOption", ".", "NoWrap", "self", ".", "setWordWrapMode", "(", "wrap_mode", ")" ]
Set wrap mode Valid *mode* values: None, 'word', 'character'
[ "Set", "wrap", "mode", "Valid", "*", "mode", "*", "values", ":", "None", "word", "character" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L551-L562
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.toPlainText
def toPlainText(self): """ Reimplement Qt method Fix PyQt4 bug on Windows and Python 3 """ # Fix what appears to be a PyQt4 bug when getting file # contents under Windows and PY3. This bug leads to # corruptions when saving files with certain combinations # of unicode chars on them (like the one attached on # Issue 1546) if os.name == 'nt' and PY3: text = self.get_text('sof', 'eof') return text.replace('\u2028', '\n').replace('\u2029', '\n')\ .replace('\u0085', '\n') else: return super(TextEditBaseWidget, self).toPlainText()
python
def toPlainText(self): """ Reimplement Qt method Fix PyQt4 bug on Windows and Python 3 """ # Fix what appears to be a PyQt4 bug when getting file # contents under Windows and PY3. This bug leads to # corruptions when saving files with certain combinations # of unicode chars on them (like the one attached on # Issue 1546) if os.name == 'nt' and PY3: text = self.get_text('sof', 'eof') return text.replace('\u2028', '\n').replace('\u2029', '\n')\ .replace('\u0085', '\n') else: return super(TextEditBaseWidget, self).toPlainText()
[ "def", "toPlainText", "(", "self", ")", ":", "# Fix what appears to be a PyQt4 bug when getting file\r", "# contents under Windows and PY3. This bug leads to\r", "# corruptions when saving files with certain combinations\r", "# of unicode chars on them (like the one attached on\r", "# Issue 1546)\r", "if", "os", ".", "name", "==", "'nt'", "and", "PY3", ":", "text", "=", "self", ".", "get_text", "(", "'sof'", ",", "'eof'", ")", "return", "text", ".", "replace", "(", "'\\u2028'", ",", "'\\n'", ")", ".", "replace", "(", "'\\u2029'", ",", "'\\n'", ")", ".", "replace", "(", "'\\u0085'", ",", "'\\n'", ")", "else", ":", "return", "super", "(", "TextEditBaseWidget", ",", "self", ")", ".", "toPlainText", "(", ")" ]
Reimplement Qt method Fix PyQt4 bug on Windows and Python 3
[ "Reimplement", "Qt", "method", "Fix", "PyQt4", "bug", "on", "Windows", "and", "Python", "3" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L575-L590
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.get_selection_as_executable_code
def get_selection_as_executable_code(self): """Return selected text as a processed text, to be executable in a Python/IPython interpreter""" ls = self.get_line_separator() _indent = lambda line: len(line)-len(line.lstrip()) line_from, line_to = self.get_selection_bounds() text = self.get_selected_text() if not text: return lines = text.split(ls) if len(lines) > 1: # Multiline selection -> eventually fixing indentation original_indent = _indent(self.get_text_line(line_from)) text = (" "*(original_indent-_indent(lines[0])))+text # If there is a common indent to all lines, find it. # Moving from bottom line to top line ensures that blank # lines inherit the indent of the line *below* it, # which is the desired behavior. min_indent = 999 current_indent = 0 lines = text.split(ls) for i in range(len(lines)-1, -1, -1): line = lines[i] if line.strip(): current_indent = _indent(line) min_indent = min(current_indent, min_indent) else: lines[i] = ' ' * current_indent if min_indent: lines = [line[min_indent:] for line in lines] # Remove any leading whitespace or comment lines # since they confuse the reserved word detector that follows below lines_removed = 0 while lines: first_line = lines[0].lstrip() if first_line == '' or first_line[0] == '#': lines_removed += 1 lines.pop(0) else: break # Add an EOL character after the last line of code so that it gets # evaluated automatically by the console and any quote characters # are separated from the triple quotes of runcell lines.append(ls) # Add removed lines back to have correct traceback line numbers leading_lines_str = ls * lines_removed return leading_lines_str + ls.join(lines)
python
def get_selection_as_executable_code(self): """Return selected text as a processed text, to be executable in a Python/IPython interpreter""" ls = self.get_line_separator() _indent = lambda line: len(line)-len(line.lstrip()) line_from, line_to = self.get_selection_bounds() text = self.get_selected_text() if not text: return lines = text.split(ls) if len(lines) > 1: # Multiline selection -> eventually fixing indentation original_indent = _indent(self.get_text_line(line_from)) text = (" "*(original_indent-_indent(lines[0])))+text # If there is a common indent to all lines, find it. # Moving from bottom line to top line ensures that blank # lines inherit the indent of the line *below* it, # which is the desired behavior. min_indent = 999 current_indent = 0 lines = text.split(ls) for i in range(len(lines)-1, -1, -1): line = lines[i] if line.strip(): current_indent = _indent(line) min_indent = min(current_indent, min_indent) else: lines[i] = ' ' * current_indent if min_indent: lines = [line[min_indent:] for line in lines] # Remove any leading whitespace or comment lines # since they confuse the reserved word detector that follows below lines_removed = 0 while lines: first_line = lines[0].lstrip() if first_line == '' or first_line[0] == '#': lines_removed += 1 lines.pop(0) else: break # Add an EOL character after the last line of code so that it gets # evaluated automatically by the console and any quote characters # are separated from the triple quotes of runcell lines.append(ls) # Add removed lines back to have correct traceback line numbers leading_lines_str = ls * lines_removed return leading_lines_str + ls.join(lines)
[ "def", "get_selection_as_executable_code", "(", "self", ")", ":", "ls", "=", "self", ".", "get_line_separator", "(", ")", "_indent", "=", "lambda", "line", ":", "len", "(", "line", ")", "-", "len", "(", "line", ".", "lstrip", "(", ")", ")", "line_from", ",", "line_to", "=", "self", ".", "get_selection_bounds", "(", ")", "text", "=", "self", ".", "get_selected_text", "(", ")", "if", "not", "text", ":", "return", "lines", "=", "text", ".", "split", "(", "ls", ")", "if", "len", "(", "lines", ")", ">", "1", ":", "# Multiline selection -> eventually fixing indentation\r", "original_indent", "=", "_indent", "(", "self", ".", "get_text_line", "(", "line_from", ")", ")", "text", "=", "(", "\" \"", "*", "(", "original_indent", "-", "_indent", "(", "lines", "[", "0", "]", ")", ")", ")", "+", "text", "# If there is a common indent to all lines, find it.\r", "# Moving from bottom line to top line ensures that blank\r", "# lines inherit the indent of the line *below* it,\r", "# which is the desired behavior.\r", "min_indent", "=", "999", "current_indent", "=", "0", "lines", "=", "text", ".", "split", "(", "ls", ")", "for", "i", "in", "range", "(", "len", "(", "lines", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "line", "=", "lines", "[", "i", "]", "if", "line", ".", "strip", "(", ")", ":", "current_indent", "=", "_indent", "(", "line", ")", "min_indent", "=", "min", "(", "current_indent", ",", "min_indent", ")", "else", ":", "lines", "[", "i", "]", "=", "' '", "*", "current_indent", "if", "min_indent", ":", "lines", "=", "[", "line", "[", "min_indent", ":", "]", "for", "line", "in", "lines", "]", "# Remove any leading whitespace or comment lines\r", "# since they confuse the reserved word detector that follows below\r", "lines_removed", "=", "0", "while", "lines", ":", "first_line", "=", "lines", "[", "0", "]", ".", "lstrip", "(", ")", "if", "first_line", "==", "''", "or", "first_line", "[", "0", "]", "==", "'#'", ":", "lines_removed", "+=", "1", "lines", ".", "pop", "(", "0", ")", "else", ":", "break", "# Add an EOL character after the last line of code so that it gets\r", "# evaluated automatically by the console and any quote characters\r", "# are separated from the triple quotes of runcell\r", "lines", ".", "append", "(", "ls", ")", "# Add removed lines back to have correct traceback line numbers\r", "leading_lines_str", "=", "ls", "*", "lines_removed", "return", "leading_lines_str", "+", "ls", ".", "join", "(", "lines", ")" ]
Return selected text as a processed text, to be executable in a Python/IPython interpreter
[ "Return", "selected", "text", "as", "a", "processed", "text", "to", "be", "executable", "in", "a", "Python", "/", "IPython", "interpreter" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L604-L658
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.is_cell_separator
def is_cell_separator(self, cursor=None, block=None): """Return True if cursor (or text block) is on a block separator""" assert cursor is not None or block is not None if cursor is not None: cursor0 = QTextCursor(cursor) cursor0.select(QTextCursor.BlockUnderCursor) text = to_text_string(cursor0.selectedText()) else: text = to_text_string(block.text()) if self.cell_separators is None: return False else: return text.lstrip().startswith(self.cell_separators)
python
def is_cell_separator(self, cursor=None, block=None): """Return True if cursor (or text block) is on a block separator""" assert cursor is not None or block is not None if cursor is not None: cursor0 = QTextCursor(cursor) cursor0.select(QTextCursor.BlockUnderCursor) text = to_text_string(cursor0.selectedText()) else: text = to_text_string(block.text()) if self.cell_separators is None: return False else: return text.lstrip().startswith(self.cell_separators)
[ "def", "is_cell_separator", "(", "self", ",", "cursor", "=", "None", ",", "block", "=", "None", ")", ":", "assert", "cursor", "is", "not", "None", "or", "block", "is", "not", "None", "if", "cursor", "is", "not", "None", ":", "cursor0", "=", "QTextCursor", "(", "cursor", ")", "cursor0", ".", "select", "(", "QTextCursor", ".", "BlockUnderCursor", ")", "text", "=", "to_text_string", "(", "cursor0", ".", "selectedText", "(", ")", ")", "else", ":", "text", "=", "to_text_string", "(", "block", ".", "text", "(", ")", ")", "if", "self", ".", "cell_separators", "is", "None", ":", "return", "False", "else", ":", "return", "text", ".", "lstrip", "(", ")", ".", "startswith", "(", "self", ".", "cell_separators", ")" ]
Return True if cursor (or text block) is on a block separator
[ "Return", "True", "if", "cursor", "(", "or", "text", "block", ")", "is", "on", "a", "block", "separator" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L686-L698
train
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", "(", ")", "# Moving to the next line that is not a separator, if we are\r", "# exactly at one of them\r", "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\r", "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)\r", "# move to the next separator (or the end of the file)\r", "# so we can grab the cell contents\r", "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" ]
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
train
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", "(", ")", "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\r", "# exactly at one of them\r", "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\r", "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\r", "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)\r", "# move to the next separator (or the end of the file)\r", "# so we can grab the cell contents\r", "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" ]
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", "entire", "file", "is", "selected", "-", "a", "boolean", "indicating", "if", "the", "entire", "visible", "portion", "of", "the", "file", "is", "selected" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L745-L806
train
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", "not", "self", ".", "is_cell_separator", "(", "cursor", ")", ":", "# Moving to the next code cell\r", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "NextBlock", ")", "prev_pos", "=", "cur_pos", "cur_pos", "=", "cursor", ".", "position", "(", ")", "if", "cur_pos", "==", "prev_pos", ":", "return", "self", ".", "setTextCursor", "(", "cursor", ")" ]
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
train
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 previous cell\r", "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\r", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "PreviousBlock", ")", "prev_pos", "=", "cur_pos", "cur_pos", "=", "cursor", ".", "position", "(", ")", "if", "cur_pos", "==", "prev_pos", ":", "return", "self", ".", "setTextCursor", "(", "cursor", ")" ]
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
train
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", ".", "KeepAnchor", ")", "self", ".", "setTextCursor", "(", "cursor", ")" ]
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
train
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_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\r", "# changes from the previous block\r", "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\r", "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", ")" ]
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
train
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", "(", ")", "last_line", "=", "False", "# ------ Select text\r", "# Get selection start location\r", "cursor", ".", "setPosition", "(", "start_pos", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "StartOfBlock", ")", "start_pos", "=", "cursor", ".", "position", "(", ")", "# Get selection end location\r", "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\r", "if", "cursor", ".", "atEnd", "(", ")", ":", "if", "not", "cursor", ".", "atBlockStart", "(", ")", "or", "end_pos", "==", "start_pos", ":", "last_line", "=", "True", "# ------ Stop if at document boundary\r", "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\r", "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\r", "cursor", ".", "endEditBlock", "(", ")", "self", ".", "setTextCursor", "(", "cursor", ")", "self", ".", "__restore_selection", "(", "start_pos", ",", "end_pos", ")", "return", "# ------ Move text\r", "sel_text", "=", "to_text_string", "(", "cursor", ".", "selectedText", "(", ")", ")", "cursor", ".", "removeSelectedText", "(", ")", "if", "after_current_line", ":", "# Shift selection down\r", "text", "=", "to_text_string", "(", "cursor", ".", "block", "(", ")", ".", "text", "(", ")", ")", "sel_text", "=", "os", ".", "linesep", "+", "sel_text", "[", "0", ":", "-", "1", "]", "# Move linesep at the start\r", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "EndOfBlock", ")", "start_pos", "+=", "len", "(", "text", ")", "+", "1", "end_pos", "+=", "len", "(", "text", ")", "if", "not", "cursor", ".", "atEnd", "(", ")", ":", "end_pos", "+=", "1", "else", ":", "# Shift selection up\r", "if", "last_line", ":", "# Remove the last linesep and add it to the selected text\r", "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", ")" ]
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
train
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
train
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", ".", "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", ")" ]
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
train
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", ".", "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", "(", ")" ]
Delete current line
[ "Delete", "current", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1017-L1036
train
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", ".", "selectionStart", "(", ")", ",", "cursor", ".", "selectionEnd", "(", ")", "if", "start", "<", "end", ":", "start", "=", "max", "(", "[", "position_from", ",", "start", "]", ")", "else", ":", "end", "=", "max", "(", "[", "position_from", ",", "end", "]", ")", "self", ".", "set_selection", "(", "start", ",", "end", ")" ]
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
train
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", "=", "self", ".", "textCursor", "(", ")", "cursor_position", "=", "cursor", ".", "position", "(", ")", "if", "cursor_position", "<", "position_from", "or", "cursor_position", ">", "position_to", ":", "self", ".", "set_cursor_position", "(", "position_to", ")" ]
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
train
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", ",", "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", "(", ")" ]
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
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.stdkey_home
def stdkey_home(self, shift, ctrl, prompt_pos=None): """Smart HOME feature: cursor is first moved at indentation position, then at the start of the line""" move_mode = self.__get_move_mode(shift) if ctrl: self.moveCursor(QTextCursor.Start, move_mode) else: cursor = self.textCursor() if prompt_pos is None: start_position = self.get_position('sol') else: start_position = self.get_position(prompt_pos) text = self.get_text(start_position, 'eol') indent_pos = start_position+len(text)-len(text.lstrip()) if cursor.position() != indent_pos: cursor.setPosition(indent_pos, move_mode) else: cursor.setPosition(start_position, move_mode) self.setTextCursor(cursor)
python
def stdkey_home(self, shift, ctrl, prompt_pos=None): """Smart HOME feature: cursor is first moved at indentation position, then at the start of the line""" move_mode = self.__get_move_mode(shift) if ctrl: self.moveCursor(QTextCursor.Start, move_mode) else: cursor = self.textCursor() if prompt_pos is None: start_position = self.get_position('sol') else: start_position = self.get_position(prompt_pos) text = self.get_text(start_position, 'eol') indent_pos = start_position+len(text)-len(text.lstrip()) if cursor.position() != indent_pos: cursor.setPosition(indent_pos, move_mode) else: cursor.setPosition(start_position, move_mode) self.setTextCursor(cursor)
[ "def", "stdkey_home", "(", "self", ",", "shift", ",", "ctrl", ",", "prompt_pos", "=", "None", ")", ":", "move_mode", "=", "self", ".", "__get_move_mode", "(", "shift", ")", "if", "ctrl", ":", "self", ".", "moveCursor", "(", "QTextCursor", ".", "Start", ",", "move_mode", ")", "else", ":", "cursor", "=", "self", ".", "textCursor", "(", ")", "if", "prompt_pos", "is", "None", ":", "start_position", "=", "self", ".", "get_position", "(", "'sol'", ")", "else", ":", "start_position", "=", "self", ".", "get_position", "(", "prompt_pos", ")", "text", "=", "self", ".", "get_text", "(", "start_position", ",", "'eol'", ")", "indent_pos", "=", "start_position", "+", "len", "(", "text", ")", "-", "len", "(", "text", ".", "lstrip", "(", ")", ")", "if", "cursor", ".", "position", "(", ")", "!=", "indent_pos", ":", "cursor", ".", "setPosition", "(", "indent_pos", ",", "move_mode", ")", "else", ":", "cursor", ".", "setPosition", "(", "start_position", ",", "move_mode", ")", "self", ".", "setTextCursor", "(", "cursor", ")" ]
Smart HOME feature: cursor is first moved at indentation position, then at the start of the line
[ "Smart", "HOME", "feature", ":", "cursor", "is", "first", "moved", "at", "indentation", "position", "then", "at", "the", "start", "of", "the", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1130-L1148
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.mousePressEvent
def mousePressEvent(self, event): """Reimplement Qt method""" if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() self.setFocus() event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier) QPlainTextEdit.mousePressEvent(self, event) QPlainTextEdit.mouseReleaseEvent(self, event) # Send selection text to clipboard to be able to use # the paste method and avoid the strange Issue 1445 # NOTE: This issue seems a focusing problem but it # seems really hard to track mode_clip = QClipboard.Clipboard mode_sel = QClipboard.Selection text_clip = QApplication.clipboard().text(mode=mode_clip) text_sel = QApplication.clipboard().text(mode=mode_sel) QApplication.clipboard().setText(text_sel, mode=mode_clip) self.paste() QApplication.clipboard().setText(text_clip, mode=mode_clip) else: self.calltip_widget.hide() QPlainTextEdit.mousePressEvent(self, event)
python
def mousePressEvent(self, event): """Reimplement Qt method""" if sys.platform.startswith('linux') and event.button() == Qt.MidButton: self.calltip_widget.hide() self.setFocus() event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier) QPlainTextEdit.mousePressEvent(self, event) QPlainTextEdit.mouseReleaseEvent(self, event) # Send selection text to clipboard to be able to use # the paste method and avoid the strange Issue 1445 # NOTE: This issue seems a focusing problem but it # seems really hard to track mode_clip = QClipboard.Clipboard mode_sel = QClipboard.Selection text_clip = QApplication.clipboard().text(mode=mode_clip) text_sel = QApplication.clipboard().text(mode=mode_sel) QApplication.clipboard().setText(text_sel, mode=mode_clip) self.paste() QApplication.clipboard().setText(text_clip, mode=mode_clip) else: self.calltip_widget.hide() QPlainTextEdit.mousePressEvent(self, event)
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", "and", "event", ".", "button", "(", ")", "==", "Qt", ".", "MidButton", ":", "self", ".", "calltip_widget", ".", "hide", "(", ")", "self", ".", "setFocus", "(", ")", "event", "=", "QMouseEvent", "(", "QEvent", ".", "MouseButtonPress", ",", "event", ".", "pos", "(", ")", ",", "Qt", ".", "LeftButton", ",", "Qt", ".", "LeftButton", ",", "Qt", ".", "NoModifier", ")", "QPlainTextEdit", ".", "mousePressEvent", "(", "self", ",", "event", ")", "QPlainTextEdit", ".", "mouseReleaseEvent", "(", "self", ",", "event", ")", "# Send selection text to clipboard to be able to use\r", "# the paste method and avoid the strange Issue 1445\r", "# NOTE: This issue seems a focusing problem but it\r", "# seems really hard to track\r", "mode_clip", "=", "QClipboard", ".", "Clipboard", "mode_sel", "=", "QClipboard", ".", "Selection", "text_clip", "=", "QApplication", ".", "clipboard", "(", ")", ".", "text", "(", "mode", "=", "mode_clip", ")", "text_sel", "=", "QApplication", ".", "clipboard", "(", ")", ".", "text", "(", "mode", "=", "mode_sel", ")", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "text_sel", ",", "mode", "=", "mode_clip", ")", "self", ".", "paste", "(", ")", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "text_clip", ",", "mode", "=", "mode_clip", ")", "else", ":", "self", ".", "calltip_widget", ".", "hide", "(", ")", "QPlainTextEdit", ".", "mousePressEvent", "(", "self", ",", "event", ")" ]
Reimplement Qt method
[ "Reimplement", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1168-L1190
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.focusInEvent
def focusInEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() self.focus_in.emit() self.highlight_current_cell() QPlainTextEdit.focusInEvent(self, event)
python
def focusInEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() self.focus_in.emit() self.highlight_current_cell() QPlainTextEdit.focusInEvent(self, event)
[ "def", "focusInEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "self", ".", "focus_in", ".", "emit", "(", ")", "self", ".", "highlight_current_cell", "(", ")", "QPlainTextEdit", ".", "focusInEvent", "(", "self", ",", "event", ")" ]
Reimplemented to handle focus
[ "Reimplemented", "to", "handle", "focus" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1192-L1197
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.focusOutEvent
def focusOutEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() QPlainTextEdit.focusOutEvent(self, event)
python
def focusOutEvent(self, event): """Reimplemented to handle focus""" self.focus_changed.emit() QPlainTextEdit.focusOutEvent(self, event)
[ "def", "focusOutEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "QPlainTextEdit", ".", "focusOutEvent", "(", "self", ",", "event", ")" ]
Reimplemented to handle focus
[ "Reimplemented", "to", "handle", "focus" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1199-L1202
train
spyder-ide/spyder
spyder/plugins/editor/widgets/base.py
TextEditBaseWidget.wheelEvent
def wheelEvent(self, event): """Reimplemented to emit zoom in/out signals when Ctrl is pressed""" # This feature is disabled on MacOS, see Issue 1510 if sys.platform != 'darwin': if event.modifiers() & Qt.ControlModifier: if hasattr(event, 'angleDelta'): if event.angleDelta().y() < 0: self.zoom_out.emit() elif event.angleDelta().y() > 0: self.zoom_in.emit() elif hasattr(event, 'delta'): if event.delta() < 0: self.zoom_out.emit() elif event.delta() > 0: self.zoom_in.emit() return QPlainTextEdit.wheelEvent(self, event) self.highlight_current_cell()
python
def wheelEvent(self, event): """Reimplemented to emit zoom in/out signals when Ctrl is pressed""" # This feature is disabled on MacOS, see Issue 1510 if sys.platform != 'darwin': if event.modifiers() & Qt.ControlModifier: if hasattr(event, 'angleDelta'): if event.angleDelta().y() < 0: self.zoom_out.emit() elif event.angleDelta().y() > 0: self.zoom_in.emit() elif hasattr(event, 'delta'): if event.delta() < 0: self.zoom_out.emit() elif event.delta() > 0: self.zoom_in.emit() return QPlainTextEdit.wheelEvent(self, event) self.highlight_current_cell()
[ "def", "wheelEvent", "(", "self", ",", "event", ")", ":", "# This feature is disabled on MacOS, see Issue 1510\r", "if", "sys", ".", "platform", "!=", "'darwin'", ":", "if", "event", ".", "modifiers", "(", ")", "&", "Qt", ".", "ControlModifier", ":", "if", "hasattr", "(", "event", ",", "'angleDelta'", ")", ":", "if", "event", ".", "angleDelta", "(", ")", ".", "y", "(", ")", "<", "0", ":", "self", ".", "zoom_out", ".", "emit", "(", ")", "elif", "event", ".", "angleDelta", "(", ")", ".", "y", "(", ")", ">", "0", ":", "self", ".", "zoom_in", ".", "emit", "(", ")", "elif", "hasattr", "(", "event", ",", "'delta'", ")", ":", "if", "event", ".", "delta", "(", ")", "<", "0", ":", "self", ".", "zoom_out", ".", "emit", "(", ")", "elif", "event", ".", "delta", "(", ")", ">", "0", ":", "self", ".", "zoom_in", ".", "emit", "(", ")", "return", "QPlainTextEdit", ".", "wheelEvent", "(", "self", ",", "event", ")", "self", ".", "highlight_current_cell", "(", ")" ]
Reimplemented to emit zoom in/out signals when Ctrl is pressed
[ "Reimplemented", "to", "emit", "zoom", "in", "/", "out", "signals", "when", "Ctrl", "is", "pressed" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1204-L1221
train
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'", ",", "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" ]
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
train
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", "(", "recent_file", ")", "try", ":", "self", ".", "CONF", "[", "WORKSPACE", "]", ".", "set", "(", "'main'", ",", "'recent_files'", ",", "list", "(", "OrderedDict", ".", "fromkeys", "(", "recent_files", ")", ")", ")", "except", "EnvironmentError", ":", "pass" ]
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
train
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", ":", "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", ")", ")" ]
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
train
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", ")", "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", "(", ")" ]
Set project root path.
[ "Set", "project", "root", "path", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/api.py#L115-L126
train
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", "[", ":", "-", "len", "(", "old_name", ")", "]", "+", "new_name", "self", ".", "relative_pythonpath", "=", "pypath", "# ??\r", "self", ".", "save", "(", ")" ]
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
train
spyder-ide/spyder
spyder/plugins/onlinehelp/widgets.py
PydocBrowser.initialize
def initialize(self): """Start pydoc server""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() self.start_server()
python
def initialize(self): """Start pydoc server""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() self.start_server()
[ "def", "initialize", "(", "self", ")", ":", "QApplication", ".", "setOverrideCursor", "(", "QCursor", "(", "Qt", ".", "WaitCursor", ")", ")", "QApplication", ".", "processEvents", "(", ")", "self", ".", "start_server", "(", ")" ]
Start pydoc server
[ "Start", "pydoc", "server" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/widgets.py#L80-L84
train
spyder-ide/spyder
spyder/plugins/onlinehelp/widgets.py
PydocBrowser.start_server
def start_server(self): """Start pydoc server""" if self.server is None: self.port = select_port(default_port=self.DEFAULT_PORT) self.set_home_url('http://localhost:%d/' % self.port) elif self.server.isRunning(): self.server.server_started.disconnect(self.initialize_continued) self.server.quit() self.server = PydocServer(port=self.port) self.server.server_started.connect(self.initialize_continued) self.server.start()
python
def start_server(self): """Start pydoc server""" if self.server is None: self.port = select_port(default_port=self.DEFAULT_PORT) self.set_home_url('http://localhost:%d/' % self.port) elif self.server.isRunning(): self.server.server_started.disconnect(self.initialize_continued) self.server.quit() self.server = PydocServer(port=self.port) self.server.server_started.connect(self.initialize_continued) self.server.start()
[ "def", "start_server", "(", "self", ")", ":", "if", "self", ".", "server", "is", "None", ":", "self", ".", "port", "=", "select_port", "(", "default_port", "=", "self", ".", "DEFAULT_PORT", ")", "self", ".", "set_home_url", "(", "'http://localhost:%d/'", "%", "self", ".", "port", ")", "elif", "self", ".", "server", ".", "isRunning", "(", ")", ":", "self", ".", "server", ".", "server_started", ".", "disconnect", "(", "self", ".", "initialize_continued", ")", "self", ".", "server", ".", "quit", "(", ")", "self", ".", "server", "=", "PydocServer", "(", "port", "=", "self", ".", "port", ")", "self", ".", "server", ".", "server_started", ".", "connect", "(", "self", ".", "initialize_continued", ")", "self", ".", "server", ".", "start", "(", ")" ]
Start pydoc server
[ "Start", "pydoc", "server" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/onlinehelp/widgets.py#L104-L114
train
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", "+", "'.html'", ")" ]
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
train
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", ".", "start_autosave_timer", "(", ")" ]
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
train
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", "(", "autosave_dir", ",", "autosave_mapping", ",", "parent", "=", "self", ".", "editor", ")", "dialog", ".", "exec_if_nonempty", "(", ")", "self", ".", "recover_files_to_open", "=", "dialog", ".", "files_to_open", "[", ":", "]" ]
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
train
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", "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" ]
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
train