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/plugins/console/widgets/internalshell.py
InternalShell.open_with_external_spyder
def open_with_external_spyder(self, text): """Load file in external Spyder's editor, if available This method is used only for embedded consoles (could also be useful if we ever implement the magic %edit command)""" match = get_error_match(to_text_string(text)) if match: fname, lnb = match.groups() builtins.open_in_spyder(fname, int(lnb))
python
def open_with_external_spyder(self, text): """Load file in external Spyder's editor, if available This method is used only for embedded consoles (could also be useful if we ever implement the magic %edit command)""" match = get_error_match(to_text_string(text)) if match: fname, lnb = match.groups() builtins.open_in_spyder(fname, int(lnb))
[ "def", "open_with_external_spyder", "(", "self", ",", "text", ")", ":", "match", "=", "get_error_match", "(", "to_text_string", "(", "text", ")", ")", "if", "match", ":", "fname", ",", "lnb", "=", "match", ".", "groups", "(", ")", "builtins", ".", "open_in_spyder", "(", "fname", ",", "int", "(", "lnb", ")", ")" ]
Load file in external Spyder's editor, if available This method is used only for embedded consoles (could also be useful if we ever implement the magic %edit command)
[ "Load", "file", "in", "external", "Spyder", "s", "editor", "if", "available", "This", "method", "is", "used", "only", "for", "embedded", "consoles", "(", "could", "also", "be", "useful", "if", "we", "ever", "implement", "the", "magic", "%edit", "command", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L289-L296
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.external_editor
def external_editor(self, filename, goto=-1): """Edit in an external editor Recommended: SciTE (e.g. to go to line where an error did occur)""" editor_path = CONF.get('internal_console', 'external_editor/path') goto_option = CONF.get('internal_console', 'external_editor/gotoline') try: args = [filename] if goto > 0 and goto_option: args.append('%s%d'.format(goto_option, goto)) programs.run_program(editor_path, args) except OSError: self.write_error("External editor was not found:" " %s\n" % editor_path)
python
def external_editor(self, filename, goto=-1): """Edit in an external editor Recommended: SciTE (e.g. to go to line where an error did occur)""" editor_path = CONF.get('internal_console', 'external_editor/path') goto_option = CONF.get('internal_console', 'external_editor/gotoline') try: args = [filename] if goto > 0 and goto_option: args.append('%s%d'.format(goto_option, goto)) programs.run_program(editor_path, args) except OSError: self.write_error("External editor was not found:" " %s\n" % editor_path)
[ "def", "external_editor", "(", "self", ",", "filename", ",", "goto", "=", "-", "1", ")", ":", "editor_path", "=", "CONF", ".", "get", "(", "'internal_console'", ",", "'external_editor/path'", ")", "goto_option", "=", "CONF", ".", "get", "(", "'internal_console'", ",", "'external_editor/gotoline'", ")", "try", ":", "args", "=", "[", "filename", "]", "if", "goto", ">", "0", "and", "goto_option", ":", "args", ".", "append", "(", "'%s%d'", ".", "format", "(", "goto_option", ",", "goto", ")", ")", "programs", ".", "run_program", "(", "editor_path", ",", "args", ")", "except", "OSError", ":", "self", ".", "write_error", "(", "\"External editor was not found:\"", "\" %s\\n\"", "%", "editor_path", ")" ]
Edit in an external editor Recommended: SciTE (e.g. to go to line where an error did occur)
[ "Edit", "in", "an", "external", "editor", "Recommended", ":", "SciTE", "(", "e", ".", "g", ".", "to", "go", "to", "line", "where", "an", "error", "did", "occur", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L298-L310
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.flush
def flush(self, error=False, prompt=False): """Reimplement ShellBaseWidget method""" PythonShellWidget.flush(self, error=error, prompt=prompt) if self.interrupted: self.interrupted = False raise KeyboardInterrupt
python
def flush(self, error=False, prompt=False): """Reimplement ShellBaseWidget method""" PythonShellWidget.flush(self, error=error, prompt=prompt) if self.interrupted: self.interrupted = False raise KeyboardInterrupt
[ "def", "flush", "(", "self", ",", "error", "=", "False", ",", "prompt", "=", "False", ")", ":", "PythonShellWidget", ".", "flush", "(", "self", ",", "error", "=", "error", ",", "prompt", "=", "prompt", ")", "if", "self", ".", "interrupted", ":", "self", ".", "interrupted", "=", "False", "raise", "KeyboardInterrupt" ]
Reimplement ShellBaseWidget method
[ "Reimplement", "ShellBaseWidget", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L314-L319
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.clear_terminal
def clear_terminal(self): """Reimplement ShellBaseWidget method""" self.clear() self.new_prompt(self.interpreter.p2 if self.interpreter.more else self.interpreter.p1)
python
def clear_terminal(self): """Reimplement ShellBaseWidget method""" self.clear() self.new_prompt(self.interpreter.p2 if self.interpreter.more else self.interpreter.p1)
[ "def", "clear_terminal", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "new_prompt", "(", "self", ".", "interpreter", ".", "p2", "if", "self", ".", "interpreter", ".", "more", "else", "self", ".", "interpreter", ".", "p1", ")" ]
Reimplement ShellBaseWidget method
[ "Reimplement", "ShellBaseWidget", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L323-L326
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.on_enter
def on_enter(self, command): """on_enter""" if self.profile: # Simple profiling test t0 = time() for _ in range(10): self.execute_command(command) self.insert_text(u"\n<Δt>=%dms\n" % (1e2*(time()-t0))) self.new_prompt(self.interpreter.p1) else: self.execute_command(command) self.__flush_eventqueue()
python
def on_enter(self, command): """on_enter""" if self.profile: # Simple profiling test t0 = time() for _ in range(10): self.execute_command(command) self.insert_text(u"\n<Δt>=%dms\n" % (1e2*(time()-t0))) self.new_prompt(self.interpreter.p1) else: self.execute_command(command) self.__flush_eventqueue()
[ "def", "on_enter", "(", "self", ",", "command", ")", ":", "if", "self", ".", "profile", ":", "# Simple profiling test\r", "t0", "=", "time", "(", ")", "for", "_", "in", "range", "(", "10", ")", ":", "self", ".", "execute_command", "(", "command", ")", "self", ".", "insert_text", "(", "u\"\\n<Δt>=%dms\\n\" ", " ", "1", "e2*", "(", "t", "ime(", ")", "-", "t", "0)", ")", ")", "\r", "self", ".", "new_prompt", "(", "self", ".", "interpreter", ".", "p1", ")", "else", ":", "self", ".", "execute_command", "(", "command", ")", "self", ".", "__flush_eventqueue", "(", ")" ]
on_enter
[ "on_enter" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L330-L341
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.__flush_eventqueue
def __flush_eventqueue(self): """Flush keyboard event queue""" while self.eventqueue: past_event = self.eventqueue.pop(0) self.postprocess_keyevent(past_event)
python
def __flush_eventqueue(self): """Flush keyboard event queue""" while self.eventqueue: past_event = self.eventqueue.pop(0) self.postprocess_keyevent(past_event)
[ "def", "__flush_eventqueue", "(", "self", ")", ":", "while", "self", ".", "eventqueue", ":", "past_event", "=", "self", ".", "eventqueue", ".", "pop", "(", "0", ")", "self", ".", "postprocess_keyevent", "(", "past_event", ")" ]
Flush keyboard event queue
[ "Flush", "keyboard", "event", "queue" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L353-L357
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.keyboard_interrupt
def keyboard_interrupt(self): """Simulate keyboard interrupt""" if self.multithreaded: self.interpreter.raise_keyboard_interrupt() else: if self.interpreter.more: self.write_error("\nKeyboardInterrupt\n") self.interpreter.more = False self.new_prompt(self.interpreter.p1) self.interpreter.resetbuffer() else: self.interrupted = True
python
def keyboard_interrupt(self): """Simulate keyboard interrupt""" if self.multithreaded: self.interpreter.raise_keyboard_interrupt() else: if self.interpreter.more: self.write_error("\nKeyboardInterrupt\n") self.interpreter.more = False self.new_prompt(self.interpreter.p1) self.interpreter.resetbuffer() else: self.interrupted = True
[ "def", "keyboard_interrupt", "(", "self", ")", ":", "if", "self", ".", "multithreaded", ":", "self", ".", "interpreter", ".", "raise_keyboard_interrupt", "(", ")", "else", ":", "if", "self", ".", "interpreter", ".", "more", ":", "self", ".", "write_error", "(", "\"\\nKeyboardInterrupt\\n\"", ")", "self", ".", "interpreter", ".", "more", "=", "False", "self", ".", "new_prompt", "(", "self", ".", "interpreter", ".", "p1", ")", "self", ".", "interpreter", ".", "resetbuffer", "(", ")", "else", ":", "self", ".", "interrupted", "=", "True" ]
Simulate keyboard interrupt
[ "Simulate", "keyboard", "interrupt" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L360-L371
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.execute_lines
def execute_lines(self, lines): """ Execute a set of lines as multiple command lines: multiple lines of text to be executed as single commands """ for line in lines.splitlines(): stripped_line = line.strip() if stripped_line.startswith('#'): continue self.write(line+os.linesep, flush=True) self.execute_command(line+"\n") self.flush()
python
def execute_lines(self, lines): """ Execute a set of lines as multiple command lines: multiple lines of text to be executed as single commands """ for line in lines.splitlines(): stripped_line = line.strip() if stripped_line.startswith('#'): continue self.write(line+os.linesep, flush=True) self.execute_command(line+"\n") self.flush()
[ "def", "execute_lines", "(", "self", ",", "lines", ")", ":", "for", "line", "in", "lines", ".", "splitlines", "(", ")", ":", "stripped_line", "=", "line", ".", "strip", "(", ")", "if", "stripped_line", ".", "startswith", "(", "'#'", ")", ":", "continue", "self", ".", "write", "(", "line", "+", "os", ".", "linesep", ",", "flush", "=", "True", ")", "self", ".", "execute_command", "(", "line", "+", "\"\\n\"", ")", "self", ".", "flush", "(", ")" ]
Execute a set of lines as multiple command lines: multiple lines of text to be executed as single commands
[ "Execute", "a", "set", "of", "lines", "as", "multiple", "command", "lines", ":", "multiple", "lines", "of", "text", "to", "be", "executed", "as", "single", "commands" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L373-L384
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.execute_command
def execute_command(self, cmd): """ Execute a command cmd: one-line command only, with '\n' at the end """ if self.input_mode: self.end_input(cmd) return if cmd.endswith('\n'): cmd = cmd[:-1] # cls command if cmd == 'cls': self.clear_terminal() return self.run_command(cmd)
python
def execute_command(self, cmd): """ Execute a command cmd: one-line command only, with '\n' at the end """ if self.input_mode: self.end_input(cmd) return if cmd.endswith('\n'): cmd = cmd[:-1] # cls command if cmd == 'cls': self.clear_terminal() return self.run_command(cmd)
[ "def", "execute_command", "(", "self", ",", "cmd", ")", ":", "if", "self", ".", "input_mode", ":", "self", ".", "end_input", "(", "cmd", ")", "return", "if", "cmd", ".", "endswith", "(", "'\\n'", ")", ":", "cmd", "=", "cmd", "[", ":", "-", "1", "]", "# cls command\r", "if", "cmd", "==", "'cls'", ":", "self", ".", "clear_terminal", "(", ")", "return", "self", ".", "run_command", "(", "cmd", ")" ]
Execute a command cmd: one-line command only, with '\n' at the end
[ "Execute", "a", "command", "cmd", ":", "one", "-", "line", "command", "only", "with", "\\", "n", "at", "the", "end" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L386-L400
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.run_command
def run_command(self, cmd, history=True, new_prompt=True): """Run command in interpreter""" if not cmd: cmd = '' else: if history: self.add_to_history(cmd) if not self.multithreaded: if 'input' not in cmd: self.interpreter.stdin_write.write( to_binary_string(cmd + '\n')) self.interpreter.run_line() self.refresh.emit() else: self.write(_('In order to use commands like "raw_input" ' 'or "input" run Spyder with the multithread ' 'option (--multithread) from a system terminal'), error=True) else: self.interpreter.stdin_write.write(to_binary_string(cmd + '\n'))
python
def run_command(self, cmd, history=True, new_prompt=True): """Run command in interpreter""" if not cmd: cmd = '' else: if history: self.add_to_history(cmd) if not self.multithreaded: if 'input' not in cmd: self.interpreter.stdin_write.write( to_binary_string(cmd + '\n')) self.interpreter.run_line() self.refresh.emit() else: self.write(_('In order to use commands like "raw_input" ' 'or "input" run Spyder with the multithread ' 'option (--multithread) from a system terminal'), error=True) else: self.interpreter.stdin_write.write(to_binary_string(cmd + '\n'))
[ "def", "run_command", "(", "self", ",", "cmd", ",", "history", "=", "True", ",", "new_prompt", "=", "True", ")", ":", "if", "not", "cmd", ":", "cmd", "=", "''", "else", ":", "if", "history", ":", "self", ".", "add_to_history", "(", "cmd", ")", "if", "not", "self", ".", "multithreaded", ":", "if", "'input'", "not", "in", "cmd", ":", "self", ".", "interpreter", ".", "stdin_write", ".", "write", "(", "to_binary_string", "(", "cmd", "+", "'\\n'", ")", ")", "self", ".", "interpreter", ".", "run_line", "(", ")", "self", ".", "refresh", ".", "emit", "(", ")", "else", ":", "self", ".", "write", "(", "_", "(", "'In order to use commands like \"raw_input\" '", "'or \"input\" run Spyder with the multithread '", "'option (--multithread) from a system terminal'", ")", ",", "error", "=", "True", ")", "else", ":", "self", ".", "interpreter", ".", "stdin_write", ".", "write", "(", "to_binary_string", "(", "cmd", "+", "'\\n'", ")", ")" ]
Run command in interpreter
[ "Run", "command", "in", "interpreter" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L402-L421
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.get_dir
def get_dir(self, objtxt): """Return dir(object)""" obj, valid = self._eval(objtxt) if valid: return getobjdir(obj)
python
def get_dir(self, objtxt): """Return dir(object)""" obj, valid = self._eval(objtxt) if valid: return getobjdir(obj)
[ "def", "get_dir", "(", "self", ",", "objtxt", ")", ":", "obj", ",", "valid", "=", "self", ".", "_eval", "(", "objtxt", ")", "if", "valid", ":", "return", "getobjdir", "(", "obj", ")" ]
Return dir(object)
[ "Return", "dir", "(", "object", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L429-L433
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.iscallable
def iscallable(self, objtxt): """Is object callable?""" obj, valid = self._eval(objtxt) if valid: return callable(obj)
python
def iscallable(self, objtxt): """Is object callable?""" obj, valid = self._eval(objtxt) if valid: return callable(obj)
[ "def", "iscallable", "(", "self", ",", "objtxt", ")", ":", "obj", ",", "valid", "=", "self", ".", "_eval", "(", "objtxt", ")", "if", "valid", ":", "return", "callable", "(", "obj", ")" ]
Is object callable?
[ "Is", "object", "callable?" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L443-L447
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.get_arglist
def get_arglist(self, objtxt): """Get func/method argument list""" obj, valid = self._eval(objtxt) if valid: return getargtxt(obj)
python
def get_arglist(self, objtxt): """Get func/method argument list""" obj, valid = self._eval(objtxt) if valid: return getargtxt(obj)
[ "def", "get_arglist", "(", "self", ",", "objtxt", ")", ":", "obj", ",", "valid", "=", "self", ".", "_eval", "(", "objtxt", ")", "if", "valid", ":", "return", "getargtxt", "(", "obj", ")" ]
Get func/method argument list
[ "Get", "func", "/", "method", "argument", "list" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L449-L453
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.get_doc
def get_doc(self, objtxt): """Get object documentation dictionary""" obj, valid = self._eval(objtxt) if valid: return getdoc(obj)
python
def get_doc(self, objtxt): """Get object documentation dictionary""" obj, valid = self._eval(objtxt) if valid: return getdoc(obj)
[ "def", "get_doc", "(", "self", ",", "objtxt", ")", ":", "obj", ",", "valid", "=", "self", ".", "_eval", "(", "objtxt", ")", "if", "valid", ":", "return", "getdoc", "(", "obj", ")" ]
Get object documentation dictionary
[ "Get", "object", "documentation", "dictionary" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L461-L465
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.get_source
def get_source(self, objtxt): """Get object source""" obj, valid = self._eval(objtxt) if valid: return getsource(obj)
python
def get_source(self, objtxt): """Get object source""" obj, valid = self._eval(objtxt) if valid: return getsource(obj)
[ "def", "get_source", "(", "self", ",", "objtxt", ")", ":", "obj", ",", "valid", "=", "self", ".", "_eval", "(", "objtxt", ")", "if", "valid", ":", "return", "getsource", "(", "obj", ")" ]
Get object source
[ "Get", "object", "source" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L467-L471
train
spyder-ide/spyder
spyder/plugins/console/widgets/internalshell.py
InternalShell.is_defined
def is_defined(self, objtxt, force_import=False): """Return True if object is defined""" return self.interpreter.is_defined(objtxt, force_import)
python
def is_defined(self, objtxt, force_import=False): """Return True if object is defined""" return self.interpreter.is_defined(objtxt, force_import)
[ "def", "is_defined", "(", "self", ",", "objtxt", ",", "force_import", "=", "False", ")", ":", "return", "self", ".", "interpreter", ".", "is_defined", "(", "objtxt", ",", "force_import", ")" ]
Return True if object is defined
[ "Return", "True", "if", "object", "is", "defined" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L473-L475
train
spyder-ide/spyder
spyder/plugins/editor/panels/edgeline.py
EdgeLine.paintEvent
def paintEvent(self, event): """Override Qt method""" painter = QPainter(self) size = self.size() color = QColor(self.color) color.setAlphaF(.5) painter.setPen(color) for column in self.columns: x = self.editor.fontMetrics().width(column * '9') painter.drawLine(x, 0, x, size.height())
python
def paintEvent(self, event): """Override Qt method""" painter = QPainter(self) size = self.size() color = QColor(self.color) color.setAlphaF(.5) painter.setPen(color) for column in self.columns: x = self.editor.fontMetrics().width(column * '9') painter.drawLine(x, 0, x, size.height())
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "painter", "=", "QPainter", "(", "self", ")", "size", "=", "self", ".", "size", "(", ")", "color", "=", "QColor", "(", "self", ".", "color", ")", "color", ".", "setAlphaF", "(", ".5", ")", "painter", ".", "setPen", "(", "color", ")", "for", "column", "in", "self", ".", "columns", ":", "x", "=", "self", ".", "editor", ".", "fontMetrics", "(", ")", ".", "width", "(", "column", "*", "'9'", ")", "painter", ".", "drawLine", "(", "x", ",", "0", ",", "x", ",", "size", ".", "height", "(", ")", ")" ]
Override Qt method
[ "Override", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/edgeline.py#L28-L39
train
spyder-ide/spyder
spyder/plugins/editor/panels/edgeline.py
EdgeLine.set_columns
def set_columns(self, columns): """Set edge line columns values.""" if isinstance(columns, tuple): self.columns = columns elif is_text_string(columns): self.columns = tuple(int(e) for e in columns.split(',')) self.update()
python
def set_columns(self, columns): """Set edge line columns values.""" if isinstance(columns, tuple): self.columns = columns elif is_text_string(columns): self.columns = tuple(int(e) for e in columns.split(',')) self.update()
[ "def", "set_columns", "(", "self", ",", "columns", ")", ":", "if", "isinstance", "(", "columns", ",", "tuple", ")", ":", "self", ".", "columns", "=", "columns", "elif", "is_text_string", "(", "columns", ")", ":", "self", ".", "columns", "=", "tuple", "(", "int", "(", "e", ")", "for", "e", "in", "columns", ".", "split", "(", "','", ")", ")", "self", ".", "update", "(", ")" ]
Set edge line columns values.
[ "Set", "edge", "line", "columns", "values", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/edgeline.py#L49-L56
train
spyder-ide/spyder
spyder/app/start.py
send_args_to_spyder
def send_args_to_spyder(args): """ Simple socket client used to send the args passed to the Spyder executable to an already running instance. Args can be Python scripts or files with these extensions: .spydata, .mat, .npy, or .h5, which can be imported by the Variable Explorer. """ port = CONF.get('main', 'open_files_port') # Wait ~50 secs for the server to be up # Taken from https://stackoverflow.com/a/4766598/438386 for _x in range(200): try: for arg in args: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) client.connect(("127.0.0.1", port)) if is_unicode(arg): arg = arg.encode('utf-8') client.send(osp.abspath(arg)) client.close() except socket.error: time.sleep(0.25) continue break
python
def send_args_to_spyder(args): """ Simple socket client used to send the args passed to the Spyder executable to an already running instance. Args can be Python scripts or files with these extensions: .spydata, .mat, .npy, or .h5, which can be imported by the Variable Explorer. """ port = CONF.get('main', 'open_files_port') # Wait ~50 secs for the server to be up # Taken from https://stackoverflow.com/a/4766598/438386 for _x in range(200): try: for arg in args: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) client.connect(("127.0.0.1", port)) if is_unicode(arg): arg = arg.encode('utf-8') client.send(osp.abspath(arg)) client.close() except socket.error: time.sleep(0.25) continue break
[ "def", "send_args_to_spyder", "(", "args", ")", ":", "port", "=", "CONF", ".", "get", "(", "'main'", ",", "'open_files_port'", ")", "# Wait ~50 secs for the server to be up\r", "# Taken from https://stackoverflow.com/a/4766598/438386\r", "for", "_x", "in", "range", "(", "200", ")", ":", "try", ":", "for", "arg", "in", "args", ":", "client", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ",", "socket", ".", "IPPROTO_TCP", ")", "client", ".", "connect", "(", "(", "\"127.0.0.1\"", ",", "port", ")", ")", "if", "is_unicode", "(", "arg", ")", ":", "arg", "=", "arg", ".", "encode", "(", "'utf-8'", ")", "client", ".", "send", "(", "osp", ".", "abspath", "(", "arg", ")", ")", "client", ".", "close", "(", ")", "except", "socket", ".", "error", ":", "time", ".", "sleep", "(", "0.25", ")", "continue", "break" ]
Simple socket client used to send the args passed to the Spyder executable to an already running instance. Args can be Python scripts or files with these extensions: .spydata, .mat, .npy, or .h5, which can be imported by the Variable Explorer.
[ "Simple", "socket", "client", "used", "to", "send", "the", "args", "passed", "to", "the", "Spyder", "executable", "to", "an", "already", "running", "instance", ".", "Args", "can", "be", "Python", "scripts", "or", "files", "with", "these", "extensions", ":", ".", "spydata", ".", "mat", ".", "npy", "or", ".", "h5", "which", "can", "be", "imported", "by", "the", "Variable", "Explorer", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/start.py#L39-L64
train
spyder-ide/spyder
spyder/app/start.py
main
def main(): """ Start Spyder application. If single instance mode is turned on (default behavior) and an instance of Spyder is already running, this will just parse and send command line options to the application. """ # Parse command line options if running_under_pytest(): try: from unittest.mock import Mock except ImportError: from mock import Mock # Python 2 options = Mock() options.new_instance = False options.reset_config_files = False options.debug_info = None args = None else: options, args = get_options() # Store variable to be used in self.restart (restart spyder instance) os.environ['SPYDER_ARGS'] = str(sys.argv[1:]) #========================================================================== # Proper high DPI scaling is available in Qt >= 5.6.0. This attibute must # be set before creating the application. #========================================================================== if CONF.get('main', 'high_dpi_custom_scale_factor'): factors = str(CONF.get('main', 'high_dpi_custom_scale_factors')) f = list(filter(None, factors.split(';'))) if len(f) == 1: os.environ['QT_SCALE_FACTOR'] = f[0] else: os.environ['QT_SCREEN_SCALE_FACTORS'] = factors else: os.environ['QT_SCALE_FACTOR'] = '' os.environ['QT_SCREEN_SCALE_FACTORS'] = '' if sys.platform == 'darwin': # Prevent Spyder from crashing in macOS if locale is not defined LANG = os.environ.get('LANG') LC_ALL = os.environ.get('LC_ALL') if bool(LANG) and not bool(LC_ALL): LC_ALL = LANG elif not bool(LANG) and bool(LC_ALL): LANG = LC_ALL else: LANG = LC_ALL = 'en_US.UTF-8' os.environ['LANG'] = LANG os.environ['LC_ALL'] = LC_ALL # Don't show useless warning in the terminal where Spyder # was started # See issue 3730 os.environ['EVENT_NOKQUEUE'] = '1' else: # Prevent our kernels to crash when Python fails to identify # the system locale. # Fixes issue 7051. try: from locale import getlocale getlocale() except ValueError: # This can fail on Windows. See issue 6886 try: os.environ['LANG'] = 'C' os.environ['LC_ALL'] = 'C' except Exception: pass if options.debug_info: levels = {'minimal': '2', 'verbose': '3'} os.environ['SPYDER_DEBUG'] = levels[options.debug_info] if CONF.get('main', 'single_instance') and not options.new_instance \ and not options.reset_config_files and not running_in_mac_app(): # Minimal delay (0.1-0.2 secs) to avoid that several # instances started at the same time step in their # own foots while trying to create the lock file time.sleep(random.randrange(1000, 2000, 90)/10000.) # Lock file creation lock_file = get_conf_path('spyder.lock') lock = lockfile.FilesystemLock(lock_file) # Try to lock spyder.lock. If it's *possible* to do it, then # there is no previous instance running and we can start a # new one. If *not*, then there is an instance already # running, which is locking that file try: lock_created = lock.lock() except: # If locking fails because of errors in the lockfile # module, try to remove a possibly stale spyder.lock. # This is reported to solve all problems with # lockfile (See issue 2363) try: if os.name == 'nt': if osp.isdir(lock_file): import shutil shutil.rmtree(lock_file, ignore_errors=True) else: if osp.islink(lock_file): os.unlink(lock_file) except: pass # Then start Spyder as usual and *don't* continue # executing this script because it doesn't make # sense from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main() else: mainwindow.main() return if lock_created: # Start a new instance from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main() else: mainwindow.main() else: # Pass args to Spyder or print an informative # message if args: send_args_to_spyder(args) else: print("Spyder is already running. If you want to open a new \n" "instance, please pass to it the --new-instance option") else: from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main() else: mainwindow.main()
python
def main(): """ Start Spyder application. If single instance mode is turned on (default behavior) and an instance of Spyder is already running, this will just parse and send command line options to the application. """ # Parse command line options if running_under_pytest(): try: from unittest.mock import Mock except ImportError: from mock import Mock # Python 2 options = Mock() options.new_instance = False options.reset_config_files = False options.debug_info = None args = None else: options, args = get_options() # Store variable to be used in self.restart (restart spyder instance) os.environ['SPYDER_ARGS'] = str(sys.argv[1:]) #========================================================================== # Proper high DPI scaling is available in Qt >= 5.6.0. This attibute must # be set before creating the application. #========================================================================== if CONF.get('main', 'high_dpi_custom_scale_factor'): factors = str(CONF.get('main', 'high_dpi_custom_scale_factors')) f = list(filter(None, factors.split(';'))) if len(f) == 1: os.environ['QT_SCALE_FACTOR'] = f[0] else: os.environ['QT_SCREEN_SCALE_FACTORS'] = factors else: os.environ['QT_SCALE_FACTOR'] = '' os.environ['QT_SCREEN_SCALE_FACTORS'] = '' if sys.platform == 'darwin': # Prevent Spyder from crashing in macOS if locale is not defined LANG = os.environ.get('LANG') LC_ALL = os.environ.get('LC_ALL') if bool(LANG) and not bool(LC_ALL): LC_ALL = LANG elif not bool(LANG) and bool(LC_ALL): LANG = LC_ALL else: LANG = LC_ALL = 'en_US.UTF-8' os.environ['LANG'] = LANG os.environ['LC_ALL'] = LC_ALL # Don't show useless warning in the terminal where Spyder # was started # See issue 3730 os.environ['EVENT_NOKQUEUE'] = '1' else: # Prevent our kernels to crash when Python fails to identify # the system locale. # Fixes issue 7051. try: from locale import getlocale getlocale() except ValueError: # This can fail on Windows. See issue 6886 try: os.environ['LANG'] = 'C' os.environ['LC_ALL'] = 'C' except Exception: pass if options.debug_info: levels = {'minimal': '2', 'verbose': '3'} os.environ['SPYDER_DEBUG'] = levels[options.debug_info] if CONF.get('main', 'single_instance') and not options.new_instance \ and not options.reset_config_files and not running_in_mac_app(): # Minimal delay (0.1-0.2 secs) to avoid that several # instances started at the same time step in their # own foots while trying to create the lock file time.sleep(random.randrange(1000, 2000, 90)/10000.) # Lock file creation lock_file = get_conf_path('spyder.lock') lock = lockfile.FilesystemLock(lock_file) # Try to lock spyder.lock. If it's *possible* to do it, then # there is no previous instance running and we can start a # new one. If *not*, then there is an instance already # running, which is locking that file try: lock_created = lock.lock() except: # If locking fails because of errors in the lockfile # module, try to remove a possibly stale spyder.lock. # This is reported to solve all problems with # lockfile (See issue 2363) try: if os.name == 'nt': if osp.isdir(lock_file): import shutil shutil.rmtree(lock_file, ignore_errors=True) else: if osp.islink(lock_file): os.unlink(lock_file) except: pass # Then start Spyder as usual and *don't* continue # executing this script because it doesn't make # sense from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main() else: mainwindow.main() return if lock_created: # Start a new instance from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main() else: mainwindow.main() else: # Pass args to Spyder or print an informative # message if args: send_args_to_spyder(args) else: print("Spyder is already running. If you want to open a new \n" "instance, please pass to it the --new-instance option") else: from spyder.app import mainwindow if running_under_pytest(): return mainwindow.main() else: mainwindow.main()
[ "def", "main", "(", ")", ":", "# Parse command line options\r", "if", "running_under_pytest", "(", ")", ":", "try", ":", "from", "unittest", ".", "mock", "import", "Mock", "except", "ImportError", ":", "from", "mock", "import", "Mock", "# Python 2\r", "options", "=", "Mock", "(", ")", "options", ".", "new_instance", "=", "False", "options", ".", "reset_config_files", "=", "False", "options", ".", "debug_info", "=", "None", "args", "=", "None", "else", ":", "options", ",", "args", "=", "get_options", "(", ")", "# Store variable to be used in self.restart (restart spyder instance)\r", "os", ".", "environ", "[", "'SPYDER_ARGS'", "]", "=", "str", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "#==========================================================================\r", "# Proper high DPI scaling is available in Qt >= 5.6.0. This attibute must\r", "# be set before creating the application.\r", "#==========================================================================\r", "if", "CONF", ".", "get", "(", "'main'", ",", "'high_dpi_custom_scale_factor'", ")", ":", "factors", "=", "str", "(", "CONF", ".", "get", "(", "'main'", ",", "'high_dpi_custom_scale_factors'", ")", ")", "f", "=", "list", "(", "filter", "(", "None", ",", "factors", ".", "split", "(", "';'", ")", ")", ")", "if", "len", "(", "f", ")", "==", "1", ":", "os", ".", "environ", "[", "'QT_SCALE_FACTOR'", "]", "=", "f", "[", "0", "]", "else", ":", "os", ".", "environ", "[", "'QT_SCREEN_SCALE_FACTORS'", "]", "=", "factors", "else", ":", "os", ".", "environ", "[", "'QT_SCALE_FACTOR'", "]", "=", "''", "os", ".", "environ", "[", "'QT_SCREEN_SCALE_FACTORS'", "]", "=", "''", "if", "sys", ".", "platform", "==", "'darwin'", ":", "# Prevent Spyder from crashing in macOS if locale is not defined\r", "LANG", "=", "os", ".", "environ", ".", "get", "(", "'LANG'", ")", "LC_ALL", "=", "os", ".", "environ", ".", "get", "(", "'LC_ALL'", ")", "if", "bool", "(", "LANG", ")", "and", "not", "bool", "(", "LC_ALL", ")", ":", "LC_ALL", "=", "LANG", "elif", "not", "bool", "(", "LANG", ")", "and", "bool", "(", "LC_ALL", ")", ":", "LANG", "=", "LC_ALL", "else", ":", "LANG", "=", "LC_ALL", "=", "'en_US.UTF-8'", "os", ".", "environ", "[", "'LANG'", "]", "=", "LANG", "os", ".", "environ", "[", "'LC_ALL'", "]", "=", "LC_ALL", "# Don't show useless warning in the terminal where Spyder\r", "# was started\r", "# See issue 3730\r", "os", ".", "environ", "[", "'EVENT_NOKQUEUE'", "]", "=", "'1'", "else", ":", "# Prevent our kernels to crash when Python fails to identify\r", "# the system locale.\r", "# Fixes issue 7051.\r", "try", ":", "from", "locale", "import", "getlocale", "getlocale", "(", ")", "except", "ValueError", ":", "# This can fail on Windows. See issue 6886\r", "try", ":", "os", ".", "environ", "[", "'LANG'", "]", "=", "'C'", "os", ".", "environ", "[", "'LC_ALL'", "]", "=", "'C'", "except", "Exception", ":", "pass", "if", "options", ".", "debug_info", ":", "levels", "=", "{", "'minimal'", ":", "'2'", ",", "'verbose'", ":", "'3'", "}", "os", ".", "environ", "[", "'SPYDER_DEBUG'", "]", "=", "levels", "[", "options", ".", "debug_info", "]", "if", "CONF", ".", "get", "(", "'main'", ",", "'single_instance'", ")", "and", "not", "options", ".", "new_instance", "and", "not", "options", ".", "reset_config_files", "and", "not", "running_in_mac_app", "(", ")", ":", "# Minimal delay (0.1-0.2 secs) to avoid that several\r", "# instances started at the same time step in their\r", "# own foots while trying to create the lock file\r", "time", ".", "sleep", "(", "random", ".", "randrange", "(", "1000", ",", "2000", ",", "90", ")", "/", "10000.", ")", "# Lock file creation\r", "lock_file", "=", "get_conf_path", "(", "'spyder.lock'", ")", "lock", "=", "lockfile", ".", "FilesystemLock", "(", "lock_file", ")", "# Try to lock spyder.lock. If it's *possible* to do it, then\r", "# there is no previous instance running and we can start a\r", "# new one. If *not*, then there is an instance already\r", "# running, which is locking that file\r", "try", ":", "lock_created", "=", "lock", ".", "lock", "(", ")", "except", ":", "# If locking fails because of errors in the lockfile\r", "# module, try to remove a possibly stale spyder.lock.\r", "# This is reported to solve all problems with\r", "# lockfile (See issue 2363)\r", "try", ":", "if", "os", ".", "name", "==", "'nt'", ":", "if", "osp", ".", "isdir", "(", "lock_file", ")", ":", "import", "shutil", "shutil", ".", "rmtree", "(", "lock_file", ",", "ignore_errors", "=", "True", ")", "else", ":", "if", "osp", ".", "islink", "(", "lock_file", ")", ":", "os", ".", "unlink", "(", "lock_file", ")", "except", ":", "pass", "# Then start Spyder as usual and *don't* continue\r", "# executing this script because it doesn't make\r", "# sense\r", "from", "spyder", ".", "app", "import", "mainwindow", "if", "running_under_pytest", "(", ")", ":", "return", "mainwindow", ".", "main", "(", ")", "else", ":", "mainwindow", ".", "main", "(", ")", "return", "if", "lock_created", ":", "# Start a new instance\r", "from", "spyder", ".", "app", "import", "mainwindow", "if", "running_under_pytest", "(", ")", ":", "return", "mainwindow", ".", "main", "(", ")", "else", ":", "mainwindow", ".", "main", "(", ")", "else", ":", "# Pass args to Spyder or print an informative\r", "# message\r", "if", "args", ":", "send_args_to_spyder", "(", "args", ")", "else", ":", "print", "(", "\"Spyder is already running. If you want to open a new \\n\"", "\"instance, please pass to it the --new-instance option\"", ")", "else", ":", "from", "spyder", ".", "app", "import", "mainwindow", "if", "running_under_pytest", "(", ")", ":", "return", "mainwindow", ".", "main", "(", ")", "else", ":", "mainwindow", ".", "main", "(", ")" ]
Start Spyder application. If single instance mode is turned on (default behavior) and an instance of Spyder is already running, this will just parse and send command line options to the application.
[ "Start", "Spyder", "application", ".", "If", "single", "instance", "mode", "is", "turned", "on", "(", "default", "behavior", ")", "and", "an", "instance", "of", "Spyder", "is", "already", "running", "this", "will", "just", "parse", "and", "send", "command", "line", "options", "to", "the", "application", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/start.py#L67-L208
train
spyder-ide/spyder
spyder/utils/stringmatching.py
get_search_regex
def get_search_regex(query, ignore_case=True): """Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensitive search (True by default). Returns ------- pattern : SRE_Pattern Notes ----- This function adds '.*' between the query characters and compiles the resulting regular expression. """ regex_text = [char for char in query if char != ' '] regex_text = '.*'.join(regex_text) regex = r'({0})'.format(regex_text) if ignore_case: pattern = re.compile(regex, re.IGNORECASE) else: pattern = re.compile(regex) return pattern
python
def get_search_regex(query, ignore_case=True): """Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensitive search (True by default). Returns ------- pattern : SRE_Pattern Notes ----- This function adds '.*' between the query characters and compiles the resulting regular expression. """ regex_text = [char for char in query if char != ' '] regex_text = '.*'.join(regex_text) regex = r'({0})'.format(regex_text) if ignore_case: pattern = re.compile(regex, re.IGNORECASE) else: pattern = re.compile(regex) return pattern
[ "def", "get_search_regex", "(", "query", ",", "ignore_case", "=", "True", ")", ":", "regex_text", "=", "[", "char", "for", "char", "in", "query", "if", "char", "!=", "' '", "]", "regex_text", "=", "'.*'", ".", "join", "(", "regex_text", ")", "regex", "=", "r'({0})'", ".", "format", "(", "regex_text", ")", "if", "ignore_case", ":", "pattern", "=", "re", ".", "compile", "(", "regex", ",", "re", ".", "IGNORECASE", ")", "else", ":", "pattern", "=", "re", ".", "compile", "(", "regex", ")", "return", "pattern" ]
Returns a compiled regex pattern to search for query letters in order. Parameters ---------- query : str String to search in another string (in order of character occurrence). ignore_case : True Optional value perform a case insensitive search (True by default). Returns ------- pattern : SRE_Pattern Notes ----- This function adds '.*' between the query characters and compiles the resulting regular expression.
[ "Returns", "a", "compiled", "regex", "pattern", "to", "search", "for", "query", "letters", "in", "order", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/stringmatching.py#L18-L47
train
spyder-ide/spyder
spyder/utils/stringmatching.py
get_search_score
def get_search_score(query, choice, ignore_case=True, apply_regex=True, template='{}'): """Returns a tuple with the enriched text (if a template is provided) and a score for the match. Parameters ---------- query : str String with letters to search in choice (in order of appearance). choice : str Sentence/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). apply_regex : bool, optional Optional value (True by default) to perform a regex search. Useful when this function is called directly. template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : tuple Tuples where the first item is the text (enriched if a template was used) and the second item is a search score. Notes ----- The score is given according the following precedence (high to low): - Letters in one word and no spaces with exact match. Example: 'up' in 'up stroke' - Letters in one word and no spaces with partial match. Example: 'up' in 'upstream stroke' - Letters in one word but with skip letters. Example: 'cls' in 'close up' - Letters in two or more words Example: 'cls' in 'car lost' """ original_choice = choice result = (original_choice, NOT_FOUND_SCORE) # Handle empty string case if not query: return result if ignore_case: query = query.lower() choice = choice.lower() if apply_regex: pattern = get_search_regex(query, ignore_case=ignore_case) r = re.search(pattern, choice) if r is None: return result else: sep = u'-' # Matches will be replaced by this character let = u'x' # Nonmatches (except spaed) will be replaced by this score = 0 exact_words = [query == word for word in choice.split(u' ')] partial_words = [query in word for word in choice.split(u' ')] if any(exact_words) or any(partial_words): pos_start = choice.find(query) pos_end = pos_start + len(query) score += pos_start text = choice.replace(query, sep*len(query), 1) enriched_text = original_choice[:pos_start] +\ template.format(original_choice[pos_start:pos_end]) +\ original_choice[pos_end:] if any(exact_words): # Check if the query words exists in a word with exact match score += 1 elif any(partial_words): # Check if the query words exists in a word with partial match score += 100 else: # Check letter by letter text = [l for l in original_choice] if ignore_case: temp_text = [l.lower() for l in original_choice] else: temp_text = text[:] # Give points to start of string score += temp_text.index(query[0]) # Find the query letters and replace them by `sep`, also apply # template as needed for enricching the letters in the text enriched_text = text[:] for char in query: if char != u'' and char in temp_text: index = temp_text.index(char) enriched_text[index] = template.format(text[index]) text[index] = sep temp_text = [u' ']*(index + 1) + temp_text[index+1:] enriched_text = u''.join(enriched_text) patterns_text = [] for i, char in enumerate(text): if char != u' ' and char != sep: new_char = let else: new_char = char patterns_text.append(new_char) patterns_text = u''.join(patterns_text) for i in reversed(range(1, len(query) + 1)): score += (len(query) - patterns_text.count(sep*i))*100000 temp = patterns_text.split(sep) while u'' in temp: temp.remove(u'') if not patterns_text.startswith(sep): temp = temp[1:] if not patterns_text.endswith(sep): temp = temp[:-1] for pat in temp: score += pat.count(u' ')*10000 score += pat.count(let)*100 return original_choice, enriched_text, score
python
def get_search_score(query, choice, ignore_case=True, apply_regex=True, template='{}'): """Returns a tuple with the enriched text (if a template is provided) and a score for the match. Parameters ---------- query : str String with letters to search in choice (in order of appearance). choice : str Sentence/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). apply_regex : bool, optional Optional value (True by default) to perform a regex search. Useful when this function is called directly. template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : tuple Tuples where the first item is the text (enriched if a template was used) and the second item is a search score. Notes ----- The score is given according the following precedence (high to low): - Letters in one word and no spaces with exact match. Example: 'up' in 'up stroke' - Letters in one word and no spaces with partial match. Example: 'up' in 'upstream stroke' - Letters in one word but with skip letters. Example: 'cls' in 'close up' - Letters in two or more words Example: 'cls' in 'car lost' """ original_choice = choice result = (original_choice, NOT_FOUND_SCORE) # Handle empty string case if not query: return result if ignore_case: query = query.lower() choice = choice.lower() if apply_regex: pattern = get_search_regex(query, ignore_case=ignore_case) r = re.search(pattern, choice) if r is None: return result else: sep = u'-' # Matches will be replaced by this character let = u'x' # Nonmatches (except spaed) will be replaced by this score = 0 exact_words = [query == word for word in choice.split(u' ')] partial_words = [query in word for word in choice.split(u' ')] if any(exact_words) or any(partial_words): pos_start = choice.find(query) pos_end = pos_start + len(query) score += pos_start text = choice.replace(query, sep*len(query), 1) enriched_text = original_choice[:pos_start] +\ template.format(original_choice[pos_start:pos_end]) +\ original_choice[pos_end:] if any(exact_words): # Check if the query words exists in a word with exact match score += 1 elif any(partial_words): # Check if the query words exists in a word with partial match score += 100 else: # Check letter by letter text = [l for l in original_choice] if ignore_case: temp_text = [l.lower() for l in original_choice] else: temp_text = text[:] # Give points to start of string score += temp_text.index(query[0]) # Find the query letters and replace them by `sep`, also apply # template as needed for enricching the letters in the text enriched_text = text[:] for char in query: if char != u'' and char in temp_text: index = temp_text.index(char) enriched_text[index] = template.format(text[index]) text[index] = sep temp_text = [u' ']*(index + 1) + temp_text[index+1:] enriched_text = u''.join(enriched_text) patterns_text = [] for i, char in enumerate(text): if char != u' ' and char != sep: new_char = let else: new_char = char patterns_text.append(new_char) patterns_text = u''.join(patterns_text) for i in reversed(range(1, len(query) + 1)): score += (len(query) - patterns_text.count(sep*i))*100000 temp = patterns_text.split(sep) while u'' in temp: temp.remove(u'') if not patterns_text.startswith(sep): temp = temp[1:] if not patterns_text.endswith(sep): temp = temp[:-1] for pat in temp: score += pat.count(u' ')*10000 score += pat.count(let)*100 return original_choice, enriched_text, score
[ "def", "get_search_score", "(", "query", ",", "choice", ",", "ignore_case", "=", "True", ",", "apply_regex", "=", "True", ",", "template", "=", "'{}'", ")", ":", "original_choice", "=", "choice", "result", "=", "(", "original_choice", ",", "NOT_FOUND_SCORE", ")", "# Handle empty string case", "if", "not", "query", ":", "return", "result", "if", "ignore_case", ":", "query", "=", "query", ".", "lower", "(", ")", "choice", "=", "choice", ".", "lower", "(", ")", "if", "apply_regex", ":", "pattern", "=", "get_search_regex", "(", "query", ",", "ignore_case", "=", "ignore_case", ")", "r", "=", "re", ".", "search", "(", "pattern", ",", "choice", ")", "if", "r", "is", "None", ":", "return", "result", "else", ":", "sep", "=", "u'-'", "# Matches will be replaced by this character", "let", "=", "u'x'", "# Nonmatches (except spaed) will be replaced by this", "score", "=", "0", "exact_words", "=", "[", "query", "==", "word", "for", "word", "in", "choice", ".", "split", "(", "u' '", ")", "]", "partial_words", "=", "[", "query", "in", "word", "for", "word", "in", "choice", ".", "split", "(", "u' '", ")", "]", "if", "any", "(", "exact_words", ")", "or", "any", "(", "partial_words", ")", ":", "pos_start", "=", "choice", ".", "find", "(", "query", ")", "pos_end", "=", "pos_start", "+", "len", "(", "query", ")", "score", "+=", "pos_start", "text", "=", "choice", ".", "replace", "(", "query", ",", "sep", "*", "len", "(", "query", ")", ",", "1", ")", "enriched_text", "=", "original_choice", "[", ":", "pos_start", "]", "+", "template", ".", "format", "(", "original_choice", "[", "pos_start", ":", "pos_end", "]", ")", "+", "original_choice", "[", "pos_end", ":", "]", "if", "any", "(", "exact_words", ")", ":", "# Check if the query words exists in a word with exact match", "score", "+=", "1", "elif", "any", "(", "partial_words", ")", ":", "# Check if the query words exists in a word with partial match", "score", "+=", "100", "else", ":", "# Check letter by letter", "text", "=", "[", "l", "for", "l", "in", "original_choice", "]", "if", "ignore_case", ":", "temp_text", "=", "[", "l", ".", "lower", "(", ")", "for", "l", "in", "original_choice", "]", "else", ":", "temp_text", "=", "text", "[", ":", "]", "# Give points to start of string", "score", "+=", "temp_text", ".", "index", "(", "query", "[", "0", "]", ")", "# Find the query letters and replace them by `sep`, also apply", "# template as needed for enricching the letters in the text", "enriched_text", "=", "text", "[", ":", "]", "for", "char", "in", "query", ":", "if", "char", "!=", "u''", "and", "char", "in", "temp_text", ":", "index", "=", "temp_text", ".", "index", "(", "char", ")", "enriched_text", "[", "index", "]", "=", "template", ".", "format", "(", "text", "[", "index", "]", ")", "text", "[", "index", "]", "=", "sep", "temp_text", "=", "[", "u' '", "]", "*", "(", "index", "+", "1", ")", "+", "temp_text", "[", "index", "+", "1", ":", "]", "enriched_text", "=", "u''", ".", "join", "(", "enriched_text", ")", "patterns_text", "=", "[", "]", "for", "i", ",", "char", "in", "enumerate", "(", "text", ")", ":", "if", "char", "!=", "u' '", "and", "char", "!=", "sep", ":", "new_char", "=", "let", "else", ":", "new_char", "=", "char", "patterns_text", ".", "append", "(", "new_char", ")", "patterns_text", "=", "u''", ".", "join", "(", "patterns_text", ")", "for", "i", "in", "reversed", "(", "range", "(", "1", ",", "len", "(", "query", ")", "+", "1", ")", ")", ":", "score", "+=", "(", "len", "(", "query", ")", "-", "patterns_text", ".", "count", "(", "sep", "*", "i", ")", ")", "*", "100000", "temp", "=", "patterns_text", ".", "split", "(", "sep", ")", "while", "u''", "in", "temp", ":", "temp", ".", "remove", "(", "u''", ")", "if", "not", "patterns_text", ".", "startswith", "(", "sep", ")", ":", "temp", "=", "temp", "[", "1", ":", "]", "if", "not", "patterns_text", ".", "endswith", "(", "sep", ")", ":", "temp", "=", "temp", "[", ":", "-", "1", "]", "for", "pat", "in", "temp", ":", "score", "+=", "pat", ".", "count", "(", "u' '", ")", "*", "10000", "score", "+=", "pat", ".", "count", "(", "let", ")", "*", "100", "return", "original_choice", ",", "enriched_text", ",", "score" ]
Returns a tuple with the enriched text (if a template is provided) and a score for the match. Parameters ---------- query : str String with letters to search in choice (in order of appearance). choice : str Sentence/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). apply_regex : bool, optional Optional value (True by default) to perform a regex search. Useful when this function is called directly. template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : tuple Tuples where the first item is the text (enriched if a template was used) and the second item is a search score. Notes ----- The score is given according the following precedence (high to low): - Letters in one word and no spaces with exact match. Example: 'up' in 'up stroke' - Letters in one word and no spaces with partial match. Example: 'up' in 'upstream stroke' - Letters in one word but with skip letters. Example: 'cls' in 'close up' - Letters in two or more words Example: 'cls' in 'car lost'
[ "Returns", "a", "tuple", "with", "the", "enriched", "text", "(", "if", "a", "template", "is", "provided", ")", "and", "a", "score", "for", "the", "match", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/stringmatching.py#L50-L176
train
spyder-ide/spyder
spyder/utils/stringmatching.py
get_search_scores
def get_search_scores(query, choices, ignore_case=True, template='{}', valid_only=False, sort=False): """Search for query inside choices and return a list of tuples. Returns a list of tuples of text with the enriched text (if a template is provided) and a score for the match. Lower scores imply a better match. Parameters ---------- query : str String with letters to search in each choice (in order of appearance). choices : list of str List of sentences/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : list of tuples List of tuples where the first item is the text (enriched if a template was used) and a search score. Lower scores means better match. """ # First remove spaces from query query = query.replace(' ', '') pattern = get_search_regex(query, ignore_case) results = [] for choice in choices: r = re.search(pattern, choice) if query and r: result = get_search_score(query, choice, ignore_case=ignore_case, apply_regex=False, template=template) else: if query: result = (choice, choice, NOT_FOUND_SCORE) else: result = (choice, choice, NO_SCORE) if valid_only: if result[-1] != NOT_FOUND_SCORE: results.append(result) else: results.append(result) if sort: results = sorted(results, key=lambda row: row[-1]) return results
python
def get_search_scores(query, choices, ignore_case=True, template='{}', valid_only=False, sort=False): """Search for query inside choices and return a list of tuples. Returns a list of tuples of text with the enriched text (if a template is provided) and a score for the match. Lower scores imply a better match. Parameters ---------- query : str String with letters to search in each choice (in order of appearance). choices : list of str List of sentences/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : list of tuples List of tuples where the first item is the text (enriched if a template was used) and a search score. Lower scores means better match. """ # First remove spaces from query query = query.replace(' ', '') pattern = get_search_regex(query, ignore_case) results = [] for choice in choices: r = re.search(pattern, choice) if query and r: result = get_search_score(query, choice, ignore_case=ignore_case, apply_regex=False, template=template) else: if query: result = (choice, choice, NOT_FOUND_SCORE) else: result = (choice, choice, NO_SCORE) if valid_only: if result[-1] != NOT_FOUND_SCORE: results.append(result) else: results.append(result) if sort: results = sorted(results, key=lambda row: row[-1]) return results
[ "def", "get_search_scores", "(", "query", ",", "choices", ",", "ignore_case", "=", "True", ",", "template", "=", "'{}'", ",", "valid_only", "=", "False", ",", "sort", "=", "False", ")", ":", "# First remove spaces from query", "query", "=", "query", ".", "replace", "(", "' '", ",", "''", ")", "pattern", "=", "get_search_regex", "(", "query", ",", "ignore_case", ")", "results", "=", "[", "]", "for", "choice", "in", "choices", ":", "r", "=", "re", ".", "search", "(", "pattern", ",", "choice", ")", "if", "query", "and", "r", ":", "result", "=", "get_search_score", "(", "query", ",", "choice", ",", "ignore_case", "=", "ignore_case", ",", "apply_regex", "=", "False", ",", "template", "=", "template", ")", "else", ":", "if", "query", ":", "result", "=", "(", "choice", ",", "choice", ",", "NOT_FOUND_SCORE", ")", "else", ":", "result", "=", "(", "choice", ",", "choice", ",", "NO_SCORE", ")", "if", "valid_only", ":", "if", "result", "[", "-", "1", "]", "!=", "NOT_FOUND_SCORE", ":", "results", ".", "append", "(", "result", ")", "else", ":", "results", ".", "append", "(", "result", ")", "if", "sort", ":", "results", "=", "sorted", "(", "results", ",", "key", "=", "lambda", "row", ":", "row", "[", "-", "1", "]", ")", "return", "results" ]
Search for query inside choices and return a list of tuples. Returns a list of tuples of text with the enriched text (if a template is provided) and a score for the match. Lower scores imply a better match. Parameters ---------- query : str String with letters to search in each choice (in order of appearance). choices : list of str List of sentences/words in which to search for the 'query' letters. ignore_case : bool, optional Optional value perform a case insensitive search (True by default). template : str, optional Optional template string to surround letters found in choices. This is useful when using a rich text editor ('{}' by default). Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>' Returns ------- results : list of tuples List of tuples where the first item is the text (enriched if a template was used) and a search score. Lower scores means better match.
[ "Search", "for", "query", "inside", "choices", "and", "return", "a", "list", "of", "tuples", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/stringmatching.py#L179-L230
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
is_start_of_function
def is_start_of_function(text): """Return True if text is the beginning of the function definition.""" if isinstance(text, str) or isinstance(text, unicode): function_prefix = ['def', 'async def'] text = text.lstrip() for prefix in function_prefix: if text.startswith(prefix): return True return False
python
def is_start_of_function(text): """Return True if text is the beginning of the function definition.""" if isinstance(text, str) or isinstance(text, unicode): function_prefix = ['def', 'async def'] text = text.lstrip() for prefix in function_prefix: if text.startswith(prefix): return True return False
[ "def", "is_start_of_function", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", "or", "isinstance", "(", "text", ",", "unicode", ")", ":", "function_prefix", "=", "[", "'def'", ",", "'async def'", "]", "text", "=", "text", ".", "lstrip", "(", ")", "for", "prefix", "in", "function_prefix", ":", "if", "text", ".", "startswith", "(", "prefix", ")", ":", "return", "True", "return", "False" ]
Return True if text is the beginning of the function definition.
[ "Return", "True", "if", "text", "is", "the", "beginning", "of", "the", "function", "definition", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L23-L33
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
get_indent
def get_indent(text): """Get indent of text. https://stackoverflow.com/questions/2268532/grab-a-lines-whitespace- indention-with-python """ indent = '' ret = re.match(r'(\s*)', text) if ret: indent = ret.group(1) return indent
python
def get_indent(text): """Get indent of text. https://stackoverflow.com/questions/2268532/grab-a-lines-whitespace- indention-with-python """ indent = '' ret = re.match(r'(\s*)', text) if ret: indent = ret.group(1) return indent
[ "def", "get_indent", "(", "text", ")", ":", "indent", "=", "''", "ret", "=", "re", ".", "match", "(", "r'(\\s*)'", ",", "text", ")", "if", "ret", ":", "indent", "=", "ret", ".", "group", "(", "1", ")", "return", "indent" ]
Get indent of text. https://stackoverflow.com/questions/2268532/grab-a-lines-whitespace- indention-with-python
[ "Get", "indent", "of", "text", ".", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "2268532", "/", "grab", "-", "a", "-", "lines", "-", "whitespace", "-", "indention", "-", "with", "-", "python" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L36-L48
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.get_function_definition_from_first_line
def get_function_definition_from_first_line(self): """Get func def when the cursor is located on the first def line.""" document = self.code_editor.document() cursor = QTextCursor( document.findBlockByLineNumber(self.line_number_cursor - 1)) func_text = '' func_indent = '' is_first_line = True line_number = cursor.blockNumber() + 1 number_of_lines = self.code_editor.blockCount() remain_lines = number_of_lines - line_number + 1 number_of_lines_of_function = 0 for __ in range(min(remain_lines, 20)): cur_text = to_text_string(cursor.block().text()).rstrip() if is_first_line: if not is_start_of_function(cur_text): return None func_indent = get_indent(cur_text) is_first_line = False else: cur_indent = get_indent(cur_text) if cur_indent <= func_indent: return None if is_start_of_function(cur_text): return None if cur_text.strip == '': return None if cur_text[-1] == '\\': cur_text = cur_text[:-1] func_text += cur_text number_of_lines_of_function += 1 if cur_text.endswith(':'): return func_text, number_of_lines_of_function cursor.movePosition(QTextCursor.NextBlock) return None
python
def get_function_definition_from_first_line(self): """Get func def when the cursor is located on the first def line.""" document = self.code_editor.document() cursor = QTextCursor( document.findBlockByLineNumber(self.line_number_cursor - 1)) func_text = '' func_indent = '' is_first_line = True line_number = cursor.blockNumber() + 1 number_of_lines = self.code_editor.blockCount() remain_lines = number_of_lines - line_number + 1 number_of_lines_of_function = 0 for __ in range(min(remain_lines, 20)): cur_text = to_text_string(cursor.block().text()).rstrip() if is_first_line: if not is_start_of_function(cur_text): return None func_indent = get_indent(cur_text) is_first_line = False else: cur_indent = get_indent(cur_text) if cur_indent <= func_indent: return None if is_start_of_function(cur_text): return None if cur_text.strip == '': return None if cur_text[-1] == '\\': cur_text = cur_text[:-1] func_text += cur_text number_of_lines_of_function += 1 if cur_text.endswith(':'): return func_text, number_of_lines_of_function cursor.movePosition(QTextCursor.NextBlock) return None
[ "def", "get_function_definition_from_first_line", "(", "self", ")", ":", "document", "=", "self", ".", "code_editor", ".", "document", "(", ")", "cursor", "=", "QTextCursor", "(", "document", ".", "findBlockByLineNumber", "(", "self", ".", "line_number_cursor", "-", "1", ")", ")", "func_text", "=", "''", "func_indent", "=", "''", "is_first_line", "=", "True", "line_number", "=", "cursor", ".", "blockNumber", "(", ")", "+", "1", "number_of_lines", "=", "self", ".", "code_editor", ".", "blockCount", "(", ")", "remain_lines", "=", "number_of_lines", "-", "line_number", "+", "1", "number_of_lines_of_function", "=", "0", "for", "__", "in", "range", "(", "min", "(", "remain_lines", ",", "20", ")", ")", ":", "cur_text", "=", "to_text_string", "(", "cursor", ".", "block", "(", ")", ".", "text", "(", ")", ")", ".", "rstrip", "(", ")", "if", "is_first_line", ":", "if", "not", "is_start_of_function", "(", "cur_text", ")", ":", "return", "None", "func_indent", "=", "get_indent", "(", "cur_text", ")", "is_first_line", "=", "False", "else", ":", "cur_indent", "=", "get_indent", "(", "cur_text", ")", "if", "cur_indent", "<=", "func_indent", ":", "return", "None", "if", "is_start_of_function", "(", "cur_text", ")", ":", "return", "None", "if", "cur_text", ".", "strip", "==", "''", ":", "return", "None", "if", "cur_text", "[", "-", "1", "]", "==", "'\\\\'", ":", "cur_text", "=", "cur_text", "[", ":", "-", "1", "]", "func_text", "+=", "cur_text", "number_of_lines_of_function", "+=", "1", "if", "cur_text", ".", "endswith", "(", "':'", ")", ":", "return", "func_text", ",", "number_of_lines_of_function", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "NextBlock", ")", "return", "None" ]
Get func def when the cursor is located on the first def line.
[ "Get", "func", "def", "when", "the", "cursor", "is", "located", "on", "the", "first", "def", "line", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L70-L115
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.get_function_definition_from_below_last_line
def get_function_definition_from_below_last_line(self): """Get func def when the cursor is located below the last def line.""" cursor = self.code_editor.textCursor() func_text = '' is_first_line = True line_number = cursor.blockNumber() + 1 number_of_lines_of_function = 0 for idx in range(min(line_number, 20)): if cursor.block().blockNumber() == 0: return None cursor.movePosition(QTextCursor.PreviousBlock) prev_text = to_text_string(cursor.block().text()).rstrip() if is_first_line: if not prev_text.endswith(':'): return None is_first_line = False elif prev_text.endswith(':') or prev_text == '': return None if prev_text[-1] == '\\': prev_text = prev_text[:-1] func_text = prev_text + func_text number_of_lines_of_function += 1 if is_start_of_function(prev_text): return func_text, number_of_lines_of_function return None
python
def get_function_definition_from_below_last_line(self): """Get func def when the cursor is located below the last def line.""" cursor = self.code_editor.textCursor() func_text = '' is_first_line = True line_number = cursor.blockNumber() + 1 number_of_lines_of_function = 0 for idx in range(min(line_number, 20)): if cursor.block().blockNumber() == 0: return None cursor.movePosition(QTextCursor.PreviousBlock) prev_text = to_text_string(cursor.block().text()).rstrip() if is_first_line: if not prev_text.endswith(':'): return None is_first_line = False elif prev_text.endswith(':') or prev_text == '': return None if prev_text[-1] == '\\': prev_text = prev_text[:-1] func_text = prev_text + func_text number_of_lines_of_function += 1 if is_start_of_function(prev_text): return func_text, number_of_lines_of_function return None
[ "def", "get_function_definition_from_below_last_line", "(", "self", ")", ":", "cursor", "=", "self", ".", "code_editor", ".", "textCursor", "(", ")", "func_text", "=", "''", "is_first_line", "=", "True", "line_number", "=", "cursor", ".", "blockNumber", "(", ")", "+", "1", "number_of_lines_of_function", "=", "0", "for", "idx", "in", "range", "(", "min", "(", "line_number", ",", "20", ")", ")", ":", "if", "cursor", ".", "block", "(", ")", ".", "blockNumber", "(", ")", "==", "0", ":", "return", "None", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "PreviousBlock", ")", "prev_text", "=", "to_text_string", "(", "cursor", ".", "block", "(", ")", ".", "text", "(", ")", ")", ".", "rstrip", "(", ")", "if", "is_first_line", ":", "if", "not", "prev_text", ".", "endswith", "(", "':'", ")", ":", "return", "None", "is_first_line", "=", "False", "elif", "prev_text", ".", "endswith", "(", "':'", ")", "or", "prev_text", "==", "''", ":", "return", "None", "if", "prev_text", "[", "-", "1", "]", "==", "'\\\\'", ":", "prev_text", "=", "prev_text", "[", ":", "-", "1", "]", "func_text", "=", "prev_text", "+", "func_text", "number_of_lines_of_function", "+=", "1", "if", "is_start_of_function", "(", "prev_text", ")", ":", "return", "func_text", ",", "number_of_lines_of_function", "return", "None" ]
Get func def when the cursor is located below the last def line.
[ "Get", "func", "def", "when", "the", "cursor", "is", "located", "below", "the", "last", "def", "line", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L117-L148
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.get_function_body
def get_function_body(self, func_indent): """Get the function body text.""" cursor = self.code_editor.textCursor() line_number = cursor.blockNumber() + 1 number_of_lines = self.code_editor.blockCount() body_list = [] for idx in range(number_of_lines - line_number + 1): text = to_text_string(cursor.block().text()) text_indent = get_indent(text) if text.strip() == '': pass elif len(text_indent) <= len(func_indent): break body_list.append(text) cursor.movePosition(QTextCursor.NextBlock) return '\n'.join(body_list)
python
def get_function_body(self, func_indent): """Get the function body text.""" cursor = self.code_editor.textCursor() line_number = cursor.blockNumber() + 1 number_of_lines = self.code_editor.blockCount() body_list = [] for idx in range(number_of_lines - line_number + 1): text = to_text_string(cursor.block().text()) text_indent = get_indent(text) if text.strip() == '': pass elif len(text_indent) <= len(func_indent): break body_list.append(text) cursor.movePosition(QTextCursor.NextBlock) return '\n'.join(body_list)
[ "def", "get_function_body", "(", "self", ",", "func_indent", ")", ":", "cursor", "=", "self", ".", "code_editor", ".", "textCursor", "(", ")", "line_number", "=", "cursor", ".", "blockNumber", "(", ")", "+", "1", "number_of_lines", "=", "self", ".", "code_editor", ".", "blockCount", "(", ")", "body_list", "=", "[", "]", "for", "idx", "in", "range", "(", "number_of_lines", "-", "line_number", "+", "1", ")", ":", "text", "=", "to_text_string", "(", "cursor", ".", "block", "(", ")", ".", "text", "(", ")", ")", "text_indent", "=", "get_indent", "(", "text", ")", "if", "text", ".", "strip", "(", ")", "==", "''", ":", "pass", "elif", "len", "(", "text_indent", ")", "<=", "len", "(", "func_indent", ")", ":", "break", "body_list", ".", "append", "(", "text", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "NextBlock", ")", "return", "'\\n'", ".", "join", "(", "body_list", ")" ]
Get the function body text.
[ "Get", "the", "function", "body", "text", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L150-L170
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.write_docstring
def write_docstring(self): """Write docstring to editor.""" line_to_cursor = self.code_editor.get_text('sol', 'cursor') if self.is_beginning_triple_quotes(line_to_cursor): cursor = self.code_editor.textCursor() prev_pos = cursor.position() quote = line_to_cursor[-1] docstring_type = CONF.get('editor', 'docstring_type') docstring = self._generate_docstring(docstring_type, quote) if docstring: self.code_editor.insert_text(docstring) cursor = self.code_editor.textCursor() cursor.setPosition(prev_pos, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.NextBlock) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) cursor.clearSelection() self.code_editor.setTextCursor(cursor) return True return False
python
def write_docstring(self): """Write docstring to editor.""" line_to_cursor = self.code_editor.get_text('sol', 'cursor') if self.is_beginning_triple_quotes(line_to_cursor): cursor = self.code_editor.textCursor() prev_pos = cursor.position() quote = line_to_cursor[-1] docstring_type = CONF.get('editor', 'docstring_type') docstring = self._generate_docstring(docstring_type, quote) if docstring: self.code_editor.insert_text(docstring) cursor = self.code_editor.textCursor() cursor.setPosition(prev_pos, QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.NextBlock) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) cursor.clearSelection() self.code_editor.setTextCursor(cursor) return True return False
[ "def", "write_docstring", "(", "self", ")", ":", "line_to_cursor", "=", "self", ".", "code_editor", ".", "get_text", "(", "'sol'", ",", "'cursor'", ")", "if", "self", ".", "is_beginning_triple_quotes", "(", "line_to_cursor", ")", ":", "cursor", "=", "self", ".", "code_editor", ".", "textCursor", "(", ")", "prev_pos", "=", "cursor", ".", "position", "(", ")", "quote", "=", "line_to_cursor", "[", "-", "1", "]", "docstring_type", "=", "CONF", ".", "get", "(", "'editor'", ",", "'docstring_type'", ")", "docstring", "=", "self", ".", "_generate_docstring", "(", "docstring_type", ",", "quote", ")", "if", "docstring", ":", "self", ".", "code_editor", ".", "insert_text", "(", "docstring", ")", "cursor", "=", "self", ".", "code_editor", ".", "textCursor", "(", ")", "cursor", ".", "setPosition", "(", "prev_pos", ",", "QTextCursor", ".", "KeepAnchor", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "NextBlock", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "EndOfLine", ",", "QTextCursor", ".", "KeepAnchor", ")", "cursor", ".", "clearSelection", "(", ")", "self", ".", "code_editor", ".", "setTextCursor", "(", "cursor", ")", "return", "True", "return", "False" ]
Write docstring to editor.
[ "Write", "docstring", "to", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L172-L195
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.write_docstring_at_first_line_of_function
def write_docstring_at_first_line_of_function(self): """Write docstring to editor at mouse position.""" result = self.get_function_definition_from_first_line() editor = self.code_editor if result: func_text, number_of_line_func = result line_number_function = (self.line_number_cursor + number_of_line_func - 1) cursor = editor.textCursor() line_number_cursor = cursor.blockNumber() + 1 offset = line_number_function - line_number_cursor if offset > 0: for __ in range(offset): cursor.movePosition(QTextCursor.NextBlock) else: for __ in range(abs(offset)): cursor.movePosition(QTextCursor.PreviousBlock) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.MoveAnchor) editor.setTextCursor(cursor) indent = get_indent(func_text) editor.insert_text('\n{}{}"""'.format(indent, editor.indent_chars)) self.write_docstring()
python
def write_docstring_at_first_line_of_function(self): """Write docstring to editor at mouse position.""" result = self.get_function_definition_from_first_line() editor = self.code_editor if result: func_text, number_of_line_func = result line_number_function = (self.line_number_cursor + number_of_line_func - 1) cursor = editor.textCursor() line_number_cursor = cursor.blockNumber() + 1 offset = line_number_function - line_number_cursor if offset > 0: for __ in range(offset): cursor.movePosition(QTextCursor.NextBlock) else: for __ in range(abs(offset)): cursor.movePosition(QTextCursor.PreviousBlock) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.MoveAnchor) editor.setTextCursor(cursor) indent = get_indent(func_text) editor.insert_text('\n{}{}"""'.format(indent, editor.indent_chars)) self.write_docstring()
[ "def", "write_docstring_at_first_line_of_function", "(", "self", ")", ":", "result", "=", "self", ".", "get_function_definition_from_first_line", "(", ")", "editor", "=", "self", ".", "code_editor", "if", "result", ":", "func_text", ",", "number_of_line_func", "=", "result", "line_number_function", "=", "(", "self", ".", "line_number_cursor", "+", "number_of_line_func", "-", "1", ")", "cursor", "=", "editor", ".", "textCursor", "(", ")", "line_number_cursor", "=", "cursor", ".", "blockNumber", "(", ")", "+", "1", "offset", "=", "line_number_function", "-", "line_number_cursor", "if", "offset", ">", "0", ":", "for", "__", "in", "range", "(", "offset", ")", ":", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "NextBlock", ")", "else", ":", "for", "__", "in", "range", "(", "abs", "(", "offset", ")", ")", ":", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "PreviousBlock", ")", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "EndOfLine", ",", "QTextCursor", ".", "MoveAnchor", ")", "editor", ".", "setTextCursor", "(", "cursor", ")", "indent", "=", "get_indent", "(", "func_text", ")", "editor", ".", "insert_text", "(", "'\\n{}{}\"\"\"'", ".", "format", "(", "indent", ",", "editor", ".", "indent_chars", ")", ")", "self", ".", "write_docstring", "(", ")" ]
Write docstring to editor at mouse position.
[ "Write", "docstring", "to", "editor", "at", "mouse", "position", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L197-L220
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.write_docstring_for_shortcut
def write_docstring_for_shortcut(self): """Write docstring to editor by shortcut of code editor.""" # cursor placed below function definition result = self.get_function_definition_from_below_last_line() if result is not None: __, number_of_lines_of_function = result cursor = self.code_editor.textCursor() for __ in range(number_of_lines_of_function): cursor.movePosition(QTextCursor.PreviousBlock) self.code_editor.setTextCursor(cursor) cursor = self.code_editor.textCursor() self.line_number_cursor = cursor.blockNumber() + 1 self.write_docstring_at_first_line_of_function()
python
def write_docstring_for_shortcut(self): """Write docstring to editor by shortcut of code editor.""" # cursor placed below function definition result = self.get_function_definition_from_below_last_line() if result is not None: __, number_of_lines_of_function = result cursor = self.code_editor.textCursor() for __ in range(number_of_lines_of_function): cursor.movePosition(QTextCursor.PreviousBlock) self.code_editor.setTextCursor(cursor) cursor = self.code_editor.textCursor() self.line_number_cursor = cursor.blockNumber() + 1 self.write_docstring_at_first_line_of_function()
[ "def", "write_docstring_for_shortcut", "(", "self", ")", ":", "# cursor placed below function definition\r", "result", "=", "self", ".", "get_function_definition_from_below_last_line", "(", ")", "if", "result", "is", "not", "None", ":", "__", ",", "number_of_lines_of_function", "=", "result", "cursor", "=", "self", ".", "code_editor", ".", "textCursor", "(", ")", "for", "__", "in", "range", "(", "number_of_lines_of_function", ")", ":", "cursor", ".", "movePosition", "(", "QTextCursor", ".", "PreviousBlock", ")", "self", ".", "code_editor", ".", "setTextCursor", "(", "cursor", ")", "cursor", "=", "self", ".", "code_editor", ".", "textCursor", "(", ")", "self", ".", "line_number_cursor", "=", "cursor", ".", "blockNumber", "(", ")", "+", "1", "self", ".", "write_docstring_at_first_line_of_function", "(", ")" ]
Write docstring to editor by shortcut of code editor.
[ "Write", "docstring", "to", "editor", "by", "shortcut", "of", "code", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L222-L237
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension._generate_docstring
def _generate_docstring(self, doc_type, quote): """Generate docstring.""" docstring = None self.quote3 = quote * 3 if quote == '"': self.quote3_other = "'''" else: self.quote3_other = '"""' result = self.get_function_definition_from_below_last_line() if result: func_def, __ = result func_info = FunctionInfo() func_info.parse_def(func_def) if func_info.has_info: func_body = self.get_function_body(func_info.func_indent) if func_body: func_info.parse_body(func_body) if doc_type == 'Numpydoc': docstring = self._generate_numpy_doc(func_info) elif doc_type == 'Googledoc': docstring = self._generate_google_doc(func_info) return docstring
python
def _generate_docstring(self, doc_type, quote): """Generate docstring.""" docstring = None self.quote3 = quote * 3 if quote == '"': self.quote3_other = "'''" else: self.quote3_other = '"""' result = self.get_function_definition_from_below_last_line() if result: func_def, __ = result func_info = FunctionInfo() func_info.parse_def(func_def) if func_info.has_info: func_body = self.get_function_body(func_info.func_indent) if func_body: func_info.parse_body(func_body) if doc_type == 'Numpydoc': docstring = self._generate_numpy_doc(func_info) elif doc_type == 'Googledoc': docstring = self._generate_google_doc(func_info) return docstring
[ "def", "_generate_docstring", "(", "self", ",", "doc_type", ",", "quote", ")", ":", "docstring", "=", "None", "self", ".", "quote3", "=", "quote", "*", "3", "if", "quote", "==", "'\"'", ":", "self", ".", "quote3_other", "=", "\"'''\"", "else", ":", "self", ".", "quote3_other", "=", "'\"\"\"'", "result", "=", "self", ".", "get_function_definition_from_below_last_line", "(", ")", "if", "result", ":", "func_def", ",", "__", "=", "result", "func_info", "=", "FunctionInfo", "(", ")", "func_info", ".", "parse_def", "(", "func_def", ")", "if", "func_info", ".", "has_info", ":", "func_body", "=", "self", ".", "get_function_body", "(", "func_info", ".", "func_indent", ")", "if", "func_body", ":", "func_info", ".", "parse_body", "(", "func_body", ")", "if", "doc_type", "==", "'Numpydoc'", ":", "docstring", "=", "self", ".", "_generate_numpy_doc", "(", "func_info", ")", "elif", "doc_type", "==", "'Googledoc'", ":", "docstring", "=", "self", ".", "_generate_google_doc", "(", "func_info", ")", "return", "docstring" ]
Generate docstring.
[ "Generate", "docstring", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L239-L266
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension._generate_numpy_doc
def _generate_numpy_doc(self, func_info): """Generate a docstring of numpy type.""" numpy_doc = '' arg_names = func_info.arg_name_list arg_types = func_info.arg_type_list arg_values = func_info.arg_value_list if len(arg_names) > 0 and arg_names[0] == 'self': del arg_names[0] del arg_types[0] del arg_values[0] indent1 = func_info.func_indent + self.code_editor.indent_chars indent2 = func_info.func_indent + self.code_editor.indent_chars * 2 numpy_doc += '\n{}\n'.format(indent1) if len(arg_names) > 0: numpy_doc += '\n{}Parameters'.format(indent1) numpy_doc += '\n{}----------\n'.format(indent1) arg_text = '' for arg_name, arg_type, arg_value in zip(arg_names, arg_types, arg_values): arg_text += '{}{} : '.format(indent1, arg_name) if arg_type: arg_text += '{}'.format(arg_type) else: arg_text += 'TYPE' if arg_value: arg_text += ', optional' arg_text += '\n{}DESCRIPTION.'.format(indent2) if arg_value: arg_value = arg_value.replace(self.quote3, self.quote3_other) arg_text += ' The default is {}.'.format(arg_value) arg_text += '\n' numpy_doc += arg_text if func_info.raise_list: numpy_doc += '\n{}Raises'.format(indent1) numpy_doc += '\n{}------'.format(indent1) for raise_type in func_info.raise_list: numpy_doc += '\n{}{}'.format(indent1, raise_type) numpy_doc += '\n{}DESCRIPTION.'.format(indent2) numpy_doc += '\n' numpy_doc += '\n' if func_info.has_yield: header = '{0}Yields\n{0}------\n'.format(indent1) else: header = '{0}Returns\n{0}-------\n'.format(indent1) return_type_annotated = func_info.return_type_annotated if return_type_annotated: return_section = '{}{}{}'.format(header, indent1, return_type_annotated) return_section += '\n{}DESCRIPTION.'.format(indent2) else: return_element_type = indent1 + '{return_type}\n' + indent2 + \ 'DESCRIPTION.' placeholder = return_element_type.format(return_type='TYPE') return_element_name = indent1 + '{return_name} : ' + \ placeholder.lstrip() try: return_section = self._generate_docstring_return_section( func_info.return_value_in_body, header, return_element_name, return_element_type, placeholder, indent1) except (ValueError, IndexError): return_section = '{}{}None.'.format(header, indent1) numpy_doc += return_section numpy_doc += '\n\n{}{}'.format(indent1, self.quote3) return numpy_doc
python
def _generate_numpy_doc(self, func_info): """Generate a docstring of numpy type.""" numpy_doc = '' arg_names = func_info.arg_name_list arg_types = func_info.arg_type_list arg_values = func_info.arg_value_list if len(arg_names) > 0 and arg_names[0] == 'self': del arg_names[0] del arg_types[0] del arg_values[0] indent1 = func_info.func_indent + self.code_editor.indent_chars indent2 = func_info.func_indent + self.code_editor.indent_chars * 2 numpy_doc += '\n{}\n'.format(indent1) if len(arg_names) > 0: numpy_doc += '\n{}Parameters'.format(indent1) numpy_doc += '\n{}----------\n'.format(indent1) arg_text = '' for arg_name, arg_type, arg_value in zip(arg_names, arg_types, arg_values): arg_text += '{}{} : '.format(indent1, arg_name) if arg_type: arg_text += '{}'.format(arg_type) else: arg_text += 'TYPE' if arg_value: arg_text += ', optional' arg_text += '\n{}DESCRIPTION.'.format(indent2) if arg_value: arg_value = arg_value.replace(self.quote3, self.quote3_other) arg_text += ' The default is {}.'.format(arg_value) arg_text += '\n' numpy_doc += arg_text if func_info.raise_list: numpy_doc += '\n{}Raises'.format(indent1) numpy_doc += '\n{}------'.format(indent1) for raise_type in func_info.raise_list: numpy_doc += '\n{}{}'.format(indent1, raise_type) numpy_doc += '\n{}DESCRIPTION.'.format(indent2) numpy_doc += '\n' numpy_doc += '\n' if func_info.has_yield: header = '{0}Yields\n{0}------\n'.format(indent1) else: header = '{0}Returns\n{0}-------\n'.format(indent1) return_type_annotated = func_info.return_type_annotated if return_type_annotated: return_section = '{}{}{}'.format(header, indent1, return_type_annotated) return_section += '\n{}DESCRIPTION.'.format(indent2) else: return_element_type = indent1 + '{return_type}\n' + indent2 + \ 'DESCRIPTION.' placeholder = return_element_type.format(return_type='TYPE') return_element_name = indent1 + '{return_name} : ' + \ placeholder.lstrip() try: return_section = self._generate_docstring_return_section( func_info.return_value_in_body, header, return_element_name, return_element_type, placeholder, indent1) except (ValueError, IndexError): return_section = '{}{}None.'.format(header, indent1) numpy_doc += return_section numpy_doc += '\n\n{}{}'.format(indent1, self.quote3) return numpy_doc
[ "def", "_generate_numpy_doc", "(", "self", ",", "func_info", ")", ":", "numpy_doc", "=", "''", "arg_names", "=", "func_info", ".", "arg_name_list", "arg_types", "=", "func_info", ".", "arg_type_list", "arg_values", "=", "func_info", ".", "arg_value_list", "if", "len", "(", "arg_names", ")", ">", "0", "and", "arg_names", "[", "0", "]", "==", "'self'", ":", "del", "arg_names", "[", "0", "]", "del", "arg_types", "[", "0", "]", "del", "arg_values", "[", "0", "]", "indent1", "=", "func_info", ".", "func_indent", "+", "self", ".", "code_editor", ".", "indent_chars", "indent2", "=", "func_info", ".", "func_indent", "+", "self", ".", "code_editor", ".", "indent_chars", "*", "2", "numpy_doc", "+=", "'\\n{}\\n'", ".", "format", "(", "indent1", ")", "if", "len", "(", "arg_names", ")", ">", "0", ":", "numpy_doc", "+=", "'\\n{}Parameters'", ".", "format", "(", "indent1", ")", "numpy_doc", "+=", "'\\n{}----------\\n'", ".", "format", "(", "indent1", ")", "arg_text", "=", "''", "for", "arg_name", ",", "arg_type", ",", "arg_value", "in", "zip", "(", "arg_names", ",", "arg_types", ",", "arg_values", ")", ":", "arg_text", "+=", "'{}{} : '", ".", "format", "(", "indent1", ",", "arg_name", ")", "if", "arg_type", ":", "arg_text", "+=", "'{}'", ".", "format", "(", "arg_type", ")", "else", ":", "arg_text", "+=", "'TYPE'", "if", "arg_value", ":", "arg_text", "+=", "', optional'", "arg_text", "+=", "'\\n{}DESCRIPTION.'", ".", "format", "(", "indent2", ")", "if", "arg_value", ":", "arg_value", "=", "arg_value", ".", "replace", "(", "self", ".", "quote3", ",", "self", ".", "quote3_other", ")", "arg_text", "+=", "' The default is {}.'", ".", "format", "(", "arg_value", ")", "arg_text", "+=", "'\\n'", "numpy_doc", "+=", "arg_text", "if", "func_info", ".", "raise_list", ":", "numpy_doc", "+=", "'\\n{}Raises'", ".", "format", "(", "indent1", ")", "numpy_doc", "+=", "'\\n{}------'", ".", "format", "(", "indent1", ")", "for", "raise_type", "in", "func_info", ".", "raise_list", ":", "numpy_doc", "+=", "'\\n{}{}'", ".", "format", "(", "indent1", ",", "raise_type", ")", "numpy_doc", "+=", "'\\n{}DESCRIPTION.'", ".", "format", "(", "indent2", ")", "numpy_doc", "+=", "'\\n'", "numpy_doc", "+=", "'\\n'", "if", "func_info", ".", "has_yield", ":", "header", "=", "'{0}Yields\\n{0}------\\n'", ".", "format", "(", "indent1", ")", "else", ":", "header", "=", "'{0}Returns\\n{0}-------\\n'", ".", "format", "(", "indent1", ")", "return_type_annotated", "=", "func_info", ".", "return_type_annotated", "if", "return_type_annotated", ":", "return_section", "=", "'{}{}{}'", ".", "format", "(", "header", ",", "indent1", ",", "return_type_annotated", ")", "return_section", "+=", "'\\n{}DESCRIPTION.'", ".", "format", "(", "indent2", ")", "else", ":", "return_element_type", "=", "indent1", "+", "'{return_type}\\n'", "+", "indent2", "+", "'DESCRIPTION.'", "placeholder", "=", "return_element_type", ".", "format", "(", "return_type", "=", "'TYPE'", ")", "return_element_name", "=", "indent1", "+", "'{return_name} : '", "+", "placeholder", ".", "lstrip", "(", ")", "try", ":", "return_section", "=", "self", ".", "_generate_docstring_return_section", "(", "func_info", ".", "return_value_in_body", ",", "header", ",", "return_element_name", ",", "return_element_type", ",", "placeholder", ",", "indent1", ")", "except", "(", "ValueError", ",", "IndexError", ")", ":", "return_section", "=", "'{}{}None.'", ".", "format", "(", "header", ",", "indent1", ")", "numpy_doc", "+=", "return_section", "numpy_doc", "+=", "'\\n\\n{}{}'", ".", "format", "(", "indent1", ",", "self", ".", "quote3", ")", "return", "numpy_doc" ]
Generate a docstring of numpy type.
[ "Generate", "a", "docstring", "of", "numpy", "type", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L268-L349
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.find_top_level_bracket_locations
def find_top_level_bracket_locations(string_toparse): """Get the locations of top-level brackets in a string.""" bracket_stack = [] replace_args_list = [] bracket_type = None literal_type = '' brackets = {'(': ')', '[': ']', '{': '}'} for idx, character in enumerate(string_toparse): if (not bracket_stack and character in brackets.keys() or character == bracket_type): bracket_stack.append(idx) bracket_type = character elif bracket_type and character == brackets[bracket_type]: begin_idx = bracket_stack.pop() if not bracket_stack: if not literal_type: if bracket_type == '(': literal_type = '(None)' elif bracket_type == '[': literal_type = '[list]' elif bracket_type == '{': if idx - begin_idx <= 1: literal_type = '{dict}' else: literal_type = '{set}' replace_args_list.append( (string_toparse[begin_idx:idx + 1], literal_type, 1)) bracket_type = None literal_type = '' elif len(bracket_stack) == 1: if bracket_type == '(' and character == ',': literal_type = '(tuple)' elif bracket_type == '{' and character == ':': literal_type = '{dict}' elif bracket_type == '(' and character == ':': literal_type = '[slice]' if bracket_stack: raise IndexError('Bracket mismatch') for replace_args in replace_args_list: string_toparse = string_toparse.replace(*replace_args) return string_toparse
python
def find_top_level_bracket_locations(string_toparse): """Get the locations of top-level brackets in a string.""" bracket_stack = [] replace_args_list = [] bracket_type = None literal_type = '' brackets = {'(': ')', '[': ']', '{': '}'} for idx, character in enumerate(string_toparse): if (not bracket_stack and character in brackets.keys() or character == bracket_type): bracket_stack.append(idx) bracket_type = character elif bracket_type and character == brackets[bracket_type]: begin_idx = bracket_stack.pop() if not bracket_stack: if not literal_type: if bracket_type == '(': literal_type = '(None)' elif bracket_type == '[': literal_type = '[list]' elif bracket_type == '{': if idx - begin_idx <= 1: literal_type = '{dict}' else: literal_type = '{set}' replace_args_list.append( (string_toparse[begin_idx:idx + 1], literal_type, 1)) bracket_type = None literal_type = '' elif len(bracket_stack) == 1: if bracket_type == '(' and character == ',': literal_type = '(tuple)' elif bracket_type == '{' and character == ':': literal_type = '{dict}' elif bracket_type == '(' and character == ':': literal_type = '[slice]' if bracket_stack: raise IndexError('Bracket mismatch') for replace_args in replace_args_list: string_toparse = string_toparse.replace(*replace_args) return string_toparse
[ "def", "find_top_level_bracket_locations", "(", "string_toparse", ")", ":", "bracket_stack", "=", "[", "]", "replace_args_list", "=", "[", "]", "bracket_type", "=", "None", "literal_type", "=", "''", "brackets", "=", "{", "'('", ":", "')'", ",", "'['", ":", "']'", ",", "'{'", ":", "'}'", "}", "for", "idx", ",", "character", "in", "enumerate", "(", "string_toparse", ")", ":", "if", "(", "not", "bracket_stack", "and", "character", "in", "brackets", ".", "keys", "(", ")", "or", "character", "==", "bracket_type", ")", ":", "bracket_stack", ".", "append", "(", "idx", ")", "bracket_type", "=", "character", "elif", "bracket_type", "and", "character", "==", "brackets", "[", "bracket_type", "]", ":", "begin_idx", "=", "bracket_stack", ".", "pop", "(", ")", "if", "not", "bracket_stack", ":", "if", "not", "literal_type", ":", "if", "bracket_type", "==", "'('", ":", "literal_type", "=", "'(None)'", "elif", "bracket_type", "==", "'['", ":", "literal_type", "=", "'[list]'", "elif", "bracket_type", "==", "'{'", ":", "if", "idx", "-", "begin_idx", "<=", "1", ":", "literal_type", "=", "'{dict}'", "else", ":", "literal_type", "=", "'{set}'", "replace_args_list", ".", "append", "(", "(", "string_toparse", "[", "begin_idx", ":", "idx", "+", "1", "]", ",", "literal_type", ",", "1", ")", ")", "bracket_type", "=", "None", "literal_type", "=", "''", "elif", "len", "(", "bracket_stack", ")", "==", "1", ":", "if", "bracket_type", "==", "'('", "and", "character", "==", "','", ":", "literal_type", "=", "'(tuple)'", "elif", "bracket_type", "==", "'{'", "and", "character", "==", "':'", ":", "literal_type", "=", "'{dict}'", "elif", "bracket_type", "==", "'('", "and", "character", "==", "':'", ":", "literal_type", "=", "'[slice]'", "if", "bracket_stack", ":", "raise", "IndexError", "(", "'Bracket mismatch'", ")", "for", "replace_args", "in", "replace_args_list", ":", "string_toparse", "=", "string_toparse", ".", "replace", "(", "*", "replace_args", ")", "return", "string_toparse" ]
Get the locations of top-level brackets in a string.
[ "Get", "the", "locations", "of", "top", "-", "level", "brackets", "in", "a", "string", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L434-L476
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension.parse_return_elements
def parse_return_elements(return_vals_group, return_element_name, return_element_type, placeholder): """Return the appropriate text for a group of return elements.""" all_eq = (return_vals_group.count(return_vals_group[0]) == len(return_vals_group)) if all([{'[list]', '(tuple)', '{dict}', '{set}'}.issuperset( return_vals_group)]) and all_eq: return return_element_type.format( return_type=return_vals_group[0][1:-1]) # Output placeholder if special Python chars present in name py_chars = {' ', '+', '-', '*', '/', '%', '@', '<', '>', '&', '|', '^', '~', '=', ',', ':', ';', '#', '(', '[', '{', '}', ']', ')', } if any([any([py_char in return_val for py_char in py_chars]) for return_val in return_vals_group]): return placeholder # Output str type and no name if only string literals if all(['"' in return_val or '\'' in return_val for return_val in return_vals_group]): return return_element_type.format(return_type='str') # Output bool type and no name if only bool literals if {'True', 'False'}.issuperset(return_vals_group): return return_element_type.format(return_type='bool') # Output numeric types and no name if only numeric literals try: [float(return_val) for return_val in return_vals_group] num_not_int = 0 for return_val in return_vals_group: try: int(return_val) except ValueError: # If not an integer (EAFP) num_not_int = num_not_int + 1 if num_not_int == 0: return return_element_type.format(return_type='int') elif num_not_int == len(return_vals_group): return return_element_type.format(return_type='float') else: return return_element_type.format(return_type='numeric') except ValueError: # Not a numeric if float conversion didn't work pass # If names are not equal, don't contain "." or are a builtin if ({'self', 'cls', 'None'}.isdisjoint(return_vals_group) and all_eq and all(['.' not in return_val for return_val in return_vals_group])): return return_element_name.format(return_name=return_vals_group[0]) return placeholder
python
def parse_return_elements(return_vals_group, return_element_name, return_element_type, placeholder): """Return the appropriate text for a group of return elements.""" all_eq = (return_vals_group.count(return_vals_group[0]) == len(return_vals_group)) if all([{'[list]', '(tuple)', '{dict}', '{set}'}.issuperset( return_vals_group)]) and all_eq: return return_element_type.format( return_type=return_vals_group[0][1:-1]) # Output placeholder if special Python chars present in name py_chars = {' ', '+', '-', '*', '/', '%', '@', '<', '>', '&', '|', '^', '~', '=', ',', ':', ';', '#', '(', '[', '{', '}', ']', ')', } if any([any([py_char in return_val for py_char in py_chars]) for return_val in return_vals_group]): return placeholder # Output str type and no name if only string literals if all(['"' in return_val or '\'' in return_val for return_val in return_vals_group]): return return_element_type.format(return_type='str') # Output bool type and no name if only bool literals if {'True', 'False'}.issuperset(return_vals_group): return return_element_type.format(return_type='bool') # Output numeric types and no name if only numeric literals try: [float(return_val) for return_val in return_vals_group] num_not_int = 0 for return_val in return_vals_group: try: int(return_val) except ValueError: # If not an integer (EAFP) num_not_int = num_not_int + 1 if num_not_int == 0: return return_element_type.format(return_type='int') elif num_not_int == len(return_vals_group): return return_element_type.format(return_type='float') else: return return_element_type.format(return_type='numeric') except ValueError: # Not a numeric if float conversion didn't work pass # If names are not equal, don't contain "." or are a builtin if ({'self', 'cls', 'None'}.isdisjoint(return_vals_group) and all_eq and all(['.' not in return_val for return_val in return_vals_group])): return return_element_name.format(return_name=return_vals_group[0]) return placeholder
[ "def", "parse_return_elements", "(", "return_vals_group", ",", "return_element_name", ",", "return_element_type", ",", "placeholder", ")", ":", "all_eq", "=", "(", "return_vals_group", ".", "count", "(", "return_vals_group", "[", "0", "]", ")", "==", "len", "(", "return_vals_group", ")", ")", "if", "all", "(", "[", "{", "'[list]'", ",", "'(tuple)'", ",", "'{dict}'", ",", "'{set}'", "}", ".", "issuperset", "(", "return_vals_group", ")", "]", ")", "and", "all_eq", ":", "return", "return_element_type", ".", "format", "(", "return_type", "=", "return_vals_group", "[", "0", "]", "[", "1", ":", "-", "1", "]", ")", "# Output placeholder if special Python chars present in name\r", "py_chars", "=", "{", "' '", ",", "'+'", ",", "'-'", ",", "'*'", ",", "'/'", ",", "'%'", ",", "'@'", ",", "'<'", ",", "'>'", ",", "'&'", ",", "'|'", ",", "'^'", ",", "'~'", ",", "'='", ",", "','", ",", "':'", ",", "';'", ",", "'#'", ",", "'('", ",", "'['", ",", "'{'", ",", "'}'", ",", "']'", ",", "')'", ",", "}", "if", "any", "(", "[", "any", "(", "[", "py_char", "in", "return_val", "for", "py_char", "in", "py_chars", "]", ")", "for", "return_val", "in", "return_vals_group", "]", ")", ":", "return", "placeholder", "# Output str type and no name if only string literals\r", "if", "all", "(", "[", "'\"'", "in", "return_val", "or", "'\\''", "in", "return_val", "for", "return_val", "in", "return_vals_group", "]", ")", ":", "return", "return_element_type", ".", "format", "(", "return_type", "=", "'str'", ")", "# Output bool type and no name if only bool literals\r", "if", "{", "'True'", ",", "'False'", "}", ".", "issuperset", "(", "return_vals_group", ")", ":", "return", "return_element_type", ".", "format", "(", "return_type", "=", "'bool'", ")", "# Output numeric types and no name if only numeric literals\r", "try", ":", "[", "float", "(", "return_val", ")", "for", "return_val", "in", "return_vals_group", "]", "num_not_int", "=", "0", "for", "return_val", "in", "return_vals_group", ":", "try", ":", "int", "(", "return_val", ")", "except", "ValueError", ":", "# If not an integer (EAFP)\r", "num_not_int", "=", "num_not_int", "+", "1", "if", "num_not_int", "==", "0", ":", "return", "return_element_type", ".", "format", "(", "return_type", "=", "'int'", ")", "elif", "num_not_int", "==", "len", "(", "return_vals_group", ")", ":", "return", "return_element_type", ".", "format", "(", "return_type", "=", "'float'", ")", "else", ":", "return", "return_element_type", ".", "format", "(", "return_type", "=", "'numeric'", ")", "except", "ValueError", ":", "# Not a numeric if float conversion didn't work\r", "pass", "# If names are not equal, don't contain \".\" or are a builtin\r", "if", "(", "{", "'self'", ",", "'cls'", ",", "'None'", "}", ".", "isdisjoint", "(", "return_vals_group", ")", "and", "all_eq", "and", "all", "(", "[", "'.'", "not", "in", "return_val", "for", "return_val", "in", "return_vals_group", "]", ")", ")", ":", "return", "return_element_name", ".", "format", "(", "return_name", "=", "return_vals_group", "[", "0", "]", ")", "return", "placeholder" ]
Return the appropriate text for a group of return elements.
[ "Return", "the", "appropriate", "text", "for", "a", "group", "of", "return", "elements", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L479-L524
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
DocstringWriterExtension._generate_docstring_return_section
def _generate_docstring_return_section(self, return_vals, header, return_element_name, return_element_type, placeholder, indent): """Generate the Returns section of a function/method docstring.""" # If all return values are None, return none non_none_vals = [return_val for return_val in return_vals if return_val and return_val != 'None'] if not non_none_vals: return header + indent + 'None.' # Get only values with matching brackets that can be cleaned up non_none_vals = [return_val.strip(' ()\t\n').rstrip(',') for return_val in non_none_vals] non_none_vals = [re.sub('([\"\'])(?:(?=(\\\\?))\\2.)*?\\1', '"string"', return_val) for return_val in non_none_vals] unambiguous_vals = [] for return_val in non_none_vals: try: cleaned_val = self.find_top_level_bracket_locations(return_val) except IndexError: continue unambiguous_vals.append(cleaned_val) if not unambiguous_vals: return header + placeholder # If remaining are a mix of tuples and not, return single placeholder single_vals, tuple_vals = [], [] for return_val in unambiguous_vals: (tuple_vals.append(return_val) if ',' in return_val else single_vals.append(return_val)) if single_vals and tuple_vals: return header + placeholder # If return values are tuples of different length, return a placeholder if tuple_vals: num_elements = [return_val.count(',') + 1 for return_val in tuple_vals] if num_elements.count(num_elements[0]) != len(num_elements): return header + placeholder num_elements = num_elements[0] else: num_elements = 1 # If all have the same len but some ambiguous return that placeholders if len(unambiguous_vals) != len(non_none_vals): return header + '\n'.join( [placeholder for __ in range(num_elements)]) # Handle tuple (or single) values position by position return_vals_grouped = zip(*[ [return_element.strip() for return_element in return_val.split(',')] for return_val in unambiguous_vals]) return_elements_out = [] for return_vals_group in return_vals_grouped: return_elements_out.append( self.parse_return_elements(return_vals_group, return_element_name, return_element_type, placeholder)) return header + '\n'.join(return_elements_out)
python
def _generate_docstring_return_section(self, return_vals, header, return_element_name, return_element_type, placeholder, indent): """Generate the Returns section of a function/method docstring.""" # If all return values are None, return none non_none_vals = [return_val for return_val in return_vals if return_val and return_val != 'None'] if not non_none_vals: return header + indent + 'None.' # Get only values with matching brackets that can be cleaned up non_none_vals = [return_val.strip(' ()\t\n').rstrip(',') for return_val in non_none_vals] non_none_vals = [re.sub('([\"\'])(?:(?=(\\\\?))\\2.)*?\\1', '"string"', return_val) for return_val in non_none_vals] unambiguous_vals = [] for return_val in non_none_vals: try: cleaned_val = self.find_top_level_bracket_locations(return_val) except IndexError: continue unambiguous_vals.append(cleaned_val) if not unambiguous_vals: return header + placeholder # If remaining are a mix of tuples and not, return single placeholder single_vals, tuple_vals = [], [] for return_val in unambiguous_vals: (tuple_vals.append(return_val) if ',' in return_val else single_vals.append(return_val)) if single_vals and tuple_vals: return header + placeholder # If return values are tuples of different length, return a placeholder if tuple_vals: num_elements = [return_val.count(',') + 1 for return_val in tuple_vals] if num_elements.count(num_elements[0]) != len(num_elements): return header + placeholder num_elements = num_elements[0] else: num_elements = 1 # If all have the same len but some ambiguous return that placeholders if len(unambiguous_vals) != len(non_none_vals): return header + '\n'.join( [placeholder for __ in range(num_elements)]) # Handle tuple (or single) values position by position return_vals_grouped = zip(*[ [return_element.strip() for return_element in return_val.split(',')] for return_val in unambiguous_vals]) return_elements_out = [] for return_vals_group in return_vals_grouped: return_elements_out.append( self.parse_return_elements(return_vals_group, return_element_name, return_element_type, placeholder)) return header + '\n'.join(return_elements_out)
[ "def", "_generate_docstring_return_section", "(", "self", ",", "return_vals", ",", "header", ",", "return_element_name", ",", "return_element_type", ",", "placeholder", ",", "indent", ")", ":", "# If all return values are None, return none\r", "non_none_vals", "=", "[", "return_val", "for", "return_val", "in", "return_vals", "if", "return_val", "and", "return_val", "!=", "'None'", "]", "if", "not", "non_none_vals", ":", "return", "header", "+", "indent", "+", "'None.'", "# Get only values with matching brackets that can be cleaned up\r", "non_none_vals", "=", "[", "return_val", ".", "strip", "(", "' ()\\t\\n'", ")", ".", "rstrip", "(", "','", ")", "for", "return_val", "in", "non_none_vals", "]", "non_none_vals", "=", "[", "re", ".", "sub", "(", "'([\\\"\\'])(?:(?=(\\\\\\\\?))\\\\2.)*?\\\\1'", ",", "'\"string\"'", ",", "return_val", ")", "for", "return_val", "in", "non_none_vals", "]", "unambiguous_vals", "=", "[", "]", "for", "return_val", "in", "non_none_vals", ":", "try", ":", "cleaned_val", "=", "self", ".", "find_top_level_bracket_locations", "(", "return_val", ")", "except", "IndexError", ":", "continue", "unambiguous_vals", ".", "append", "(", "cleaned_val", ")", "if", "not", "unambiguous_vals", ":", "return", "header", "+", "placeholder", "# If remaining are a mix of tuples and not, return single placeholder\r", "single_vals", ",", "tuple_vals", "=", "[", "]", ",", "[", "]", "for", "return_val", "in", "unambiguous_vals", ":", "(", "tuple_vals", ".", "append", "(", "return_val", ")", "if", "','", "in", "return_val", "else", "single_vals", ".", "append", "(", "return_val", ")", ")", "if", "single_vals", "and", "tuple_vals", ":", "return", "header", "+", "placeholder", "# If return values are tuples of different length, return a placeholder\r", "if", "tuple_vals", ":", "num_elements", "=", "[", "return_val", ".", "count", "(", "','", ")", "+", "1", "for", "return_val", "in", "tuple_vals", "]", "if", "num_elements", ".", "count", "(", "num_elements", "[", "0", "]", ")", "!=", "len", "(", "num_elements", ")", ":", "return", "header", "+", "placeholder", "num_elements", "=", "num_elements", "[", "0", "]", "else", ":", "num_elements", "=", "1", "# If all have the same len but some ambiguous return that placeholders\r", "if", "len", "(", "unambiguous_vals", ")", "!=", "len", "(", "non_none_vals", ")", ":", "return", "header", "+", "'\\n'", ".", "join", "(", "[", "placeholder", "for", "__", "in", "range", "(", "num_elements", ")", "]", ")", "# Handle tuple (or single) values position by position\r", "return_vals_grouped", "=", "zip", "(", "*", "[", "[", "return_element", ".", "strip", "(", ")", "for", "return_element", "in", "return_val", ".", "split", "(", "','", ")", "]", "for", "return_val", "in", "unambiguous_vals", "]", ")", "return_elements_out", "=", "[", "]", "for", "return_vals_group", "in", "return_vals_grouped", ":", "return_elements_out", ".", "append", "(", "self", ".", "parse_return_elements", "(", "return_vals_group", ",", "return_element_name", ",", "return_element_type", ",", "placeholder", ")", ")", "return", "header", "+", "'\\n'", ".", "join", "(", "return_elements_out", ")" ]
Generate the Returns section of a function/method docstring.
[ "Generate", "the", "Returns", "section", "of", "a", "function", "/", "method", "docstring", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L526-L589
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.is_char_in_pairs
def is_char_in_pairs(pos_char, pairs): """Return True if the charactor is in pairs of brackets or quotes.""" for pos_left, pos_right in pairs.items(): if pos_left < pos_char < pos_right: return True return False
python
def is_char_in_pairs(pos_char, pairs): """Return True if the charactor is in pairs of brackets or quotes.""" for pos_left, pos_right in pairs.items(): if pos_left < pos_char < pos_right: return True return False
[ "def", "is_char_in_pairs", "(", "pos_char", ",", "pairs", ")", ":", "for", "pos_left", ",", "pos_right", "in", "pairs", ".", "items", "(", ")", ":", "if", "pos_left", "<", "pos_char", "<", "pos_right", ":", "return", "True", "return", "False" ]
Return True if the charactor is in pairs of brackets or quotes.
[ "Return", "True", "if", "the", "charactor", "is", "in", "pairs", "of", "brackets", "or", "quotes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L610-L616
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo._find_quote_position
def _find_quote_position(text): """Return the start and end position of pairs of quotes.""" pos = {} is_found_left_quote = False for idx, character in enumerate(text): if is_found_left_quote is False: if character == "'" or character == '"': is_found_left_quote = True quote = character left_pos = idx else: if character == quote and text[idx - 1] != '\\': pos[left_pos] = idx is_found_left_quote = False if is_found_left_quote: raise IndexError("No matching close quote at: " + str(left_pos)) return pos
python
def _find_quote_position(text): """Return the start and end position of pairs of quotes.""" pos = {} is_found_left_quote = False for idx, character in enumerate(text): if is_found_left_quote is False: if character == "'" or character == '"': is_found_left_quote = True quote = character left_pos = idx else: if character == quote and text[idx - 1] != '\\': pos[left_pos] = idx is_found_left_quote = False if is_found_left_quote: raise IndexError("No matching close quote at: " + str(left_pos)) return pos
[ "def", "_find_quote_position", "(", "text", ")", ":", "pos", "=", "{", "}", "is_found_left_quote", "=", "False", "for", "idx", ",", "character", "in", "enumerate", "(", "text", ")", ":", "if", "is_found_left_quote", "is", "False", ":", "if", "character", "==", "\"'\"", "or", "character", "==", "'\"'", ":", "is_found_left_quote", "=", "True", "quote", "=", "character", "left_pos", "=", "idx", "else", ":", "if", "character", "==", "quote", "and", "text", "[", "idx", "-", "1", "]", "!=", "'\\\\'", ":", "pos", "[", "left_pos", "]", "=", "idx", "is_found_left_quote", "=", "False", "if", "is_found_left_quote", ":", "raise", "IndexError", "(", "\"No matching close quote at: \"", "+", "str", "(", "left_pos", ")", ")", "return", "pos" ]
Return the start and end position of pairs of quotes.
[ "Return", "the", "start", "and", "end", "position", "of", "pairs", "of", "quotes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L619-L638
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo._find_bracket_position
def _find_bracket_position(self, text, bracket_left, bracket_right, pos_quote): """Return the start and end position of pairs of brackets. https://stackoverflow.com/questions/29991917/ indices-of-matching-parentheses-in-python """ pos = {} pstack = [] for idx, character in enumerate(text): if character == bracket_left and \ not self.is_char_in_pairs(idx, pos_quote): pstack.append(idx) elif character == bracket_right and \ not self.is_char_in_pairs(idx, pos_quote): if len(pstack) == 0: raise IndexError( "No matching closing parens at: " + str(idx)) pos[pstack.pop()] = idx if len(pstack) > 0: raise IndexError( "No matching opening parens at: " + str(pstack.pop())) return pos
python
def _find_bracket_position(self, text, bracket_left, bracket_right, pos_quote): """Return the start and end position of pairs of brackets. https://stackoverflow.com/questions/29991917/ indices-of-matching-parentheses-in-python """ pos = {} pstack = [] for idx, character in enumerate(text): if character == bracket_left and \ not self.is_char_in_pairs(idx, pos_quote): pstack.append(idx) elif character == bracket_right and \ not self.is_char_in_pairs(idx, pos_quote): if len(pstack) == 0: raise IndexError( "No matching closing parens at: " + str(idx)) pos[pstack.pop()] = idx if len(pstack) > 0: raise IndexError( "No matching opening parens at: " + str(pstack.pop())) return pos
[ "def", "_find_bracket_position", "(", "self", ",", "text", ",", "bracket_left", ",", "bracket_right", ",", "pos_quote", ")", ":", "pos", "=", "{", "}", "pstack", "=", "[", "]", "for", "idx", ",", "character", "in", "enumerate", "(", "text", ")", ":", "if", "character", "==", "bracket_left", "and", "not", "self", ".", "is_char_in_pairs", "(", "idx", ",", "pos_quote", ")", ":", "pstack", ".", "append", "(", "idx", ")", "elif", "character", "==", "bracket_right", "and", "not", "self", ".", "is_char_in_pairs", "(", "idx", ",", "pos_quote", ")", ":", "if", "len", "(", "pstack", ")", "==", "0", ":", "raise", "IndexError", "(", "\"No matching closing parens at: \"", "+", "str", "(", "idx", ")", ")", "pos", "[", "pstack", ".", "pop", "(", ")", "]", "=", "idx", "if", "len", "(", "pstack", ")", ">", "0", ":", "raise", "IndexError", "(", "\"No matching opening parens at: \"", "+", "str", "(", "pstack", ".", "pop", "(", ")", ")", ")", "return", "pos" ]
Return the start and end position of pairs of brackets. https://stackoverflow.com/questions/29991917/ indices-of-matching-parentheses-in-python
[ "Return", "the", "start", "and", "end", "position", "of", "pairs", "of", "brackets", ".", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "29991917", "/", "indices", "-", "of", "-", "matching", "-", "parentheses", "-", "in", "-", "python" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L640-L665
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.split_arg_to_name_type_value
def split_arg_to_name_type_value(self, args_list): """Split argument text to name, type, value.""" for arg in args_list: arg_type = None arg_value = None has_type = False has_value = False pos_colon = arg.find(':') pos_equal = arg.find('=') if pos_equal > -1: has_value = True if pos_colon > -1: if not has_value: has_type = True elif pos_equal > pos_colon: # exception for def foo(arg1=":") has_type = True if has_value and has_type: arg_name = arg[0:pos_colon].strip() arg_type = arg[pos_colon + 1:pos_equal].strip() arg_value = arg[pos_equal + 1:].strip() elif not has_value and has_type: arg_name = arg[0:pos_colon].strip() arg_type = arg[pos_colon + 1:].strip() elif has_value and not has_type: arg_name = arg[0:pos_equal].strip() arg_value = arg[pos_equal + 1:].strip() else: arg_name = arg.strip() self.arg_name_list.append(arg_name) self.arg_type_list.append(arg_type) self.arg_value_list.append(arg_value)
python
def split_arg_to_name_type_value(self, args_list): """Split argument text to name, type, value.""" for arg in args_list: arg_type = None arg_value = None has_type = False has_value = False pos_colon = arg.find(':') pos_equal = arg.find('=') if pos_equal > -1: has_value = True if pos_colon > -1: if not has_value: has_type = True elif pos_equal > pos_colon: # exception for def foo(arg1=":") has_type = True if has_value and has_type: arg_name = arg[0:pos_colon].strip() arg_type = arg[pos_colon + 1:pos_equal].strip() arg_value = arg[pos_equal + 1:].strip() elif not has_value and has_type: arg_name = arg[0:pos_colon].strip() arg_type = arg[pos_colon + 1:].strip() elif has_value and not has_type: arg_name = arg[0:pos_equal].strip() arg_value = arg[pos_equal + 1:].strip() else: arg_name = arg.strip() self.arg_name_list.append(arg_name) self.arg_type_list.append(arg_type) self.arg_value_list.append(arg_value)
[ "def", "split_arg_to_name_type_value", "(", "self", ",", "args_list", ")", ":", "for", "arg", "in", "args_list", ":", "arg_type", "=", "None", "arg_value", "=", "None", "has_type", "=", "False", "has_value", "=", "False", "pos_colon", "=", "arg", ".", "find", "(", "':'", ")", "pos_equal", "=", "arg", ".", "find", "(", "'='", ")", "if", "pos_equal", ">", "-", "1", ":", "has_value", "=", "True", "if", "pos_colon", ">", "-", "1", ":", "if", "not", "has_value", ":", "has_type", "=", "True", "elif", "pos_equal", ">", "pos_colon", ":", "# exception for def foo(arg1=\":\")\r", "has_type", "=", "True", "if", "has_value", "and", "has_type", ":", "arg_name", "=", "arg", "[", "0", ":", "pos_colon", "]", ".", "strip", "(", ")", "arg_type", "=", "arg", "[", "pos_colon", "+", "1", ":", "pos_equal", "]", ".", "strip", "(", ")", "arg_value", "=", "arg", "[", "pos_equal", "+", "1", ":", "]", ".", "strip", "(", ")", "elif", "not", "has_value", "and", "has_type", ":", "arg_name", "=", "arg", "[", "0", ":", "pos_colon", "]", ".", "strip", "(", ")", "arg_type", "=", "arg", "[", "pos_colon", "+", "1", ":", "]", ".", "strip", "(", ")", "elif", "has_value", "and", "not", "has_type", ":", "arg_name", "=", "arg", "[", "0", ":", "pos_equal", "]", ".", "strip", "(", ")", "arg_value", "=", "arg", "[", "pos_equal", "+", "1", ":", "]", ".", "strip", "(", ")", "else", ":", "arg_name", "=", "arg", ".", "strip", "(", ")", "self", ".", "arg_name_list", ".", "append", "(", "arg_name", ")", "self", ".", "arg_type_list", ".", "append", "(", "arg_type", ")", "self", ".", "arg_value_list", ".", "append", "(", "arg_value", ")" ]
Split argument text to name, type, value.
[ "Split", "argument", "text", "to", "name", "type", "value", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L667-L703
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.split_args_text_to_list
def split_args_text_to_list(self, args_text): """Split the text including multiple arguments to list. This function uses a comma to separate arguments and ignores a comma in brackets ans quotes. """ args_list = [] idx_find_start = 0 idx_arg_start = 0 try: pos_quote = self._find_quote_position(args_text) pos_round = self._find_bracket_position(args_text, '(', ')', pos_quote) pos_curly = self._find_bracket_position(args_text, '{', '}', pos_quote) pos_square = self._find_bracket_position(args_text, '[', ']', pos_quote) except IndexError: return None while True: pos_comma = args_text.find(',', idx_find_start) if pos_comma == -1: break idx_find_start = pos_comma + 1 if self.is_char_in_pairs(pos_comma, pos_round) or \ self.is_char_in_pairs(pos_comma, pos_curly) or \ self.is_char_in_pairs(pos_comma, pos_square) or \ self.is_char_in_pairs(pos_comma, pos_quote): continue args_list.append(args_text[idx_arg_start:pos_comma]) idx_arg_start = pos_comma + 1 if idx_arg_start < len(args_text): args_list.append(args_text[idx_arg_start:]) return args_list
python
def split_args_text_to_list(self, args_text): """Split the text including multiple arguments to list. This function uses a comma to separate arguments and ignores a comma in brackets ans quotes. """ args_list = [] idx_find_start = 0 idx_arg_start = 0 try: pos_quote = self._find_quote_position(args_text) pos_round = self._find_bracket_position(args_text, '(', ')', pos_quote) pos_curly = self._find_bracket_position(args_text, '{', '}', pos_quote) pos_square = self._find_bracket_position(args_text, '[', ']', pos_quote) except IndexError: return None while True: pos_comma = args_text.find(',', idx_find_start) if pos_comma == -1: break idx_find_start = pos_comma + 1 if self.is_char_in_pairs(pos_comma, pos_round) or \ self.is_char_in_pairs(pos_comma, pos_curly) or \ self.is_char_in_pairs(pos_comma, pos_square) or \ self.is_char_in_pairs(pos_comma, pos_quote): continue args_list.append(args_text[idx_arg_start:pos_comma]) idx_arg_start = pos_comma + 1 if idx_arg_start < len(args_text): args_list.append(args_text[idx_arg_start:]) return args_list
[ "def", "split_args_text_to_list", "(", "self", ",", "args_text", ")", ":", "args_list", "=", "[", "]", "idx_find_start", "=", "0", "idx_arg_start", "=", "0", "try", ":", "pos_quote", "=", "self", ".", "_find_quote_position", "(", "args_text", ")", "pos_round", "=", "self", ".", "_find_bracket_position", "(", "args_text", ",", "'('", ",", "')'", ",", "pos_quote", ")", "pos_curly", "=", "self", ".", "_find_bracket_position", "(", "args_text", ",", "'{'", ",", "'}'", ",", "pos_quote", ")", "pos_square", "=", "self", ".", "_find_bracket_position", "(", "args_text", ",", "'['", ",", "']'", ",", "pos_quote", ")", "except", "IndexError", ":", "return", "None", "while", "True", ":", "pos_comma", "=", "args_text", ".", "find", "(", "','", ",", "idx_find_start", ")", "if", "pos_comma", "==", "-", "1", ":", "break", "idx_find_start", "=", "pos_comma", "+", "1", "if", "self", ".", "is_char_in_pairs", "(", "pos_comma", ",", "pos_round", ")", "or", "self", ".", "is_char_in_pairs", "(", "pos_comma", ",", "pos_curly", ")", "or", "self", ".", "is_char_in_pairs", "(", "pos_comma", ",", "pos_square", ")", "or", "self", ".", "is_char_in_pairs", "(", "pos_comma", ",", "pos_quote", ")", ":", "continue", "args_list", ".", "append", "(", "args_text", "[", "idx_arg_start", ":", "pos_comma", "]", ")", "idx_arg_start", "=", "pos_comma", "+", "1", "if", "idx_arg_start", "<", "len", "(", "args_text", ")", ":", "args_list", ".", "append", "(", "args_text", "[", "idx_arg_start", ":", "]", ")", "return", "args_list" ]
Split the text including multiple arguments to list. This function uses a comma to separate arguments and ignores a comma in brackets ans quotes.
[ "Split", "the", "text", "including", "multiple", "arguments", "to", "list", ".", "This", "function", "uses", "a", "comma", "to", "separate", "arguments", "and", "ignores", "a", "comma", "in", "brackets", "ans", "quotes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L705-L746
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.parse_def
def parse_def(self, text): """Parse the function definition text.""" self.__init__() if not is_start_of_function(text): return self.func_indent = get_indent(text) text = text.strip() text = text.replace('\r\n', '') text = text.replace('\n', '') return_type_re = re.search(r'->[ ]*([a-zA-Z0-9_,()\[\] ]*):$', text) if return_type_re: self.return_type_annotated = return_type_re.group(1) text_end = text.rfind(return_type_re.group(0)) else: self.return_type_annotated = None text_end = len(text) pos_args_start = text.find('(') + 1 pos_args_end = text.rfind(')', pos_args_start, text_end) self.args_text = text[pos_args_start:pos_args_end] args_list = self.split_args_text_to_list(self.args_text) if args_list is not None: self.has_info = True self.split_arg_to_name_type_value(args_list)
python
def parse_def(self, text): """Parse the function definition text.""" self.__init__() if not is_start_of_function(text): return self.func_indent = get_indent(text) text = text.strip() text = text.replace('\r\n', '') text = text.replace('\n', '') return_type_re = re.search(r'->[ ]*([a-zA-Z0-9_,()\[\] ]*):$', text) if return_type_re: self.return_type_annotated = return_type_re.group(1) text_end = text.rfind(return_type_re.group(0)) else: self.return_type_annotated = None text_end = len(text) pos_args_start = text.find('(') + 1 pos_args_end = text.rfind(')', pos_args_start, text_end) self.args_text = text[pos_args_start:pos_args_end] args_list = self.split_args_text_to_list(self.args_text) if args_list is not None: self.has_info = True self.split_arg_to_name_type_value(args_list)
[ "def", "parse_def", "(", "self", ",", "text", ")", ":", "self", ".", "__init__", "(", ")", "if", "not", "is_start_of_function", "(", "text", ")", ":", "return", "self", ".", "func_indent", "=", "get_indent", "(", "text", ")", "text", "=", "text", ".", "strip", "(", ")", "text", "=", "text", ".", "replace", "(", "'\\r\\n'", ",", "''", ")", "text", "=", "text", ".", "replace", "(", "'\\n'", ",", "''", ")", "return_type_re", "=", "re", ".", "search", "(", "r'->[ ]*([a-zA-Z0-9_,()\\[\\] ]*):$'", ",", "text", ")", "if", "return_type_re", ":", "self", ".", "return_type_annotated", "=", "return_type_re", ".", "group", "(", "1", ")", "text_end", "=", "text", ".", "rfind", "(", "return_type_re", ".", "group", "(", "0", ")", ")", "else", ":", "self", ".", "return_type_annotated", "=", "None", "text_end", "=", "len", "(", "text", ")", "pos_args_start", "=", "text", ".", "find", "(", "'('", ")", "+", "1", "pos_args_end", "=", "text", ".", "rfind", "(", "')'", ",", "pos_args_start", ",", "text_end", ")", "self", ".", "args_text", "=", "text", "[", "pos_args_start", ":", "pos_args_end", "]", "args_list", "=", "self", ".", "split_args_text_to_list", "(", "self", ".", "args_text", ")", "if", "args_list", "is", "not", "None", ":", "self", ".", "has_info", "=", "True", "self", ".", "split_arg_to_name_type_value", "(", "args_list", ")" ]
Parse the function definition text.
[ "Parse", "the", "function", "definition", "text", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L748-L777
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
FunctionInfo.parse_body
def parse_body(self, text): """Parse the function body text.""" re_raise = re.findall(r'[ \t]raise ([a-zA-Z0-9_]*)', text) if len(re_raise) > 0: self.raise_list = [x.strip() for x in re_raise] # remove duplicates from list while keeping it in the order # in python 2.7 # stackoverflow.com/questions/7961363/removing-duplicates-in-lists self.raise_list = list(OrderedDict.fromkeys(self.raise_list)) re_yield = re.search(r'[ \t]yield ', text) if re_yield: self.has_yield = True # get return value pattern_return = r'return |yield ' line_list = text.split('\n') is_found_return = False line_return_tmp = '' for line in line_list: line = line.strip() if is_found_return is False: if re.match(pattern_return, line): is_found_return = True if is_found_return: line_return_tmp += line # check the integrity of line try: pos_quote = self._find_quote_position(line_return_tmp) if line_return_tmp[-1] == '\\': line_return_tmp = line_return_tmp[:-1] continue self._find_bracket_position(line_return_tmp, '(', ')', pos_quote) self._find_bracket_position(line_return_tmp, '{', '}', pos_quote) self._find_bracket_position(line_return_tmp, '[', ']', pos_quote) except IndexError: continue return_value = re.sub(pattern_return, '', line_return_tmp) self.return_value_in_body.append(return_value) is_found_return = False line_return_tmp = ''
python
def parse_body(self, text): """Parse the function body text.""" re_raise = re.findall(r'[ \t]raise ([a-zA-Z0-9_]*)', text) if len(re_raise) > 0: self.raise_list = [x.strip() for x in re_raise] # remove duplicates from list while keeping it in the order # in python 2.7 # stackoverflow.com/questions/7961363/removing-duplicates-in-lists self.raise_list = list(OrderedDict.fromkeys(self.raise_list)) re_yield = re.search(r'[ \t]yield ', text) if re_yield: self.has_yield = True # get return value pattern_return = r'return |yield ' line_list = text.split('\n') is_found_return = False line_return_tmp = '' for line in line_list: line = line.strip() if is_found_return is False: if re.match(pattern_return, line): is_found_return = True if is_found_return: line_return_tmp += line # check the integrity of line try: pos_quote = self._find_quote_position(line_return_tmp) if line_return_tmp[-1] == '\\': line_return_tmp = line_return_tmp[:-1] continue self._find_bracket_position(line_return_tmp, '(', ')', pos_quote) self._find_bracket_position(line_return_tmp, '{', '}', pos_quote) self._find_bracket_position(line_return_tmp, '[', ']', pos_quote) except IndexError: continue return_value = re.sub(pattern_return, '', line_return_tmp) self.return_value_in_body.append(return_value) is_found_return = False line_return_tmp = ''
[ "def", "parse_body", "(", "self", ",", "text", ")", ":", "re_raise", "=", "re", ".", "findall", "(", "r'[ \\t]raise ([a-zA-Z0-9_]*)'", ",", "text", ")", "if", "len", "(", "re_raise", ")", ">", "0", ":", "self", ".", "raise_list", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "re_raise", "]", "# remove duplicates from list while keeping it in the order\r", "# in python 2.7\r", "# stackoverflow.com/questions/7961363/removing-duplicates-in-lists\r", "self", ".", "raise_list", "=", "list", "(", "OrderedDict", ".", "fromkeys", "(", "self", ".", "raise_list", ")", ")", "re_yield", "=", "re", ".", "search", "(", "r'[ \\t]yield '", ",", "text", ")", "if", "re_yield", ":", "self", ".", "has_yield", "=", "True", "# get return value\r", "pattern_return", "=", "r'return |yield '", "line_list", "=", "text", ".", "split", "(", "'\\n'", ")", "is_found_return", "=", "False", "line_return_tmp", "=", "''", "for", "line", "in", "line_list", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "is_found_return", "is", "False", ":", "if", "re", ".", "match", "(", "pattern_return", ",", "line", ")", ":", "is_found_return", "=", "True", "if", "is_found_return", ":", "line_return_tmp", "+=", "line", "# check the integrity of line\r", "try", ":", "pos_quote", "=", "self", ".", "_find_quote_position", "(", "line_return_tmp", ")", "if", "line_return_tmp", "[", "-", "1", "]", "==", "'\\\\'", ":", "line_return_tmp", "=", "line_return_tmp", "[", ":", "-", "1", "]", "continue", "self", ".", "_find_bracket_position", "(", "line_return_tmp", ",", "'('", ",", "')'", ",", "pos_quote", ")", "self", ".", "_find_bracket_position", "(", "line_return_tmp", ",", "'{'", ",", "'}'", ",", "pos_quote", ")", "self", ".", "_find_bracket_position", "(", "line_return_tmp", ",", "'['", ",", "']'", ",", "pos_quote", ")", "except", "IndexError", ":", "continue", "return_value", "=", "re", ".", "sub", "(", "pattern_return", ",", "''", ",", "line_return_tmp", ")", "self", ".", "return_value_in_body", ".", "append", "(", "return_value", ")", "is_found_return", "=", "False", "line_return_tmp", "=", "''" ]
Parse the function body text.
[ "Parse", "the", "function", "body", "text", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L779-L829
train
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
QMenuOnlyForEnter.keyPressEvent
def keyPressEvent(self, event): """Close the instance if key is not enter key.""" key = event.key() if key not in (Qt.Key_Enter, Qt.Key_Return): self.code_editor.keyPressEvent(event) self.close() else: super(QMenuOnlyForEnter, self).keyPressEvent(event)
python
def keyPressEvent(self, event): """Close the instance if key is not enter key.""" key = event.key() if key not in (Qt.Key_Enter, Qt.Key_Return): self.code_editor.keyPressEvent(event) self.close() else: super(QMenuOnlyForEnter, self).keyPressEvent(event)
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "key", "=", "event", ".", "key", "(", ")", "if", "key", "not", "in", "(", "Qt", ".", "Key_Enter", ",", "Qt", ".", "Key_Return", ")", ":", "self", ".", "code_editor", ".", "keyPressEvent", "(", "event", ")", "self", ".", "close", "(", ")", "else", ":", "super", "(", "QMenuOnlyForEnter", ",", "self", ")", ".", "keyPressEvent", "(", "event", ")" ]
Close the instance if key is not enter key.
[ "Close", "the", "instance", "if", "key", "is", "not", "enter", "key", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L844-L851
train
spyder-ide/spyder
spyder/app/restart.py
_is_pid_running_on_windows
def _is_pid_running_on_windows(pid): """Check if a process is running on windows systems based on the pid.""" pid = str(pid) # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen(r'tasklist /fi "PID eq {0}"'.format(pid), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) stdoutdata, stderrdata = process.communicate() stdoutdata = to_text_string(stdoutdata) process.kill() check = pid in stdoutdata return check
python
def _is_pid_running_on_windows(pid): """Check if a process is running on windows systems based on the pid.""" pid = str(pid) # Hide flashing command prompt startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen(r'tasklist /fi "PID eq {0}"'.format(pid), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) stdoutdata, stderrdata = process.communicate() stdoutdata = to_text_string(stdoutdata) process.kill() check = pid in stdoutdata return check
[ "def", "_is_pid_running_on_windows", "(", "pid", ")", ":", "pid", "=", "str", "(", "pid", ")", "# Hide flashing command prompt\r", "startupinfo", "=", "subprocess", ".", "STARTUPINFO", "(", ")", "startupinfo", ".", "dwFlags", "|=", "subprocess", ".", "STARTF_USESHOWWINDOW", "process", "=", "subprocess", ".", "Popen", "(", "r'tasklist /fi \"PID eq {0}\"'", ".", "format", "(", "pid", ")", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "startupinfo", "=", "startupinfo", ")", "stdoutdata", ",", "stderrdata", "=", "process", ".", "communicate", "(", ")", "stdoutdata", "=", "to_text_string", "(", "stdoutdata", ")", "process", ".", "kill", "(", ")", "check", "=", "pid", "in", "stdoutdata", "return", "check" ]
Check if a process is running on windows systems based on the pid.
[ "Check", "if", "a", "process", "is", "running", "on", "windows", "systems", "based", "on", "the", "pid", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L42-L59
train
spyder-ide/spyder
spyder/app/restart.py
Restarter._show_message
def _show_message(self, text): """Show message on splash screen.""" self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.white))
python
def _show_message(self, text): """Show message on splash screen.""" self.splash.showMessage(text, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute, QColor(Qt.white))
[ "def", "_show_message", "(", "self", ",", "text", ")", ":", "self", ".", "splash", ".", "showMessage", "(", "text", ",", "Qt", ".", "AlignBottom", "|", "Qt", ".", "AlignCenter", "|", "Qt", ".", "AlignAbsolute", ",", "QColor", "(", "Qt", ".", "white", ")", ")" ]
Show message on splash screen.
[ "Show", "message", "on", "splash", "screen", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L106-L109
train
spyder-ide/spyder
spyder/app/restart.py
Restarter.animate_ellipsis
def animate_ellipsis(self): """Animate dots at the end of the splash screen message.""" ellipsis = self.ellipsis.pop(0) text = ' '*len(ellipsis) + self.splash_text + ellipsis self.ellipsis.append(ellipsis) self._show_message(text)
python
def animate_ellipsis(self): """Animate dots at the end of the splash screen message.""" ellipsis = self.ellipsis.pop(0) text = ' '*len(ellipsis) + self.splash_text + ellipsis self.ellipsis.append(ellipsis) self._show_message(text)
[ "def", "animate_ellipsis", "(", "self", ")", ":", "ellipsis", "=", "self", ".", "ellipsis", ".", "pop", "(", "0", ")", "text", "=", "' '", "*", "len", "(", "ellipsis", ")", "+", "self", ".", "splash_text", "+", "ellipsis", "self", ".", "ellipsis", ".", "append", "(", "ellipsis", ")", "self", ".", "_show_message", "(", "text", ")" ]
Animate dots at the end of the splash screen message.
[ "Animate", "dots", "at", "the", "end", "of", "the", "splash", "screen", "message", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L111-L116
train
spyder-ide/spyder
spyder/app/restart.py
Restarter.set_splash_message
def set_splash_message(self, text): """Sets the text in the bottom of the Splash screen.""" self.splash_text = text self._show_message(text) self.timer_ellipsis.start(500)
python
def set_splash_message(self, text): """Sets the text in the bottom of the Splash screen.""" self.splash_text = text self._show_message(text) self.timer_ellipsis.start(500)
[ "def", "set_splash_message", "(", "self", ",", "text", ")", ":", "self", ".", "splash_text", "=", "text", "self", ".", "_show_message", "(", "text", ")", "self", ".", "timer_ellipsis", ".", "start", "(", "500", ")" ]
Sets the text in the bottom of the Splash screen.
[ "Sets", "the", "text", "in", "the", "bottom", "of", "the", "Splash", "screen", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L118-L122
train
spyder-ide/spyder
spyder/app/restart.py
Restarter.launch_error_message
def launch_error_message(self, error_type, error=None): """Launch a message box with a predefined error message. Parameters ---------- error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR] Possible error codes when restarting/reseting spyder. error : Exception Actual Python exception error caught. """ messages = {CLOSE_ERROR: _("It was not possible to close the previous " "Spyder instance.\nRestart aborted."), RESET_ERROR: _("Spyder could not reset to factory " "defaults.\nRestart aborted."), RESTART_ERROR: _("It was not possible to restart Spyder.\n" "Operation aborted.")} titles = {CLOSE_ERROR: _("Spyder exit error"), RESET_ERROR: _("Spyder reset error"), RESTART_ERROR: _("Spyder restart error")} if error: e = error.__repr__() message = messages[error_type] + "\n\n{0}".format(e) else: message = messages[error_type] title = titles[error_type] self.splash.hide() QMessageBox.warning(self, title, message, QMessageBox.Ok) raise RuntimeError(message)
python
def launch_error_message(self, error_type, error=None): """Launch a message box with a predefined error message. Parameters ---------- error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR] Possible error codes when restarting/reseting spyder. error : Exception Actual Python exception error caught. """ messages = {CLOSE_ERROR: _("It was not possible to close the previous " "Spyder instance.\nRestart aborted."), RESET_ERROR: _("Spyder could not reset to factory " "defaults.\nRestart aborted."), RESTART_ERROR: _("It was not possible to restart Spyder.\n" "Operation aborted.")} titles = {CLOSE_ERROR: _("Spyder exit error"), RESET_ERROR: _("Spyder reset error"), RESTART_ERROR: _("Spyder restart error")} if error: e = error.__repr__() message = messages[error_type] + "\n\n{0}".format(e) else: message = messages[error_type] title = titles[error_type] self.splash.hide() QMessageBox.warning(self, title, message, QMessageBox.Ok) raise RuntimeError(message)
[ "def", "launch_error_message", "(", "self", ",", "error_type", ",", "error", "=", "None", ")", ":", "messages", "=", "{", "CLOSE_ERROR", ":", "_", "(", "\"It was not possible to close the previous \"", "\"Spyder instance.\\nRestart aborted.\"", ")", ",", "RESET_ERROR", ":", "_", "(", "\"Spyder could not reset to factory \"", "\"defaults.\\nRestart aborted.\"", ")", ",", "RESTART_ERROR", ":", "_", "(", "\"It was not possible to restart Spyder.\\n\"", "\"Operation aborted.\"", ")", "}", "titles", "=", "{", "CLOSE_ERROR", ":", "_", "(", "\"Spyder exit error\"", ")", ",", "RESET_ERROR", ":", "_", "(", "\"Spyder reset error\"", ")", ",", "RESTART_ERROR", ":", "_", "(", "\"Spyder restart error\"", ")", "}", "if", "error", ":", "e", "=", "error", ".", "__repr__", "(", ")", "message", "=", "messages", "[", "error_type", "]", "+", "\"\\n\\n{0}\"", ".", "format", "(", "e", ")", "else", ":", "message", "=", "messages", "[", "error_type", "]", "title", "=", "titles", "[", "error_type", "]", "self", ".", "splash", ".", "hide", "(", ")", "QMessageBox", ".", "warning", "(", "self", ",", "title", ",", "message", ",", "QMessageBox", ".", "Ok", ")", "raise", "RuntimeError", "(", "message", ")" ]
Launch a message box with a predefined error message. Parameters ---------- error_type : int [CLOSE_ERROR, RESET_ERROR, RESTART_ERROR] Possible error codes when restarting/reseting spyder. error : Exception Actual Python exception error caught.
[ "Launch", "a", "message", "box", "with", "a", "predefined", "error", "message", ".", "Parameters", "----------", "error_type", ":", "int", "[", "CLOSE_ERROR", "RESET_ERROR", "RESTART_ERROR", "]", "Possible", "error", "codes", "when", "restarting", "/", "reseting", "spyder", ".", "error", ":", "Exception", "Actual", "Python", "exception", "error", "caught", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/restart.py#L124-L153
train
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.refresh_plugin
def refresh_plugin(self): """Refresh tabwidget""" if self.tabwidget.count(): editor = self.tabwidget.currentWidget() else: editor = None self.find_widget.set_editor(editor)
python
def refresh_plugin(self): """Refresh tabwidget""" if self.tabwidget.count(): editor = self.tabwidget.currentWidget() else: editor = None self.find_widget.set_editor(editor)
[ "def", "refresh_plugin", "(", "self", ")", ":", "if", "self", ".", "tabwidget", ".", "count", "(", ")", ":", "editor", "=", "self", ".", "tabwidget", ".", "currentWidget", "(", ")", "else", ":", "editor", "=", "None", "self", ".", "find_widget", ".", "set_editor", "(", "editor", ")" ]
Refresh tabwidget
[ "Refresh", "tabwidget" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L104-L110
train
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.get_plugin_actions
def get_plugin_actions(self): """Return a list of actions related to plugin""" self.history_action = create_action(self, _("History..."), None, ima.icon('history'), _("Set history maximum entries"), triggered=self.change_history_depth) self.wrap_action = create_action(self, _("Wrap lines"), toggled=self.toggle_wrap_mode) self.wrap_action.setChecked( self.get_option('wrap') ) self.linenumbers_action = create_action( self, _("Show line numbers"), toggled=self.toggle_line_numbers) self.linenumbers_action.setChecked(self.get_option('line_numbers')) menu_actions = [self.history_action, self.wrap_action, self.linenumbers_action] return menu_actions
python
def get_plugin_actions(self): """Return a list of actions related to plugin""" self.history_action = create_action(self, _("History..."), None, ima.icon('history'), _("Set history maximum entries"), triggered=self.change_history_depth) self.wrap_action = create_action(self, _("Wrap lines"), toggled=self.toggle_wrap_mode) self.wrap_action.setChecked( self.get_option('wrap') ) self.linenumbers_action = create_action( self, _("Show line numbers"), toggled=self.toggle_line_numbers) self.linenumbers_action.setChecked(self.get_option('line_numbers')) menu_actions = [self.history_action, self.wrap_action, self.linenumbers_action] return menu_actions
[ "def", "get_plugin_actions", "(", "self", ")", ":", "self", ".", "history_action", "=", "create_action", "(", "self", ",", "_", "(", "\"History...\"", ")", ",", "None", ",", "ima", ".", "icon", "(", "'history'", ")", ",", "_", "(", "\"Set history maximum entries\"", ")", ",", "triggered", "=", "self", ".", "change_history_depth", ")", "self", ".", "wrap_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Wrap lines\"", ")", ",", "toggled", "=", "self", ".", "toggle_wrap_mode", ")", "self", ".", "wrap_action", ".", "setChecked", "(", "self", ".", "get_option", "(", "'wrap'", ")", ")", "self", ".", "linenumbers_action", "=", "create_action", "(", "self", ",", "_", "(", "\"Show line numbers\"", ")", ",", "toggled", "=", "self", ".", "toggle_line_numbers", ")", "self", ".", "linenumbers_action", ".", "setChecked", "(", "self", ".", "get_option", "(", "'line_numbers'", ")", ")", "menu_actions", "=", "[", "self", ".", "history_action", ",", "self", ".", "wrap_action", ",", "self", ".", "linenumbers_action", "]", "return", "menu_actions" ]
Return a list of actions related to plugin
[ "Return", "a", "list", "of", "actions", "related", "to", "plugin" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L112-L127
train
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.register_plugin
def register_plugin(self): """Register plugin in Spyder's main window""" self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) # self.main.console.set_historylog(self) self.main.console.shell.refresh.connect(self.refresh_plugin)
python
def register_plugin(self): """Register plugin in Spyder's main window""" self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) # self.main.console.set_historylog(self) self.main.console.shell.refresh.connect(self.refresh_plugin)
[ "def", "register_plugin", "(", "self", ")", ":", "self", ".", "focus_changed", ".", "connect", "(", "self", ".", "main", ".", "plugin_focus_changed", ")", "self", ".", "main", ".", "add_dockwidget", "(", "self", ")", "# self.main.console.set_historylog(self)\r", "self", ".", "main", ".", "console", ".", "shell", ".", "refresh", ".", "connect", "(", "self", ".", "refresh_plugin", ")" ]
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/history/plugin.py#L133-L138
train
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.update_font
def update_font(self): """Update font from Preferences""" color_scheme = self.get_color_scheme() font = self.get_plugin_font() for editor in self.editors: editor.set_font(font, color_scheme)
python
def update_font(self): """Update font from Preferences""" color_scheme = self.get_color_scheme() font = self.get_plugin_font() for editor in self.editors: editor.set_font(font, color_scheme)
[ "def", "update_font", "(", "self", ")", ":", "color_scheme", "=", "self", ".", "get_color_scheme", "(", ")", "font", "=", "self", ".", "get_plugin_font", "(", ")", "for", "editor", "in", "self", ".", "editors", ":", "editor", ".", "set_font", "(", "font", ",", "color_scheme", ")" ]
Update font from Preferences
[ "Update", "font", "from", "Preferences" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L140-L145
train
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.apply_plugin_settings
def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" color_scheme_n = 'color_scheme_name' color_scheme_o = self.get_color_scheme() font_n = 'plugin_font' font_o = self.get_plugin_font() wrap_n = 'wrap' wrap_o = self.get_option(wrap_n) self.wrap_action.setChecked(wrap_o) linenb_n = 'line_numbers' linenb_o = self.get_option(linenb_n) for editor in self.editors: if font_n in options: scs = color_scheme_o if color_scheme_n in options else None editor.set_font(font_o, scs) elif color_scheme_n in options: editor.set_color_scheme(color_scheme_o) if wrap_n in options: editor.toggle_wrap_mode(wrap_o) if linenb_n in options: editor.toggle_line_numbers(linenumbers=linenb_o, markers=False)
python
def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" color_scheme_n = 'color_scheme_name' color_scheme_o = self.get_color_scheme() font_n = 'plugin_font' font_o = self.get_plugin_font() wrap_n = 'wrap' wrap_o = self.get_option(wrap_n) self.wrap_action.setChecked(wrap_o) linenb_n = 'line_numbers' linenb_o = self.get_option(linenb_n) for editor in self.editors: if font_n in options: scs = color_scheme_o if color_scheme_n in options else None editor.set_font(font_o, scs) elif color_scheme_n in options: editor.set_color_scheme(color_scheme_o) if wrap_n in options: editor.toggle_wrap_mode(wrap_o) if linenb_n in options: editor.toggle_line_numbers(linenumbers=linenb_o, markers=False)
[ "def", "apply_plugin_settings", "(", "self", ",", "options", ")", ":", "color_scheme_n", "=", "'color_scheme_name'", "color_scheme_o", "=", "self", ".", "get_color_scheme", "(", ")", "font_n", "=", "'plugin_font'", "font_o", "=", "self", ".", "get_plugin_font", "(", ")", "wrap_n", "=", "'wrap'", "wrap_o", "=", "self", ".", "get_option", "(", "wrap_n", ")", "self", ".", "wrap_action", ".", "setChecked", "(", "wrap_o", ")", "linenb_n", "=", "'line_numbers'", "linenb_o", "=", "self", ".", "get_option", "(", "linenb_n", ")", "for", "editor", "in", "self", ".", "editors", ":", "if", "font_n", "in", "options", ":", "scs", "=", "color_scheme_o", "if", "color_scheme_n", "in", "options", "else", "None", "editor", ".", "set_font", "(", "font_o", ",", "scs", ")", "elif", "color_scheme_n", "in", "options", ":", "editor", ".", "set_color_scheme", "(", "color_scheme_o", ")", "if", "wrap_n", "in", "options", ":", "editor", ".", "toggle_wrap_mode", "(", "wrap_o", ")", "if", "linenb_n", "in", "options", ":", "editor", ".", "toggle_line_numbers", "(", "linenumbers", "=", "linenb_o", ",", "markers", "=", "False", ")" ]
Apply configuration file's plugin settings
[ "Apply", "configuration", "file", "s", "plugin", "settings" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L147-L167
train
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.add_history
def add_history(self, filename): """ Add new history tab Slot for add_history signal emitted by shell instance """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = codeeditor.CodeEditor(self) if osp.splitext(filename)[1] == '.py': language = 'py' else: language = 'bat' editor.setup_editor(linenumbers=self.get_option('line_numbers'), language=language, scrollflagarea=False) editor.focus_changed.connect(lambda: self.focus_changed.emit()) editor.setReadOnly(True) color_scheme = self.get_color_scheme() editor.set_font( self.get_plugin_font(), color_scheme ) editor.toggle_wrap_mode( self.get_option('wrap') ) # Avoid a possible error when reading the history file try: text, _ = encoding.read(filename) except (IOError, OSError): text = "# Previous history could not be read from disk, sorry\n\n" text = normalize_eols(text) linebreaks = [m.start() for m in re.finditer('\n', text)] maxNline = self.get_option('max_entries') if len(linebreaks) > maxNline: text = text[linebreaks[-maxNline - 1] + 1:] # Avoid an error when trying to write the trimmed text to # disk. # See issue 9093 try: encoding.write(text, filename) except (IOError, OSError): pass editor.set_text(text) editor.set_cursor_position('eof') self.editors.append(editor) self.filenames.append(filename) index = self.tabwidget.addTab(editor, osp.basename(filename)) self.find_widget.set_editor(editor) self.tabwidget.setTabToolTip(index, filename) self.tabwidget.setCurrentIndex(index)
python
def add_history(self, filename): """ Add new history tab Slot for add_history signal emitted by shell instance """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = codeeditor.CodeEditor(self) if osp.splitext(filename)[1] == '.py': language = 'py' else: language = 'bat' editor.setup_editor(linenumbers=self.get_option('line_numbers'), language=language, scrollflagarea=False) editor.focus_changed.connect(lambda: self.focus_changed.emit()) editor.setReadOnly(True) color_scheme = self.get_color_scheme() editor.set_font( self.get_plugin_font(), color_scheme ) editor.toggle_wrap_mode( self.get_option('wrap') ) # Avoid a possible error when reading the history file try: text, _ = encoding.read(filename) except (IOError, OSError): text = "# Previous history could not be read from disk, sorry\n\n" text = normalize_eols(text) linebreaks = [m.start() for m in re.finditer('\n', text)] maxNline = self.get_option('max_entries') if len(linebreaks) > maxNline: text = text[linebreaks[-maxNline - 1] + 1:] # Avoid an error when trying to write the trimmed text to # disk. # See issue 9093 try: encoding.write(text, filename) except (IOError, OSError): pass editor.set_text(text) editor.set_cursor_position('eof') self.editors.append(editor) self.filenames.append(filename) index = self.tabwidget.addTab(editor, osp.basename(filename)) self.find_widget.set_editor(editor) self.tabwidget.setTabToolTip(index, filename) self.tabwidget.setCurrentIndex(index)
[ "def", "add_history", "(", "self", ",", "filename", ")", ":", "filename", "=", "encoding", ".", "to_unicode_from_fs", "(", "filename", ")", "if", "filename", "in", "self", ".", "filenames", ":", "return", "editor", "=", "codeeditor", ".", "CodeEditor", "(", "self", ")", "if", "osp", ".", "splitext", "(", "filename", ")", "[", "1", "]", "==", "'.py'", ":", "language", "=", "'py'", "else", ":", "language", "=", "'bat'", "editor", ".", "setup_editor", "(", "linenumbers", "=", "self", ".", "get_option", "(", "'line_numbers'", ")", ",", "language", "=", "language", ",", "scrollflagarea", "=", "False", ")", "editor", ".", "focus_changed", ".", "connect", "(", "lambda", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", ")", "editor", ".", "setReadOnly", "(", "True", ")", "color_scheme", "=", "self", ".", "get_color_scheme", "(", ")", "editor", ".", "set_font", "(", "self", ".", "get_plugin_font", "(", ")", ",", "color_scheme", ")", "editor", ".", "toggle_wrap_mode", "(", "self", ".", "get_option", "(", "'wrap'", ")", ")", "# Avoid a possible error when reading the history file\r", "try", ":", "text", ",", "_", "=", "encoding", ".", "read", "(", "filename", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "text", "=", "\"# Previous history could not be read from disk, sorry\\n\\n\"", "text", "=", "normalize_eols", "(", "text", ")", "linebreaks", "=", "[", "m", ".", "start", "(", ")", "for", "m", "in", "re", ".", "finditer", "(", "'\\n'", ",", "text", ")", "]", "maxNline", "=", "self", ".", "get_option", "(", "'max_entries'", ")", "if", "len", "(", "linebreaks", ")", ">", "maxNline", ":", "text", "=", "text", "[", "linebreaks", "[", "-", "maxNline", "-", "1", "]", "+", "1", ":", "]", "# Avoid an error when trying to write the trimmed text to\r", "# disk.\r", "# See issue 9093\r", "try", ":", "encoding", ".", "write", "(", "text", ",", "filename", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "pass", "editor", ".", "set_text", "(", "text", ")", "editor", ".", "set_cursor_position", "(", "'eof'", ")", "self", ".", "editors", ".", "append", "(", "editor", ")", "self", ".", "filenames", ".", "append", "(", "filename", ")", "index", "=", "self", ".", "tabwidget", ".", "addTab", "(", "editor", ",", "osp", ".", "basename", "(", "filename", ")", ")", "self", ".", "find_widget", ".", "set_editor", "(", "editor", ")", "self", ".", "tabwidget", ".", "setTabToolTip", "(", "index", ",", "filename", ")", "self", ".", "tabwidget", ".", "setCurrentIndex", "(", "index", ")" ]
Add new history tab Slot for add_history signal emitted by shell instance
[ "Add", "new", "history", "tab", "Slot", "for", "add_history", "signal", "emitted", "by", "shell", "instance" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L181-L228
train
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.toggle_wrap_mode
def toggle_wrap_mode(self, checked): """Toggle wrap mode""" if self.tabwidget is None: return for editor in self.editors: editor.toggle_wrap_mode(checked) self.set_option('wrap', checked)
python
def toggle_wrap_mode(self, checked): """Toggle wrap mode""" if self.tabwidget is None: return for editor in self.editors: editor.toggle_wrap_mode(checked) self.set_option('wrap', checked)
[ "def", "toggle_wrap_mode", "(", "self", ",", "checked", ")", ":", "if", "self", ".", "tabwidget", "is", "None", ":", "return", "for", "editor", "in", "self", ".", "editors", ":", "editor", ".", "toggle_wrap_mode", "(", "checked", ")", "self", ".", "set_option", "(", "'wrap'", ",", "checked", ")" ]
Toggle wrap mode
[ "Toggle", "wrap", "mode" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L256-L262
train
spyder-ide/spyder
spyder/plugins/history/plugin.py
HistoryLog.toggle_line_numbers
def toggle_line_numbers(self, checked): """Toggle line numbers.""" if self.tabwidget is None: return for editor in self.editors: editor.toggle_line_numbers(linenumbers=checked, markers=False) self.set_option('line_numbers', checked)
python
def toggle_line_numbers(self, checked): """Toggle line numbers.""" if self.tabwidget is None: return for editor in self.editors: editor.toggle_line_numbers(linenumbers=checked, markers=False) self.set_option('line_numbers', checked)
[ "def", "toggle_line_numbers", "(", "self", ",", "checked", ")", ":", "if", "self", ".", "tabwidget", "is", "None", ":", "return", "for", "editor", "in", "self", ".", "editors", ":", "editor", ".", "toggle_line_numbers", "(", "linenumbers", "=", "checked", ",", "markers", "=", "False", ")", "self", ".", "set_option", "(", "'line_numbers'", ",", "checked", ")" ]
Toggle line numbers.
[ "Toggle", "line", "numbers", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/history/plugin.py#L265-L271
train
spyder-ide/spyder
spyder/plugins/editor/lsp/providers/document.py
DocumentProvider.document_did_save_notification
def document_did_save_notification(self, params): """ Handle the textDocument/didSave message received from an LSP server. """ text = None if 'text' in params: text = params['text'] params = { 'textDocument': { 'uri': path_as_uri(params['file']) } } if text is not None: params['text'] = text return params
python
def document_did_save_notification(self, params): """ Handle the textDocument/didSave message received from an LSP server. """ text = None if 'text' in params: text = params['text'] params = { 'textDocument': { 'uri': path_as_uri(params['file']) } } if text is not None: params['text'] = text return params
[ "def", "document_did_save_notification", "(", "self", ",", "params", ")", ":", "text", "=", "None", "if", "'text'", "in", "params", ":", "text", "=", "params", "[", "'text'", "]", "params", "=", "{", "'textDocument'", ":", "{", "'uri'", ":", "path_as_uri", "(", "params", "[", "'file'", "]", ")", "}", "}", "if", "text", "is", "not", "None", ":", "params", "[", "'text'", "]", "=", "text", "return", "params" ]
Handle the textDocument/didSave message received from an LSP server.
[ "Handle", "the", "textDocument", "/", "didSave", "message", "received", "from", "an", "LSP", "server", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/lsp/providers/document.py#L216-L230
train
spyder-ide/spyder
spyder/widgets/browser.py
WebPage.acceptNavigationRequest
def acceptNavigationRequest(self, url, navigation_type, isMainFrame): """ Overloaded method to handle links ourselves """ if navigation_type == QWebEnginePage.NavigationTypeLinkClicked: self.linkClicked.emit(url) return False return True
python
def acceptNavigationRequest(self, url, navigation_type, isMainFrame): """ Overloaded method to handle links ourselves """ if navigation_type == QWebEnginePage.NavigationTypeLinkClicked: self.linkClicked.emit(url) return False return True
[ "def", "acceptNavigationRequest", "(", "self", ",", "url", ",", "navigation_type", ",", "isMainFrame", ")", ":", "if", "navigation_type", "==", "QWebEnginePage", ".", "NavigationTypeLinkClicked", ":", "self", ".", "linkClicked", ".", "emit", "(", "url", ")", "return", "False", "return", "True" ]
Overloaded method to handle links ourselves
[ "Overloaded", "method", "to", "handle", "links", "ourselves" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L43-L50
train
spyder-ide/spyder
spyder/widgets/browser.py
WebView.find_text
def find_text(self, text, changed=True, forward=True, case=False, words=False, regexp=False): """Find text""" if not WEBENGINE: findflag = QWebEnginePage.FindWrapsAroundDocument else: findflag = 0 if not forward: findflag = findflag | QWebEnginePage.FindBackward if case: findflag = findflag | QWebEnginePage.FindCaseSensitively return self.findText(text, QWebEnginePage.FindFlags(findflag))
python
def find_text(self, text, changed=True, forward=True, case=False, words=False, regexp=False): """Find text""" if not WEBENGINE: findflag = QWebEnginePage.FindWrapsAroundDocument else: findflag = 0 if not forward: findflag = findflag | QWebEnginePage.FindBackward if case: findflag = findflag | QWebEnginePage.FindCaseSensitively return self.findText(text, QWebEnginePage.FindFlags(findflag))
[ "def", "find_text", "(", "self", ",", "text", ",", "changed", "=", "True", ",", "forward", "=", "True", ",", "case", "=", "False", ",", "words", "=", "False", ",", "regexp", "=", "False", ")", ":", "if", "not", "WEBENGINE", ":", "findflag", "=", "QWebEnginePage", ".", "FindWrapsAroundDocument", "else", ":", "findflag", "=", "0", "if", "not", "forward", ":", "findflag", "=", "findflag", "|", "QWebEnginePage", ".", "FindBackward", "if", "case", ":", "findflag", "=", "findflag", "|", "QWebEnginePage", ".", "FindCaseSensitively", "return", "self", ".", "findText", "(", "text", ",", "QWebEnginePage", ".", "FindFlags", "(", "findflag", ")", ")" ]
Find text
[ "Find", "text" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L69-L83
train
spyder-ide/spyder
spyder/widgets/browser.py
WebView.apply_zoom_factor
def apply_zoom_factor(self): """Apply zoom factor""" if hasattr(self, 'setZoomFactor'): # Assuming Qt >=v4.5 self.setZoomFactor(self.zoom_factor) else: # Qt v4.4 self.setTextSizeMultiplier(self.zoom_factor)
python
def apply_zoom_factor(self): """Apply zoom factor""" if hasattr(self, 'setZoomFactor'): # Assuming Qt >=v4.5 self.setZoomFactor(self.zoom_factor) else: # Qt v4.4 self.setTextSizeMultiplier(self.zoom_factor)
[ "def", "apply_zoom_factor", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'setZoomFactor'", ")", ":", "# Assuming Qt >=v4.5\r", "self", ".", "setZoomFactor", "(", "self", ".", "zoom_factor", ")", "else", ":", "# Qt v4.4\r", "self", ".", "setTextSizeMultiplier", "(", "self", ".", "zoom_factor", ")" ]
Apply zoom factor
[ "Apply", "zoom", "factor" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L135-L142
train
spyder-ide/spyder
spyder/widgets/browser.py
WebView.setHtml
def setHtml(self, html, baseUrl=QUrl()): """ Reimplement Qt method to prevent WebEngine to steal focus when setting html on the page Solution taken from https://bugreports.qt.io/browse/QTBUG-52999 """ if WEBENGINE: self.setEnabled(False) super(WebView, self).setHtml(html, baseUrl) self.setEnabled(True) else: super(WebView, self).setHtml(html, baseUrl)
python
def setHtml(self, html, baseUrl=QUrl()): """ Reimplement Qt method to prevent WebEngine to steal focus when setting html on the page Solution taken from https://bugreports.qt.io/browse/QTBUG-52999 """ if WEBENGINE: self.setEnabled(False) super(WebView, self).setHtml(html, baseUrl) self.setEnabled(True) else: super(WebView, self).setHtml(html, baseUrl)
[ "def", "setHtml", "(", "self", ",", "html", ",", "baseUrl", "=", "QUrl", "(", ")", ")", ":", "if", "WEBENGINE", ":", "self", ".", "setEnabled", "(", "False", ")", "super", "(", "WebView", ",", "self", ")", ".", "setHtml", "(", "html", ",", "baseUrl", ")", "self", ".", "setEnabled", "(", "True", ")", "else", ":", "super", "(", "WebView", ",", "self", ")", ".", "setHtml", "(", "html", ",", "baseUrl", ")" ]
Reimplement Qt method to prevent WebEngine to steal focus when setting html on the page Solution taken from https://bugreports.qt.io/browse/QTBUG-52999
[ "Reimplement", "Qt", "method", "to", "prevent", "WebEngine", "to", "steal", "focus", "when", "setting", "html", "on", "the", "page", "Solution", "taken", "from", "https", ":", "//", "bugreports", ".", "qt", ".", "io", "/", "browse", "/", "QTBUG", "-", "52999" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L185-L198
train
spyder-ide/spyder
spyder/widgets/browser.py
WebBrowser.go_to
def go_to(self, url_or_text): """Go to page *address*""" if is_text_string(url_or_text): url = QUrl(url_or_text) else: url = url_or_text self.webview.load(url)
python
def go_to(self, url_or_text): """Go to page *address*""" if is_text_string(url_or_text): url = QUrl(url_or_text) else: url = url_or_text self.webview.load(url)
[ "def", "go_to", "(", "self", ",", "url_or_text", ")", ":", "if", "is_text_string", "(", "url_or_text", ")", ":", "url", "=", "QUrl", "(", "url_or_text", ")", "else", ":", "url", "=", "url_or_text", "self", ".", "webview", ".", "load", "(", "url", ")" ]
Go to page *address*
[ "Go", "to", "page", "*", "address", "*" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L283-L289
train
spyder-ide/spyder
spyder/widgets/browser.py
WebBrowser.url_combo_activated
def url_combo_activated(self, valid): """Load URL from combo box first item""" text = to_text_string(self.url_combo.currentText()) self.go_to(self.text_to_url(text))
python
def url_combo_activated(self, valid): """Load URL from combo box first item""" text = to_text_string(self.url_combo.currentText()) self.go_to(self.text_to_url(text))
[ "def", "url_combo_activated", "(", "self", ",", "valid", ")", ":", "text", "=", "to_text_string", "(", "self", ".", "url_combo", ".", "currentText", "(", ")", ")", "self", ".", "go_to", "(", "self", ".", "text_to_url", "(", "text", ")", ")" ]
Load URL from combo box first item
[ "Load", "URL", "from", "combo", "box", "first", "item" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L301-L304
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.initialize_plugin
def initialize_plugin(self): """ Initialize plugin: connect signals, setup actions, etc. It must be run at the end of __init__ """ self.create_toggle_view_action() self.plugin_actions = self.get_plugin_actions() + [MENU_SEPARATOR, self.undock_action] add_actions(self.options_menu, self.plugin_actions) self.options_button.setMenu(self.options_menu) self.options_menu.aboutToShow.connect(self.refresh_actions) self.sig_show_message.connect(self.show_message) self.sig_update_plugin_title.connect(self.update_plugin_title) self.sig_option_changed.connect(self.set_option) self.setWindowTitle(self.get_plugin_title())
python
def initialize_plugin(self): """ Initialize plugin: connect signals, setup actions, etc. It must be run at the end of __init__ """ self.create_toggle_view_action() self.plugin_actions = self.get_plugin_actions() + [MENU_SEPARATOR, self.undock_action] add_actions(self.options_menu, self.plugin_actions) self.options_button.setMenu(self.options_menu) self.options_menu.aboutToShow.connect(self.refresh_actions) self.sig_show_message.connect(self.show_message) self.sig_update_plugin_title.connect(self.update_plugin_title) self.sig_option_changed.connect(self.set_option) self.setWindowTitle(self.get_plugin_title())
[ "def", "initialize_plugin", "(", "self", ")", ":", "self", ".", "create_toggle_view_action", "(", ")", "self", ".", "plugin_actions", "=", "self", ".", "get_plugin_actions", "(", ")", "+", "[", "MENU_SEPARATOR", ",", "self", ".", "undock_action", "]", "add_actions", "(", "self", ".", "options_menu", ",", "self", ".", "plugin_actions", ")", "self", ".", "options_button", ".", "setMenu", "(", "self", ".", "options_menu", ")", "self", ".", "options_menu", ".", "aboutToShow", ".", "connect", "(", "self", ".", "refresh_actions", ")", "self", ".", "sig_show_message", ".", "connect", "(", "self", ".", "show_message", ")", "self", ".", "sig_update_plugin_title", ".", "connect", "(", "self", ".", "update_plugin_title", ")", "self", ".", "sig_option_changed", ".", "connect", "(", "self", ".", "set_option", ")", "self", ".", "setWindowTitle", "(", "self", ".", "get_plugin_title", "(", ")", ")" ]
Initialize plugin: connect signals, setup actions, etc. It must be run at the end of __init__
[ "Initialize", "plugin", ":", "connect", "signals", "setup", "actions", "etc", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L102-L119
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.register_shortcut
def register_shortcut(self, qaction_or_qshortcut, context, name, add_sc_to_tip=False): """ Register QAction or QShortcut to Spyder main application. if add_sc_to_tip is True, the shortcut is added to the action's tooltip """ self.main.register_shortcut(qaction_or_qshortcut, context, name, add_sc_to_tip)
python
def register_shortcut(self, qaction_or_qshortcut, context, name, add_sc_to_tip=False): """ Register QAction or QShortcut to Spyder main application. if add_sc_to_tip is True, the shortcut is added to the action's tooltip """ self.main.register_shortcut(qaction_or_qshortcut, context, name, add_sc_to_tip)
[ "def", "register_shortcut", "(", "self", ",", "qaction_or_qshortcut", ",", "context", ",", "name", ",", "add_sc_to_tip", "=", "False", ")", ":", "self", ".", "main", ".", "register_shortcut", "(", "qaction_or_qshortcut", ",", "context", ",", "name", ",", "add_sc_to_tip", ")" ]
Register QAction or QShortcut to Spyder main application. if add_sc_to_tip is True, the shortcut is added to the action's tooltip
[ "Register", "QAction", "or", "QShortcut", "to", "Spyder", "main", "application", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L121-L130
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.register_widget_shortcuts
def register_widget_shortcuts(self, widget): """ Register widget shortcuts. Widget interface must have a method called 'get_shortcut_data' """ for qshortcut, context, name in widget.get_shortcut_data(): self.register_shortcut(qshortcut, context, name)
python
def register_widget_shortcuts(self, widget): """ Register widget shortcuts. Widget interface must have a method called 'get_shortcut_data' """ for qshortcut, context, name in widget.get_shortcut_data(): self.register_shortcut(qshortcut, context, name)
[ "def", "register_widget_shortcuts", "(", "self", ",", "widget", ")", ":", "for", "qshortcut", ",", "context", ",", "name", "in", "widget", ".", "get_shortcut_data", "(", ")", ":", "self", ".", "register_shortcut", "(", "qshortcut", ",", "context", ",", "name", ")" ]
Register widget shortcuts. Widget interface must have a method called 'get_shortcut_data'
[ "Register", "widget", "shortcuts", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L132-L139
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.visibility_changed
def visibility_changed(self, enable): """ Dock widget visibility has changed. """ if self.dockwidget is None: return if enable: self.dockwidget.raise_() widget = self.get_focus_widget() if widget is not None and self.undocked_window is not None: widget.setFocus() visible = self.dockwidget.isVisible() or self.ismaximized if self.DISABLE_ACTIONS_WHEN_HIDDEN: toggle_actions(self.plugin_actions, visible) self.isvisible = enable and visible if self.isvisible: self.refresh_plugin()
python
def visibility_changed(self, enable): """ Dock widget visibility has changed. """ if self.dockwidget is None: return if enable: self.dockwidget.raise_() widget = self.get_focus_widget() if widget is not None and self.undocked_window is not None: widget.setFocus() visible = self.dockwidget.isVisible() or self.ismaximized if self.DISABLE_ACTIONS_WHEN_HIDDEN: toggle_actions(self.plugin_actions, visible) self.isvisible = enable and visible if self.isvisible: self.refresh_plugin()
[ "def", "visibility_changed", "(", "self", ",", "enable", ")", ":", "if", "self", ".", "dockwidget", "is", "None", ":", "return", "if", "enable", ":", "self", ".", "dockwidget", ".", "raise_", "(", ")", "widget", "=", "self", ".", "get_focus_widget", "(", ")", "if", "widget", "is", "not", "None", "and", "self", ".", "undocked_window", "is", "not", "None", ":", "widget", ".", "setFocus", "(", ")", "visible", "=", "self", ".", "dockwidget", ".", "isVisible", "(", ")", "or", "self", ".", "ismaximized", "if", "self", ".", "DISABLE_ACTIONS_WHEN_HIDDEN", ":", "toggle_actions", "(", "self", ".", "plugin_actions", ",", "visible", ")", "self", ".", "isvisible", "=", "enable", "and", "visible", "if", "self", ".", "isvisible", ":", "self", ".", "refresh_plugin", "(", ")" ]
Dock widget visibility has changed.
[ "Dock", "widget", "visibility", "has", "changed", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L141-L157
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.set_option
def set_option(self, option, value): """ Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin. """ CONF.set(self.CONF_SECTION, str(option), value)
python
def set_option(self, option, value): """ Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin. """ CONF.set(self.CONF_SECTION, str(option), value)
[ "def", "set_option", "(", "self", ",", "option", ",", "value", ")", ":", "CONF", ".", "set", "(", "self", ".", "CONF_SECTION", ",", "str", "(", "option", ")", ",", "value", ")" ]
Set a plugin option in configuration file. Note: Use sig_option_changed to call it from widgets of the same or another plugin.
[ "Set", "a", "plugin", "option", "in", "configuration", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L159-L166
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.starting_long_process
def starting_long_process(self, message): """ Showing message in main window's status bar. This also changes mouse cursor to Qt.WaitCursor """ self.show_message(message) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents()
python
def starting_long_process(self, message): """ Showing message in main window's status bar. This also changes mouse cursor to Qt.WaitCursor """ self.show_message(message) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents()
[ "def", "starting_long_process", "(", "self", ",", "message", ")", ":", "self", ".", "show_message", "(", "message", ")", "QApplication", ".", "setOverrideCursor", "(", "QCursor", "(", "Qt", ".", "WaitCursor", ")", ")", "QApplication", ".", "processEvents", "(", ")" ]
Showing message in main window's status bar. This also changes mouse cursor to Qt.WaitCursor
[ "Showing", "message", "in", "main", "window", "s", "status", "bar", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L174-L182
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.ending_long_process
def ending_long_process(self, message=""): """ Clear main window's status bar and restore mouse cursor. """ QApplication.restoreOverrideCursor() self.show_message(message, timeout=2000) QApplication.processEvents()
python
def ending_long_process(self, message=""): """ Clear main window's status bar and restore mouse cursor. """ QApplication.restoreOverrideCursor() self.show_message(message, timeout=2000) QApplication.processEvents()
[ "def", "ending_long_process", "(", "self", ",", "message", "=", "\"\"", ")", ":", "QApplication", ".", "restoreOverrideCursor", "(", ")", "self", ".", "show_message", "(", "message", ",", "timeout", "=", "2000", ")", "QApplication", ".", "processEvents", "(", ")" ]
Clear main window's status bar and restore mouse cursor.
[ "Clear", "main", "window", "s", "status", "bar", "and", "restore", "mouse", "cursor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L184-L190
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.show_compatibility_message
def show_compatibility_message(self, message): """ Show compatibility message. """ messageBox = QMessageBox(self) messageBox.setWindowModality(Qt.NonModal) messageBox.setAttribute(Qt.WA_DeleteOnClose) messageBox.setWindowTitle('Compatibility Check') messageBox.setText(message) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.show()
python
def show_compatibility_message(self, message): """ Show compatibility message. """ messageBox = QMessageBox(self) messageBox.setWindowModality(Qt.NonModal) messageBox.setAttribute(Qt.WA_DeleteOnClose) messageBox.setWindowTitle('Compatibility Check') messageBox.setText(message) messageBox.setStandardButtons(QMessageBox.Ok) messageBox.show()
[ "def", "show_compatibility_message", "(", "self", ",", "message", ")", ":", "messageBox", "=", "QMessageBox", "(", "self", ")", "messageBox", ".", "setWindowModality", "(", "Qt", ".", "NonModal", ")", "messageBox", ".", "setAttribute", "(", "Qt", ".", "WA_DeleteOnClose", ")", "messageBox", ".", "setWindowTitle", "(", "'Compatibility Check'", ")", "messageBox", ".", "setText", "(", "message", ")", "messageBox", ".", "setStandardButtons", "(", "QMessageBox", ".", "Ok", ")", "messageBox", ".", "show", "(", ")" ]
Show compatibility message.
[ "Show", "compatibility", "message", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L198-L208
train
spyder-ide/spyder
spyder/api/plugins.py
PluginWidget.refresh_actions
def refresh_actions(self): """ Create options menu. """ self.options_menu.clear() # Decide what additional actions to show if self.undocked_window is None: additional_actions = [MENU_SEPARATOR, self.undock_action, self.close_plugin_action] else: additional_actions = [MENU_SEPARATOR, self.dock_action] # Create actions list self.plugin_actions = self.get_plugin_actions() + additional_actions add_actions(self.options_menu, self.plugin_actions)
python
def refresh_actions(self): """ Create options menu. """ self.options_menu.clear() # Decide what additional actions to show if self.undocked_window is None: additional_actions = [MENU_SEPARATOR, self.undock_action, self.close_plugin_action] else: additional_actions = [MENU_SEPARATOR, self.dock_action] # Create actions list self.plugin_actions = self.get_plugin_actions() + additional_actions add_actions(self.options_menu, self.plugin_actions)
[ "def", "refresh_actions", "(", "self", ")", ":", "self", ".", "options_menu", ".", "clear", "(", ")", "# Decide what additional actions to show", "if", "self", ".", "undocked_window", "is", "None", ":", "additional_actions", "=", "[", "MENU_SEPARATOR", ",", "self", ".", "undock_action", ",", "self", ".", "close_plugin_action", "]", "else", ":", "additional_actions", "=", "[", "MENU_SEPARATOR", ",", "self", ".", "dock_action", "]", "# Create actions list", "self", ".", "plugin_actions", "=", "self", ".", "get_plugin_actions", "(", ")", "+", "additional_actions", "add_actions", "(", "self", ".", "options_menu", ",", "self", ".", "plugin_actions", ")" ]
Create options menu.
[ "Create", "options", "menu", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/plugins.py#L210-L227
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/control.py
ControlWidget._key_paren_left
def _key_paren_left(self, text): """ Action for '(' """ self.current_prompt_pos = self.parentWidget()._prompt_pos if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_object_info(last_obj) self.insert_text(text)
python
def _key_paren_left(self, text): """ Action for '(' """ self.current_prompt_pos = self.parentWidget()._prompt_pos if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.show_object_info(last_obj) self.insert_text(text)
[ "def", "_key_paren_left", "(", "self", ",", "text", ")", ":", "self", ".", "current_prompt_pos", "=", "self", ".", "parentWidget", "(", ")", ".", "_prompt_pos", "if", "self", ".", "get_current_line_to_cursor", "(", ")", ":", "last_obj", "=", "self", ".", "get_last_obj", "(", ")", "if", "last_obj", "and", "not", "last_obj", ".", "isdigit", "(", ")", ":", "self", ".", "show_object_info", "(", "last_obj", ")", "self", ".", "insert_text", "(", "text", ")" ]
Action for '('
[ "Action", "for", "(" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/control.py#L47-L54
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/control.py
ControlWidget.keyPressEvent
def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if key == Qt.Key_ParenLeft and not self.has_selected_text() \ and self.help_enabled and not self.parent()._reading: self._key_paren_left(text) else: # Let the parent widget handle the key press event QTextEdit.keyPressEvent(self, event)
python
def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if key == Qt.Key_ParenLeft and not self.has_selected_text() \ and self.help_enabled and not self.parent()._reading: self._key_paren_left(text) else: # Let the parent widget handle the key press event QTextEdit.keyPressEvent(self, event)
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "event", ",", "text", ",", "key", ",", "ctrl", ",", "shift", "=", "restore_keyevent", "(", "event", ")", "if", "key", "==", "Qt", ".", "Key_ParenLeft", "and", "not", "self", ".", "has_selected_text", "(", ")", "and", "self", ".", "help_enabled", "and", "not", "self", ".", "parent", "(", ")", ".", "_reading", ":", "self", ".", "_key_paren_left", "(", "text", ")", "else", ":", "# Let the parent widget handle the key press event", "QTextEdit", ".", "keyPressEvent", "(", "self", ",", "event", ")" ]
Reimplement Qt Method - Basic keypress event handler
[ "Reimplement", "Qt", "Method", "-", "Basic", "keypress", "event", "handler" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/control.py#L56-L64
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/control.py
ControlWidget.focusInEvent
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ControlWidget, self).focusInEvent(event)
python
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ControlWidget, self).focusInEvent(event)
[ "def", "focusInEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "return", "super", "(", "ControlWidget", ",", "self", ")", ".", "focusInEvent", "(", "event", ")" ]
Reimplement Qt method to send focus change notification
[ "Reimplement", "Qt", "method", "to", "send", "focus", "change", "notification" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/control.py#L66-L69
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/control.py
ControlWidget.focusOutEvent
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ControlWidget, self).focusOutEvent(event)
python
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ControlWidget, self).focusOutEvent(event)
[ "def", "focusOutEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "return", "super", "(", "ControlWidget", ",", "self", ")", ".", "focusOutEvent", "(", "event", ")" ]
Reimplement Qt method to send focus change notification
[ "Reimplement", "Qt", "method", "to", "send", "focus", "change", "notification" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/control.py#L71-L74
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/control.py
PageControlWidget.keyPressEvent
def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if key == Qt.Key_Slash and self.isVisible(): self.show_find_widget.emit()
python
def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if key == Qt.Key_Slash and self.isVisible(): self.show_find_widget.emit()
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "event", ",", "text", ",", "key", ",", "ctrl", ",", "shift", "=", "restore_keyevent", "(", "event", ")", "if", "key", "==", "Qt", ".", "Key_Slash", "and", "self", ".", "isVisible", "(", ")", ":", "self", ".", "show_find_widget", ".", "emit", "(", ")" ]
Reimplement Qt Method - Basic keypress event handler
[ "Reimplement", "Qt", "Method", "-", "Basic", "keypress", "event", "handler" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/control.py#L96-L101
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/control.py
PageControlWidget.focusInEvent
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(PageControlWidget, self).focusInEvent(event)
python
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(PageControlWidget, self).focusInEvent(event)
[ "def", "focusInEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "return", "super", "(", "PageControlWidget", ",", "self", ")", ".", "focusInEvent", "(", "event", ")" ]
Reimplement Qt method to send focus change notification
[ "Reimplement", "Qt", "method", "to", "send", "focus", "change", "notification" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/control.py#L103-L106
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/control.py
PageControlWidget.focusOutEvent
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(PageControlWidget, self).focusOutEvent(event)
python
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(PageControlWidget, self).focusOutEvent(event)
[ "def", "focusOutEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "return", "super", "(", "PageControlWidget", ",", "self", ")", ".", "focusOutEvent", "(", "event", ")" ]
Reimplement Qt method to send focus change notification
[ "Reimplement", "Qt", "method", "to", "send", "focus", "change", "notification" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/control.py#L108-L111
train
spyder-ide/spyder
spyder/widgets/shortcutssummary.py
ShortcutsSummaryDialog.get_screen_resolution
def get_screen_resolution(self): """Return the screen resolution of the primary screen.""" widget = QDesktopWidget() geometry = widget.availableGeometry(widget.primaryScreen()) return geometry.width(), geometry.height()
python
def get_screen_resolution(self): """Return the screen resolution of the primary screen.""" widget = QDesktopWidget() geometry = widget.availableGeometry(widget.primaryScreen()) return geometry.width(), geometry.height()
[ "def", "get_screen_resolution", "(", "self", ")", ":", "widget", "=", "QDesktopWidget", "(", ")", "geometry", "=", "widget", ".", "availableGeometry", "(", "widget", ".", "primaryScreen", "(", ")", ")", "return", "geometry", ".", "width", "(", ")", ",", "geometry", ".", "height", "(", ")" ]
Return the screen resolution of the primary screen.
[ "Return", "the", "screen", "resolution", "of", "the", "primary", "screen", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/shortcutssummary.py#L147-L151
train
spyder-ide/spyder
spyder/plugins/plots/plugin.py
Plots.set_current_widget
def set_current_widget(self, fig_browser): """ Set the currently visible fig_browser in the stack widget, refresh the actions of the cog menu button and move it to the layout of the new fig_browser. """ self.stack.setCurrentWidget(fig_browser) # We update the actions of the options button (cog menu) and # we move it to the layout of the current widget. self.refresh_actions() fig_browser.setup_options_button()
python
def set_current_widget(self, fig_browser): """ Set the currently visible fig_browser in the stack widget, refresh the actions of the cog menu button and move it to the layout of the new fig_browser. """ self.stack.setCurrentWidget(fig_browser) # We update the actions of the options button (cog menu) and # we move it to the layout of the current widget. self.refresh_actions() fig_browser.setup_options_button()
[ "def", "set_current_widget", "(", "self", ",", "fig_browser", ")", ":", "self", ".", "stack", ".", "setCurrentWidget", "(", "fig_browser", ")", "# We update the actions of the options button (cog menu) and", "# we move it to the layout of the current widget.", "self", ".", "refresh_actions", "(", ")", "fig_browser", ".", "setup_options_button", "(", ")" ]
Set the currently visible fig_browser in the stack widget, refresh the actions of the cog menu button and move it to the layout of the new fig_browser.
[ "Set", "the", "currently", "visible", "fig_browser", "in", "the", "stack", "widget", "refresh", "the", "actions", "of", "the", "cog", "menu", "button", "and", "move", "it", "to", "the", "layout", "of", "the", "new", "fig_browser", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/plugin.py#L53-L63
train
spyder-ide/spyder
spyder/plugins/plots/plugin.py
Plots.add_shellwidget
def add_shellwidget(self, shellwidget): """ Register shell with figure explorer. This function opens a new FigureBrowser for browsing the figures in the shell. """ shellwidget_id = id(shellwidget) if shellwidget_id not in self.shellwidgets: self.options_button.setVisible(True) fig_browser = FigureBrowser( self, options_button=self.options_button, background_color=MAIN_BG_COLOR) fig_browser.set_shellwidget(shellwidget) fig_browser.setup(**self.get_settings()) fig_browser.sig_option_changed.connect( self.sig_option_changed.emit) fig_browser.thumbnails_sb.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.register_widget_shortcuts(fig_browser) self.add_widget(fig_browser) self.shellwidgets[shellwidget_id] = fig_browser self.set_shellwidget_from_id(shellwidget_id) return fig_browser
python
def add_shellwidget(self, shellwidget): """ Register shell with figure explorer. This function opens a new FigureBrowser for browsing the figures in the shell. """ shellwidget_id = id(shellwidget) if shellwidget_id not in self.shellwidgets: self.options_button.setVisible(True) fig_browser = FigureBrowser( self, options_button=self.options_button, background_color=MAIN_BG_COLOR) fig_browser.set_shellwidget(shellwidget) fig_browser.setup(**self.get_settings()) fig_browser.sig_option_changed.connect( self.sig_option_changed.emit) fig_browser.thumbnails_sb.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.register_widget_shortcuts(fig_browser) self.add_widget(fig_browser) self.shellwidgets[shellwidget_id] = fig_browser self.set_shellwidget_from_id(shellwidget_id) return fig_browser
[ "def", "add_shellwidget", "(", "self", ",", "shellwidget", ")", ":", "shellwidget_id", "=", "id", "(", "shellwidget", ")", "if", "shellwidget_id", "not", "in", "self", ".", "shellwidgets", ":", "self", ".", "options_button", ".", "setVisible", "(", "True", ")", "fig_browser", "=", "FigureBrowser", "(", "self", ",", "options_button", "=", "self", ".", "options_button", ",", "background_color", "=", "MAIN_BG_COLOR", ")", "fig_browser", ".", "set_shellwidget", "(", "shellwidget", ")", "fig_browser", ".", "setup", "(", "*", "*", "self", ".", "get_settings", "(", ")", ")", "fig_browser", ".", "sig_option_changed", ".", "connect", "(", "self", ".", "sig_option_changed", ".", "emit", ")", "fig_browser", ".", "thumbnails_sb", ".", "redirect_stdio", ".", "connect", "(", "self", ".", "main", ".", "redirect_internalshell_stdio", ")", "self", ".", "register_widget_shortcuts", "(", "fig_browser", ")", "self", ".", "add_widget", "(", "fig_browser", ")", "self", ".", "shellwidgets", "[", "shellwidget_id", "]", "=", "fig_browser", "self", ".", "set_shellwidget_from_id", "(", "shellwidget_id", ")", "return", "fig_browser" ]
Register shell with figure explorer. This function opens a new FigureBrowser for browsing the figures in the shell.
[ "Register", "shell", "with", "figure", "explorer", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/plugin.py#L78-L101
train
spyder-ide/spyder
spyder/plugins/plots/plugin.py
Plots.apply_plugin_settings
def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" for fig_browser in list(self.shellwidgets.values()): fig_browser.setup(**self.get_settings())
python
def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" for fig_browser in list(self.shellwidgets.values()): fig_browser.setup(**self.get_settings())
[ "def", "apply_plugin_settings", "(", "self", ",", "options", ")", ":", "for", "fig_browser", "in", "list", "(", "self", ".", "shellwidgets", ".", "values", "(", ")", ")", ":", "fig_browser", ".", "setup", "(", "*", "*", "self", ".", "get_settings", "(", ")", ")" ]
Apply configuration file's plugin settings
[ "Apply", "configuration", "file", "s", "plugin", "settings" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/plots/plugin.py#L148-L151
train
spyder-ide/spyder
spyder/preferences/layoutdialog.py
LayoutModel.flags
def flags(self, index): """Override Qt method""" if not index.isValid(): return Qt.ItemIsEnabled column = index.column() if column in [0]: return Qt.ItemFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEditable) else: return Qt.ItemFlags(Qt.ItemIsEnabled)
python
def flags(self, index): """Override Qt method""" if not index.isValid(): return Qt.ItemIsEnabled column = index.column() if column in [0]: return Qt.ItemFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEditable) else: return Qt.ItemFlags(Qt.ItemIsEnabled)
[ "def", "flags", "(", "self", ",", "index", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "Qt", ".", "ItemIsEnabled", "column", "=", "index", ".", "column", "(", ")", "if", "column", "in", "[", "0", "]", ":", "return", "Qt", ".", "ItemFlags", "(", "Qt", ".", "ItemIsEnabled", "|", "Qt", ".", "ItemIsSelectable", "|", "Qt", ".", "ItemIsUserCheckable", "|", "Qt", ".", "ItemIsEditable", ")", "else", ":", "return", "Qt", ".", "ItemFlags", "(", "Qt", ".", "ItemIsEnabled", ")" ]
Override Qt method
[ "Override", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/layoutdialog.py#L48-L57
train
spyder-ide/spyder
spyder/preferences/layoutdialog.py
LayoutModel.data
def data(self, index, role=Qt.DisplayRole): """Override Qt method""" if not index.isValid() or not 0 <= index.row() < len(self._rows): return to_qvariant() row = index.row() column = index.column() name, state = self.row(row) if role == Qt.DisplayRole or role == Qt.EditRole: if column == 0: return to_qvariant(name) elif role == Qt.CheckStateRole: if column == 0: if state: return Qt.Checked else: return Qt.Unchecked if column == 1: return to_qvariant(state) return to_qvariant()
python
def data(self, index, role=Qt.DisplayRole): """Override Qt method""" if not index.isValid() or not 0 <= index.row() < len(self._rows): return to_qvariant() row = index.row() column = index.column() name, state = self.row(row) if role == Qt.DisplayRole or role == Qt.EditRole: if column == 0: return to_qvariant(name) elif role == Qt.CheckStateRole: if column == 0: if state: return Qt.Checked else: return Qt.Unchecked if column == 1: return to_qvariant(state) return to_qvariant()
[ "def", "data", "(", "self", ",", "index", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", "or", "not", "0", "<=", "index", ".", "row", "(", ")", "<", "len", "(", "self", ".", "_rows", ")", ":", "return", "to_qvariant", "(", ")", "row", "=", "index", ".", "row", "(", ")", "column", "=", "index", ".", "column", "(", ")", "name", ",", "state", "=", "self", ".", "row", "(", "row", ")", "if", "role", "==", "Qt", ".", "DisplayRole", "or", "role", "==", "Qt", ".", "EditRole", ":", "if", "column", "==", "0", ":", "return", "to_qvariant", "(", "name", ")", "elif", "role", "==", "Qt", ".", "CheckStateRole", ":", "if", "column", "==", "0", ":", "if", "state", ":", "return", "Qt", ".", "Checked", "else", ":", "return", "Qt", ".", "Unchecked", "if", "column", "==", "1", ":", "return", "to_qvariant", "(", "state", ")", "return", "to_qvariant", "(", ")" ]
Override Qt method
[ "Override", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/layoutdialog.py#L59-L79
train
spyder-ide/spyder
spyder/preferences/layoutdialog.py
LayoutModel.setData
def setData(self, index, value, role): """Override Qt method""" row = index.row() name, state = self.row(row) if role == Qt.CheckStateRole: self.set_row(row, [name, not state]) self._parent.setCurrentIndex(index) self._parent.setFocus() self.dataChanged.emit(index, index) return True elif role == Qt.EditRole: self.set_row(row, [from_qvariant(value, to_text_string), state]) self.dataChanged.emit(index, index) return True return True
python
def setData(self, index, value, role): """Override Qt method""" row = index.row() name, state = self.row(row) if role == Qt.CheckStateRole: self.set_row(row, [name, not state]) self._parent.setCurrentIndex(index) self._parent.setFocus() self.dataChanged.emit(index, index) return True elif role == Qt.EditRole: self.set_row(row, [from_qvariant(value, to_text_string), state]) self.dataChanged.emit(index, index) return True return True
[ "def", "setData", "(", "self", ",", "index", ",", "value", ",", "role", ")", ":", "row", "=", "index", ".", "row", "(", ")", "name", ",", "state", "=", "self", ".", "row", "(", "row", ")", "if", "role", "==", "Qt", ".", "CheckStateRole", ":", "self", ".", "set_row", "(", "row", ",", "[", "name", ",", "not", "state", "]", ")", "self", ".", "_parent", ".", "setCurrentIndex", "(", "index", ")", "self", ".", "_parent", ".", "setFocus", "(", ")", "self", ".", "dataChanged", ".", "emit", "(", "index", ",", "index", ")", "return", "True", "elif", "role", "==", "Qt", ".", "EditRole", ":", "self", ".", "set_row", "(", "row", ",", "[", "from_qvariant", "(", "value", ",", "to_text_string", ")", ",", "state", "]", ")", "self", ".", "dataChanged", ".", "emit", "(", "index", ",", "index", ")", "return", "True", "return", "True" ]
Override Qt method
[ "Override", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/layoutdialog.py#L81-L96
train
spyder-ide/spyder
spyder/preferences/layoutdialog.py
LayoutSaveDialog.check_text
def check_text(self, text): """Disable empty layout name possibility""" if to_text_string(text) == u'': self.button_ok.setEnabled(False) else: self.button_ok.setEnabled(True)
python
def check_text(self, text): """Disable empty layout name possibility""" if to_text_string(text) == u'': self.button_ok.setEnabled(False) else: self.button_ok.setEnabled(True)
[ "def", "check_text", "(", "self", ",", "text", ")", ":", "if", "to_text_string", "(", "text", ")", "==", "u''", ":", "self", ".", "button_ok", ".", "setEnabled", "(", "False", ")", "else", ":", "self", ".", "button_ok", ".", "setEnabled", "(", "True", ")" ]
Disable empty layout name possibility
[ "Disable", "empty", "layout", "name", "possibility" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/layoutdialog.py#L156-L161
train
spyder-ide/spyder
spyder/utils/bsdsocket.py
temp_fail_retry
def temp_fail_retry(error, fun, *args): """Retry to execute function, ignoring EINTR error (interruptions)""" while 1: try: return fun(*args) except error as e: eintr = errno.WSAEINTR if os.name == 'nt' else errno.EINTR if e.args[0] == eintr: continue raise
python
def temp_fail_retry(error, fun, *args): """Retry to execute function, ignoring EINTR error (interruptions)""" while 1: try: return fun(*args) except error as e: eintr = errno.WSAEINTR if os.name == 'nt' else errno.EINTR if e.args[0] == eintr: continue raise
[ "def", "temp_fail_retry", "(", "error", ",", "fun", ",", "*", "args", ")", ":", "while", "1", ":", "try", ":", "return", "fun", "(", "*", "args", ")", "except", "error", "as", "e", ":", "eintr", "=", "errno", ".", "WSAEINTR", "if", "os", ".", "name", "==", "'nt'", "else", "errno", ".", "EINTR", "if", "e", ".", "args", "[", "0", "]", "==", "eintr", ":", "continue", "raise" ]
Retry to execute function, ignoring EINTR error (interruptions)
[ "Retry", "to", "execute", "function", "ignoring", "EINTR", "error", "(", "interruptions", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/bsdsocket.py#L27-L36
train
spyder-ide/spyder
spyder/utils/bsdsocket.py
write_packet
def write_packet(sock, data, already_pickled=False): """Write *data* to socket *sock*""" if already_pickled: sent_data = data else: sent_data = pickle.dumps(data, PICKLE_HIGHEST_PROTOCOL) sent_data = struct.pack("l", len(sent_data)) + sent_data nsend = len(sent_data) while nsend > 0: nsend -= temp_fail_retry(socket.error, sock.send, sent_data)
python
def write_packet(sock, data, already_pickled=False): """Write *data* to socket *sock*""" if already_pickled: sent_data = data else: sent_data = pickle.dumps(data, PICKLE_HIGHEST_PROTOCOL) sent_data = struct.pack("l", len(sent_data)) + sent_data nsend = len(sent_data) while nsend > 0: nsend -= temp_fail_retry(socket.error, sock.send, sent_data)
[ "def", "write_packet", "(", "sock", ",", "data", ",", "already_pickled", "=", "False", ")", ":", "if", "already_pickled", ":", "sent_data", "=", "data", "else", ":", "sent_data", "=", "pickle", ".", "dumps", "(", "data", ",", "PICKLE_HIGHEST_PROTOCOL", ")", "sent_data", "=", "struct", ".", "pack", "(", "\"l\"", ",", "len", "(", "sent_data", ")", ")", "+", "sent_data", "nsend", "=", "len", "(", "sent_data", ")", "while", "nsend", ">", "0", ":", "nsend", "-=", "temp_fail_retry", "(", "socket", ".", "error", ",", "sock", ".", "send", ",", "sent_data", ")" ]
Write *data* to socket *sock*
[ "Write", "*", "data", "*", "to", "socket", "*", "sock", "*" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/bsdsocket.py#L42-L51
train
spyder-ide/spyder
spyder/utils/bsdsocket.py
read_packet
def read_packet(sock, timeout=None): """ Read data from socket *sock* Returns None if something went wrong """ sock.settimeout(timeout) dlen, data = None, None try: if os.name == 'nt': # Windows implementation datalen = sock.recv(SZ) dlen, = struct.unpack("l", datalen) data = b'' while len(data) < dlen: data += sock.recv(dlen) else: # Linux/MacOSX implementation # Thanks to eborisch: # See issue 1106 datalen = temp_fail_retry(socket.error, sock.recv, SZ, socket.MSG_WAITALL) if len(datalen) == SZ: dlen, = struct.unpack("l", datalen) data = temp_fail_retry(socket.error, sock.recv, dlen, socket.MSG_WAITALL) except socket.timeout: raise except socket.error: data = None finally: sock.settimeout(None) if data is not None: try: return pickle.loads(data) except Exception: # Catch all exceptions to avoid locking spyder if DEBUG_EDITOR: traceback.print_exc(file=STDERR) return
python
def read_packet(sock, timeout=None): """ Read data from socket *sock* Returns None if something went wrong """ sock.settimeout(timeout) dlen, data = None, None try: if os.name == 'nt': # Windows implementation datalen = sock.recv(SZ) dlen, = struct.unpack("l", datalen) data = b'' while len(data) < dlen: data += sock.recv(dlen) else: # Linux/MacOSX implementation # Thanks to eborisch: # See issue 1106 datalen = temp_fail_retry(socket.error, sock.recv, SZ, socket.MSG_WAITALL) if len(datalen) == SZ: dlen, = struct.unpack("l", datalen) data = temp_fail_retry(socket.error, sock.recv, dlen, socket.MSG_WAITALL) except socket.timeout: raise except socket.error: data = None finally: sock.settimeout(None) if data is not None: try: return pickle.loads(data) except Exception: # Catch all exceptions to avoid locking spyder if DEBUG_EDITOR: traceback.print_exc(file=STDERR) return
[ "def", "read_packet", "(", "sock", ",", "timeout", "=", "None", ")", ":", "sock", ".", "settimeout", "(", "timeout", ")", "dlen", ",", "data", "=", "None", ",", "None", "try", ":", "if", "os", ".", "name", "==", "'nt'", ":", "# Windows implementation\r", "datalen", "=", "sock", ".", "recv", "(", "SZ", ")", "dlen", ",", "=", "struct", ".", "unpack", "(", "\"l\"", ",", "datalen", ")", "data", "=", "b''", "while", "len", "(", "data", ")", "<", "dlen", ":", "data", "+=", "sock", ".", "recv", "(", "dlen", ")", "else", ":", "# Linux/MacOSX implementation\r", "# Thanks to eborisch:\r", "# See issue 1106\r", "datalen", "=", "temp_fail_retry", "(", "socket", ".", "error", ",", "sock", ".", "recv", ",", "SZ", ",", "socket", ".", "MSG_WAITALL", ")", "if", "len", "(", "datalen", ")", "==", "SZ", ":", "dlen", ",", "=", "struct", ".", "unpack", "(", "\"l\"", ",", "datalen", ")", "data", "=", "temp_fail_retry", "(", "socket", ".", "error", ",", "sock", ".", "recv", ",", "dlen", ",", "socket", ".", "MSG_WAITALL", ")", "except", "socket", ".", "timeout", ":", "raise", "except", "socket", ".", "error", ":", "data", "=", "None", "finally", ":", "sock", ".", "settimeout", "(", "None", ")", "if", "data", "is", "not", "None", ":", "try", ":", "return", "pickle", ".", "loads", "(", "data", ")", "except", "Exception", ":", "# Catch all exceptions to avoid locking spyder\r", "if", "DEBUG_EDITOR", ":", "traceback", ".", "print_exc", "(", "file", "=", "STDERR", ")", "return" ]
Read data from socket *sock* Returns None if something went wrong
[ "Read", "data", "from", "socket", "*", "sock", "*", "Returns", "None", "if", "something", "went", "wrong" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/bsdsocket.py#L54-L92
train
spyder-ide/spyder
spyder/utils/bsdsocket.py
communicate
def communicate(sock, command, settings=[]): """Communicate with monitor""" try: COMMUNICATE_LOCK.acquire() write_packet(sock, command) for option in settings: write_packet(sock, option) return read_packet(sock) finally: COMMUNICATE_LOCK.release()
python
def communicate(sock, command, settings=[]): """Communicate with monitor""" try: COMMUNICATE_LOCK.acquire() write_packet(sock, command) for option in settings: write_packet(sock, option) return read_packet(sock) finally: COMMUNICATE_LOCK.release()
[ "def", "communicate", "(", "sock", ",", "command", ",", "settings", "=", "[", "]", ")", ":", "try", ":", "COMMUNICATE_LOCK", ".", "acquire", "(", ")", "write_packet", "(", "sock", ",", "command", ")", "for", "option", "in", "settings", ":", "write_packet", "(", "sock", ",", "option", ")", "return", "read_packet", "(", "sock", ")", "finally", ":", "COMMUNICATE_LOCK", ".", "release", "(", ")" ]
Communicate with monitor
[ "Communicate", "with", "monitor" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/bsdsocket.py#L100-L109
train
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
gettime_s
def gettime_s(text): """ Parse text and return a time in seconds. The text is of the format 0h : 0.min:0.0s:0 ms:0us:0 ns. Spaces are not taken into account and any of the specifiers can be ignored. """ pattern = r'([+-]?\d+\.?\d*) ?([munsecinh]+)' matches = re.findall(pattern, text) if len(matches) == 0: return None time = 0. for res in matches: tmp = float(res[0]) if res[1] == 'ns': tmp *= 1e-9 elif res[1] == 'us': tmp *= 1e-6 elif res[1] == 'ms': tmp *= 1e-3 elif res[1] == 'min': tmp *= 60 elif res[1] == 'h': tmp *= 3600 time += tmp return time
python
def gettime_s(text): """ Parse text and return a time in seconds. The text is of the format 0h : 0.min:0.0s:0 ms:0us:0 ns. Spaces are not taken into account and any of the specifiers can be ignored. """ pattern = r'([+-]?\d+\.?\d*) ?([munsecinh]+)' matches = re.findall(pattern, text) if len(matches) == 0: return None time = 0. for res in matches: tmp = float(res[0]) if res[1] == 'ns': tmp *= 1e-9 elif res[1] == 'us': tmp *= 1e-6 elif res[1] == 'ms': tmp *= 1e-3 elif res[1] == 'min': tmp *= 60 elif res[1] == 'h': tmp *= 3600 time += tmp return time
[ "def", "gettime_s", "(", "text", ")", ":", "pattern", "=", "r'([+-]?\\d+\\.?\\d*) ?([munsecinh]+)'", "matches", "=", "re", ".", "findall", "(", "pattern", ",", "text", ")", "if", "len", "(", "matches", ")", "==", "0", ":", "return", "None", "time", "=", "0.", "for", "res", "in", "matches", ":", "tmp", "=", "float", "(", "res", "[", "0", "]", ")", "if", "res", "[", "1", "]", "==", "'ns'", ":", "tmp", "*=", "1e-9", "elif", "res", "[", "1", "]", "==", "'us'", ":", "tmp", "*=", "1e-6", "elif", "res", "[", "1", "]", "==", "'ms'", ":", "tmp", "*=", "1e-3", "elif", "res", "[", "1", "]", "==", "'min'", ":", "tmp", "*=", "60", "elif", "res", "[", "1", "]", "==", "'h'", ":", "tmp", "*=", "3600", "time", "+=", "tmp", "return", "time" ]
Parse text and return a time in seconds. The text is of the format 0h : 0.min:0.0s:0 ms:0us:0 ns. Spaces are not taken into account and any of the specifiers can be ignored.
[ "Parse", "text", "and", "return", "a", "time", "in", "seconds", ".", "The", "text", "is", "of", "the", "format", "0h", ":", "0", ".", "min", ":", "0", ".", "0s", ":", "0", "ms", ":", "0us", ":", "0", "ns", ".", "Spaces", "are", "not", "taken", "into", "account", "and", "any", "of", "the", "specifiers", "can", "be", "ignored", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L378-L403
train
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
primes
def primes(n): """ Simple test function Taken from http://www.huyng.com/posts/python-performance-analysis/ """ if n==2: return [2] elif n<2: return [] s=list(range(3,n+1,2)) mroot = n ** 0.5 half=(n+1)//2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)//2 s[j]=0 while j<half: s[j]=0 j+=m i=i+1 m=2*i+3 return [2]+[x for x in s if x]
python
def primes(n): """ Simple test function Taken from http://www.huyng.com/posts/python-performance-analysis/ """ if n==2: return [2] elif n<2: return [] s=list(range(3,n+1,2)) mroot = n ** 0.5 half=(n+1)//2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)//2 s[j]=0 while j<half: s[j]=0 j+=m i=i+1 m=2*i+3 return [2]+[x for x in s if x]
[ "def", "primes", "(", "n", ")", ":", "if", "n", "==", "2", ":", "return", "[", "2", "]", "elif", "n", "<", "2", ":", "return", "[", "]", "s", "=", "list", "(", "range", "(", "3", ",", "n", "+", "1", ",", "2", ")", ")", "mroot", "=", "n", "**", "0.5", "half", "=", "(", "n", "+", "1", ")", "//", "2", "-", "1", "i", "=", "0", "m", "=", "3", "while", "m", "<=", "mroot", ":", "if", "s", "[", "i", "]", ":", "j", "=", "(", "m", "*", "m", "-", "3", ")", "//", "2", "s", "[", "j", "]", "=", "0", "while", "j", "<", "half", ":", "s", "[", "j", "]", "=", "0", "j", "+=", "m", "i", "=", "i", "+", "1", "m", "=", "2", "*", "i", "+", "3", "return", "[", "2", "]", "+", "[", "x", "for", "x", "in", "s", "if", "x", "]" ]
Simple test function Taken from http://www.huyng.com/posts/python-performance-analysis/
[ "Simple", "test", "function", "Taken", "from", "http", ":", "//", "www", ".", "huyng", ".", "com", "/", "posts", "/", "python", "-", "performance", "-", "analysis", "/" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L758-L781
train
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerWidget.save_data
def save_data(self): """Save data""" title = _( "Save profiler result") filename, _selfilter = getsavefilename( self, title, getcwd_or_home(), _("Profiler result")+" (*.Result)") if filename: self.datatree.save_data(filename)
python
def save_data(self): """Save data""" title = _( "Save profiler result") filename, _selfilter = getsavefilename( self, title, getcwd_or_home(), _("Profiler result")+" (*.Result)") if filename: self.datatree.save_data(filename)
[ "def", "save_data", "(", "self", ")", ":", "title", "=", "_", "(", "\"Save profiler result\"", ")", "filename", ",", "_selfilter", "=", "getsavefilename", "(", "self", ",", "title", ",", "getcwd_or_home", "(", ")", ",", "_", "(", "\"Profiler result\"", ")", "+", "\" (*.Result)\"", ")", "if", "filename", ":", "self", ".", "datatree", ".", "save_data", "(", "filename", ")" ]
Save data
[ "Save", "data" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L186-L193
train
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.set_item_data
def set_item_data(self, item, filename, line_number): """Set tree item user data: filename (string) and line_number (int)""" set_item_user_text(item, '%s%s%d' % (filename, self.SEP, line_number))
python
def set_item_data(self, item, filename, line_number): """Set tree item user data: filename (string) and line_number (int)""" set_item_user_text(item, '%s%s%d' % (filename, self.SEP, line_number))
[ "def", "set_item_data", "(", "self", ",", "item", ",", "filename", ",", "line_number", ")", ":", "set_item_user_text", "(", "item", ",", "'%s%s%d'", "%", "(", "filename", ",", "self", ".", "SEP", ",", "line_number", ")", ")" ]
Set tree item user data: filename (string) and line_number (int)
[ "Set", "tree", "item", "user", "data", ":", "filename", "(", "string", ")", "and", "line_number", "(", "int", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L468-L470
train
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.get_item_data
def get_item_data(self, item): """Get tree item user data: (filename, line_number)""" filename, line_number_str = get_item_user_text(item).split(self.SEP) return filename, int(line_number_str)
python
def get_item_data(self, item): """Get tree item user data: (filename, line_number)""" filename, line_number_str = get_item_user_text(item).split(self.SEP) return filename, int(line_number_str)
[ "def", "get_item_data", "(", "self", ",", "item", ")", ":", "filename", ",", "line_number_str", "=", "get_item_user_text", "(", "item", ")", ".", "split", "(", "self", ".", "SEP", ")", "return", "filename", ",", "int", "(", "line_number_str", ")" ]
Get tree item user data: (filename, line_number)
[ "Get", "tree", "item", "user", "data", ":", "(", "filename", "line_number", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L472-L475
train
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.initialize_view
def initialize_view(self): """Clean the tree and view parameters""" self.clear() self.item_depth = 0 # To be use for collapsing/expanding one level self.item_list = [] # To be use for collapsing/expanding one level self.items_to_be_shown = {} self.current_view_depth = 0
python
def initialize_view(self): """Clean the tree and view parameters""" self.clear() self.item_depth = 0 # To be use for collapsing/expanding one level self.item_list = [] # To be use for collapsing/expanding one level self.items_to_be_shown = {} self.current_view_depth = 0
[ "def", "initialize_view", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "item_depth", "=", "0", "# To be use for collapsing/expanding one level\r", "self", ".", "item_list", "=", "[", "]", "# To be use for collapsing/expanding one level\r", "self", ".", "items_to_be_shown", "=", "{", "}", "self", ".", "current_view_depth", "=", "0" ]
Clean the tree and view parameters
[ "Clean", "the", "tree", "and", "view", "parameters" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L477-L483
train
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.load_data
def load_data(self, profdatafile): """Load profiler data saved by profile/cProfile module""" import pstats try: stats_indi = [pstats.Stats(profdatafile), ] except (OSError, IOError): return self.profdata = stats_indi[0] if self.compare_file is not None: try: stats_indi.append(pstats.Stats(self.compare_file)) except (OSError, IOError) as e: QMessageBox.critical( self, _("Error"), _("Error when trying to load profiler results")) logger.debug("Error when calling pstats, {}".format(e)) self.compare_file = None map(lambda x: x.calc_callees(), stats_indi) self.profdata.calc_callees() self.stats1 = stats_indi self.stats = stats_indi[0].stats
python
def load_data(self, profdatafile): """Load profiler data saved by profile/cProfile module""" import pstats try: stats_indi = [pstats.Stats(profdatafile), ] except (OSError, IOError): return self.profdata = stats_indi[0] if self.compare_file is not None: try: stats_indi.append(pstats.Stats(self.compare_file)) except (OSError, IOError) as e: QMessageBox.critical( self, _("Error"), _("Error when trying to load profiler results")) logger.debug("Error when calling pstats, {}".format(e)) self.compare_file = None map(lambda x: x.calc_callees(), stats_indi) self.profdata.calc_callees() self.stats1 = stats_indi self.stats = stats_indi[0].stats
[ "def", "load_data", "(", "self", ",", "profdatafile", ")", ":", "import", "pstats", "try", ":", "stats_indi", "=", "[", "pstats", ".", "Stats", "(", "profdatafile", ")", ",", "]", "except", "(", "OSError", ",", "IOError", ")", ":", "return", "self", ".", "profdata", "=", "stats_indi", "[", "0", "]", "if", "self", ".", "compare_file", "is", "not", "None", ":", "try", ":", "stats_indi", ".", "append", "(", "pstats", ".", "Stats", "(", "self", ".", "compare_file", ")", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "QMessageBox", ".", "critical", "(", "self", ",", "_", "(", "\"Error\"", ")", ",", "_", "(", "\"Error when trying to load profiler results\"", ")", ")", "logger", ".", "debug", "(", "\"Error when calling pstats, {}\"", ".", "format", "(", "e", ")", ")", "self", ".", "compare_file", "=", "None", "map", "(", "lambda", "x", ":", "x", ".", "calc_callees", "(", ")", ",", "stats_indi", ")", "self", ".", "profdata", ".", "calc_callees", "(", ")", "self", ".", "stats1", "=", "stats_indi", "self", ".", "stats", "=", "stats_indi", "[", "0", "]", ".", "stats" ]
Load profiler data saved by profile/cProfile module
[ "Load", "profiler", "data", "saved", "by", "profile", "/", "cProfile", "module" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L485-L506
train
spyder-ide/spyder
spyder/plugins/profiler/widgets/profilergui.py
ProfilerDataTree.find_root
def find_root(self): """Find a function without a caller""" self.profdata.sort_stats("cumulative") for func in self.profdata.fcn_list: if ('~', 0) != func[0:2] and not func[2].startswith( '<built-in method exec>'): # This skips the profiler function at the top of the list # it does only occur in Python 3 return func
python
def find_root(self): """Find a function without a caller""" self.profdata.sort_stats("cumulative") for func in self.profdata.fcn_list: if ('~', 0) != func[0:2] and not func[2].startswith( '<built-in method exec>'): # This skips the profiler function at the top of the list # it does only occur in Python 3 return func
[ "def", "find_root", "(", "self", ")", ":", "self", ".", "profdata", ".", "sort_stats", "(", "\"cumulative\"", ")", "for", "func", "in", "self", ".", "profdata", ".", "fcn_list", ":", "if", "(", "'~'", ",", "0", ")", "!=", "func", "[", "0", ":", "2", "]", "and", "not", "func", "[", "2", "]", ".", "startswith", "(", "'<built-in method exec>'", ")", ":", "# This skips the profiler function at the top of the list\r", "# it does only occur in Python 3\r", "return", "func" ]
Find a function without a caller
[ "Find", "a", "function", "without", "a", "caller" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L520-L528
train