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/editor/utils/autosave.py
AutosaveForStack.remove_autosave_file
def remove_autosave_file(self, fileinfo): """ Remove autosave file for specified file. This function also updates `self.autosave_mapping` and clears the `changed_since_autosave` flag. """ filename = fileinfo.filename if filename not in self.name_mapping: return autosave_filename = self.name_mapping[filename] try: os.remove(autosave_filename) except EnvironmentError as error: action = (_('Error while removing autosave file {}') .format(autosave_filename)) msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled() del self.name_mapping[filename] self.stack.sig_option_changed.emit( 'autosave_mapping', self.name_mapping) logger.debug('Removing autosave file %s', autosave_filename)
python
def remove_autosave_file(self, fileinfo): """ Remove autosave file for specified file. This function also updates `self.autosave_mapping` and clears the `changed_since_autosave` flag. """ filename = fileinfo.filename if filename not in self.name_mapping: return autosave_filename = self.name_mapping[filename] try: os.remove(autosave_filename) except EnvironmentError as error: action = (_('Error while removing autosave file {}') .format(autosave_filename)) msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled() del self.name_mapping[filename] self.stack.sig_option_changed.emit( 'autosave_mapping', self.name_mapping) logger.debug('Removing autosave file %s', autosave_filename)
[ "def", "remove_autosave_file", "(", "self", ",", "fileinfo", ")", ":", "filename", "=", "fileinfo", ".", "filename", "if", "filename", "not", "in", "self", ".", "name_mapping", ":", "return", "autosave_filename", "=", "self", ".", "name_mapping", "[", "filename", "]", "try", ":", "os", ".", "remove", "(", "autosave_filename", ")", "except", "EnvironmentError", "as", "error", ":", "action", "=", "(", "_", "(", "'Error while removing autosave file {}'", ")", ".", "format", "(", "autosave_filename", ")", ")", "msgbox", "=", "AutosaveErrorDialog", "(", "action", ",", "error", ")", "msgbox", ".", "exec_if_enabled", "(", ")", "del", "self", ".", "name_mapping", "[", "filename", "]", "self", ".", "stack", ".", "sig_option_changed", ".", "emit", "(", "'autosave_mapping'", ",", "self", ".", "name_mapping", ")", "logger", ".", "debug", "(", "'Removing autosave file %s'", ",", "autosave_filename", ")" ]
Remove autosave file for specified file. This function also updates `self.autosave_mapping` and clears the `changed_since_autosave` flag.
[ "Remove", "autosave", "file", "for", "specified", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L154-L175
train
spyder-ide/spyder
spyder/plugins/editor/utils/autosave.py
AutosaveForStack.get_autosave_filename
def get_autosave_filename(self, filename): """ Get name of autosave file for specified file name. This function uses the dict in `self.name_mapping`. If `filename` is in the mapping, then return the corresponding autosave file name. Otherwise, construct a unique file name and update the mapping. Args: filename (str): original file name """ try: autosave_filename = self.name_mapping[filename] except KeyError: autosave_dir = get_conf_path('autosave') if not osp.isdir(autosave_dir): try: os.mkdir(autosave_dir) except EnvironmentError as error: action = _('Error while creating autosave directory') msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled() autosave_filename = self.create_unique_autosave_filename( filename, autosave_dir) self.name_mapping[filename] = autosave_filename self.stack.sig_option_changed.emit( 'autosave_mapping', self.name_mapping) logger.debug('New autosave file name') return autosave_filename
python
def get_autosave_filename(self, filename): """ Get name of autosave file for specified file name. This function uses the dict in `self.name_mapping`. If `filename` is in the mapping, then return the corresponding autosave file name. Otherwise, construct a unique file name and update the mapping. Args: filename (str): original file name """ try: autosave_filename = self.name_mapping[filename] except KeyError: autosave_dir = get_conf_path('autosave') if not osp.isdir(autosave_dir): try: os.mkdir(autosave_dir) except EnvironmentError as error: action = _('Error while creating autosave directory') msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled() autosave_filename = self.create_unique_autosave_filename( filename, autosave_dir) self.name_mapping[filename] = autosave_filename self.stack.sig_option_changed.emit( 'autosave_mapping', self.name_mapping) logger.debug('New autosave file name') return autosave_filename
[ "def", "get_autosave_filename", "(", "self", ",", "filename", ")", ":", "try", ":", "autosave_filename", "=", "self", ".", "name_mapping", "[", "filename", "]", "except", "KeyError", ":", "autosave_dir", "=", "get_conf_path", "(", "'autosave'", ")", "if", "not", "osp", ".", "isdir", "(", "autosave_dir", ")", ":", "try", ":", "os", ".", "mkdir", "(", "autosave_dir", ")", "except", "EnvironmentError", "as", "error", ":", "action", "=", "_", "(", "'Error while creating autosave directory'", ")", "msgbox", "=", "AutosaveErrorDialog", "(", "action", ",", "error", ")", "msgbox", ".", "exec_if_enabled", "(", ")", "autosave_filename", "=", "self", ".", "create_unique_autosave_filename", "(", "filename", ",", "autosave_dir", ")", "self", ".", "name_mapping", "[", "filename", "]", "=", "autosave_filename", "self", ".", "stack", ".", "sig_option_changed", ".", "emit", "(", "'autosave_mapping'", ",", "self", ".", "name_mapping", ")", "logger", ".", "debug", "(", "'New autosave file name'", ")", "return", "autosave_filename" ]
Get name of autosave file for specified file name. This function uses the dict in `self.name_mapping`. If `filename` is in the mapping, then return the corresponding autosave file name. Otherwise, construct a unique file name and update the mapping. Args: filename (str): original file name
[ "Get", "name", "of", "autosave", "file", "for", "specified", "file", "name", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L177-L205
train
spyder-ide/spyder
spyder/plugins/editor/utils/autosave.py
AutosaveForStack.autosave
def autosave(self, index): """ Autosave a file. Do nothing if the `changed_since_autosave` flag is not set or the file is newly created (and thus not named by the user). Otherwise, save a copy of the file with the name given by `self.get_autosave_filename()` and clear the `changed_since_autosave` flag. Errors raised when saving are silently ignored. Args: index (int): index into self.stack.data """ finfo = self.stack.data[index] document = finfo.editor.document() if not document.changed_since_autosave or finfo.newly_created: return autosave_filename = self.get_autosave_filename(finfo.filename) logger.debug('Autosaving %s to %s', finfo.filename, autosave_filename) try: self.stack._write_to_file(finfo, autosave_filename) document.changed_since_autosave = False except EnvironmentError as error: action = (_('Error while autosaving {} to {}') .format(finfo.filename, autosave_filename)) msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled()
python
def autosave(self, index): """ Autosave a file. Do nothing if the `changed_since_autosave` flag is not set or the file is newly created (and thus not named by the user). Otherwise, save a copy of the file with the name given by `self.get_autosave_filename()` and clear the `changed_since_autosave` flag. Errors raised when saving are silently ignored. Args: index (int): index into self.stack.data """ finfo = self.stack.data[index] document = finfo.editor.document() if not document.changed_since_autosave or finfo.newly_created: return autosave_filename = self.get_autosave_filename(finfo.filename) logger.debug('Autosaving %s to %s', finfo.filename, autosave_filename) try: self.stack._write_to_file(finfo, autosave_filename) document.changed_since_autosave = False except EnvironmentError as error: action = (_('Error while autosaving {} to {}') .format(finfo.filename, autosave_filename)) msgbox = AutosaveErrorDialog(action, error) msgbox.exec_if_enabled()
[ "def", "autosave", "(", "self", ",", "index", ")", ":", "finfo", "=", "self", ".", "stack", ".", "data", "[", "index", "]", "document", "=", "finfo", ".", "editor", ".", "document", "(", ")", "if", "not", "document", ".", "changed_since_autosave", "or", "finfo", ".", "newly_created", ":", "return", "autosave_filename", "=", "self", ".", "get_autosave_filename", "(", "finfo", ".", "filename", ")", "logger", ".", "debug", "(", "'Autosaving %s to %s'", ",", "finfo", ".", "filename", ",", "autosave_filename", ")", "try", ":", "self", ".", "stack", ".", "_write_to_file", "(", "finfo", ",", "autosave_filename", ")", "document", ".", "changed_since_autosave", "=", "False", "except", "EnvironmentError", "as", "error", ":", "action", "=", "(", "_", "(", "'Error while autosaving {} to {}'", ")", ".", "format", "(", "finfo", ".", "filename", ",", "autosave_filename", ")", ")", "msgbox", "=", "AutosaveErrorDialog", "(", "action", ",", "error", ")", "msgbox", ".", "exec_if_enabled", "(", ")" ]
Autosave a file. Do nothing if the `changed_since_autosave` flag is not set or the file is newly created (and thus not named by the user). Otherwise, save a copy of the file with the name given by `self.get_autosave_filename()` and clear the `changed_since_autosave` flag. Errors raised when saving are silently ignored. Args: index (int): index into self.stack.data
[ "Autosave", "a", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L207-L233
train
spyder-ide/spyder
spyder/plugins/editor/utils/autosave.py
AutosaveForStack.autosave_all
def autosave_all(self): """Autosave all opened files.""" for index in range(self.stack.get_stack_count()): self.autosave(index)
python
def autosave_all(self): """Autosave all opened files.""" for index in range(self.stack.get_stack_count()): self.autosave(index)
[ "def", "autosave_all", "(", "self", ")", ":", "for", "index", "in", "range", "(", "self", ".", "stack", ".", "get_stack_count", "(", ")", ")", ":", "self", ".", "autosave", "(", "index", ")" ]
Autosave all opened files.
[ "Autosave", "all", "opened", "files", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L235-L238
train
spyder-ide/spyder
spyder/utils/fixtures.py
tmpconfig
def tmpconfig(request): """ Fixtures that returns a temporary CONF element. """ SUBFOLDER = tempfile.mkdtemp() CONF = UserConfig('spyder-test', defaults=DEFAULTS, version=CONF_VERSION, subfolder=SUBFOLDER, raw_mode=True, ) def fin(): """ Fixture finalizer to delete the temporary CONF element. """ shutil.rmtree(SUBFOLDER) request.addfinalizer(fin) return CONF
python
def tmpconfig(request): """ Fixtures that returns a temporary CONF element. """ SUBFOLDER = tempfile.mkdtemp() CONF = UserConfig('spyder-test', defaults=DEFAULTS, version=CONF_VERSION, subfolder=SUBFOLDER, raw_mode=True, ) def fin(): """ Fixture finalizer to delete the temporary CONF element. """ shutil.rmtree(SUBFOLDER) request.addfinalizer(fin) return CONF
[ "def", "tmpconfig", "(", "request", ")", ":", "SUBFOLDER", "=", "tempfile", ".", "mkdtemp", "(", ")", "CONF", "=", "UserConfig", "(", "'spyder-test'", ",", "defaults", "=", "DEFAULTS", ",", "version", "=", "CONF_VERSION", ",", "subfolder", "=", "SUBFOLDER", ",", "raw_mode", "=", "True", ",", ")", "def", "fin", "(", ")", ":", "\"\"\"\n Fixture finalizer to delete the temporary CONF element.\n \"\"\"", "shutil", ".", "rmtree", "(", "SUBFOLDER", ")", "request", ".", "addfinalizer", "(", "fin", ")", "return", "CONF" ]
Fixtures that returns a temporary CONF element.
[ "Fixtures", "that", "returns", "a", "temporary", "CONF", "element", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/fixtures.py#L27-L46
train
spyder-ide/spyder
spyder/utils/debug.py
log_last_error
def log_last_error(fname, context=None): """Log last error in filename *fname* -- *context*: string (optional)""" fd = open(fname, 'a') log_time(fd) if context: print("Context", file=fd) print("-------", file=fd) print("", file=fd) if PY2: print(u' '.join(context).encode('utf-8').strip(), file=fd) else: print(context, file=fd) print("", file=fd) print("Traceback", file=fd) print("---------", file=fd) print("", file=fd) traceback.print_exc(file=fd) print("", file=fd) print("", file=fd)
python
def log_last_error(fname, context=None): """Log last error in filename *fname* -- *context*: string (optional)""" fd = open(fname, 'a') log_time(fd) if context: print("Context", file=fd) print("-------", file=fd) print("", file=fd) if PY2: print(u' '.join(context).encode('utf-8').strip(), file=fd) else: print(context, file=fd) print("", file=fd) print("Traceback", file=fd) print("---------", file=fd) print("", file=fd) traceback.print_exc(file=fd) print("", file=fd) print("", file=fd)
[ "def", "log_last_error", "(", "fname", ",", "context", "=", "None", ")", ":", "fd", "=", "open", "(", "fname", ",", "'a'", ")", "log_time", "(", "fd", ")", "if", "context", ":", "print", "(", "\"Context\"", ",", "file", "=", "fd", ")", "print", "(", "\"-------\"", ",", "file", "=", "fd", ")", "print", "(", "\"\"", ",", "file", "=", "fd", ")", "if", "PY2", ":", "print", "(", "u' '", ".", "join", "(", "context", ")", ".", "encode", "(", "'utf-8'", ")", ".", "strip", "(", ")", ",", "file", "=", "fd", ")", "else", ":", "print", "(", "context", ",", "file", "=", "fd", ")", "print", "(", "\"\"", ",", "file", "=", "fd", ")", "print", "(", "\"Traceback\"", ",", "file", "=", "fd", ")", "print", "(", "\"---------\"", ",", "file", "=", "fd", ")", "print", "(", "\"\"", ",", "file", "=", "fd", ")", "traceback", ".", "print_exc", "(", "file", "=", "fd", ")", "print", "(", "\"\"", ",", "file", "=", "fd", ")", "print", "(", "\"\"", ",", "file", "=", "fd", ")" ]
Log last error in filename *fname* -- *context*: string (optional)
[ "Log", "last", "error", "in", "filename", "*", "fname", "*", "--", "*", "context", "*", ":", "string", "(", "optional", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/debug.py#L30-L48
train
spyder-ide/spyder
spyder/utils/debug.py
log_methods_calls
def log_methods_calls(fname, some_class, prefix=None): """ Hack `some_class` to log all method calls into `fname` file. If `prefix` format is not set, each log entry is prefixed with: --[ asked / called / defined ] -- asked - name of `some_class` called - name of class for which a method is called defined - name of class where method is defined Must be used carefully, because it monkeypatches __getattribute__ call. Example: log_methods_calls('log.log', ShellBaseWidget) """ # test if file is writable open(fname, 'a').close() FILENAME = fname CLASS = some_class PREFIX = "--[ %(asked)s / %(called)s / %(defined)s ]--" if prefix != None: PREFIX = prefix MAXWIDTH = {'o_O': 10} # hack with editable closure dict, to align names def format_prefix(method, methodobj): """ --[ ShellBase / Internal / BaseEdit ]------- get_position """ classnames = { 'asked': CLASS.__name__, 'called': methodobj.__class__.__name__, 'defined': get_class_that_defined(method) } line = PREFIX % classnames MAXWIDTH['o_O'] = max(len(line), MAXWIDTH['o_O']) return line.ljust(MAXWIDTH['o_O'], '-') import types def __getattribute__(self, name): attr = object.__getattribute__(self, name) if type(attr) is not types.MethodType: return attr else: def newfunc(*args, **kwargs): log = open(FILENAME, 'a') prefix = format_prefix(attr, self) log.write('%s %s\n' % (prefix, name)) log.close() result = attr(*args, **kwargs) return result return newfunc some_class.__getattribute__ = __getattribute__
python
def log_methods_calls(fname, some_class, prefix=None): """ Hack `some_class` to log all method calls into `fname` file. If `prefix` format is not set, each log entry is prefixed with: --[ asked / called / defined ] -- asked - name of `some_class` called - name of class for which a method is called defined - name of class where method is defined Must be used carefully, because it monkeypatches __getattribute__ call. Example: log_methods_calls('log.log', ShellBaseWidget) """ # test if file is writable open(fname, 'a').close() FILENAME = fname CLASS = some_class PREFIX = "--[ %(asked)s / %(called)s / %(defined)s ]--" if prefix != None: PREFIX = prefix MAXWIDTH = {'o_O': 10} # hack with editable closure dict, to align names def format_prefix(method, methodobj): """ --[ ShellBase / Internal / BaseEdit ]------- get_position """ classnames = { 'asked': CLASS.__name__, 'called': methodobj.__class__.__name__, 'defined': get_class_that_defined(method) } line = PREFIX % classnames MAXWIDTH['o_O'] = max(len(line), MAXWIDTH['o_O']) return line.ljust(MAXWIDTH['o_O'], '-') import types def __getattribute__(self, name): attr = object.__getattribute__(self, name) if type(attr) is not types.MethodType: return attr else: def newfunc(*args, **kwargs): log = open(FILENAME, 'a') prefix = format_prefix(attr, self) log.write('%s %s\n' % (prefix, name)) log.close() result = attr(*args, **kwargs) return result return newfunc some_class.__getattribute__ = __getattribute__
[ "def", "log_methods_calls", "(", "fname", ",", "some_class", ",", "prefix", "=", "None", ")", ":", "# test if file is writable\r", "open", "(", "fname", ",", "'a'", ")", ".", "close", "(", ")", "FILENAME", "=", "fname", "CLASS", "=", "some_class", "PREFIX", "=", "\"--[ %(asked)s / %(called)s / %(defined)s ]--\"", "if", "prefix", "!=", "None", ":", "PREFIX", "=", "prefix", "MAXWIDTH", "=", "{", "'o_O'", ":", "10", "}", "# hack with editable closure dict, to align names\r", "def", "format_prefix", "(", "method", ",", "methodobj", ")", ":", "\"\"\"\r\n --[ ShellBase / Internal / BaseEdit ]------- get_position\r\n \"\"\"", "classnames", "=", "{", "'asked'", ":", "CLASS", ".", "__name__", ",", "'called'", ":", "methodobj", ".", "__class__", ".", "__name__", ",", "'defined'", ":", "get_class_that_defined", "(", "method", ")", "}", "line", "=", "PREFIX", "%", "classnames", "MAXWIDTH", "[", "'o_O'", "]", "=", "max", "(", "len", "(", "line", ")", ",", "MAXWIDTH", "[", "'o_O'", "]", ")", "return", "line", ".", "ljust", "(", "MAXWIDTH", "[", "'o_O'", "]", ",", "'-'", ")", "import", "types", "def", "__getattribute__", "(", "self", ",", "name", ")", ":", "attr", "=", "object", ".", "__getattribute__", "(", "self", ",", "name", ")", "if", "type", "(", "attr", ")", "is", "not", "types", ".", "MethodType", ":", "return", "attr", "else", ":", "def", "newfunc", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log", "=", "open", "(", "FILENAME", ",", "'a'", ")", "prefix", "=", "format_prefix", "(", "attr", ",", "self", ")", "log", ".", "write", "(", "'%s %s\\n'", "%", "(", "prefix", ",", "name", ")", ")", "log", ".", "close", "(", ")", "result", "=", "attr", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "result", "return", "newfunc", "some_class", ".", "__getattribute__", "=", "__getattribute__" ]
Hack `some_class` to log all method calls into `fname` file. If `prefix` format is not set, each log entry is prefixed with: --[ asked / called / defined ] -- asked - name of `some_class` called - name of class for which a method is called defined - name of class where method is defined Must be used carefully, because it monkeypatches __getattribute__ call. Example: log_methods_calls('log.log', ShellBaseWidget)
[ "Hack", "some_class", "to", "log", "all", "method", "calls", "into", "fname", "file", ".", "If", "prefix", "format", "is", "not", "set", "each", "log", "entry", "is", "prefixed", "with", ":", "--", "[", "asked", "/", "called", "/", "defined", "]", "--", "asked", "-", "name", "of", "some_class", "called", "-", "name", "of", "class", "for", "which", "a", "method", "is", "called", "defined", "-", "name", "of", "class", "where", "method", "is", "defined", "Must", "be", "used", "carefully", "because", "it", "monkeypatches", "__getattribute__", "call", ".", "Example", ":", "log_methods_calls", "(", "log", ".", "log", "ShellBaseWidget", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/debug.py#L95-L146
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.offset
def offset(self): """This property holds the vertical offset of the scroll flag area relative to the top of the text editor.""" vsb = self.editor.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in which the slider handle may move. groove_rect = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self) return groove_rect.y()
python
def offset(self): """This property holds the vertical offset of the scroll flag area relative to the top of the text editor.""" vsb = self.editor.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in which the slider handle may move. groove_rect = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self) return groove_rect.y()
[ "def", "offset", "(", "self", ")", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "style", "=", "vsb", ".", "style", "(", ")", "opt", "=", "QStyleOptionSlider", "(", ")", "vsb", ".", "initStyleOption", "(", "opt", ")", "# Get the area in which the slider handle may move.", "groove_rect", "=", "style", ".", "subControlRect", "(", "QStyle", ".", "CC_ScrollBar", ",", "opt", ",", "QStyle", ".", "SC_ScrollBarGroove", ",", "self", ")", "return", "groove_rect", ".", "y", "(", ")" ]
This property holds the vertical offset of the scroll flag area relative to the top of the text editor.
[ "This", "property", "holds", "the", "vertical", "offset", "of", "the", "scroll", "flag", "area", "relative", "to", "the", "top", "of", "the", "text", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L49-L61
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.paintEvent
def paintEvent(self, event): """ Override Qt method. Painting the scroll flag area """ make_flag = self.make_flag_qrect # Fill the whole painting area painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) # Paint warnings and todos block = self.editor.document().firstBlock() for line_number in range(self.editor.document().blockCount()+1): data = block.userData() if data: if data.code_analysis: # Paint the warnings color = self.editor.warning_color for source, code, severity, message in data.code_analysis: error = severity == DiagnosticSeverity.ERROR if error: color = self.editor.error_color break self.set_painter(painter, color) painter.drawRect(make_flag(line_number)) if data.todo: # Paint the todos self.set_painter(painter, self.editor.todo_color) painter.drawRect(make_flag(line_number)) if data.breakpoint: # Paint the breakpoints self.set_painter(painter, self.editor.breakpoint_color) painter.drawRect(make_flag(line_number)) block = block.next() # Paint the occurrences if self.editor.occurrences: self.set_painter(painter, self.editor.occurrence_color) for line_number in self.editor.occurrences: painter.drawRect(make_flag(line_number)) # Paint the found results if self.editor.found_results: self.set_painter(painter, self.editor.found_results_color) for line_number in self.editor.found_results: painter.drawRect(make_flag(line_number)) # Paint the slider range if not self._unit_testing: alt = QApplication.queryKeyboardModifiers() & Qt.AltModifier else: alt = self._alt_key_is_down cursor_pos = self.mapFromGlobal(QCursor().pos()) is_over_self = self.rect().contains(cursor_pos) is_over_editor = self.editor.rect().contains( self.editor.mapFromGlobal(QCursor().pos())) # We use QRect.contains instead of QWidget.underMouse method to # determined if the cursor is over the editor or the flag scrollbar # because the later gives a wrong result when a mouse button # is pressed. if ((is_over_self or (alt and is_over_editor)) and self.slider): pen_color = QColor(Qt.gray) pen_color.setAlphaF(.85) painter.setPen(pen_color) brush_color = QColor(Qt.gray) brush_color.setAlphaF(.5) painter.setBrush(QBrush(brush_color)) painter.drawRect(self.make_slider_range(cursor_pos)) self._range_indicator_is_visible = True else: self._range_indicator_is_visible = False
python
def paintEvent(self, event): """ Override Qt method. Painting the scroll flag area """ make_flag = self.make_flag_qrect # Fill the whole painting area painter = QPainter(self) painter.fillRect(event.rect(), self.editor.sideareas_color) # Paint warnings and todos block = self.editor.document().firstBlock() for line_number in range(self.editor.document().blockCount()+1): data = block.userData() if data: if data.code_analysis: # Paint the warnings color = self.editor.warning_color for source, code, severity, message in data.code_analysis: error = severity == DiagnosticSeverity.ERROR if error: color = self.editor.error_color break self.set_painter(painter, color) painter.drawRect(make_flag(line_number)) if data.todo: # Paint the todos self.set_painter(painter, self.editor.todo_color) painter.drawRect(make_flag(line_number)) if data.breakpoint: # Paint the breakpoints self.set_painter(painter, self.editor.breakpoint_color) painter.drawRect(make_flag(line_number)) block = block.next() # Paint the occurrences if self.editor.occurrences: self.set_painter(painter, self.editor.occurrence_color) for line_number in self.editor.occurrences: painter.drawRect(make_flag(line_number)) # Paint the found results if self.editor.found_results: self.set_painter(painter, self.editor.found_results_color) for line_number in self.editor.found_results: painter.drawRect(make_flag(line_number)) # Paint the slider range if not self._unit_testing: alt = QApplication.queryKeyboardModifiers() & Qt.AltModifier else: alt = self._alt_key_is_down cursor_pos = self.mapFromGlobal(QCursor().pos()) is_over_self = self.rect().contains(cursor_pos) is_over_editor = self.editor.rect().contains( self.editor.mapFromGlobal(QCursor().pos())) # We use QRect.contains instead of QWidget.underMouse method to # determined if the cursor is over the editor or the flag scrollbar # because the later gives a wrong result when a mouse button # is pressed. if ((is_over_self or (alt and is_over_editor)) and self.slider): pen_color = QColor(Qt.gray) pen_color.setAlphaF(.85) painter.setPen(pen_color) brush_color = QColor(Qt.gray) brush_color.setAlphaF(.5) painter.setBrush(QBrush(brush_color)) painter.drawRect(self.make_slider_range(cursor_pos)) self._range_indicator_is_visible = True else: self._range_indicator_is_visible = False
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "make_flag", "=", "self", ".", "make_flag_qrect", "# Fill the whole painting area", "painter", "=", "QPainter", "(", "self", ")", "painter", ".", "fillRect", "(", "event", ".", "rect", "(", ")", ",", "self", ".", "editor", ".", "sideareas_color", ")", "# Paint warnings and todos", "block", "=", "self", ".", "editor", ".", "document", "(", ")", ".", "firstBlock", "(", ")", "for", "line_number", "in", "range", "(", "self", ".", "editor", ".", "document", "(", ")", ".", "blockCount", "(", ")", "+", "1", ")", ":", "data", "=", "block", ".", "userData", "(", ")", "if", "data", ":", "if", "data", ".", "code_analysis", ":", "# Paint the warnings", "color", "=", "self", ".", "editor", ".", "warning_color", "for", "source", ",", "code", ",", "severity", ",", "message", "in", "data", ".", "code_analysis", ":", "error", "=", "severity", "==", "DiagnosticSeverity", ".", "ERROR", "if", "error", ":", "color", "=", "self", ".", "editor", ".", "error_color", "break", "self", ".", "set_painter", "(", "painter", ",", "color", ")", "painter", ".", "drawRect", "(", "make_flag", "(", "line_number", ")", ")", "if", "data", ".", "todo", ":", "# Paint the todos", "self", ".", "set_painter", "(", "painter", ",", "self", ".", "editor", ".", "todo_color", ")", "painter", ".", "drawRect", "(", "make_flag", "(", "line_number", ")", ")", "if", "data", ".", "breakpoint", ":", "# Paint the breakpoints", "self", ".", "set_painter", "(", "painter", ",", "self", ".", "editor", ".", "breakpoint_color", ")", "painter", ".", "drawRect", "(", "make_flag", "(", "line_number", ")", ")", "block", "=", "block", ".", "next", "(", ")", "# Paint the occurrences", "if", "self", ".", "editor", ".", "occurrences", ":", "self", ".", "set_painter", "(", "painter", ",", "self", ".", "editor", ".", "occurrence_color", ")", "for", "line_number", "in", "self", ".", "editor", ".", "occurrences", ":", "painter", ".", "drawRect", "(", "make_flag", "(", "line_number", ")", ")", "# Paint the found results", "if", "self", ".", "editor", ".", "found_results", ":", "self", ".", "set_painter", "(", "painter", ",", "self", ".", "editor", ".", "found_results_color", ")", "for", "line_number", "in", "self", ".", "editor", ".", "found_results", ":", "painter", ".", "drawRect", "(", "make_flag", "(", "line_number", ")", ")", "# Paint the slider range", "if", "not", "self", ".", "_unit_testing", ":", "alt", "=", "QApplication", ".", "queryKeyboardModifiers", "(", ")", "&", "Qt", ".", "AltModifier", "else", ":", "alt", "=", "self", ".", "_alt_key_is_down", "cursor_pos", "=", "self", ".", "mapFromGlobal", "(", "QCursor", "(", ")", ".", "pos", "(", ")", ")", "is_over_self", "=", "self", ".", "rect", "(", ")", ".", "contains", "(", "cursor_pos", ")", "is_over_editor", "=", "self", ".", "editor", ".", "rect", "(", ")", ".", "contains", "(", "self", ".", "editor", ".", "mapFromGlobal", "(", "QCursor", "(", ")", ".", "pos", "(", ")", ")", ")", "# We use QRect.contains instead of QWidget.underMouse method to", "# determined if the cursor is over the editor or the flag scrollbar", "# because the later gives a wrong result when a mouse button", "# is pressed.", "if", "(", "(", "is_over_self", "or", "(", "alt", "and", "is_over_editor", ")", ")", "and", "self", ".", "slider", ")", ":", "pen_color", "=", "QColor", "(", "Qt", ".", "gray", ")", "pen_color", ".", "setAlphaF", "(", ".85", ")", "painter", ".", "setPen", "(", "pen_color", ")", "brush_color", "=", "QColor", "(", "Qt", ".", "gray", ")", "brush_color", ".", "setAlphaF", "(", ".5", ")", "painter", ".", "setBrush", "(", "QBrush", "(", "brush_color", ")", ")", "painter", ".", "drawRect", "(", "self", ".", "make_slider_range", "(", "cursor_pos", ")", ")", "self", ".", "_range_indicator_is_visible", "=", "True", "else", ":", "self", ".", "_range_indicator_is_visible", "=", "False" ]
Override Qt method. Painting the scroll flag area
[ "Override", "Qt", "method", ".", "Painting", "the", "scroll", "flag", "area" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L67-L138
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.mousePressEvent
def mousePressEvent(self, event): """Override Qt method""" if self.slider and event.button() == Qt.LeftButton: vsb = self.editor.verticalScrollBar() value = self.position_to_value(event.pos().y()) vsb.setValue(value-vsb.pageStep()/2)
python
def mousePressEvent(self, event): """Override Qt method""" if self.slider and event.button() == Qt.LeftButton: vsb = self.editor.verticalScrollBar() value = self.position_to_value(event.pos().y()) vsb.setValue(value-vsb.pageStep()/2)
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "slider", "and", "event", ".", "button", "(", ")", "==", "Qt", ".", "LeftButton", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "value", "=", "self", ".", "position_to_value", "(", "event", ".", "pos", "(", ")", ".", "y", "(", ")", ")", "vsb", ".", "setValue", "(", "value", "-", "vsb", ".", "pageStep", "(", ")", "/", "2", ")" ]
Override Qt method
[ "Override", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L152-L157
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.keyReleaseEvent
def keyReleaseEvent(self, event): """Override Qt method.""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = False self.update()
python
def keyReleaseEvent(self, event): """Override Qt method.""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = False self.update()
[ "def", "keyReleaseEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_Alt", ":", "self", ".", "_alt_key_is_down", "=", "False", "self", ".", "update", "(", ")" ]
Override Qt method.
[ "Override", "Qt", "method", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L159-L163
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.keyPressEvent
def keyPressEvent(self, event): """Override Qt method""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = True self.update()
python
def keyPressEvent(self, event): """Override Qt method""" if event.key() == Qt.Key_Alt: self._alt_key_is_down = True self.update()
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_Alt", ":", "self", ".", "_alt_key_is_down", "=", "True", "self", ".", "update", "(", ")" ]
Override Qt method
[ "Override", "Qt", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L165-L169
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.get_scrollbar_position_height
def get_scrollbar_position_height(self): """Return the pixel span height of the scrollbar area in which the slider handle may move""" vsb = self.editor.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in which the slider handle may move. groove_rect = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self) return float(groove_rect.height())
python
def get_scrollbar_position_height(self): """Return the pixel span height of the scrollbar area in which the slider handle may move""" vsb = self.editor.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in which the slider handle may move. groove_rect = style.subControlRect( QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarGroove, self) return float(groove_rect.height())
[ "def", "get_scrollbar_position_height", "(", "self", ")", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "style", "=", "vsb", ".", "style", "(", ")", "opt", "=", "QStyleOptionSlider", "(", ")", "vsb", ".", "initStyleOption", "(", "opt", ")", "# Get the area in which the slider handle may move.", "groove_rect", "=", "style", ".", "subControlRect", "(", "QStyle", ".", "CC_ScrollBar", ",", "opt", ",", "QStyle", ".", "SC_ScrollBarGroove", ",", "self", ")", "return", "float", "(", "groove_rect", ".", "height", "(", ")", ")" ]
Return the pixel span height of the scrollbar area in which the slider handle may move
[ "Return", "the", "pixel", "span", "height", "of", "the", "scrollbar", "area", "in", "which", "the", "slider", "handle", "may", "move" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L171-L183
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.get_scrollbar_value_height
def get_scrollbar_value_height(self): """Return the value span height of the scrollbar""" vsb = self.editor.verticalScrollBar() return vsb.maximum()-vsb.minimum()+vsb.pageStep()
python
def get_scrollbar_value_height(self): """Return the value span height of the scrollbar""" vsb = self.editor.verticalScrollBar() return vsb.maximum()-vsb.minimum()+vsb.pageStep()
[ "def", "get_scrollbar_value_height", "(", "self", ")", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "return", "vsb", ".", "maximum", "(", ")", "-", "vsb", ".", "minimum", "(", ")", "+", "vsb", ".", "pageStep", "(", ")" ]
Return the value span height of the scrollbar
[ "Return", "the", "value", "span", "height", "of", "the", "scrollbar" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L185-L188
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.value_to_position
def value_to_position(self, y): """Convert value to position in pixels""" vsb = self.editor.verticalScrollBar() return (y-vsb.minimum())*self.get_scale_factor()+self.offset
python
def value_to_position(self, y): """Convert value to position in pixels""" vsb = self.editor.verticalScrollBar() return (y-vsb.minimum())*self.get_scale_factor()+self.offset
[ "def", "value_to_position", "(", "self", ",", "y", ")", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "return", "(", "y", "-", "vsb", ".", "minimum", "(", ")", ")", "*", "self", ".", "get_scale_factor", "(", ")", "+", "self", ".", "offset" ]
Convert value to position in pixels
[ "Convert", "value", "to", "position", "in", "pixels" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L196-L199
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.position_to_value
def position_to_value(self, y): """Convert position in pixels to value""" vsb = self.editor.verticalScrollBar() return vsb.minimum()+max([0, (y-self.offset)/self.get_scale_factor()])
python
def position_to_value(self, y): """Convert position in pixels to value""" vsb = self.editor.verticalScrollBar() return vsb.minimum()+max([0, (y-self.offset)/self.get_scale_factor()])
[ "def", "position_to_value", "(", "self", ",", "y", ")", ":", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "return", "vsb", ".", "minimum", "(", ")", "+", "max", "(", "[", "0", ",", "(", "y", "-", "self", ".", "offset", ")", "/", "self", ".", "get_scale_factor", "(", ")", "]", ")" ]
Convert position in pixels to value
[ "Convert", "position", "in", "pixels", "to", "value" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L201-L204
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.make_flag_qrect
def make_flag_qrect(self, value): """Make flag QRect""" if self.slider: position = self.value_to_position(value+0.5) # The 0.5 offset is used to align the flags with the center of # their corresponding text edit block before scaling. return QRect(self.FLAGS_DX/2, position-self.FLAGS_DY/2, self.WIDTH-self.FLAGS_DX, self.FLAGS_DY) else: # When the vertical scrollbar is not visible, the flags are # vertically aligned with the center of their corresponding # text block with no scaling. block = self.editor.document().findBlockByLineNumber(value) top = self.editor.blockBoundingGeometry(block).translated( self.editor.contentOffset()).top() bottom = top + self.editor.blockBoundingRect(block).height() middle = (top + bottom)/2 return QRect(self.FLAGS_DX/2, middle-self.FLAGS_DY/2, self.WIDTH-self.FLAGS_DX, self.FLAGS_DY)
python
def make_flag_qrect(self, value): """Make flag QRect""" if self.slider: position = self.value_to_position(value+0.5) # The 0.5 offset is used to align the flags with the center of # their corresponding text edit block before scaling. return QRect(self.FLAGS_DX/2, position-self.FLAGS_DY/2, self.WIDTH-self.FLAGS_DX, self.FLAGS_DY) else: # When the vertical scrollbar is not visible, the flags are # vertically aligned with the center of their corresponding # text block with no scaling. block = self.editor.document().findBlockByLineNumber(value) top = self.editor.blockBoundingGeometry(block).translated( self.editor.contentOffset()).top() bottom = top + self.editor.blockBoundingRect(block).height() middle = (top + bottom)/2 return QRect(self.FLAGS_DX/2, middle-self.FLAGS_DY/2, self.WIDTH-self.FLAGS_DX, self.FLAGS_DY)
[ "def", "make_flag_qrect", "(", "self", ",", "value", ")", ":", "if", "self", ".", "slider", ":", "position", "=", "self", ".", "value_to_position", "(", "value", "+", "0.5", ")", "# The 0.5 offset is used to align the flags with the center of", "# their corresponding text edit block before scaling.", "return", "QRect", "(", "self", ".", "FLAGS_DX", "/", "2", ",", "position", "-", "self", ".", "FLAGS_DY", "/", "2", ",", "self", ".", "WIDTH", "-", "self", ".", "FLAGS_DX", ",", "self", ".", "FLAGS_DY", ")", "else", ":", "# When the vertical scrollbar is not visible, the flags are", "# vertically aligned with the center of their corresponding", "# text block with no scaling.", "block", "=", "self", ".", "editor", ".", "document", "(", ")", ".", "findBlockByLineNumber", "(", "value", ")", "top", "=", "self", ".", "editor", ".", "blockBoundingGeometry", "(", "block", ")", ".", "translated", "(", "self", ".", "editor", ".", "contentOffset", "(", ")", ")", ".", "top", "(", ")", "bottom", "=", "top", "+", "self", ".", "editor", ".", "blockBoundingRect", "(", "block", ")", ".", "height", "(", ")", "middle", "=", "(", "top", "+", "bottom", ")", "/", "2", "return", "QRect", "(", "self", ".", "FLAGS_DX", "/", "2", ",", "middle", "-", "self", ".", "FLAGS_DY", "/", "2", ",", "self", ".", "WIDTH", "-", "self", ".", "FLAGS_DX", ",", "self", ".", "FLAGS_DY", ")" ]
Make flag QRect
[ "Make", "flag", "QRect" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L206-L226
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.make_slider_range
def make_slider_range(self, cursor_pos): """Make slider range QRect""" # The slider range indicator position follows the mouse vertical # position while its height corresponds to the part of the file that # is currently visible on screen. vsb = self.editor.verticalScrollBar() groove_height = self.get_scrollbar_position_height() slider_height = self.value_to_position(vsb.pageStep())-self.offset # Calcul the minimum and maximum y-value to constraint the slider # range indicator position to the height span of the scrollbar area # where the slider may move. min_ypos = self.offset max_ypos = groove_height + self.offset - slider_height # Determine the bounded y-position of the slider rect. slider_y = max(min_ypos, min(max_ypos, cursor_pos.y()-slider_height/2)) return QRect(1, slider_y, self.WIDTH-2, slider_height)
python
def make_slider_range(self, cursor_pos): """Make slider range QRect""" # The slider range indicator position follows the mouse vertical # position while its height corresponds to the part of the file that # is currently visible on screen. vsb = self.editor.verticalScrollBar() groove_height = self.get_scrollbar_position_height() slider_height = self.value_to_position(vsb.pageStep())-self.offset # Calcul the minimum and maximum y-value to constraint the slider # range indicator position to the height span of the scrollbar area # where the slider may move. min_ypos = self.offset max_ypos = groove_height + self.offset - slider_height # Determine the bounded y-position of the slider rect. slider_y = max(min_ypos, min(max_ypos, cursor_pos.y()-slider_height/2)) return QRect(1, slider_y, self.WIDTH-2, slider_height)
[ "def", "make_slider_range", "(", "self", ",", "cursor_pos", ")", ":", "# The slider range indicator position follows the mouse vertical", "# position while its height corresponds to the part of the file that", "# is currently visible on screen.", "vsb", "=", "self", ".", "editor", ".", "verticalScrollBar", "(", ")", "groove_height", "=", "self", ".", "get_scrollbar_position_height", "(", ")", "slider_height", "=", "self", ".", "value_to_position", "(", "vsb", ".", "pageStep", "(", ")", ")", "-", "self", ".", "offset", "# Calcul the minimum and maximum y-value to constraint the slider", "# range indicator position to the height span of the scrollbar area", "# where the slider may move.", "min_ypos", "=", "self", ".", "offset", "max_ypos", "=", "groove_height", "+", "self", ".", "offset", "-", "slider_height", "# Determine the bounded y-position of the slider rect.", "slider_y", "=", "max", "(", "min_ypos", ",", "min", "(", "max_ypos", ",", "cursor_pos", ".", "y", "(", ")", "-", "slider_height", "/", "2", ")", ")", "return", "QRect", "(", "1", ",", "slider_y", ",", "self", ".", "WIDTH", "-", "2", ",", "slider_height", ")" ]
Make slider range QRect
[ "Make", "slider", "range", "QRect" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L228-L247
train
spyder-ide/spyder
spyder/plugins/editor/panels/scrollflag.py
ScrollFlagArea.set_painter
def set_painter(self, painter, light_color): """Set scroll flag area painter pen and brush colors""" painter.setPen(QColor(light_color).darker(120)) painter.setBrush(QBrush(QColor(light_color)))
python
def set_painter(self, painter, light_color): """Set scroll flag area painter pen and brush colors""" painter.setPen(QColor(light_color).darker(120)) painter.setBrush(QBrush(QColor(light_color)))
[ "def", "set_painter", "(", "self", ",", "painter", ",", "light_color", ")", ":", "painter", ".", "setPen", "(", "QColor", "(", "light_color", ")", ".", "darker", "(", "120", ")", ")", "painter", ".", "setBrush", "(", "QBrush", "(", "QColor", "(", "light_color", ")", ")", ")" ]
Set scroll flag area painter pen and brush colors
[ "Set", "scroll", "flag", "area", "painter", "pen", "and", "brush", "colors" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L253-L256
train
spyder-ide/spyder
spyder/plugins/profiler/plugin.py
Profiler.on_first_registration
def on_first_registration(self): """Action to be performed on first plugin registration""" self.main.tabify_plugins(self.main.help, self) self.dockwidget.hide()
python
def on_first_registration(self): """Action to be performed on first plugin registration""" self.main.tabify_plugins(self.main.help, self) self.dockwidget.hide()
[ "def", "on_first_registration", "(", "self", ")", ":", "self", ".", "main", ".", "tabify_plugins", "(", "self", ".", "main", ".", "help", ",", "self", ")", "self", ".", "dockwidget", ".", "hide", "(", ")" ]
Action to be performed on first plugin registration
[ "Action", "to", "be", "performed", "on", "first", "plugin", "registration" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/plugin.py#L75-L78
train
spyder-ide/spyder
spyder/plugins/profiler/plugin.py
Profiler.register_plugin
def register_plugin(self): """Register plugin in Spyder's main window""" self.profiler.datatree.sig_edit_goto.connect(self.main.editor.load) self.profiler.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.main.add_dockwidget(self) profiler_act = create_action(self, _("Profile"), icon=self.get_plugin_icon(), triggered=self.run_profiler) profiler_act.setEnabled(is_profiler_installed()) self.register_shortcut(profiler_act, context="Profiler", name="Run profiler") self.main.run_menu_actions += [profiler_act] self.main.editor.pythonfile_dependent_actions += [profiler_act]
python
def register_plugin(self): """Register plugin in Spyder's main window""" self.profiler.datatree.sig_edit_goto.connect(self.main.editor.load) self.profiler.redirect_stdio.connect( self.main.redirect_internalshell_stdio) self.main.add_dockwidget(self) profiler_act = create_action(self, _("Profile"), icon=self.get_plugin_icon(), triggered=self.run_profiler) profiler_act.setEnabled(is_profiler_installed()) self.register_shortcut(profiler_act, context="Profiler", name="Run profiler") self.main.run_menu_actions += [profiler_act] self.main.editor.pythonfile_dependent_actions += [profiler_act]
[ "def", "register_plugin", "(", "self", ")", ":", "self", ".", "profiler", ".", "datatree", ".", "sig_edit_goto", ".", "connect", "(", "self", ".", "main", ".", "editor", ".", "load", ")", "self", ".", "profiler", ".", "redirect_stdio", ".", "connect", "(", "self", ".", "main", ".", "redirect_internalshell_stdio", ")", "self", ".", "main", ".", "add_dockwidget", "(", "self", ")", "profiler_act", "=", "create_action", "(", "self", ",", "_", "(", "\"Profile\"", ")", ",", "icon", "=", "self", ".", "get_plugin_icon", "(", ")", ",", "triggered", "=", "self", ".", "run_profiler", ")", "profiler_act", ".", "setEnabled", "(", "is_profiler_installed", "(", ")", ")", "self", ".", "register_shortcut", "(", "profiler_act", ",", "context", "=", "\"Profiler\"", ",", "name", "=", "\"Run profiler\"", ")", "self", ".", "main", ".", "run_menu_actions", "+=", "[", "profiler_act", "]", "self", ".", "main", ".", "editor", ".", "pythonfile_dependent_actions", "+=", "[", "profiler_act", "]" ]
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/profiler/plugin.py#L80-L95
train
spyder-ide/spyder
spyder/plugins/profiler/plugin.py
Profiler.run_profiler
def run_profiler(self): """Run profiler""" if self.main.editor.save(): self.switch_to_plugin() self.analyze(self.main.editor.get_current_filename())
python
def run_profiler(self): """Run profiler""" if self.main.editor.save(): self.switch_to_plugin() self.analyze(self.main.editor.get_current_filename())
[ "def", "run_profiler", "(", "self", ")", ":", "if", "self", ".", "main", ".", "editor", ".", "save", "(", ")", ":", "self", ".", "switch_to_plugin", "(", ")", "self", ".", "analyze", "(", "self", ".", "main", ".", "editor", ".", "get_current_filename", "(", ")", ")" ]
Run profiler
[ "Run", "profiler" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/plugin.py#L112-L116
train
spyder-ide/spyder
spyder/plugins/profiler/plugin.py
Profiler.analyze
def analyze(self, filename): """Reimplement analyze method""" if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.setFocus() self.dockwidget.raise_() pythonpath = self.main.get_spyder_pythonpath() runconf = get_run_configuration(filename) wdir, args = None, [] if runconf is not None: if runconf.wdir_enabled: wdir = runconf.wdir if runconf.args_enabled: args = runconf.args self.profiler.analyze(filename, wdir=wdir, args=args, pythonpath=pythonpath)
python
def analyze(self, filename): """Reimplement analyze method""" if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.setFocus() self.dockwidget.raise_() pythonpath = self.main.get_spyder_pythonpath() runconf = get_run_configuration(filename) wdir, args = None, [] if runconf is not None: if runconf.wdir_enabled: wdir = runconf.wdir if runconf.args_enabled: args = runconf.args self.profiler.analyze(filename, wdir=wdir, args=args, pythonpath=pythonpath)
[ "def", "analyze", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "dockwidget", "and", "not", "self", ".", "ismaximized", ":", "self", ".", "dockwidget", ".", "setVisible", "(", "True", ")", "self", ".", "dockwidget", ".", "setFocus", "(", ")", "self", ".", "dockwidget", ".", "raise_", "(", ")", "pythonpath", "=", "self", ".", "main", ".", "get_spyder_pythonpath", "(", ")", "runconf", "=", "get_run_configuration", "(", "filename", ")", "wdir", ",", "args", "=", "None", ",", "[", "]", "if", "runconf", "is", "not", "None", ":", "if", "runconf", ".", "wdir_enabled", ":", "wdir", "=", "runconf", ".", "wdir", "if", "runconf", ".", "args_enabled", ":", "args", "=", "runconf", ".", "args", "self", ".", "profiler", ".", "analyze", "(", "filename", ",", "wdir", "=", "wdir", ",", "args", "=", "args", ",", "pythonpath", "=", "pythonpath", ")" ]
Reimplement analyze method
[ "Reimplement", "analyze", "method" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/plugin.py#L118-L133
train
spyder-ide/spyder
spyder/utils/system.py
windows_memory_usage
def windows_memory_usage(): """Return physical memory usage (float) Works on Windows platforms only""" from ctypes import windll, Structure, c_uint64, sizeof, byref from ctypes.wintypes import DWORD class MemoryStatus(Structure): _fields_ = [('dwLength', DWORD), ('dwMemoryLoad',DWORD), ('ullTotalPhys', c_uint64), ('ullAvailPhys', c_uint64), ('ullTotalPageFile', c_uint64), ('ullAvailPageFile', c_uint64), ('ullTotalVirtual', c_uint64), ('ullAvailVirtual', c_uint64), ('ullAvailExtendedVirtual', c_uint64),] memorystatus = MemoryStatus() # MSDN documetation states that dwLength must be set to MemoryStatus # size before calling GlobalMemoryStatusEx # https://msdn.microsoft.com/en-us/library/aa366770(v=vs.85) memorystatus.dwLength = sizeof(memorystatus) windll.kernel32.GlobalMemoryStatusEx(byref(memorystatus)) return float(memorystatus.dwMemoryLoad)
python
def windows_memory_usage(): """Return physical memory usage (float) Works on Windows platforms only""" from ctypes import windll, Structure, c_uint64, sizeof, byref from ctypes.wintypes import DWORD class MemoryStatus(Structure): _fields_ = [('dwLength', DWORD), ('dwMemoryLoad',DWORD), ('ullTotalPhys', c_uint64), ('ullAvailPhys', c_uint64), ('ullTotalPageFile', c_uint64), ('ullAvailPageFile', c_uint64), ('ullTotalVirtual', c_uint64), ('ullAvailVirtual', c_uint64), ('ullAvailExtendedVirtual', c_uint64),] memorystatus = MemoryStatus() # MSDN documetation states that dwLength must be set to MemoryStatus # size before calling GlobalMemoryStatusEx # https://msdn.microsoft.com/en-us/library/aa366770(v=vs.85) memorystatus.dwLength = sizeof(memorystatus) windll.kernel32.GlobalMemoryStatusEx(byref(memorystatus)) return float(memorystatus.dwMemoryLoad)
[ "def", "windows_memory_usage", "(", ")", ":", "from", "ctypes", "import", "windll", ",", "Structure", ",", "c_uint64", ",", "sizeof", ",", "byref", "from", "ctypes", ".", "wintypes", "import", "DWORD", "class", "MemoryStatus", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "'dwLength'", ",", "DWORD", ")", ",", "(", "'dwMemoryLoad'", ",", "DWORD", ")", ",", "(", "'ullTotalPhys'", ",", "c_uint64", ")", ",", "(", "'ullAvailPhys'", ",", "c_uint64", ")", ",", "(", "'ullTotalPageFile'", ",", "c_uint64", ")", ",", "(", "'ullAvailPageFile'", ",", "c_uint64", ")", ",", "(", "'ullTotalVirtual'", ",", "c_uint64", ")", ",", "(", "'ullAvailVirtual'", ",", "c_uint64", ")", ",", "(", "'ullAvailExtendedVirtual'", ",", "c_uint64", ")", ",", "]", "memorystatus", "=", "MemoryStatus", "(", ")", "# MSDN documetation states that dwLength must be set to MemoryStatus\r", "# size before calling GlobalMemoryStatusEx\r", "# https://msdn.microsoft.com/en-us/library/aa366770(v=vs.85)\r", "memorystatus", ".", "dwLength", "=", "sizeof", "(", "memorystatus", ")", "windll", ".", "kernel32", ".", "GlobalMemoryStatusEx", "(", "byref", "(", "memorystatus", ")", ")", "return", "float", "(", "memorystatus", ".", "dwMemoryLoad", ")" ]
Return physical memory usage (float) Works on Windows platforms only
[ "Return", "physical", "memory", "usage", "(", "float", ")", "Works", "on", "Windows", "platforms", "only" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/system.py#L22-L43
train
spyder-ide/spyder
spyder/utils/system.py
psutil_phymem_usage
def psutil_phymem_usage(): """ Return physical memory usage (float) Requires the cross-platform psutil (>=v0.3) library (https://github.com/giampaolo/psutil) """ import psutil # This is needed to avoid a deprecation warning error with # newer psutil versions try: percent = psutil.virtual_memory().percent except: percent = psutil.phymem_usage().percent return percent
python
def psutil_phymem_usage(): """ Return physical memory usage (float) Requires the cross-platform psutil (>=v0.3) library (https://github.com/giampaolo/psutil) """ import psutil # This is needed to avoid a deprecation warning error with # newer psutil versions try: percent = psutil.virtual_memory().percent except: percent = psutil.phymem_usage().percent return percent
[ "def", "psutil_phymem_usage", "(", ")", ":", "import", "psutil", "# This is needed to avoid a deprecation warning error with\r", "# newer psutil versions\r", "try", ":", "percent", "=", "psutil", ".", "virtual_memory", "(", ")", ".", "percent", "except", ":", "percent", "=", "psutil", ".", "phymem_usage", "(", ")", ".", "percent", "return", "percent" ]
Return physical memory usage (float) Requires the cross-platform psutil (>=v0.3) library (https://github.com/giampaolo/psutil)
[ "Return", "physical", "memory", "usage", "(", "float", ")", "Requires", "the", "cross", "-", "platform", "psutil", "(", ">", "=", "v0", ".", "3", ")", "library", "(", "https", ":", "//", "github", ".", "com", "/", "giampaolo", "/", "psutil", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/system.py#L45-L58
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
drift_color
def drift_color(base_color, factor=110): """ Return color that is lighter or darker than the base color. If base_color.lightness is higher than 128, the returned color is darker otherwise is is lighter. :param base_color: The base color to drift from ;:param factor: drift factor (%) :return A lighter or darker color. """ base_color = QColor(base_color) if base_color.lightness() > 128: return base_color.darker(factor) else: if base_color == QColor('#000000'): return drift_color(QColor('#101010'), factor + 20) else: return base_color.lighter(factor + 10)
python
def drift_color(base_color, factor=110): """ Return color that is lighter or darker than the base color. If base_color.lightness is higher than 128, the returned color is darker otherwise is is lighter. :param base_color: The base color to drift from ;:param factor: drift factor (%) :return A lighter or darker color. """ base_color = QColor(base_color) if base_color.lightness() > 128: return base_color.darker(factor) else: if base_color == QColor('#000000'): return drift_color(QColor('#101010'), factor + 20) else: return base_color.lighter(factor + 10)
[ "def", "drift_color", "(", "base_color", ",", "factor", "=", "110", ")", ":", "base_color", "=", "QColor", "(", "base_color", ")", "if", "base_color", ".", "lightness", "(", ")", ">", "128", ":", "return", "base_color", ".", "darker", "(", "factor", ")", "else", ":", "if", "base_color", "==", "QColor", "(", "'#000000'", ")", ":", "return", "drift_color", "(", "QColor", "(", "'#101010'", ")", ",", "factor", "+", "20", ")", "else", ":", "return", "base_color", ".", "lighter", "(", "factor", "+", "10", ")" ]
Return color that is lighter or darker than the base color. If base_color.lightness is higher than 128, the returned color is darker otherwise is is lighter. :param base_color: The base color to drift from ;:param factor: drift factor (%) :return A lighter or darker color.
[ "Return", "color", "that", "is", "lighter", "or", "darker", "than", "the", "base", "color", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L33-L51
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
get_block_symbol_data
def get_block_symbol_data(editor, block): """ Gets the list of ParenthesisInfo for specific text block. :param editor: Code editor instance :param block: block to parse """ def list_symbols(editor, block, character): """ Retuns a list of symbols found in the block text :param editor: code editor instance :param block: block to parse :param character: character to look for. """ text = block.text() symbols = [] cursor = QTextCursor(block) cursor.movePosition(cursor.StartOfBlock) pos = text.find(character, 0) cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos) while pos != -1: if not TextHelper(editor).is_comment_or_string(cursor): # skips symbols in string literal or comment info = ParenthesisInfo(pos, character) symbols.append(info) pos = text.find(character, pos + 1) cursor.movePosition(cursor.StartOfBlock) cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos) return symbols parentheses = sorted( list_symbols(editor, block, '(') + list_symbols(editor, block, ')'), key=lambda x: x.position) square_brackets = sorted( list_symbols(editor, block, '[') + list_symbols(editor, block, ']'), key=lambda x: x.position) braces = sorted( list_symbols(editor, block, '{') + list_symbols(editor, block, '}'), key=lambda x: x.position) return parentheses, square_brackets, braces
python
def get_block_symbol_data(editor, block): """ Gets the list of ParenthesisInfo for specific text block. :param editor: Code editor instance :param block: block to parse """ def list_symbols(editor, block, character): """ Retuns a list of symbols found in the block text :param editor: code editor instance :param block: block to parse :param character: character to look for. """ text = block.text() symbols = [] cursor = QTextCursor(block) cursor.movePosition(cursor.StartOfBlock) pos = text.find(character, 0) cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos) while pos != -1: if not TextHelper(editor).is_comment_or_string(cursor): # skips symbols in string literal or comment info = ParenthesisInfo(pos, character) symbols.append(info) pos = text.find(character, pos + 1) cursor.movePosition(cursor.StartOfBlock) cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos) return symbols parentheses = sorted( list_symbols(editor, block, '(') + list_symbols(editor, block, ')'), key=lambda x: x.position) square_brackets = sorted( list_symbols(editor, block, '[') + list_symbols(editor, block, ']'), key=lambda x: x.position) braces = sorted( list_symbols(editor, block, '{') + list_symbols(editor, block, '}'), key=lambda x: x.position) return parentheses, square_brackets, braces
[ "def", "get_block_symbol_data", "(", "editor", ",", "block", ")", ":", "def", "list_symbols", "(", "editor", ",", "block", ",", "character", ")", ":", "\"\"\"\n Retuns a list of symbols found in the block text\n\n :param editor: code editor instance\n :param block: block to parse\n :param character: character to look for.\n \"\"\"", "text", "=", "block", ".", "text", "(", ")", "symbols", "=", "[", "]", "cursor", "=", "QTextCursor", "(", "block", ")", "cursor", ".", "movePosition", "(", "cursor", ".", "StartOfBlock", ")", "pos", "=", "text", ".", "find", "(", "character", ",", "0", ")", "cursor", ".", "movePosition", "(", "cursor", ".", "Right", ",", "cursor", ".", "MoveAnchor", ",", "pos", ")", "while", "pos", "!=", "-", "1", ":", "if", "not", "TextHelper", "(", "editor", ")", ".", "is_comment_or_string", "(", "cursor", ")", ":", "# skips symbols in string literal or comment", "info", "=", "ParenthesisInfo", "(", "pos", ",", "character", ")", "symbols", ".", "append", "(", "info", ")", "pos", "=", "text", ".", "find", "(", "character", ",", "pos", "+", "1", ")", "cursor", ".", "movePosition", "(", "cursor", ".", "StartOfBlock", ")", "cursor", ".", "movePosition", "(", "cursor", ".", "Right", ",", "cursor", ".", "MoveAnchor", ",", "pos", ")", "return", "symbols", "parentheses", "=", "sorted", "(", "list_symbols", "(", "editor", ",", "block", ",", "'('", ")", "+", "list_symbols", "(", "editor", ",", "block", ",", "')'", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "position", ")", "square_brackets", "=", "sorted", "(", "list_symbols", "(", "editor", ",", "block", ",", "'['", ")", "+", "list_symbols", "(", "editor", ",", "block", ",", "']'", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "position", ")", "braces", "=", "sorted", "(", "list_symbols", "(", "editor", ",", "block", ",", "'{'", ")", "+", "list_symbols", "(", "editor", ",", "block", ",", "'}'", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "position", ")", "return", "parentheses", ",", "square_brackets", ",", "braces" ]
Gets the list of ParenthesisInfo for specific text block. :param editor: Code editor instance :param block: block to parse
[ "Gets", "the", "list", "of", "ParenthesisInfo", "for", "specific", "text", "block", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L1035-L1076
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
keep_tc_pos
def keep_tc_pos(func): """ Cache text cursor position and restore it when the wrapped function exits. This decorator can only be used on modes or panels. :param func: wrapped function """ @functools.wraps(func) def wrapper(editor, *args, **kwds): """ Decorator """ sb = editor.verticalScrollBar() spos = sb.sliderPosition() pos = editor.textCursor().position() retval = func(editor, *args, **kwds) text_cursor = editor.textCursor() text_cursor.setPosition(pos) editor.setTextCursor(text_cursor) sb.setSliderPosition(spos) return retval return wrapper
python
def keep_tc_pos(func): """ Cache text cursor position and restore it when the wrapped function exits. This decorator can only be used on modes or panels. :param func: wrapped function """ @functools.wraps(func) def wrapper(editor, *args, **kwds): """ Decorator """ sb = editor.verticalScrollBar() spos = sb.sliderPosition() pos = editor.textCursor().position() retval = func(editor, *args, **kwds) text_cursor = editor.textCursor() text_cursor.setPosition(pos) editor.setTextCursor(text_cursor) sb.setSliderPosition(spos) return retval return wrapper
[ "def", "keep_tc_pos", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "editor", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "\"\"\" Decorator \"\"\"", "sb", "=", "editor", ".", "verticalScrollBar", "(", ")", "spos", "=", "sb", ".", "sliderPosition", "(", ")", "pos", "=", "editor", ".", "textCursor", "(", ")", ".", "position", "(", ")", "retval", "=", "func", "(", "editor", ",", "*", "args", ",", "*", "*", "kwds", ")", "text_cursor", "=", "editor", ".", "textCursor", "(", ")", "text_cursor", ".", "setPosition", "(", "pos", ")", "editor", ".", "setTextCursor", "(", "text_cursor", ")", "sb", ".", "setSliderPosition", "(", "spos", ")", "return", "retval", "return", "wrapper" ]
Cache text cursor position and restore it when the wrapped function exits. This decorator can only be used on modes or panels. :param func: wrapped function
[ "Cache", "text", "cursor", "position", "and", "restore", "it", "when", "the", "wrapped", "function", "exits", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L1079-L1100
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
with_wait_cursor
def with_wait_cursor(func): """ Show a wait cursor while the wrapped function is running. The cursor is restored as soon as the function exits. :param func: wrapped function """ @functools.wraps(func) def wrapper(*args, **kwargs): QApplication.setOverrideCursor( QCursor(Qt.WaitCursor)) try: ret_val = func(*args, **kwargs) finally: QApplication.restoreOverrideCursor() return ret_val return wrapper
python
def with_wait_cursor(func): """ Show a wait cursor while the wrapped function is running. The cursor is restored as soon as the function exits. :param func: wrapped function """ @functools.wraps(func) def wrapper(*args, **kwargs): QApplication.setOverrideCursor( QCursor(Qt.WaitCursor)) try: ret_val = func(*args, **kwargs) finally: QApplication.restoreOverrideCursor() return ret_val return wrapper
[ "def", "with_wait_cursor", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "QApplication", ".", "setOverrideCursor", "(", "QCursor", "(", "Qt", ".", "WaitCursor", ")", ")", "try", ":", "ret_val", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "QApplication", ".", "restoreOverrideCursor", "(", ")", "return", "ret_val", "return", "wrapper" ]
Show a wait cursor while the wrapped function is running. The cursor is restored as soon as the function exits. :param func: wrapped function
[ "Show", "a", "wait", "cursor", "while", "the", "wrapped", "function", "is", "running", ".", "The", "cursor", "is", "restored", "as", "soon", "as", "the", "function", "exits", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L1103-L1119
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
BlockUserData.is_empty
def is_empty(self): """Return whether the block of user data is empty.""" return (not self.breakpoint and not self.code_analysis and not self.todo and not self.bookmarks)
python
def is_empty(self): """Return whether the block of user data is empty.""" return (not self.breakpoint and not self.code_analysis and not self.todo and not self.bookmarks)
[ "def", "is_empty", "(", "self", ")", ":", "return", "(", "not", "self", ".", "breakpoint", "and", "not", "self", ".", "code_analysis", "and", "not", "self", ".", "todo", "and", "not", "self", ".", "bookmarks", ")" ]
Return whether the block of user data is empty.
[ "Return", "whether", "the", "block", "of", "user", "data", "is", "empty", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L67-L70
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
DelayJobRunner.request_job
def request_job(self, job, *args, **kwargs): """ Request a job execution. The job will be executed after the delay specified in the DelayJobRunner contructor elapsed if no other job is requested until then. :param job: job. :type job: callable :param args: job's position arguments :param kwargs: job's keyworded arguments """ self.cancel_requests() self._job = job self._args = args self._kwargs = kwargs self._timer.start(self.delay)
python
def request_job(self, job, *args, **kwargs): """ Request a job execution. The job will be executed after the delay specified in the DelayJobRunner contructor elapsed if no other job is requested until then. :param job: job. :type job: callable :param args: job's position arguments :param kwargs: job's keyworded arguments """ self.cancel_requests() self._job = job self._args = args self._kwargs = kwargs self._timer.start(self.delay)
[ "def", "request_job", "(", "self", ",", "job", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "cancel_requests", "(", ")", "self", ".", "_job", "=", "job", "self", ".", "_args", "=", "args", "self", ".", "_kwargs", "=", "kwargs", "self", ".", "_timer", ".", "start", "(", "self", ".", "delay", ")" ]
Request a job execution. The job will be executed after the delay specified in the DelayJobRunner contructor elapsed if no other job is requested until then. :param job: job. :type job: callable :param args: job's position arguments :param kwargs: job's keyworded arguments
[ "Request", "a", "job", "execution", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L100-L117
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
DelayJobRunner.cancel_requests
def cancel_requests(self): """Cancels pending requests.""" self._timer.stop() self._job = None self._args = None self._kwargs = None
python
def cancel_requests(self): """Cancels pending requests.""" self._timer.stop() self._job = None self._args = None self._kwargs = None
[ "def", "cancel_requests", "(", "self", ")", ":", "self", ".", "_timer", ".", "stop", "(", ")", "self", ".", "_job", "=", "None", "self", ".", "_args", "=", "None", "self", ".", "_kwargs", "=", "None" ]
Cancels pending requests.
[ "Cancels", "pending", "requests", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L119-L124
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
DelayJobRunner._exec_requested_job
def _exec_requested_job(self): """Execute the requested job after the timer has timeout.""" self._timer.stop() self._job(*self._args, **self._kwargs)
python
def _exec_requested_job(self): """Execute the requested job after the timer has timeout.""" self._timer.stop() self._job(*self._args, **self._kwargs)
[ "def", "_exec_requested_job", "(", "self", ")", ":", "self", ".", "_timer", ".", "stop", "(", ")", "self", ".", "_job", "(", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")" ]
Execute the requested job after the timer has timeout.
[ "Execute", "the", "requested", "job", "after", "the", "timer", "has", "timeout", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L126-L129
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.goto_line
def goto_line(self, line, column=0, end_column=0, move=True, word=''): """ Moves the text cursor to the specified position. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. :param word: Highlight the word, when moving to the line. :return: The new text cursor :rtype: QtGui.QTextCursor """ line = min(line, self.line_count()) text_cursor = self._move_cursor_to(line) if column: text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, column) if end_column: text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor, end_column) if move: block = text_cursor.block() self.unfold_if_colapsed(block) self._editor.setTextCursor(text_cursor) if self._editor.isVisible(): self._editor.centerCursor() else: self._editor.focus_in.connect( self._editor.center_cursor_on_next_focus) if word and to_text_string(word) in to_text_string(block.text()): self._editor.find(word, QTextDocument.FindCaseSensitively) return text_cursor
python
def goto_line(self, line, column=0, end_column=0, move=True, word=''): """ Moves the text cursor to the specified position. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. :param word: Highlight the word, when moving to the line. :return: The new text cursor :rtype: QtGui.QTextCursor """ line = min(line, self.line_count()) text_cursor = self._move_cursor_to(line) if column: text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, column) if end_column: text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor, end_column) if move: block = text_cursor.block() self.unfold_if_colapsed(block) self._editor.setTextCursor(text_cursor) if self._editor.isVisible(): self._editor.centerCursor() else: self._editor.focus_in.connect( self._editor.center_cursor_on_next_focus) if word and to_text_string(word) in to_text_string(block.text()): self._editor.find(word, QTextDocument.FindCaseSensitively) return text_cursor
[ "def", "goto_line", "(", "self", ",", "line", ",", "column", "=", "0", ",", "end_column", "=", "0", ",", "move", "=", "True", ",", "word", "=", "''", ")", ":", "line", "=", "min", "(", "line", ",", "self", ".", "line_count", "(", ")", ")", "text_cursor", "=", "self", ".", "_move_cursor_to", "(", "line", ")", "if", "column", ":", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "Right", ",", "text_cursor", ".", "MoveAnchor", ",", "column", ")", "if", "end_column", ":", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "Right", ",", "text_cursor", ".", "KeepAnchor", ",", "end_column", ")", "if", "move", ":", "block", "=", "text_cursor", ".", "block", "(", ")", "self", ".", "unfold_if_colapsed", "(", "block", ")", "self", ".", "_editor", ".", "setTextCursor", "(", "text_cursor", ")", "if", "self", ".", "_editor", ".", "isVisible", "(", ")", ":", "self", ".", "_editor", ".", "centerCursor", "(", ")", "else", ":", "self", ".", "_editor", ".", "focus_in", ".", "connect", "(", "self", ".", "_editor", ".", "center_cursor_on_next_focus", ")", "if", "word", "and", "to_text_string", "(", "word", ")", "in", "to_text_string", "(", "block", ".", "text", "(", ")", ")", ":", "self", ".", "_editor", ".", "find", "(", "word", ",", "QTextDocument", ".", "FindCaseSensitively", ")", "return", "text_cursor" ]
Moves the text cursor to the specified position. :param line: Number of the line to go to (0 based) :param column: Optional column number. Default is 0 (start of line). :param move: True to move the cursor. False will return the cursor without setting it on the editor. :param word: Highlight the word, when moving to the line. :return: The new text cursor :rtype: QtGui.QTextCursor
[ "Moves", "the", "text", "cursor", "to", "the", "specified", "position", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L154-L186
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.unfold_if_colapsed
def unfold_if_colapsed(self, block): """Unfold parent fold trigger if the block is collapsed. :param block: Block to unfold. """ try: folding_panel = self._editor.panels.get('FoldingPanel') except KeyError: pass else: from spyder.plugins.editor.utils.folding import FoldScope if not block.isVisible(): block = FoldScope.find_parent_scope(block) if TextBlockHelper.is_collapsed(block): folding_panel.toggle_fold_trigger(block)
python
def unfold_if_colapsed(self, block): """Unfold parent fold trigger if the block is collapsed. :param block: Block to unfold. """ try: folding_panel = self._editor.panels.get('FoldingPanel') except KeyError: pass else: from spyder.plugins.editor.utils.folding import FoldScope if not block.isVisible(): block = FoldScope.find_parent_scope(block) if TextBlockHelper.is_collapsed(block): folding_panel.toggle_fold_trigger(block)
[ "def", "unfold_if_colapsed", "(", "self", ",", "block", ")", ":", "try", ":", "folding_panel", "=", "self", ".", "_editor", ".", "panels", ".", "get", "(", "'FoldingPanel'", ")", "except", "KeyError", ":", "pass", "else", ":", "from", "spyder", ".", "plugins", ".", "editor", ".", "utils", ".", "folding", "import", "FoldScope", "if", "not", "block", ".", "isVisible", "(", ")", ":", "block", "=", "FoldScope", ".", "find_parent_scope", "(", "block", ")", "if", "TextBlockHelper", ".", "is_collapsed", "(", "block", ")", ":", "folding_panel", ".", "toggle_fold_trigger", "(", "block", ")" ]
Unfold parent fold trigger if the block is collapsed. :param block: Block to unfold.
[ "Unfold", "parent", "fold", "trigger", "if", "the", "block", "is", "collapsed", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L188-L202
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.word_under_cursor
def word_under_cursor(self, select_whole_word=False, text_cursor=None): """ Gets the word under cursor using the separators defined by :attr:`spyder.plugins.editor.widgets.codeeditor.CodeEditor.word_separators`. FIXME: This is not working because CodeEditor have no attribute word_separators .. note: Instead of returning the word string, this function returns a QTextCursor, that way you may get more information than just the string. To get the word, just call ``selectedText`` on the returned value. :param select_whole_word: If set to true the whole word is selected, else the selection stops at the cursor position. :param text_cursor: Optional custom text cursor (e.g. from a QTextDocument clone) :returns: The QTextCursor that contains the selected word. """ editor = self._editor if not text_cursor: text_cursor = editor.textCursor() word_separators = editor.word_separators end_pos = start_pos = text_cursor.position() # select char by char until we are at the original cursor position. while not text_cursor.atStart(): text_cursor.movePosition( text_cursor.Left, text_cursor.KeepAnchor, 1) try: char = text_cursor.selectedText()[0] word_separators = editor.word_separators selected_txt = text_cursor.selectedText() if (selected_txt in word_separators and (selected_txt != "n" and selected_txt != "t") or char.isspace()): break # start boundary found except IndexError: break # nothing selectable start_pos = text_cursor.position() text_cursor.setPosition(start_pos) if select_whole_word: # select the resot of the word text_cursor.setPosition(end_pos) while not text_cursor.atEnd(): text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor, 1) char = text_cursor.selectedText()[0] selected_txt = text_cursor.selectedText() if (selected_txt in word_separators and (selected_txt != "n" and selected_txt != "t") or char.isspace()): break # end boundary found end_pos = text_cursor.position() text_cursor.setPosition(end_pos) # now that we habe the boundaries, we can select the text text_cursor.setPosition(start_pos) text_cursor.setPosition(end_pos, text_cursor.KeepAnchor) return text_cursor
python
def word_under_cursor(self, select_whole_word=False, text_cursor=None): """ Gets the word under cursor using the separators defined by :attr:`spyder.plugins.editor.widgets.codeeditor.CodeEditor.word_separators`. FIXME: This is not working because CodeEditor have no attribute word_separators .. note: Instead of returning the word string, this function returns a QTextCursor, that way you may get more information than just the string. To get the word, just call ``selectedText`` on the returned value. :param select_whole_word: If set to true the whole word is selected, else the selection stops at the cursor position. :param text_cursor: Optional custom text cursor (e.g. from a QTextDocument clone) :returns: The QTextCursor that contains the selected word. """ editor = self._editor if not text_cursor: text_cursor = editor.textCursor() word_separators = editor.word_separators end_pos = start_pos = text_cursor.position() # select char by char until we are at the original cursor position. while not text_cursor.atStart(): text_cursor.movePosition( text_cursor.Left, text_cursor.KeepAnchor, 1) try: char = text_cursor.selectedText()[0] word_separators = editor.word_separators selected_txt = text_cursor.selectedText() if (selected_txt in word_separators and (selected_txt != "n" and selected_txt != "t") or char.isspace()): break # start boundary found except IndexError: break # nothing selectable start_pos = text_cursor.position() text_cursor.setPosition(start_pos) if select_whole_word: # select the resot of the word text_cursor.setPosition(end_pos) while not text_cursor.atEnd(): text_cursor.movePosition(text_cursor.Right, text_cursor.KeepAnchor, 1) char = text_cursor.selectedText()[0] selected_txt = text_cursor.selectedText() if (selected_txt in word_separators and (selected_txt != "n" and selected_txt != "t") or char.isspace()): break # end boundary found end_pos = text_cursor.position() text_cursor.setPosition(end_pos) # now that we habe the boundaries, we can select the text text_cursor.setPosition(start_pos) text_cursor.setPosition(end_pos, text_cursor.KeepAnchor) return text_cursor
[ "def", "word_under_cursor", "(", "self", ",", "select_whole_word", "=", "False", ",", "text_cursor", "=", "None", ")", ":", "editor", "=", "self", ".", "_editor", "if", "not", "text_cursor", ":", "text_cursor", "=", "editor", ".", "textCursor", "(", ")", "word_separators", "=", "editor", ".", "word_separators", "end_pos", "=", "start_pos", "=", "text_cursor", ".", "position", "(", ")", "# select char by char until we are at the original cursor position.", "while", "not", "text_cursor", ".", "atStart", "(", ")", ":", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "Left", ",", "text_cursor", ".", "KeepAnchor", ",", "1", ")", "try", ":", "char", "=", "text_cursor", ".", "selectedText", "(", ")", "[", "0", "]", "word_separators", "=", "editor", ".", "word_separators", "selected_txt", "=", "text_cursor", ".", "selectedText", "(", ")", "if", "(", "selected_txt", "in", "word_separators", "and", "(", "selected_txt", "!=", "\"n\"", "and", "selected_txt", "!=", "\"t\"", ")", "or", "char", ".", "isspace", "(", ")", ")", ":", "break", "# start boundary found", "except", "IndexError", ":", "break", "# nothing selectable", "start_pos", "=", "text_cursor", ".", "position", "(", ")", "text_cursor", ".", "setPosition", "(", "start_pos", ")", "if", "select_whole_word", ":", "# select the resot of the word", "text_cursor", ".", "setPosition", "(", "end_pos", ")", "while", "not", "text_cursor", ".", "atEnd", "(", ")", ":", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "Right", ",", "text_cursor", ".", "KeepAnchor", ",", "1", ")", "char", "=", "text_cursor", ".", "selectedText", "(", ")", "[", "0", "]", "selected_txt", "=", "text_cursor", ".", "selectedText", "(", ")", "if", "(", "selected_txt", "in", "word_separators", "and", "(", "selected_txt", "!=", "\"n\"", "and", "selected_txt", "!=", "\"t\"", ")", "or", "char", ".", "isspace", "(", ")", ")", ":", "break", "# end boundary found", "end_pos", "=", "text_cursor", ".", "position", "(", ")", "text_cursor", ".", "setPosition", "(", "end_pos", ")", "# now that we habe the boundaries, we can select the text", "text_cursor", ".", "setPosition", "(", "start_pos", ")", "text_cursor", ".", "setPosition", "(", "end_pos", ",", "text_cursor", ".", "KeepAnchor", ")", "return", "text_cursor" ]
Gets the word under cursor using the separators defined by :attr:`spyder.plugins.editor.widgets.codeeditor.CodeEditor.word_separators`. FIXME: This is not working because CodeEditor have no attribute word_separators .. note: Instead of returning the word string, this function returns a QTextCursor, that way you may get more information than just the string. To get the word, just call ``selectedText`` on the returned value. :param select_whole_word: If set to true the whole word is selected, else the selection stops at the cursor position. :param text_cursor: Optional custom text cursor (e.g. from a QTextDocument clone) :returns: The QTextCursor that contains the selected word.
[ "Gets", "the", "word", "under", "cursor", "using", "the", "separators", "defined", "by", ":", "attr", ":", "spyder", ".", "plugins", ".", "editor", ".", "widgets", ".", "codeeditor", ".", "CodeEditor", ".", "word_separators", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L208-L265
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.word_under_mouse_cursor
def word_under_mouse_cursor(self): """ Selects the word under the **mouse** cursor. :return: A QTextCursor with the word under mouse cursor selected. """ editor = self._editor text_cursor = editor.cursorForPosition(editor._last_mouse_pos) text_cursor = self.word_under_cursor(True, text_cursor) return text_cursor
python
def word_under_mouse_cursor(self): """ Selects the word under the **mouse** cursor. :return: A QTextCursor with the word under mouse cursor selected. """ editor = self._editor text_cursor = editor.cursorForPosition(editor._last_mouse_pos) text_cursor = self.word_under_cursor(True, text_cursor) return text_cursor
[ "def", "word_under_mouse_cursor", "(", "self", ")", ":", "editor", "=", "self", ".", "_editor", "text_cursor", "=", "editor", ".", "cursorForPosition", "(", "editor", ".", "_last_mouse_pos", ")", "text_cursor", "=", "self", ".", "word_under_cursor", "(", "True", ",", "text_cursor", ")", "return", "text_cursor" ]
Selects the word under the **mouse** cursor. :return: A QTextCursor with the word under mouse cursor selected.
[ "Selects", "the", "word", "under", "the", "**", "mouse", "**", "cursor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L267-L276
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.cursor_position
def cursor_position(self): """ Returns the QTextCursor position. The position is a tuple made up of the line number (0 based) and the column number (0 based). :return: tuple(line, column) """ return (self._editor.textCursor().blockNumber(), self._editor.textCursor().columnNumber())
python
def cursor_position(self): """ Returns the QTextCursor position. The position is a tuple made up of the line number (0 based) and the column number (0 based). :return: tuple(line, column) """ return (self._editor.textCursor().blockNumber(), self._editor.textCursor().columnNumber())
[ "def", "cursor_position", "(", "self", ")", ":", "return", "(", "self", ".", "_editor", ".", "textCursor", "(", ")", ".", "blockNumber", "(", ")", ",", "self", ".", "_editor", ".", "textCursor", "(", ")", ".", "columnNumber", "(", ")", ")" ]
Returns the QTextCursor position. The position is a tuple made up of the line number (0 based) and the column number (0 based). :return: tuple(line, column)
[ "Returns", "the", "QTextCursor", "position", ".", "The", "position", "is", "a", "tuple", "made", "up", "of", "the", "line", "number", "(", "0", "based", ")", "and", "the", "column", "number", "(", "0", "based", ")", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L278-L286
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.line_text
def line_text(self, line_nbr): """ Gets the text of the specified line. :param line_nbr: The line number of the text to get :return: Entire line's text :rtype: str """ doc = self._editor.document() block = doc.findBlockByNumber(line_nbr) return block.text()
python
def line_text(self, line_nbr): """ Gets the text of the specified line. :param line_nbr: The line number of the text to get :return: Entire line's text :rtype: str """ doc = self._editor.document() block = doc.findBlockByNumber(line_nbr) return block.text()
[ "def", "line_text", "(", "self", ",", "line_nbr", ")", ":", "doc", "=", "self", ".", "_editor", ".", "document", "(", ")", "block", "=", "doc", ".", "findBlockByNumber", "(", "line_nbr", ")", "return", "block", ".", "text", "(", ")" ]
Gets the text of the specified line. :param line_nbr: The line number of the text to get :return: Entire line's text :rtype: str
[ "Gets", "the", "text", "of", "the", "specified", "line", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L312-L323
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.set_line_text
def set_line_text(self, line_nbr, new_text): """ Replace an entire line with ``new_text``. :param line_nbr: line number of the line to change. :param new_text: The replacement text. """ editor = self._editor text_cursor = self._move_cursor_to(line_nbr) text_cursor.select(text_cursor.LineUnderCursor) text_cursor.insertText(new_text) editor.setTextCursor(text_cursor)
python
def set_line_text(self, line_nbr, new_text): """ Replace an entire line with ``new_text``. :param line_nbr: line number of the line to change. :param new_text: The replacement text. """ editor = self._editor text_cursor = self._move_cursor_to(line_nbr) text_cursor.select(text_cursor.LineUnderCursor) text_cursor.insertText(new_text) editor.setTextCursor(text_cursor)
[ "def", "set_line_text", "(", "self", ",", "line_nbr", ",", "new_text", ")", ":", "editor", "=", "self", ".", "_editor", "text_cursor", "=", "self", ".", "_move_cursor_to", "(", "line_nbr", ")", "text_cursor", ".", "select", "(", "text_cursor", ".", "LineUnderCursor", ")", "text_cursor", ".", "insertText", "(", "new_text", ")", "editor", ".", "setTextCursor", "(", "text_cursor", ")" ]
Replace an entire line with ``new_text``. :param line_nbr: line number of the line to change. :param new_text: The replacement text.
[ "Replace", "an", "entire", "line", "with", "new_text", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L342-L354
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.remove_last_line
def remove_last_line(self): """Removes the last line of the document.""" editor = self._editor text_cursor = editor.textCursor() text_cursor.movePosition(text_cursor.End, text_cursor.MoveAnchor) text_cursor.select(text_cursor.LineUnderCursor) text_cursor.removeSelectedText() text_cursor.deletePreviousChar() editor.setTextCursor(text_cursor)
python
def remove_last_line(self): """Removes the last line of the document.""" editor = self._editor text_cursor = editor.textCursor() text_cursor.movePosition(text_cursor.End, text_cursor.MoveAnchor) text_cursor.select(text_cursor.LineUnderCursor) text_cursor.removeSelectedText() text_cursor.deletePreviousChar() editor.setTextCursor(text_cursor)
[ "def", "remove_last_line", "(", "self", ")", ":", "editor", "=", "self", ".", "_editor", "text_cursor", "=", "editor", ".", "textCursor", "(", ")", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "End", ",", "text_cursor", ".", "MoveAnchor", ")", "text_cursor", ".", "select", "(", "text_cursor", ".", "LineUnderCursor", ")", "text_cursor", ".", "removeSelectedText", "(", ")", "text_cursor", ".", "deletePreviousChar", "(", ")", "editor", ".", "setTextCursor", "(", "text_cursor", ")" ]
Removes the last line of the document.
[ "Removes", "the", "last", "line", "of", "the", "document", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L356-L364
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.clean_document
def clean_document(self): """ Removes trailing whitespaces and ensure one single blank line at the end of the QTextDocument. FIXME: It was deprecated in pyqode, maybe It should be deleted """ editor = self._editor value = editor.verticalScrollBar().value() pos = self.cursor_position() editor.textCursor().beginEditBlock() # cleanup whitespaces editor._cleaning = True eaten = 0 removed = set() for line in editor._modified_lines: # parse line before and line after modified line (for cases where # key_delete or key_return has been pressed) for j in range(-1, 2): # skip current line if line + j != pos[0]: if line + j >= 0: txt = self.line_text(line + j) stxt = txt.rstrip() if txt != stxt: self.set_line_text(line + j, stxt) removed.add(line + j) editor._modified_lines -= removed # ensure there is only one blank line left at the end of the file i = self.line_count() while i: line = self.line_text(i - 1) if line.strip(): break self.remove_last_line() i -= 1 if self.line_text(self.line_count() - 1): editor.appendPlainText('') # restore cursor and scrollbars text_cursor = editor.textCursor() doc = editor.document() assert isinstance(doc, QTextDocument) text_cursor = self._move_cursor_to(pos[0]) text_cursor.movePosition(text_cursor.StartOfLine, text_cursor.MoveAnchor) cpos = text_cursor.position() text_cursor.select(text_cursor.LineUnderCursor) if text_cursor.selectedText(): text_cursor.setPosition(cpos) offset = pos[1] - eaten text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, offset) else: text_cursor.setPosition(cpos) editor.setTextCursor(text_cursor) editor.verticalScrollBar().setValue(value) text_cursor.endEditBlock() editor._cleaning = False
python
def clean_document(self): """ Removes trailing whitespaces and ensure one single blank line at the end of the QTextDocument. FIXME: It was deprecated in pyqode, maybe It should be deleted """ editor = self._editor value = editor.verticalScrollBar().value() pos = self.cursor_position() editor.textCursor().beginEditBlock() # cleanup whitespaces editor._cleaning = True eaten = 0 removed = set() for line in editor._modified_lines: # parse line before and line after modified line (for cases where # key_delete or key_return has been pressed) for j in range(-1, 2): # skip current line if line + j != pos[0]: if line + j >= 0: txt = self.line_text(line + j) stxt = txt.rstrip() if txt != stxt: self.set_line_text(line + j, stxt) removed.add(line + j) editor._modified_lines -= removed # ensure there is only one blank line left at the end of the file i = self.line_count() while i: line = self.line_text(i - 1) if line.strip(): break self.remove_last_line() i -= 1 if self.line_text(self.line_count() - 1): editor.appendPlainText('') # restore cursor and scrollbars text_cursor = editor.textCursor() doc = editor.document() assert isinstance(doc, QTextDocument) text_cursor = self._move_cursor_to(pos[0]) text_cursor.movePosition(text_cursor.StartOfLine, text_cursor.MoveAnchor) cpos = text_cursor.position() text_cursor.select(text_cursor.LineUnderCursor) if text_cursor.selectedText(): text_cursor.setPosition(cpos) offset = pos[1] - eaten text_cursor.movePosition(text_cursor.Right, text_cursor.MoveAnchor, offset) else: text_cursor.setPosition(cpos) editor.setTextCursor(text_cursor) editor.verticalScrollBar().setValue(value) text_cursor.endEditBlock() editor._cleaning = False
[ "def", "clean_document", "(", "self", ")", ":", "editor", "=", "self", ".", "_editor", "value", "=", "editor", ".", "verticalScrollBar", "(", ")", ".", "value", "(", ")", "pos", "=", "self", ".", "cursor_position", "(", ")", "editor", ".", "textCursor", "(", ")", ".", "beginEditBlock", "(", ")", "# cleanup whitespaces", "editor", ".", "_cleaning", "=", "True", "eaten", "=", "0", "removed", "=", "set", "(", ")", "for", "line", "in", "editor", ".", "_modified_lines", ":", "# parse line before and line after modified line (for cases where", "# key_delete or key_return has been pressed)", "for", "j", "in", "range", "(", "-", "1", ",", "2", ")", ":", "# skip current line", "if", "line", "+", "j", "!=", "pos", "[", "0", "]", ":", "if", "line", "+", "j", ">=", "0", ":", "txt", "=", "self", ".", "line_text", "(", "line", "+", "j", ")", "stxt", "=", "txt", ".", "rstrip", "(", ")", "if", "txt", "!=", "stxt", ":", "self", ".", "set_line_text", "(", "line", "+", "j", ",", "stxt", ")", "removed", ".", "add", "(", "line", "+", "j", ")", "editor", ".", "_modified_lines", "-=", "removed", "# ensure there is only one blank line left at the end of the file", "i", "=", "self", ".", "line_count", "(", ")", "while", "i", ":", "line", "=", "self", ".", "line_text", "(", "i", "-", "1", ")", "if", "line", ".", "strip", "(", ")", ":", "break", "self", ".", "remove_last_line", "(", ")", "i", "-=", "1", "if", "self", ".", "line_text", "(", "self", ".", "line_count", "(", ")", "-", "1", ")", ":", "editor", ".", "appendPlainText", "(", "''", ")", "# restore cursor and scrollbars", "text_cursor", "=", "editor", ".", "textCursor", "(", ")", "doc", "=", "editor", ".", "document", "(", ")", "assert", "isinstance", "(", "doc", ",", "QTextDocument", ")", "text_cursor", "=", "self", ".", "_move_cursor_to", "(", "pos", "[", "0", "]", ")", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "StartOfLine", ",", "text_cursor", ".", "MoveAnchor", ")", "cpos", "=", "text_cursor", ".", "position", "(", ")", "text_cursor", ".", "select", "(", "text_cursor", ".", "LineUnderCursor", ")", "if", "text_cursor", ".", "selectedText", "(", ")", ":", "text_cursor", ".", "setPosition", "(", "cpos", ")", "offset", "=", "pos", "[", "1", "]", "-", "eaten", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "Right", ",", "text_cursor", ".", "MoveAnchor", ",", "offset", ")", "else", ":", "text_cursor", ".", "setPosition", "(", "cpos", ")", "editor", ".", "setTextCursor", "(", "text_cursor", ")", "editor", ".", "verticalScrollBar", "(", ")", ".", "setValue", "(", "value", ")", "text_cursor", ".", "endEditBlock", "(", ")", "editor", ".", "_cleaning", "=", "False" ]
Removes trailing whitespaces and ensure one single blank line at the end of the QTextDocument. FIXME: It was deprecated in pyqode, maybe It should be deleted
[ "Removes", "trailing", "whitespaces", "and", "ensure", "one", "single", "blank", "line", "at", "the", "end", "of", "the", "QTextDocument", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L366-L427
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.select_whole_line
def select_whole_line(self, line=None, apply_selection=True): """ Selects an entire line. :param line: Line to select. If None, the current line will be selected :param apply_selection: True to apply selection on the text editor widget, False to just return the text cursor without setting it on the editor. :return: QTextCursor """ if line is None: line = self.current_line_nbr() return self.select_lines(line, line, apply_selection=apply_selection)
python
def select_whole_line(self, line=None, apply_selection=True): """ Selects an entire line. :param line: Line to select. If None, the current line will be selected :param apply_selection: True to apply selection on the text editor widget, False to just return the text cursor without setting it on the editor. :return: QTextCursor """ if line is None: line = self.current_line_nbr() return self.select_lines(line, line, apply_selection=apply_selection)
[ "def", "select_whole_line", "(", "self", ",", "line", "=", "None", ",", "apply_selection", "=", "True", ")", ":", "if", "line", "is", "None", ":", "line", "=", "self", ".", "current_line_nbr", "(", ")", "return", "self", ".", "select_lines", "(", "line", ",", "line", ",", "apply_selection", "=", "apply_selection", ")" ]
Selects an entire line. :param line: Line to select. If None, the current line will be selected :param apply_selection: True to apply selection on the text editor widget, False to just return the text cursor without setting it on the editor. :return: QTextCursor
[ "Selects", "an", "entire", "line", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L429-L441
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.selection_range
def selection_range(self): """ Returns the selected lines boundaries (start line, end line) :return: tuple(int, int) """ editor = self._editor doc = editor.document() start = doc.findBlock( editor.textCursor().selectionStart()).blockNumber() end = doc.findBlock( editor.textCursor().selectionEnd()).blockNumber() text_cursor = QTextCursor(editor.textCursor()) text_cursor.setPosition(editor.textCursor().selectionEnd()) if text_cursor.columnNumber() == 0 and start != end: end -= 1 return start, end
python
def selection_range(self): """ Returns the selected lines boundaries (start line, end line) :return: tuple(int, int) """ editor = self._editor doc = editor.document() start = doc.findBlock( editor.textCursor().selectionStart()).blockNumber() end = doc.findBlock( editor.textCursor().selectionEnd()).blockNumber() text_cursor = QTextCursor(editor.textCursor()) text_cursor.setPosition(editor.textCursor().selectionEnd()) if text_cursor.columnNumber() == 0 and start != end: end -= 1 return start, end
[ "def", "selection_range", "(", "self", ")", ":", "editor", "=", "self", ".", "_editor", "doc", "=", "editor", ".", "document", "(", ")", "start", "=", "doc", ".", "findBlock", "(", "editor", ".", "textCursor", "(", ")", ".", "selectionStart", "(", ")", ")", ".", "blockNumber", "(", ")", "end", "=", "doc", ".", "findBlock", "(", "editor", ".", "textCursor", "(", ")", ".", "selectionEnd", "(", ")", ")", ".", "blockNumber", "(", ")", "text_cursor", "=", "QTextCursor", "(", "editor", ".", "textCursor", "(", ")", ")", "text_cursor", ".", "setPosition", "(", "editor", ".", "textCursor", "(", ")", ".", "selectionEnd", "(", ")", ")", "if", "text_cursor", ".", "columnNumber", "(", ")", "==", "0", "and", "start", "!=", "end", ":", "end", "-=", "1", "return", "start", ",", "end" ]
Returns the selected lines boundaries (start line, end line) :return: tuple(int, int)
[ "Returns", "the", "selected", "lines", "boundaries", "(", "start", "line", "end", "line", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L492-L508
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.line_pos_from_number
def line_pos_from_number(self, line_number): """ Computes line position on Y-Axis (at the center of the line) from line number. :param line_number: The line number for which we want to know the position in pixels. :return: The center position of the line. """ editor = self._editor block = editor.document().findBlockByNumber(line_number) if block.isValid(): return int(editor.blockBoundingGeometry(block).translated( editor.contentOffset()).top()) if line_number <= 0: return 0 else: return int(editor.blockBoundingGeometry( block.previous()).translated(editor.contentOffset()).bottom())
python
def line_pos_from_number(self, line_number): """ Computes line position on Y-Axis (at the center of the line) from line number. :param line_number: The line number for which we want to know the position in pixels. :return: The center position of the line. """ editor = self._editor block = editor.document().findBlockByNumber(line_number) if block.isValid(): return int(editor.blockBoundingGeometry(block).translated( editor.contentOffset()).top()) if line_number <= 0: return 0 else: return int(editor.blockBoundingGeometry( block.previous()).translated(editor.contentOffset()).bottom())
[ "def", "line_pos_from_number", "(", "self", ",", "line_number", ")", ":", "editor", "=", "self", ".", "_editor", "block", "=", "editor", ".", "document", "(", ")", ".", "findBlockByNumber", "(", "line_number", ")", "if", "block", ".", "isValid", "(", ")", ":", "return", "int", "(", "editor", ".", "blockBoundingGeometry", "(", "block", ")", ".", "translated", "(", "editor", ".", "contentOffset", "(", ")", ")", ".", "top", "(", ")", ")", "if", "line_number", "<=", "0", ":", "return", "0", "else", ":", "return", "int", "(", "editor", ".", "blockBoundingGeometry", "(", "block", ".", "previous", "(", ")", ")", ".", "translated", "(", "editor", ".", "contentOffset", "(", ")", ")", ".", "bottom", "(", ")", ")" ]
Computes line position on Y-Axis (at the center of the line) from line number. :param line_number: The line number for which we want to know the position in pixels. :return: The center position of the line.
[ "Computes", "line", "position", "on", "Y", "-", "Axis", "(", "at", "the", "center", "of", "the", "line", ")", "from", "line", "number", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L510-L528
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.line_nbr_from_position
def line_nbr_from_position(self, y_pos): """ Returns the line number from the y_pos. :param y_pos: Y pos in the editor :return: Line number (0 based), -1 if out of range """ editor = self._editor height = editor.fontMetrics().height() for top, line, block in editor.visible_blocks: if top <= y_pos <= top + height: return line return -1
python
def line_nbr_from_position(self, y_pos): """ Returns the line number from the y_pos. :param y_pos: Y pos in the editor :return: Line number (0 based), -1 if out of range """ editor = self._editor height = editor.fontMetrics().height() for top, line, block in editor.visible_blocks: if top <= y_pos <= top + height: return line return -1
[ "def", "line_nbr_from_position", "(", "self", ",", "y_pos", ")", ":", "editor", "=", "self", ".", "_editor", "height", "=", "editor", ".", "fontMetrics", "(", ")", ".", "height", "(", ")", "for", "top", ",", "line", ",", "block", "in", "editor", ".", "visible_blocks", ":", "if", "top", "<=", "y_pos", "<=", "top", "+", "height", ":", "return", "line", "return", "-", "1" ]
Returns the line number from the y_pos. :param y_pos: Y pos in the editor :return: Line number (0 based), -1 if out of range
[ "Returns", "the", "line", "number", "from", "the", "y_pos", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L530-L542
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.mark_whole_doc_dirty
def mark_whole_doc_dirty(self): """ Marks the whole document as dirty to force a full refresh. **SLOW** """ text_cursor = self._editor.textCursor() text_cursor.select(text_cursor.Document) self._editor.document().markContentsDirty(text_cursor.selectionStart(), text_cursor.selectionEnd())
python
def mark_whole_doc_dirty(self): """ Marks the whole document as dirty to force a full refresh. **SLOW** """ text_cursor = self._editor.textCursor() text_cursor.select(text_cursor.Document) self._editor.document().markContentsDirty(text_cursor.selectionStart(), text_cursor.selectionEnd())
[ "def", "mark_whole_doc_dirty", "(", "self", ")", ":", "text_cursor", "=", "self", ".", "_editor", ".", "textCursor", "(", ")", "text_cursor", ".", "select", "(", "text_cursor", ".", "Document", ")", "self", ".", "_editor", ".", "document", "(", ")", ".", "markContentsDirty", "(", "text_cursor", ".", "selectionStart", "(", ")", ",", "text_cursor", ".", "selectionEnd", "(", ")", ")" ]
Marks the whole document as dirty to force a full refresh. **SLOW**
[ "Marks", "the", "whole", "document", "as", "dirty", "to", "force", "a", "full", "refresh", ".", "**", "SLOW", "**" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L544-L551
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.get_right_character
def get_right_character(self, cursor=None): """ Gets the character that is on the right of the text cursor. :param cursor: QTextCursor that defines the position where the search will start. """ next_char = self.get_right_word(cursor=cursor) if len(next_char): next_char = next_char[0] else: next_char = None return next_char
python
def get_right_character(self, cursor=None): """ Gets the character that is on the right of the text cursor. :param cursor: QTextCursor that defines the position where the search will start. """ next_char = self.get_right_word(cursor=cursor) if len(next_char): next_char = next_char[0] else: next_char = None return next_char
[ "def", "get_right_character", "(", "self", ",", "cursor", "=", "None", ")", ":", "next_char", "=", "self", ".", "get_right_word", "(", "cursor", "=", "cursor", ")", "if", "len", "(", "next_char", ")", ":", "next_char", "=", "next_char", "[", "0", "]", "else", ":", "next_char", "=", "None", "return", "next_char" ]
Gets the character that is on the right of the text cursor. :param cursor: QTextCursor that defines the position where the search will start.
[ "Gets", "the", "character", "that", "is", "on", "the", "right", "of", "the", "text", "cursor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L585-L597
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.insert_text
def insert_text(self, text, keep_position=True): """ Inserts text at the cursor position. :param text: text to insert :param keep_position: Flag that specifies if the cursor position must be kept. Pass False for a regular insert (the cursor will be at the end of the inserted text). """ text_cursor = self._editor.textCursor() if keep_position: s = text_cursor.selectionStart() e = text_cursor.selectionEnd() text_cursor.insertText(text) if keep_position: text_cursor.setPosition(s) text_cursor.setPosition(e, text_cursor.KeepAnchor) self._editor.setTextCursor(text_cursor)
python
def insert_text(self, text, keep_position=True): """ Inserts text at the cursor position. :param text: text to insert :param keep_position: Flag that specifies if the cursor position must be kept. Pass False for a regular insert (the cursor will be at the end of the inserted text). """ text_cursor = self._editor.textCursor() if keep_position: s = text_cursor.selectionStart() e = text_cursor.selectionEnd() text_cursor.insertText(text) if keep_position: text_cursor.setPosition(s) text_cursor.setPosition(e, text_cursor.KeepAnchor) self._editor.setTextCursor(text_cursor)
[ "def", "insert_text", "(", "self", ",", "text", ",", "keep_position", "=", "True", ")", ":", "text_cursor", "=", "self", ".", "_editor", ".", "textCursor", "(", ")", "if", "keep_position", ":", "s", "=", "text_cursor", ".", "selectionStart", "(", ")", "e", "=", "text_cursor", ".", "selectionEnd", "(", ")", "text_cursor", ".", "insertText", "(", "text", ")", "if", "keep_position", ":", "text_cursor", ".", "setPosition", "(", "s", ")", "text_cursor", ".", "setPosition", "(", "e", ",", "text_cursor", ".", "KeepAnchor", ")", "self", ".", "_editor", ".", "setTextCursor", "(", "text_cursor", ")" ]
Inserts text at the cursor position. :param text: text to insert :param keep_position: Flag that specifies if the cursor position must be kept. Pass False for a regular insert (the cursor will be at the end of the inserted text).
[ "Inserts", "text", "at", "the", "cursor", "position", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L599-L616
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.clear_selection
def clear_selection(self): """Clears text cursor selection.""" text_cursor = self._editor.textCursor() text_cursor.clearSelection() self._editor.setTextCursor(text_cursor)
python
def clear_selection(self): """Clears text cursor selection.""" text_cursor = self._editor.textCursor() text_cursor.clearSelection() self._editor.setTextCursor(text_cursor)
[ "def", "clear_selection", "(", "self", ")", ":", "text_cursor", "=", "self", ".", "_editor", ".", "textCursor", "(", ")", "text_cursor", ".", "clearSelection", "(", ")", "self", ".", "_editor", ".", "setTextCursor", "(", "text_cursor", ")" ]
Clears text cursor selection.
[ "Clears", "text", "cursor", "selection", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L618-L622
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.move_right
def move_right(self, keep_anchor=False, nb_chars=1): """ Moves the cursor on the right. :param keep_anchor: True to keep anchor (to select text) or False to move the anchor (no selection) :param nb_chars: Number of characters to move. """ text_cursor = self._editor.textCursor() text_cursor.movePosition( text_cursor.Right, text_cursor.KeepAnchor if keep_anchor else text_cursor.MoveAnchor, nb_chars) self._editor.setTextCursor(text_cursor)
python
def move_right(self, keep_anchor=False, nb_chars=1): """ Moves the cursor on the right. :param keep_anchor: True to keep anchor (to select text) or False to move the anchor (no selection) :param nb_chars: Number of characters to move. """ text_cursor = self._editor.textCursor() text_cursor.movePosition( text_cursor.Right, text_cursor.KeepAnchor if keep_anchor else text_cursor.MoveAnchor, nb_chars) self._editor.setTextCursor(text_cursor)
[ "def", "move_right", "(", "self", ",", "keep_anchor", "=", "False", ",", "nb_chars", "=", "1", ")", ":", "text_cursor", "=", "self", ".", "_editor", ".", "textCursor", "(", ")", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "Right", ",", "text_cursor", ".", "KeepAnchor", "if", "keep_anchor", "else", "text_cursor", ".", "MoveAnchor", ",", "nb_chars", ")", "self", ".", "_editor", ".", "setTextCursor", "(", "text_cursor", ")" ]
Moves the cursor on the right. :param keep_anchor: True to keep anchor (to select text) or False to move the anchor (no selection) :param nb_chars: Number of characters to move.
[ "Moves", "the", "cursor", "on", "the", "right", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L624-L636
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextHelper.select_extended_word
def select_extended_word(self, continuation_chars=('.',)): """ Performs extended word selection. Extended selection consists in selecting the word under cursor and any other words that are linked by a ``continuation_chars``. :param continuation_chars: the list of characters that may extend a word. """ cursor = self._editor.textCursor() original_pos = cursor.position() start_pos = None end_pos = None # go left stop = False seps = self._editor.word_separators + [' '] while not stop: cursor.clearSelection() cursor.movePosition(cursor.Left, cursor.KeepAnchor) char = cursor.selectedText() if cursor.atBlockStart(): stop = True start_pos = cursor.position() elif char in seps and char not in continuation_chars: stop = True start_pos = cursor.position() + 1 # go right cursor.setPosition(original_pos) stop = False while not stop: cursor.clearSelection() cursor.movePosition(cursor.Right, cursor.KeepAnchor) char = cursor.selectedText() if cursor.atBlockEnd(): stop = True end_pos = cursor.position() if char in seps: end_pos -= 1 elif char in seps and char not in continuation_chars: stop = True end_pos = cursor.position() - 1 if start_pos and end_pos: cursor.setPosition(start_pos) cursor.movePosition(cursor.Right, cursor.KeepAnchor, end_pos - start_pos) self._editor.setTextCursor(cursor)
python
def select_extended_word(self, continuation_chars=('.',)): """ Performs extended word selection. Extended selection consists in selecting the word under cursor and any other words that are linked by a ``continuation_chars``. :param continuation_chars: the list of characters that may extend a word. """ cursor = self._editor.textCursor() original_pos = cursor.position() start_pos = None end_pos = None # go left stop = False seps = self._editor.word_separators + [' '] while not stop: cursor.clearSelection() cursor.movePosition(cursor.Left, cursor.KeepAnchor) char = cursor.selectedText() if cursor.atBlockStart(): stop = True start_pos = cursor.position() elif char in seps and char not in continuation_chars: stop = True start_pos = cursor.position() + 1 # go right cursor.setPosition(original_pos) stop = False while not stop: cursor.clearSelection() cursor.movePosition(cursor.Right, cursor.KeepAnchor) char = cursor.selectedText() if cursor.atBlockEnd(): stop = True end_pos = cursor.position() if char in seps: end_pos -= 1 elif char in seps and char not in continuation_chars: stop = True end_pos = cursor.position() - 1 if start_pos and end_pos: cursor.setPosition(start_pos) cursor.movePosition(cursor.Right, cursor.KeepAnchor, end_pos - start_pos) self._editor.setTextCursor(cursor)
[ "def", "select_extended_word", "(", "self", ",", "continuation_chars", "=", "(", "'.'", ",", ")", ")", ":", "cursor", "=", "self", ".", "_editor", ".", "textCursor", "(", ")", "original_pos", "=", "cursor", ".", "position", "(", ")", "start_pos", "=", "None", "end_pos", "=", "None", "# go left", "stop", "=", "False", "seps", "=", "self", ".", "_editor", ".", "word_separators", "+", "[", "' '", "]", "while", "not", "stop", ":", "cursor", ".", "clearSelection", "(", ")", "cursor", ".", "movePosition", "(", "cursor", ".", "Left", ",", "cursor", ".", "KeepAnchor", ")", "char", "=", "cursor", ".", "selectedText", "(", ")", "if", "cursor", ".", "atBlockStart", "(", ")", ":", "stop", "=", "True", "start_pos", "=", "cursor", ".", "position", "(", ")", "elif", "char", "in", "seps", "and", "char", "not", "in", "continuation_chars", ":", "stop", "=", "True", "start_pos", "=", "cursor", ".", "position", "(", ")", "+", "1", "# go right", "cursor", ".", "setPosition", "(", "original_pos", ")", "stop", "=", "False", "while", "not", "stop", ":", "cursor", ".", "clearSelection", "(", ")", "cursor", ".", "movePosition", "(", "cursor", ".", "Right", ",", "cursor", ".", "KeepAnchor", ")", "char", "=", "cursor", ".", "selectedText", "(", ")", "if", "cursor", ".", "atBlockEnd", "(", ")", ":", "stop", "=", "True", "end_pos", "=", "cursor", ".", "position", "(", ")", "if", "char", "in", "seps", ":", "end_pos", "-=", "1", "elif", "char", "in", "seps", "and", "char", "not", "in", "continuation_chars", ":", "stop", "=", "True", "end_pos", "=", "cursor", ".", "position", "(", ")", "-", "1", "if", "start_pos", "and", "end_pos", ":", "cursor", ".", "setPosition", "(", "start_pos", ")", "cursor", ".", "movePosition", "(", "cursor", ".", "Right", ",", "cursor", ".", "KeepAnchor", ",", "end_pos", "-", "start_pos", ")", "self", ".", "_editor", ".", "setTextCursor", "(", "cursor", ")" ]
Performs extended word selection. Extended selection consists in selecting the word under cursor and any other words that are linked by a ``continuation_chars``. :param continuation_chars: the list of characters that may extend a word.
[ "Performs", "extended", "word", "selection", ".", "Extended", "selection", "consists", "in", "selecting", "the", "word", "under", "cursor", "and", "any", "other", "words", "that", "are", "linked", "by", "a", "continuation_chars", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L720-L765
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextBlockHelper.set_state
def set_state(block, state): """ Sets the user state, generally used for syntax highlighting. :param block: block to modify :param state: new state value. :return: """ if block is None: return user_state = block.userState() if user_state == -1: user_state = 0 higher_part = user_state & 0x7FFF0000 state &= 0x0000FFFF state |= higher_part block.setUserState(state)
python
def set_state(block, state): """ Sets the user state, generally used for syntax highlighting. :param block: block to modify :param state: new state value. :return: """ if block is None: return user_state = block.userState() if user_state == -1: user_state = 0 higher_part = user_state & 0x7FFF0000 state &= 0x0000FFFF state |= higher_part block.setUserState(state)
[ "def", "set_state", "(", "block", ",", "state", ")", ":", "if", "block", "is", "None", ":", "return", "user_state", "=", "block", ".", "userState", "(", ")", "if", "user_state", "==", "-", "1", ":", "user_state", "=", "0", "higher_part", "=", "user_state", "&", "0x7FFF0000", "state", "&=", "0x0000FFFF", "state", "|=", "higher_part", "block", ".", "setUserState", "(", "state", ")" ]
Sets the user state, generally used for syntax highlighting. :param block: block to modify :param state: new state value. :return:
[ "Sets", "the", "user", "state", "generally", "used", "for", "syntax", "highlighting", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L905-L921
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextBlockHelper.set_fold_lvl
def set_fold_lvl(block, val): """ Sets the block fold level. :param block: block to modify :param val: The new fold level [0-7] """ if block is None: return state = block.userState() if state == -1: state = 0 if val >= 0x3FF: val = 0x3FF state &= 0x7C00FFFF state |= val << 16 block.setUserState(state)
python
def set_fold_lvl(block, val): """ Sets the block fold level. :param block: block to modify :param val: The new fold level [0-7] """ if block is None: return state = block.userState() if state == -1: state = 0 if val >= 0x3FF: val = 0x3FF state &= 0x7C00FFFF state |= val << 16 block.setUserState(state)
[ "def", "set_fold_lvl", "(", "block", ",", "val", ")", ":", "if", "block", "is", "None", ":", "return", "state", "=", "block", ".", "userState", "(", ")", "if", "state", "==", "-", "1", ":", "state", "=", "0", "if", "val", ">=", "0x3FF", ":", "val", "=", "0x3FF", "state", "&=", "0x7C00FFFF", "state", "|=", "val", "<<", "16", "block", ".", "setUserState", "(", "state", ")" ]
Sets the block fold level. :param block: block to modify :param val: The new fold level [0-7]
[ "Sets", "the", "block", "fold", "level", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L939-L955
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextBlockHelper.is_fold_trigger
def is_fold_trigger(block): """ Checks if the block is a fold trigger. :param block: block to check :return: True if the block is a fold trigger (represented as a node in the fold panel) """ if block is None: return False state = block.userState() if state == -1: state = 0 return bool(state & 0x04000000)
python
def is_fold_trigger(block): """ Checks if the block is a fold trigger. :param block: block to check :return: True if the block is a fold trigger (represented as a node in the fold panel) """ if block is None: return False state = block.userState() if state == -1: state = 0 return bool(state & 0x04000000)
[ "def", "is_fold_trigger", "(", "block", ")", ":", "if", "block", "is", "None", ":", "return", "False", "state", "=", "block", ".", "userState", "(", ")", "if", "state", "==", "-", "1", ":", "state", "=", "0", "return", "bool", "(", "state", "&", "0x04000000", ")" ]
Checks if the block is a fold trigger. :param block: block to check :return: True if the block is a fold trigger (represented as a node in the fold panel)
[ "Checks", "if", "the", "block", "is", "a", "fold", "trigger", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L958-L971
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextBlockHelper.set_fold_trigger
def set_fold_trigger(block, val): """ Set the block fold trigger flag (True means the block is a fold trigger). :param block: block to set :param val: value to set """ if block is None: return state = block.userState() if state == -1: state = 0 state &= 0x7BFFFFFF state |= int(val) << 26 block.setUserState(state)
python
def set_fold_trigger(block, val): """ Set the block fold trigger flag (True means the block is a fold trigger). :param block: block to set :param val: value to set """ if block is None: return state = block.userState() if state == -1: state = 0 state &= 0x7BFFFFFF state |= int(val) << 26 block.setUserState(state)
[ "def", "set_fold_trigger", "(", "block", ",", "val", ")", ":", "if", "block", "is", "None", ":", "return", "state", "=", "block", ".", "userState", "(", ")", "if", "state", "==", "-", "1", ":", "state", "=", "0", "state", "&=", "0x7BFFFFFF", "state", "|=", "int", "(", "val", ")", "<<", "26", "block", ".", "setUserState", "(", "state", ")" ]
Set the block fold trigger flag (True means the block is a fold trigger). :param block: block to set :param val: value to set
[ "Set", "the", "block", "fold", "trigger", "flag", "(", "True", "means", "the", "block", "is", "a", "fold", "trigger", ")", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L974-L989
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextBlockHelper.is_collapsed
def is_collapsed(block): """ Checks if the block is expanded or collased. :param block: QTextBlock :return: False for an open trigger, True for for closed trigger """ if block is None: return False state = block.userState() if state == -1: state = 0 return bool(state & 0x08000000)
python
def is_collapsed(block): """ Checks if the block is expanded or collased. :param block: QTextBlock :return: False for an open trigger, True for for closed trigger """ if block is None: return False state = block.userState() if state == -1: state = 0 return bool(state & 0x08000000)
[ "def", "is_collapsed", "(", "block", ")", ":", "if", "block", "is", "None", ":", "return", "False", "state", "=", "block", ".", "userState", "(", ")", "if", "state", "==", "-", "1", ":", "state", "=", "0", "return", "bool", "(", "state", "&", "0x08000000", ")" ]
Checks if the block is expanded or collased. :param block: QTextBlock :return: False for an open trigger, True for for closed trigger
[ "Checks", "if", "the", "block", "is", "expanded", "or", "collased", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L992-L1004
train
spyder-ide/spyder
spyder/plugins/editor/utils/editor.py
TextBlockHelper.set_collapsed
def set_collapsed(block, val): """ Sets the fold trigger state (collapsed or expanded). :param block: The block to modify :param val: The new trigger state (True=collapsed, False=expanded) """ if block is None: return state = block.userState() if state == -1: state = 0 state &= 0x77FFFFFF state |= int(val) << 27 block.setUserState(state)
python
def set_collapsed(block, val): """ Sets the fold trigger state (collapsed or expanded). :param block: The block to modify :param val: The new trigger state (True=collapsed, False=expanded) """ if block is None: return state = block.userState() if state == -1: state = 0 state &= 0x77FFFFFF state |= int(val) << 27 block.setUserState(state)
[ "def", "set_collapsed", "(", "block", ",", "val", ")", ":", "if", "block", "is", "None", ":", "return", "state", "=", "block", ".", "userState", "(", ")", "if", "state", "==", "-", "1", ":", "state", "=", "0", "state", "&=", "0x77FFFFFF", "state", "|=", "int", "(", "val", ")", "<<", "27", "block", ".", "setUserState", "(", "state", ")" ]
Sets the fold trigger state (collapsed or expanded). :param block: The block to modify :param val: The new trigger state (True=collapsed, False=expanded)
[ "Sets", "the", "fold", "trigger", "state", "(", "collapsed", "or", "expanded", ")", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L1007-L1021
train
spyder-ide/spyder
spyder/utils/external/binaryornot/helpers.py
get_starting_chunk
def get_starting_chunk(filename, length=1024): """ :param filename: File to open and get the first little chunk of. :param length: Number of bytes to read, default 1024. :returns: Starting chunk of bytes. """ # Ensure we open the file in binary mode with open(filename, 'rb') as f: chunk = f.read(length) return chunk
python
def get_starting_chunk(filename, length=1024): """ :param filename: File to open and get the first little chunk of. :param length: Number of bytes to read, default 1024. :returns: Starting chunk of bytes. """ # Ensure we open the file in binary mode with open(filename, 'rb') as f: chunk = f.read(length) return chunk
[ "def", "get_starting_chunk", "(", "filename", ",", "length", "=", "1024", ")", ":", "# Ensure we open the file in binary mode", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "chunk", "=", "f", ".", "read", "(", "length", ")", "return", "chunk" ]
:param filename: File to open and get the first little chunk of. :param length: Number of bytes to read, default 1024. :returns: Starting chunk of bytes.
[ ":", "param", "filename", ":", "File", "to", "open", "and", "get", "the", "first", "little", "chunk", "of", ".", ":", "param", "length", ":", "Number", "of", "bytes", "to", "read", "default", "1024", ".", ":", "returns", ":", "Starting", "chunk", "of", "bytes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/external/binaryornot/helpers.py#L34-L43
train
spyder-ide/spyder
spyder/utils/external/binaryornot/helpers.py
is_binary_string
def is_binary_string(bytes_to_check): """ Uses a simplified version of the Perl detection algorithm, based roughly on Eli Bendersky's translation to Python: https://eli.thegreenplace.net/2011/10/19/perls-guess-if-file-is-text-or-binary-implemented-in-python/ This is biased slightly more in favour of deeming files as text files than the Perl algorithm, since all ASCII compatible character sets are accepted as text, not just utf-8. :param bytes: A chunk of bytes to check. :returns: True if appears to be a binary, otherwise False. """ # Empty files are considered text files if not bytes_to_check: return False # Now check for a high percentage of ASCII control characters # Binary if control chars are > 30% of the string low_chars = bytes_to_check.translate(None, _printable_ascii) nontext_ratio1 = float(len(low_chars)) / float(len(bytes_to_check)) logger.debug('nontext_ratio1: %(nontext_ratio1)r', locals()) # and check for a low percentage of high ASCII characters: # Binary if high ASCII chars are < 5% of the string # From: https://en.wikipedia.org/wiki/UTF-8 # If the bytes are random, the chances of a byte with the high bit set # starting a valid UTF-8 character is only 6.64%. The chances of finding 7 # of these without finding an invalid sequence is actually lower than the # chance of the first three bytes randomly being the UTF-8 BOM. high_chars = bytes_to_check.translate(None, _printable_high_ascii) nontext_ratio2 = float(len(high_chars)) / float(len(bytes_to_check)) logger.debug('nontext_ratio2: %(nontext_ratio2)r', locals()) is_likely_binary = ( (nontext_ratio1 > 0.3 and nontext_ratio2 < 0.05) or (nontext_ratio1 > 0.8 and nontext_ratio2 > 0.8) ) logger.debug('is_likely_binary: %(is_likely_binary)r', locals()) # then check for binary for possible encoding detection with chardet detected_encoding = chardet.detect(bytes_to_check) logger.debug('detected_encoding: %(detected_encoding)r', locals()) # finally use all the check to decide binary or text decodable_as_unicode = False if (detected_encoding['confidence'] > 0.9 and detected_encoding['encoding'] != 'ascii'): try: try: bytes_to_check.decode(encoding=detected_encoding['encoding']) except TypeError: # happens only on Python 2.6 unicode(bytes_to_check, encoding=detected_encoding['encoding']) # noqa decodable_as_unicode = True logger.debug('success: decodable_as_unicode: ' '%(decodable_as_unicode)r', locals()) except LookupError: logger.debug('failure: could not look up encoding %(encoding)s', detected_encoding) except UnicodeDecodeError: logger.debug('failure: decodable_as_unicode: ' '%(decodable_as_unicode)r', locals()) logger.debug('failure: decodable_as_unicode: ' '%(decodable_as_unicode)r', locals()) if is_likely_binary: if decodable_as_unicode: return False else: return True else: if decodable_as_unicode: return False else: if b'\x00' in bytes_to_check or b'\xff' in bytes_to_check: # Check for NULL bytes last logger.debug('has nulls:' + repr(b'\x00' in bytes_to_check)) return True return False
python
def is_binary_string(bytes_to_check): """ Uses a simplified version of the Perl detection algorithm, based roughly on Eli Bendersky's translation to Python: https://eli.thegreenplace.net/2011/10/19/perls-guess-if-file-is-text-or-binary-implemented-in-python/ This is biased slightly more in favour of deeming files as text files than the Perl algorithm, since all ASCII compatible character sets are accepted as text, not just utf-8. :param bytes: A chunk of bytes to check. :returns: True if appears to be a binary, otherwise False. """ # Empty files are considered text files if not bytes_to_check: return False # Now check for a high percentage of ASCII control characters # Binary if control chars are > 30% of the string low_chars = bytes_to_check.translate(None, _printable_ascii) nontext_ratio1 = float(len(low_chars)) / float(len(bytes_to_check)) logger.debug('nontext_ratio1: %(nontext_ratio1)r', locals()) # and check for a low percentage of high ASCII characters: # Binary if high ASCII chars are < 5% of the string # From: https://en.wikipedia.org/wiki/UTF-8 # If the bytes are random, the chances of a byte with the high bit set # starting a valid UTF-8 character is only 6.64%. The chances of finding 7 # of these without finding an invalid sequence is actually lower than the # chance of the first three bytes randomly being the UTF-8 BOM. high_chars = bytes_to_check.translate(None, _printable_high_ascii) nontext_ratio2 = float(len(high_chars)) / float(len(bytes_to_check)) logger.debug('nontext_ratio2: %(nontext_ratio2)r', locals()) is_likely_binary = ( (nontext_ratio1 > 0.3 and nontext_ratio2 < 0.05) or (nontext_ratio1 > 0.8 and nontext_ratio2 > 0.8) ) logger.debug('is_likely_binary: %(is_likely_binary)r', locals()) # then check for binary for possible encoding detection with chardet detected_encoding = chardet.detect(bytes_to_check) logger.debug('detected_encoding: %(detected_encoding)r', locals()) # finally use all the check to decide binary or text decodable_as_unicode = False if (detected_encoding['confidence'] > 0.9 and detected_encoding['encoding'] != 'ascii'): try: try: bytes_to_check.decode(encoding=detected_encoding['encoding']) except TypeError: # happens only on Python 2.6 unicode(bytes_to_check, encoding=detected_encoding['encoding']) # noqa decodable_as_unicode = True logger.debug('success: decodable_as_unicode: ' '%(decodable_as_unicode)r', locals()) except LookupError: logger.debug('failure: could not look up encoding %(encoding)s', detected_encoding) except UnicodeDecodeError: logger.debug('failure: decodable_as_unicode: ' '%(decodable_as_unicode)r', locals()) logger.debug('failure: decodable_as_unicode: ' '%(decodable_as_unicode)r', locals()) if is_likely_binary: if decodable_as_unicode: return False else: return True else: if decodable_as_unicode: return False else: if b'\x00' in bytes_to_check or b'\xff' in bytes_to_check: # Check for NULL bytes last logger.debug('has nulls:' + repr(b'\x00' in bytes_to_check)) return True return False
[ "def", "is_binary_string", "(", "bytes_to_check", ")", ":", "# Empty files are considered text files", "if", "not", "bytes_to_check", ":", "return", "False", "# Now check for a high percentage of ASCII control characters", "# Binary if control chars are > 30% of the string", "low_chars", "=", "bytes_to_check", ".", "translate", "(", "None", ",", "_printable_ascii", ")", "nontext_ratio1", "=", "float", "(", "len", "(", "low_chars", ")", ")", "/", "float", "(", "len", "(", "bytes_to_check", ")", ")", "logger", ".", "debug", "(", "'nontext_ratio1: %(nontext_ratio1)r'", ",", "locals", "(", ")", ")", "# and check for a low percentage of high ASCII characters:", "# Binary if high ASCII chars are < 5% of the string", "# From: https://en.wikipedia.org/wiki/UTF-8", "# If the bytes are random, the chances of a byte with the high bit set", "# starting a valid UTF-8 character is only 6.64%. The chances of finding 7", "# of these without finding an invalid sequence is actually lower than the", "# chance of the first three bytes randomly being the UTF-8 BOM.", "high_chars", "=", "bytes_to_check", ".", "translate", "(", "None", ",", "_printable_high_ascii", ")", "nontext_ratio2", "=", "float", "(", "len", "(", "high_chars", ")", ")", "/", "float", "(", "len", "(", "bytes_to_check", ")", ")", "logger", ".", "debug", "(", "'nontext_ratio2: %(nontext_ratio2)r'", ",", "locals", "(", ")", ")", "is_likely_binary", "=", "(", "(", "nontext_ratio1", ">", "0.3", "and", "nontext_ratio2", "<", "0.05", ")", "or", "(", "nontext_ratio1", ">", "0.8", "and", "nontext_ratio2", ">", "0.8", ")", ")", "logger", ".", "debug", "(", "'is_likely_binary: %(is_likely_binary)r'", ",", "locals", "(", ")", ")", "# then check for binary for possible encoding detection with chardet", "detected_encoding", "=", "chardet", ".", "detect", "(", "bytes_to_check", ")", "logger", ".", "debug", "(", "'detected_encoding: %(detected_encoding)r'", ",", "locals", "(", ")", ")", "# finally use all the check to decide binary or text", "decodable_as_unicode", "=", "False", "if", "(", "detected_encoding", "[", "'confidence'", "]", ">", "0.9", "and", "detected_encoding", "[", "'encoding'", "]", "!=", "'ascii'", ")", ":", "try", ":", "try", ":", "bytes_to_check", ".", "decode", "(", "encoding", "=", "detected_encoding", "[", "'encoding'", "]", ")", "except", "TypeError", ":", "# happens only on Python 2.6", "unicode", "(", "bytes_to_check", ",", "encoding", "=", "detected_encoding", "[", "'encoding'", "]", ")", "# noqa", "decodable_as_unicode", "=", "True", "logger", ".", "debug", "(", "'success: decodable_as_unicode: '", "'%(decodable_as_unicode)r'", ",", "locals", "(", ")", ")", "except", "LookupError", ":", "logger", ".", "debug", "(", "'failure: could not look up encoding %(encoding)s'", ",", "detected_encoding", ")", "except", "UnicodeDecodeError", ":", "logger", ".", "debug", "(", "'failure: decodable_as_unicode: '", "'%(decodable_as_unicode)r'", ",", "locals", "(", ")", ")", "logger", ".", "debug", "(", "'failure: decodable_as_unicode: '", "'%(decodable_as_unicode)r'", ",", "locals", "(", ")", ")", "if", "is_likely_binary", ":", "if", "decodable_as_unicode", ":", "return", "False", "else", ":", "return", "True", "else", ":", "if", "decodable_as_unicode", ":", "return", "False", "else", ":", "if", "b'\\x00'", "in", "bytes_to_check", "or", "b'\\xff'", "in", "bytes_to_check", ":", "# Check for NULL bytes last", "logger", ".", "debug", "(", "'has nulls:'", "+", "repr", "(", "b'\\x00'", "in", "bytes_to_check", ")", ")", "return", "True", "return", "False" ]
Uses a simplified version of the Perl detection algorithm, based roughly on Eli Bendersky's translation to Python: https://eli.thegreenplace.net/2011/10/19/perls-guess-if-file-is-text-or-binary-implemented-in-python/ This is biased slightly more in favour of deeming files as text files than the Perl algorithm, since all ASCII compatible character sets are accepted as text, not just utf-8. :param bytes: A chunk of bytes to check. :returns: True if appears to be a binary, otherwise False.
[ "Uses", "a", "simplified", "version", "of", "the", "Perl", "detection", "algorithm", "based", "roughly", "on", "Eli", "Bendersky", "s", "translation", "to", "Python", ":", "https", ":", "//", "eli", ".", "thegreenplace", ".", "net", "/", "2011", "/", "10", "/", "19", "/", "perls", "-", "guess", "-", "if", "-", "file", "-", "is", "-", "text", "-", "or", "-", "binary", "-", "implemented", "-", "in", "-", "python", "/" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/external/binaryornot/helpers.py#L57-L138
train
spyder-ide/spyder
spyder/widgets/status.py
StatusBarWidget.set_value
def set_value(self, value): """Set formatted text value.""" self.value = value if self.isVisible(): self.label_value.setText(value)
python
def set_value(self, value): """Set formatted text value.""" self.value = value if self.isVisible(): self.label_value.setText(value)
[ "def", "set_value", "(", "self", ",", "value", ")", ":", "self", ".", "value", "=", "value", "if", "self", ".", "isVisible", "(", ")", ":", "self", ".", "label_value", ".", "setText", "(", "value", ")" ]
Set formatted text value.
[ "Set", "formatted", "text", "value", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/status.py#L74-L78
train
spyder-ide/spyder
spyder/widgets/status.py
BaseTimerStatus.setVisible
def setVisible(self, value): """Override Qt method to stops timers if widget is not visible.""" if self.timer is not None: if value: self.timer.start(self._interval) else: self.timer.stop() super(BaseTimerStatus, self).setVisible(value)
python
def setVisible(self, value): """Override Qt method to stops timers if widget is not visible.""" if self.timer is not None: if value: self.timer.start(self._interval) else: self.timer.stop() super(BaseTimerStatus, self).setVisible(value)
[ "def", "setVisible", "(", "self", ",", "value", ")", ":", "if", "self", ".", "timer", "is", "not", "None", ":", "if", "value", ":", "self", ".", "timer", ".", "start", "(", "self", ".", "_interval", ")", "else", ":", "self", ".", "timer", ".", "stop", "(", ")", "super", "(", "BaseTimerStatus", ",", "self", ")", ".", "setVisible", "(", "value", ")" ]
Override Qt method to stops timers if widget is not visible.
[ "Override", "Qt", "method", "to", "stops", "timers", "if", "widget", "is", "not", "visible", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/status.py#L102-L109
train
spyder-ide/spyder
spyder/widgets/status.py
BaseTimerStatus.set_interval
def set_interval(self, interval): """Set timer interval (ms).""" self._interval = interval if self.timer is not None: self.timer.setInterval(interval)
python
def set_interval(self, interval): """Set timer interval (ms).""" self._interval = interval if self.timer is not None: self.timer.setInterval(interval)
[ "def", "set_interval", "(", "self", ",", "interval", ")", ":", "self", ".", "_interval", "=", "interval", "if", "self", ".", "timer", "is", "not", "None", ":", "self", ".", "timer", ".", "setInterval", "(", "interval", ")" ]
Set timer interval (ms).
[ "Set", "timer", "interval", "(", "ms", ")", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/status.py#L111-L115
train
spyder-ide/spyder
spyder/widgets/status.py
MemoryStatus.get_value
def get_value(self): """Return memory usage.""" from spyder.utils.system import memory_usage text = '%d%%' % memory_usage() return 'Mem ' + text.rjust(3)
python
def get_value(self): """Return memory usage.""" from spyder.utils.system import memory_usage text = '%d%%' % memory_usage() return 'Mem ' + text.rjust(3)
[ "def", "get_value", "(", "self", ")", ":", "from", "spyder", ".", "utils", ".", "system", "import", "memory_usage", "text", "=", "'%d%%'", "%", "memory_usage", "(", ")", "return", "'Mem '", "+", "text", ".", "rjust", "(", "3", ")" ]
Return memory usage.
[ "Return", "memory", "usage", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/status.py#L150-L154
train
spyder-ide/spyder
spyder/plugins/help/utils/sphinxify.py
warning
def warning(message, css_path=CSS_PATH): """Print a warning message on the rich text view""" env = Environment() env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates')) warning = env.get_template("warning.html") return warning.render(css_path=css_path, text=message)
python
def warning(message, css_path=CSS_PATH): """Print a warning message on the rich text view""" env = Environment() env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates')) warning = env.get_template("warning.html") return warning.render(css_path=css_path, text=message)
[ "def", "warning", "(", "message", ",", "css_path", "=", "CSS_PATH", ")", ":", "env", "=", "Environment", "(", ")", "env", ".", "loader", "=", "FileSystemLoader", "(", "osp", ".", "join", "(", "CONFDIR_PATH", ",", "'templates'", ")", ")", "warning", "=", "env", ".", "get_template", "(", "\"warning.html\"", ")", "return", "warning", ".", "render", "(", "css_path", "=", "css_path", ",", "text", "=", "message", ")" ]
Print a warning message on the rich text view
[ "Print", "a", "warning", "message", "on", "the", "rich", "text", "view" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L77-L82
train
spyder-ide/spyder
spyder/plugins/help/utils/sphinxify.py
usage
def usage(title, message, tutorial_message, tutorial, css_path=CSS_PATH): """Print a usage message on the rich text view""" env = Environment() env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates')) usage = env.get_template("usage.html") return usage.render(css_path=css_path, title=title, intro_message=message, tutorial_message=tutorial_message, tutorial=tutorial)
python
def usage(title, message, tutorial_message, tutorial, css_path=CSS_PATH): """Print a usage message on the rich text view""" env = Environment() env.loader = FileSystemLoader(osp.join(CONFDIR_PATH, 'templates')) usage = env.get_template("usage.html") return usage.render(css_path=css_path, title=title, intro_message=message, tutorial_message=tutorial_message, tutorial=tutorial)
[ "def", "usage", "(", "title", ",", "message", ",", "tutorial_message", ",", "tutorial", ",", "css_path", "=", "CSS_PATH", ")", ":", "env", "=", "Environment", "(", ")", "env", ".", "loader", "=", "FileSystemLoader", "(", "osp", ".", "join", "(", "CONFDIR_PATH", ",", "'templates'", ")", ")", "usage", "=", "env", ".", "get_template", "(", "\"usage.html\"", ")", "return", "usage", ".", "render", "(", "css_path", "=", "css_path", ",", "title", "=", "title", ",", "intro_message", "=", "message", ",", "tutorial_message", "=", "tutorial_message", ",", "tutorial", "=", "tutorial", ")" ]
Print a usage message on the rich text view
[ "Print", "a", "usage", "message", "on", "the", "rich", "text", "view" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L85-L91
train
spyder-ide/spyder
spyder/plugins/help/utils/sphinxify.py
generate_context
def generate_context(name='', argspec='', note='', math=False, collapse=False, img_path='', css_path=CSS_PATH): """ Generate the html_context dictionary for our Sphinx conf file. This is a set of variables to be passed to the Jinja template engine and that are used to control how the webpage is rendered in connection with Sphinx Parameters ---------- name : str Object's name. note : str A note describing what type has the function or method being introspected argspec : str Argspec of the the function or method being introspected math : bool Turn on/off Latex rendering on the OI. If False, Latex will be shown in plain text. collapse : bool Collapse sections img_path : str Path for images relative to the file containing the docstring Returns ------- A dict of strings to be used by Jinja to generate the webpage """ if img_path and os.name == 'nt': img_path = img_path.replace('\\', '/') context = \ { # Arg dependent variables 'math_on': 'true' if math else '', 'name': name, 'argspec': argspec, 'note': note, 'collapse': collapse, 'img_path': img_path, # Static variables 'css_path': css_path, 'js_path': JS_PATH, 'jquery_path': JQUERY_PATH, 'mathjax_path': MATHJAX_PATH, 'right_sphinx_version': '' if sphinx.__version__ < "1.1" else 'true', 'platform': sys.platform } return context
python
def generate_context(name='', argspec='', note='', math=False, collapse=False, img_path='', css_path=CSS_PATH): """ Generate the html_context dictionary for our Sphinx conf file. This is a set of variables to be passed to the Jinja template engine and that are used to control how the webpage is rendered in connection with Sphinx Parameters ---------- name : str Object's name. note : str A note describing what type has the function or method being introspected argspec : str Argspec of the the function or method being introspected math : bool Turn on/off Latex rendering on the OI. If False, Latex will be shown in plain text. collapse : bool Collapse sections img_path : str Path for images relative to the file containing the docstring Returns ------- A dict of strings to be used by Jinja to generate the webpage """ if img_path and os.name == 'nt': img_path = img_path.replace('\\', '/') context = \ { # Arg dependent variables 'math_on': 'true' if math else '', 'name': name, 'argspec': argspec, 'note': note, 'collapse': collapse, 'img_path': img_path, # Static variables 'css_path': css_path, 'js_path': JS_PATH, 'jquery_path': JQUERY_PATH, 'mathjax_path': MATHJAX_PATH, 'right_sphinx_version': '' if sphinx.__version__ < "1.1" else 'true', 'platform': sys.platform } return context
[ "def", "generate_context", "(", "name", "=", "''", ",", "argspec", "=", "''", ",", "note", "=", "''", ",", "math", "=", "False", ",", "collapse", "=", "False", ",", "img_path", "=", "''", ",", "css_path", "=", "CSS_PATH", ")", ":", "if", "img_path", "and", "os", ".", "name", "==", "'nt'", ":", "img_path", "=", "img_path", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "context", "=", "{", "# Arg dependent variables", "'math_on'", ":", "'true'", "if", "math", "else", "''", ",", "'name'", ":", "name", ",", "'argspec'", ":", "argspec", ",", "'note'", ":", "note", ",", "'collapse'", ":", "collapse", ",", "'img_path'", ":", "img_path", ",", "# Static variables", "'css_path'", ":", "css_path", ",", "'js_path'", ":", "JS_PATH", ",", "'jquery_path'", ":", "JQUERY_PATH", ",", "'mathjax_path'", ":", "MATHJAX_PATH", ",", "'right_sphinx_version'", ":", "''", "if", "sphinx", ".", "__version__", "<", "\"1.1\"", "else", "'true'", ",", "'platform'", ":", "sys", ".", "platform", "}", "return", "context" ]
Generate the html_context dictionary for our Sphinx conf file. This is a set of variables to be passed to the Jinja template engine and that are used to control how the webpage is rendered in connection with Sphinx Parameters ---------- name : str Object's name. note : str A note describing what type has the function or method being introspected argspec : str Argspec of the the function or method being introspected math : bool Turn on/off Latex rendering on the OI. If False, Latex will be shown in plain text. collapse : bool Collapse sections img_path : str Path for images relative to the file containing the docstring Returns ------- A dict of strings to be used by Jinja to generate the webpage
[ "Generate", "the", "html_context", "dictionary", "for", "our", "Sphinx", "conf", "file", ".", "This", "is", "a", "set", "of", "variables", "to", "be", "passed", "to", "the", "Jinja", "template", "engine", "and", "that", "are", "used", "to", "control", "how", "the", "webpage", "is", "rendered", "in", "connection", "with", "Sphinx" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L94-L146
train
spyder-ide/spyder
spyder/plugins/help/utils/sphinxify.py
sphinxify
def sphinxify(docstring, context, buildername='html'): """ Runs Sphinx on a docstring and outputs the processed documentation. Parameters ---------- docstring : str a ReST-formatted docstring context : dict Variables to be passed to the layout template to control how its rendered (through the Sphinx variable *html_context*). buildername: str It can be either `html` or `text`. Returns ------- An Sphinx-processed string, in either HTML or plain text format, depending on the value of `buildername` """ srcdir = mkdtemp() srcdir = encoding.to_unicode_from_fs(srcdir) destdir = osp.join(srcdir, '_build') rst_name = osp.join(srcdir, 'docstring.rst') if buildername == 'html': suffix = '.html' else: suffix = '.txt' output_name = osp.join(destdir, 'docstring' + suffix) # This is needed so users can type \\ on latex eqnarray envs inside raw # docstrings if context['right_sphinx_version'] and context['math_on']: docstring = docstring.replace('\\\\', '\\\\\\\\') # Add a class to several characters on the argspec. This way we can # highlight them using css, in a similar way to what IPython does. # NOTE: Before doing this, we escape common html chars so that they # don't interfere with the rest of html present in the page argspec = escape(context['argspec']) for char in ['=', ',', '(', ')', '*', '**']: argspec = argspec.replace(char, '<span class="argspec-highlight">' + char + '</span>') context['argspec'] = argspec doc_file = codecs.open(rst_name, 'w', encoding='utf-8') doc_file.write(docstring) doc_file.close() temp_confdir = False if temp_confdir: # TODO: This may be inefficient. Find a faster way to do it. confdir = mkdtemp() confdir = encoding.to_unicode_from_fs(confdir) generate_configuration(confdir) else: confdir = osp.join(get_module_source_path('spyder.plugins.help.utils')) confoverrides = {'html_context': context} doctreedir = osp.join(srcdir, 'doctrees') sphinx_app = Sphinx(srcdir, confdir, destdir, doctreedir, buildername, confoverrides, status=None, warning=None, freshenv=True, warningiserror=False, tags=None) try: sphinx_app.build(None, [rst_name]) except SystemMessage: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) # TODO: Investigate if this is necessary/important for us if osp.exists(output_name): output = codecs.open(output_name, 'r', encoding='utf-8').read() output = output.replace('<pre>', '<pre class="literal-block">') else: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) if temp_confdir: shutil.rmtree(confdir, ignore_errors=True) shutil.rmtree(srcdir, ignore_errors=True) return output
python
def sphinxify(docstring, context, buildername='html'): """ Runs Sphinx on a docstring and outputs the processed documentation. Parameters ---------- docstring : str a ReST-formatted docstring context : dict Variables to be passed to the layout template to control how its rendered (through the Sphinx variable *html_context*). buildername: str It can be either `html` or `text`. Returns ------- An Sphinx-processed string, in either HTML or plain text format, depending on the value of `buildername` """ srcdir = mkdtemp() srcdir = encoding.to_unicode_from_fs(srcdir) destdir = osp.join(srcdir, '_build') rst_name = osp.join(srcdir, 'docstring.rst') if buildername == 'html': suffix = '.html' else: suffix = '.txt' output_name = osp.join(destdir, 'docstring' + suffix) # This is needed so users can type \\ on latex eqnarray envs inside raw # docstrings if context['right_sphinx_version'] and context['math_on']: docstring = docstring.replace('\\\\', '\\\\\\\\') # Add a class to several characters on the argspec. This way we can # highlight them using css, in a similar way to what IPython does. # NOTE: Before doing this, we escape common html chars so that they # don't interfere with the rest of html present in the page argspec = escape(context['argspec']) for char in ['=', ',', '(', ')', '*', '**']: argspec = argspec.replace(char, '<span class="argspec-highlight">' + char + '</span>') context['argspec'] = argspec doc_file = codecs.open(rst_name, 'w', encoding='utf-8') doc_file.write(docstring) doc_file.close() temp_confdir = False if temp_confdir: # TODO: This may be inefficient. Find a faster way to do it. confdir = mkdtemp() confdir = encoding.to_unicode_from_fs(confdir) generate_configuration(confdir) else: confdir = osp.join(get_module_source_path('spyder.plugins.help.utils')) confoverrides = {'html_context': context} doctreedir = osp.join(srcdir, 'doctrees') sphinx_app = Sphinx(srcdir, confdir, destdir, doctreedir, buildername, confoverrides, status=None, warning=None, freshenv=True, warningiserror=False, tags=None) try: sphinx_app.build(None, [rst_name]) except SystemMessage: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) # TODO: Investigate if this is necessary/important for us if osp.exists(output_name): output = codecs.open(output_name, 'r', encoding='utf-8').read() output = output.replace('<pre>', '<pre class="literal-block">') else: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) if temp_confdir: shutil.rmtree(confdir, ignore_errors=True) shutil.rmtree(srcdir, ignore_errors=True) return output
[ "def", "sphinxify", "(", "docstring", ",", "context", ",", "buildername", "=", "'html'", ")", ":", "srcdir", "=", "mkdtemp", "(", ")", "srcdir", "=", "encoding", ".", "to_unicode_from_fs", "(", "srcdir", ")", "destdir", "=", "osp", ".", "join", "(", "srcdir", ",", "'_build'", ")", "rst_name", "=", "osp", ".", "join", "(", "srcdir", ",", "'docstring.rst'", ")", "if", "buildername", "==", "'html'", ":", "suffix", "=", "'.html'", "else", ":", "suffix", "=", "'.txt'", "output_name", "=", "osp", ".", "join", "(", "destdir", ",", "'docstring'", "+", "suffix", ")", "# This is needed so users can type \\\\ on latex eqnarray envs inside raw", "# docstrings", "if", "context", "[", "'right_sphinx_version'", "]", "and", "context", "[", "'math_on'", "]", ":", "docstring", "=", "docstring", ".", "replace", "(", "'\\\\\\\\'", ",", "'\\\\\\\\\\\\\\\\'", ")", "# Add a class to several characters on the argspec. This way we can", "# highlight them using css, in a similar way to what IPython does.", "# NOTE: Before doing this, we escape common html chars so that they", "# don't interfere with the rest of html present in the page", "argspec", "=", "escape", "(", "context", "[", "'argspec'", "]", ")", "for", "char", "in", "[", "'='", ",", "','", ",", "'('", ",", "')'", ",", "'*'", ",", "'**'", "]", ":", "argspec", "=", "argspec", ".", "replace", "(", "char", ",", "'<span class=\"argspec-highlight\">'", "+", "char", "+", "'</span>'", ")", "context", "[", "'argspec'", "]", "=", "argspec", "doc_file", "=", "codecs", ".", "open", "(", "rst_name", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "doc_file", ".", "write", "(", "docstring", ")", "doc_file", ".", "close", "(", ")", "temp_confdir", "=", "False", "if", "temp_confdir", ":", "# TODO: This may be inefficient. Find a faster way to do it.", "confdir", "=", "mkdtemp", "(", ")", "confdir", "=", "encoding", ".", "to_unicode_from_fs", "(", "confdir", ")", "generate_configuration", "(", "confdir", ")", "else", ":", "confdir", "=", "osp", ".", "join", "(", "get_module_source_path", "(", "'spyder.plugins.help.utils'", ")", ")", "confoverrides", "=", "{", "'html_context'", ":", "context", "}", "doctreedir", "=", "osp", ".", "join", "(", "srcdir", ",", "'doctrees'", ")", "sphinx_app", "=", "Sphinx", "(", "srcdir", ",", "confdir", ",", "destdir", ",", "doctreedir", ",", "buildername", ",", "confoverrides", ",", "status", "=", "None", ",", "warning", "=", "None", ",", "freshenv", "=", "True", ",", "warningiserror", "=", "False", ",", "tags", "=", "None", ")", "try", ":", "sphinx_app", ".", "build", "(", "None", ",", "[", "rst_name", "]", ")", "except", "SystemMessage", ":", "output", "=", "_", "(", "\"It was not possible to generate rich text help for this \"", "\"object.</br>\"", "\"Please see it in plain text.\"", ")", "return", "warning", "(", "output", ")", "# TODO: Investigate if this is necessary/important for us", "if", "osp", ".", "exists", "(", "output_name", ")", ":", "output", "=", "codecs", ".", "open", "(", "output_name", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", ".", "read", "(", ")", "output", "=", "output", ".", "replace", "(", "'<pre>'", ",", "'<pre class=\"literal-block\">'", ")", "else", ":", "output", "=", "_", "(", "\"It was not possible to generate rich text help for this \"", "\"object.</br>\"", "\"Please see it in plain text.\"", ")", "return", "warning", "(", "output", ")", "if", "temp_confdir", ":", "shutil", ".", "rmtree", "(", "confdir", ",", "ignore_errors", "=", "True", ")", "shutil", ".", "rmtree", "(", "srcdir", ",", "ignore_errors", "=", "True", ")", "return", "output" ]
Runs Sphinx on a docstring and outputs the processed documentation. Parameters ---------- docstring : str a ReST-formatted docstring context : dict Variables to be passed to the layout template to control how its rendered (through the Sphinx variable *html_context*). buildername: str It can be either `html` or `text`. Returns ------- An Sphinx-processed string, in either HTML or plain text format, depending on the value of `buildername`
[ "Runs", "Sphinx", "on", "a", "docstring", "and", "outputs", "the", "processed", "documentation", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L149-L239
train
spyder-ide/spyder
spyder/plugins/help/utils/sphinxify.py
generate_configuration
def generate_configuration(directory): """ Generates a Sphinx configuration in `directory`. Parameters ---------- directory : str Base directory to use """ # conf.py file for Sphinx conf = osp.join(get_module_source_path('spyder.plugins.help.utils'), 'conf.py') # Docstring layout page (in Jinja): layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html') os.makedirs(osp.join(directory, 'templates')) os.makedirs(osp.join(directory, 'static')) shutil.copy(conf, directory) shutil.copy(layout, osp.join(directory, 'templates')) open(osp.join(directory, '__init__.py'), 'w').write('') open(osp.join(directory, 'static', 'empty'), 'w').write('')
python
def generate_configuration(directory): """ Generates a Sphinx configuration in `directory`. Parameters ---------- directory : str Base directory to use """ # conf.py file for Sphinx conf = osp.join(get_module_source_path('spyder.plugins.help.utils'), 'conf.py') # Docstring layout page (in Jinja): layout = osp.join(osp.join(CONFDIR_PATH, 'templates'), 'layout.html') os.makedirs(osp.join(directory, 'templates')) os.makedirs(osp.join(directory, 'static')) shutil.copy(conf, directory) shutil.copy(layout, osp.join(directory, 'templates')) open(osp.join(directory, '__init__.py'), 'w').write('') open(osp.join(directory, 'static', 'empty'), 'w').write('')
[ "def", "generate_configuration", "(", "directory", ")", ":", "# conf.py file for Sphinx", "conf", "=", "osp", ".", "join", "(", "get_module_source_path", "(", "'spyder.plugins.help.utils'", ")", ",", "'conf.py'", ")", "# Docstring layout page (in Jinja):", "layout", "=", "osp", ".", "join", "(", "osp", ".", "join", "(", "CONFDIR_PATH", ",", "'templates'", ")", ",", "'layout.html'", ")", "os", ".", "makedirs", "(", "osp", ".", "join", "(", "directory", ",", "'templates'", ")", ")", "os", ".", "makedirs", "(", "osp", ".", "join", "(", "directory", ",", "'static'", ")", ")", "shutil", ".", "copy", "(", "conf", ",", "directory", ")", "shutil", ".", "copy", "(", "layout", ",", "osp", ".", "join", "(", "directory", ",", "'templates'", ")", ")", "open", "(", "osp", ".", "join", "(", "directory", ",", "'__init__.py'", ")", ",", "'w'", ")", ".", "write", "(", "''", ")", "open", "(", "osp", ".", "join", "(", "directory", ",", "'static'", ",", "'empty'", ")", ",", "'w'", ")", ".", "write", "(", "''", ")" ]
Generates a Sphinx configuration in `directory`. Parameters ---------- directory : str Base directory to use
[ "Generates", "a", "Sphinx", "configuration", "in", "directory", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/utils/sphinxify.py#L242-L264
train
spyder-ide/spyder
spyder/plugins/editor/widgets/status.py
EOLStatus.update_eol
def update_eol(self, os_name): """Update end of line status.""" os_name = to_text_string(os_name) value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR") self.set_value(value)
python
def update_eol(self, os_name): """Update end of line status.""" os_name = to_text_string(os_name) value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR") self.set_value(value)
[ "def", "update_eol", "(", "self", ",", "os_name", ")", ":", "os_name", "=", "to_text_string", "(", "os_name", ")", "value", "=", "{", "\"nt\"", ":", "\"CRLF\"", ",", "\"posix\"", ":", "\"LF\"", "}", ".", "get", "(", "os_name", ",", "\"CR\"", ")", "self", ".", "set_value", "(", "value", ")" ]
Update end of line status.
[ "Update", "end", "of", "line", "status", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L34-L38
train
spyder-ide/spyder
spyder/plugins/editor/widgets/status.py
EncodingStatus.update_encoding
def update_encoding(self, encoding): """Update encoding of current file.""" value = str(encoding).upper() self.set_value(value)
python
def update_encoding(self, encoding): """Update encoding of current file.""" value = str(encoding).upper() self.set_value(value)
[ "def", "update_encoding", "(", "self", ",", "encoding", ")", ":", "value", "=", "str", "(", "encoding", ")", ".", "upper", "(", ")", "self", ".", "set_value", "(", "value", ")" ]
Update encoding of current file.
[ "Update", "encoding", "of", "current", "file", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L45-L48
train
spyder-ide/spyder
spyder/plugins/editor/widgets/status.py
CursorPositionStatus.update_cursor_position
def update_cursor_position(self, line, index): """Update cursor position.""" value = 'Line {}, Col {}'.format(line + 1, index + 1) self.set_value(value)
python
def update_cursor_position(self, line, index): """Update cursor position.""" value = 'Line {}, Col {}'.format(line + 1, index + 1) self.set_value(value)
[ "def", "update_cursor_position", "(", "self", ",", "line", ",", "index", ")", ":", "value", "=", "'Line {}, Col {}'", ".", "format", "(", "line", "+", "1", ",", "index", "+", "1", ")", "self", ".", "set_value", "(", "value", ")" ]
Update cursor position.
[ "Update", "cursor", "position", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L55-L58
train
spyder-ide/spyder
spyder/plugins/editor/widgets/status.py
VCSStatus.update_vcs
def update_vcs(self, fname, index): """Update vcs status.""" fpath = os.path.dirname(fname) branches, branch, files_modified = get_git_refs(fpath) text = branch if branch else '' if len(files_modified): text = text + ' [{}]'.format(len(files_modified)) self.setVisible(bool(branch)) self.set_value(text)
python
def update_vcs(self, fname, index): """Update vcs status.""" fpath = os.path.dirname(fname) branches, branch, files_modified = get_git_refs(fpath) text = branch if branch else '' if len(files_modified): text = text + ' [{}]'.format(len(files_modified)) self.setVisible(bool(branch)) self.set_value(text)
[ "def", "update_vcs", "(", "self", ",", "fname", ",", "index", ")", ":", "fpath", "=", "os", ".", "path", ".", "dirname", "(", "fname", ")", "branches", ",", "branch", ",", "files_modified", "=", "get_git_refs", "(", "fpath", ")", "text", "=", "branch", "if", "branch", "else", "''", "if", "len", "(", "files_modified", ")", ":", "text", "=", "text", "+", "' [{}]'", ".", "format", "(", "len", "(", "files_modified", ")", ")", "self", ".", "setVisible", "(", "bool", "(", "branch", ")", ")", "self", ".", "set_value", "(", "text", ")" ]
Update vcs status.
[ "Update", "vcs", "status", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/status.py#L73-L83
train
spyder-ide/spyder
spyder/plugins/variableexplorer/plugin.py
VariableExplorer.get_settings
def get_settings(self): """ Retrieve all Variable Explorer configuration settings. Specifically, return the settings in CONF_SECTION with keys in REMOTE_SETTINGS, and the setting 'dataframe_format'. Returns: dict: settings """ settings = {} for name in REMOTE_SETTINGS: settings[name] = self.get_option(name) # dataframe_format is stored without percent sign in config # to avoid interference with ConfigParser's interpolation name = 'dataframe_format' settings[name] = '%{0}'.format(self.get_option(name)) return settings
python
def get_settings(self): """ Retrieve all Variable Explorer configuration settings. Specifically, return the settings in CONF_SECTION with keys in REMOTE_SETTINGS, and the setting 'dataframe_format'. Returns: dict: settings """ settings = {} for name in REMOTE_SETTINGS: settings[name] = self.get_option(name) # dataframe_format is stored without percent sign in config # to avoid interference with ConfigParser's interpolation name = 'dataframe_format' settings[name] = '%{0}'.format(self.get_option(name)) return settings
[ "def", "get_settings", "(", "self", ")", ":", "settings", "=", "{", "}", "for", "name", "in", "REMOTE_SETTINGS", ":", "settings", "[", "name", "]", "=", "self", ".", "get_option", "(", "name", ")", "# dataframe_format is stored without percent sign in config\r", "# to avoid interference with ConfigParser's interpolation\r", "name", "=", "'dataframe_format'", "settings", "[", "name", "]", "=", "'%{0}'", ".", "format", "(", "self", ".", "get_option", "(", "name", ")", ")", "return", "settings" ]
Retrieve all Variable Explorer configuration settings. Specifically, return the settings in CONF_SECTION with keys in REMOTE_SETTINGS, and the setting 'dataframe_format'. Returns: dict: settings
[ "Retrieve", "all", "Variable", "Explorer", "configuration", "settings", ".", "Specifically", "return", "the", "settings", "in", "CONF_SECTION", "with", "keys", "in", "REMOTE_SETTINGS", "and", "the", "setting", "dataframe_format", ".", "Returns", ":", "dict", ":", "settings" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/plugin.py#L59-L77
train
spyder-ide/spyder
spyder/plugins/variableexplorer/plugin.py
VariableExplorer.change_option
def change_option(self, option_name, new_value): """ Change a config option. This function is called if sig_option_changed is received. If the option changed is the dataframe format, then the leading '%' character is stripped (because it can't be stored in the user config). Then, the signal is emitted again, so that the new value is saved in the user config. """ if option_name == 'dataframe_format': assert new_value.startswith('%') new_value = new_value[1:] self.sig_option_changed.emit(option_name, new_value)
python
def change_option(self, option_name, new_value): """ Change a config option. This function is called if sig_option_changed is received. If the option changed is the dataframe format, then the leading '%' character is stripped (because it can't be stored in the user config). Then, the signal is emitted again, so that the new value is saved in the user config. """ if option_name == 'dataframe_format': assert new_value.startswith('%') new_value = new_value[1:] self.sig_option_changed.emit(option_name, new_value)
[ "def", "change_option", "(", "self", ",", "option_name", ",", "new_value", ")", ":", "if", "option_name", "==", "'dataframe_format'", ":", "assert", "new_value", ".", "startswith", "(", "'%'", ")", "new_value", "=", "new_value", "[", "1", ":", "]", "self", ".", "sig_option_changed", ".", "emit", "(", "option_name", ",", "new_value", ")" ]
Change a config option. This function is called if sig_option_changed is received. If the option changed is the dataframe format, then the leading '%' character is stripped (because it can't be stored in the user config). Then, the signal is emitted again, so that the new value is saved in the user config.
[ "Change", "a", "config", "option", ".", "This", "function", "is", "called", "if", "sig_option_changed", "is", "received", ".", "If", "the", "option", "changed", "is", "the", "dataframe", "format", "then", "the", "leading", "%", "character", "is", "stripped", "(", "because", "it", "can", "t", "be", "stored", "in", "the", "user", "config", ")", ".", "Then", "the", "signal", "is", "emitted", "again", "so", "that", "the", "new", "value", "is", "saved", "in", "the", "user", "config", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/plugin.py#L80-L93
train
spyder-ide/spyder
spyder/plugins/variableexplorer/plugin.py
VariableExplorer.free_memory
def free_memory(self): """Free memory signal.""" self.main.free_memory() QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER, lambda: self.main.free_memory()) QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER, lambda: self.main.free_memory())
python
def free_memory(self): """Free memory signal.""" self.main.free_memory() QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER, lambda: self.main.free_memory()) QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER, lambda: self.main.free_memory())
[ "def", "free_memory", "(", "self", ")", ":", "self", ".", "main", ".", "free_memory", "(", ")", "QTimer", ".", "singleShot", "(", "self", ".", "INITIAL_FREE_MEMORY_TIME_TRIGGER", ",", "lambda", ":", "self", ".", "main", ".", "free_memory", "(", ")", ")", "QTimer", ".", "singleShot", "(", "self", ".", "SECONDARY_FREE_MEMORY_TIME_TRIGGER", ",", "lambda", ":", "self", ".", "main", ".", "free_memory", "(", ")", ")" ]
Free memory signal.
[ "Free", "memory", "signal", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/plugin.py#L96-L102
train
spyder-ide/spyder
spyder/plugins/variableexplorer/plugin.py
VariableExplorer.add_shellwidget
def add_shellwidget(self, shellwidget): """ Register shell with variable explorer. This function opens a new NamespaceBrowser for browsing the variables in the shell. """ shellwidget_id = id(shellwidget) if shellwidget_id not in self.shellwidgets: self.options_button.setVisible(True) nsb = NamespaceBrowser(self, options_button=self.options_button) nsb.set_shellwidget(shellwidget) nsb.setup(**self.get_settings()) nsb.sig_option_changed.connect(self.change_option) nsb.sig_free_memory.connect(self.free_memory) self.add_widget(nsb) self.shellwidgets[shellwidget_id] = nsb self.set_shellwidget_from_id(shellwidget_id) return nsb
python
def add_shellwidget(self, shellwidget): """ Register shell with variable explorer. This function opens a new NamespaceBrowser for browsing the variables in the shell. """ shellwidget_id = id(shellwidget) if shellwidget_id not in self.shellwidgets: self.options_button.setVisible(True) nsb = NamespaceBrowser(self, options_button=self.options_button) nsb.set_shellwidget(shellwidget) nsb.setup(**self.get_settings()) nsb.sig_option_changed.connect(self.change_option) nsb.sig_free_memory.connect(self.free_memory) self.add_widget(nsb) self.shellwidgets[shellwidget_id] = nsb self.set_shellwidget_from_id(shellwidget_id) return nsb
[ "def", "add_shellwidget", "(", "self", ",", "shellwidget", ")", ":", "shellwidget_id", "=", "id", "(", "shellwidget", ")", "if", "shellwidget_id", "not", "in", "self", ".", "shellwidgets", ":", "self", ".", "options_button", ".", "setVisible", "(", "True", ")", "nsb", "=", "NamespaceBrowser", "(", "self", ",", "options_button", "=", "self", ".", "options_button", ")", "nsb", ".", "set_shellwidget", "(", "shellwidget", ")", "nsb", ".", "setup", "(", "*", "*", "self", ".", "get_settings", "(", ")", ")", "nsb", ".", "sig_option_changed", ".", "connect", "(", "self", ".", "change_option", ")", "nsb", ".", "sig_free_memory", ".", "connect", "(", "self", ".", "free_memory", ")", "self", ".", "add_widget", "(", "nsb", ")", "self", ".", "shellwidgets", "[", "shellwidget_id", "]", "=", "nsb", "self", ".", "set_shellwidget_from_id", "(", "shellwidget_id", ")", "return", "nsb" ]
Register shell with variable explorer. This function opens a new NamespaceBrowser for browsing the variables in the shell.
[ "Register", "shell", "with", "variable", "explorer", ".", "This", "function", "opens", "a", "new", "NamespaceBrowser", "for", "browsing", "the", "variables", "in", "the", "shell", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/plugin.py#L125-L143
train
spyder-ide/spyder
spyder/plugins/variableexplorer/plugin.py
VariableExplorer.import_data
def import_data(self, fname): """Import data in current namespace""" if self.count(): nsb = self.current_widget() nsb.refresh_table() nsb.import_data(filenames=fname) if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.raise_()
python
def import_data(self, fname): """Import data in current namespace""" if self.count(): nsb = self.current_widget() nsb.refresh_table() nsb.import_data(filenames=fname) if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.raise_()
[ "def", "import_data", "(", "self", ",", "fname", ")", ":", "if", "self", ".", "count", "(", ")", ":", "nsb", "=", "self", ".", "current_widget", "(", ")", "nsb", ".", "refresh_table", "(", ")", "nsb", ".", "import_data", "(", "filenames", "=", "fname", ")", "if", "self", ".", "dockwidget", "and", "not", "self", ".", "ismaximized", ":", "self", ".", "dockwidget", ".", "setVisible", "(", "True", ")", "self", ".", "dockwidget", ".", "raise_", "(", ")" ]
Import data in current namespace
[ "Import", "data", "in", "current", "namespace" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/plugin.py#L158-L166
train
spyder-ide/spyder
spyder/plugins/help/widgets.py
ObjectComboBox.is_valid
def is_valid(self, qstr=None): """Return True if string is valid""" if not self.help.source_is_console(): return True if qstr is None: qstr = self.currentText() if not re.search(r'^[a-zA-Z0-9_\.]*$', str(qstr), 0): return False objtxt = to_text_string(qstr) shell_is_defined = False if self.help.get_option('automatic_import'): shell = self.help.internal_shell if shell is not None: shell_is_defined = shell.is_defined(objtxt, force_import=True) if not shell_is_defined: shell = self.help.get_shell() if shell is not None: try: shell_is_defined = shell.is_defined(objtxt) except socket.error: shell = self.help.get_shell() try: shell_is_defined = shell.is_defined(objtxt) except socket.error: # Well... too bad! pass return shell_is_defined
python
def is_valid(self, qstr=None): """Return True if string is valid""" if not self.help.source_is_console(): return True if qstr is None: qstr = self.currentText() if not re.search(r'^[a-zA-Z0-9_\.]*$', str(qstr), 0): return False objtxt = to_text_string(qstr) shell_is_defined = False if self.help.get_option('automatic_import'): shell = self.help.internal_shell if shell is not None: shell_is_defined = shell.is_defined(objtxt, force_import=True) if not shell_is_defined: shell = self.help.get_shell() if shell is not None: try: shell_is_defined = shell.is_defined(objtxt) except socket.error: shell = self.help.get_shell() try: shell_is_defined = shell.is_defined(objtxt) except socket.error: # Well... too bad! pass return shell_is_defined
[ "def", "is_valid", "(", "self", ",", "qstr", "=", "None", ")", ":", "if", "not", "self", ".", "help", ".", "source_is_console", "(", ")", ":", "return", "True", "if", "qstr", "is", "None", ":", "qstr", "=", "self", ".", "currentText", "(", ")", "if", "not", "re", ".", "search", "(", "r'^[a-zA-Z0-9_\\.]*$'", ",", "str", "(", "qstr", ")", ",", "0", ")", ":", "return", "False", "objtxt", "=", "to_text_string", "(", "qstr", ")", "shell_is_defined", "=", "False", "if", "self", ".", "help", ".", "get_option", "(", "'automatic_import'", ")", ":", "shell", "=", "self", ".", "help", ".", "internal_shell", "if", "shell", "is", "not", "None", ":", "shell_is_defined", "=", "shell", ".", "is_defined", "(", "objtxt", ",", "force_import", "=", "True", ")", "if", "not", "shell_is_defined", ":", "shell", "=", "self", ".", "help", ".", "get_shell", "(", ")", "if", "shell", "is", "not", "None", ":", "try", ":", "shell_is_defined", "=", "shell", ".", "is_defined", "(", "objtxt", ")", "except", "socket", ".", "error", ":", "shell", "=", "self", ".", "help", ".", "get_shell", "(", ")", "try", ":", "shell_is_defined", "=", "shell", ".", "is_defined", "(", "objtxt", ")", "except", "socket", ".", "error", ":", "# Well... too bad!", "pass", "return", "shell_is_defined" ]
Return True if string is valid
[ "Return", "True", "if", "string", "is", "valid" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/widgets.py#L47-L73
train
spyder-ide/spyder
spyder/plugins/help/widgets.py
ObjectComboBox.validate
def validate(self, qstr, editing=True): """Reimplemented to avoid formatting actions""" valid = self.is_valid(qstr) if self.hasFocus() and valid is not None: if editing and not valid: # Combo box text is being modified: invalidate the entry self.show_tip(self.tips[valid]) self.valid.emit(False, False) else: # A new item has just been selected if valid: self.selected() else: self.valid.emit(False, False)
python
def validate(self, qstr, editing=True): """Reimplemented to avoid formatting actions""" valid = self.is_valid(qstr) if self.hasFocus() and valid is not None: if editing and not valid: # Combo box text is being modified: invalidate the entry self.show_tip(self.tips[valid]) self.valid.emit(False, False) else: # A new item has just been selected if valid: self.selected() else: self.valid.emit(False, False)
[ "def", "validate", "(", "self", ",", "qstr", ",", "editing", "=", "True", ")", ":", "valid", "=", "self", ".", "is_valid", "(", "qstr", ")", "if", "self", ".", "hasFocus", "(", ")", "and", "valid", "is", "not", "None", ":", "if", "editing", "and", "not", "valid", ":", "# Combo box text is being modified: invalidate the entry", "self", ".", "show_tip", "(", "self", ".", "tips", "[", "valid", "]", ")", "self", ".", "valid", ".", "emit", "(", "False", ",", "False", ")", "else", ":", "# A new item has just been selected", "if", "valid", ":", "self", ".", "selected", "(", ")", "else", ":", "self", ".", "valid", ".", "emit", "(", "False", ",", "False", ")" ]
Reimplemented to avoid formatting actions
[ "Reimplemented", "to", "avoid", "formatting", "actions" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/widgets.py#L78-L91
train
spyder-ide/spyder
spyder/plugins/help/widgets.py
RichText.set_font
def set_font(self, font, fixed_font=None): """Set font""" self.webview.set_font(font, fixed_font=fixed_font)
python
def set_font(self, font, fixed_font=None): """Set font""" self.webview.set_font(font, fixed_font=fixed_font)
[ "def", "set_font", "(", "self", ",", "font", ",", "fixed_font", "=", "None", ")", ":", "self", ".", "webview", ".", "set_font", "(", "font", ",", "fixed_font", "=", "fixed_font", ")" ]
Set font
[ "Set", "font" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/widgets.py#L118-L120
train
spyder-ide/spyder
spyder/plugins/help/widgets.py
PlainText.set_font
def set_font(self, font, color_scheme=None): """Set font""" self.editor.set_font(font, color_scheme=color_scheme)
python
def set_font(self, font, color_scheme=None): """Set font""" self.editor.set_font(font, color_scheme=color_scheme)
[ "def", "set_font", "(", "self", ",", "font", ",", "color_scheme", "=", "None", ")", ":", "self", ".", "editor", ".", "set_font", "(", "font", ",", "color_scheme", "=", "color_scheme", ")" ]
Set font
[ "Set", "font" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/widgets.py#L159-L161
train
spyder-ide/spyder
spyder/utils/codeanalysis.py
find_tasks
def find_tasks(source_code): """Find tasks in source code (TODO, FIXME, XXX, ...)""" results = [] for line, text in enumerate(source_code.splitlines()): for todo in re.findall(TASKS_PATTERN, text): todo_text = (todo[-1].strip(' :').capitalize() if todo[-1] else todo[-2]) results.append((todo_text, line + 1)) return results
python
def find_tasks(source_code): """Find tasks in source code (TODO, FIXME, XXX, ...)""" results = [] for line, text in enumerate(source_code.splitlines()): for todo in re.findall(TASKS_PATTERN, text): todo_text = (todo[-1].strip(' :').capitalize() if todo[-1] else todo[-2]) results.append((todo_text, line + 1)) return results
[ "def", "find_tasks", "(", "source_code", ")", ":", "results", "=", "[", "]", "for", "line", ",", "text", "in", "enumerate", "(", "source_code", ".", "splitlines", "(", ")", ")", ":", "for", "todo", "in", "re", ".", "findall", "(", "TASKS_PATTERN", ",", "text", ")", ":", "todo_text", "=", "(", "todo", "[", "-", "1", "]", ".", "strip", "(", "' :'", ")", ".", "capitalize", "(", ")", "if", "todo", "[", "-", "1", "]", "else", "todo", "[", "-", "2", "]", ")", "results", ".", "append", "(", "(", "todo_text", ",", "line", "+", "1", ")", ")", "return", "results" ]
Find tasks in source code (TODO, FIXME, XXX, ...)
[ "Find", "tasks", "in", "source", "code", "(", "TODO", "FIXME", "XXX", "...", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L30-L38
train
spyder-ide/spyder
spyder/utils/codeanalysis.py
check_with_pyflakes
def check_with_pyflakes(source_code, filename=None): """Check source code with pyflakes Returns an empty list if pyflakes is not installed""" try: if filename is None: filename = '<string>' try: source_code += '\n' except TypeError: # Python 3 source_code += to_binary_string('\n') import _ast from pyflakes.checker import Checker # First, compile into an AST and handle syntax errors. try: tree = compile(source_code, filename, "exec", _ast.PyCF_ONLY_AST) except SyntaxError as value: # If there's an encoding problem with the file, the text is None. if value.text is None: results = [] else: results = [(value.args[0], value.lineno)] except (ValueError, TypeError): # Example of ValueError: file contains invalid \x escape character # (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674797) # Example of TypeError: file contains null character # (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674796) results = [] else: # Okay, it's syntactically valid. Now check it. w = Checker(tree, filename) w.messages.sort(key=lambda x: x.lineno) results = [] coding = encoding.get_coding(source_code) lines = source_code.splitlines() for warning in w.messages: if 'analysis:ignore' not in \ to_text_string(lines[warning.lineno-1], coding): results.append((warning.message % warning.message_args, warning.lineno)) except Exception: # Never return None to avoid lock in spyder/widgets/editor.py # See Issue 1547 results = [] if DEBUG_EDITOR: traceback.print_exc() # Print exception in internal console return results
python
def check_with_pyflakes(source_code, filename=None): """Check source code with pyflakes Returns an empty list if pyflakes is not installed""" try: if filename is None: filename = '<string>' try: source_code += '\n' except TypeError: # Python 3 source_code += to_binary_string('\n') import _ast from pyflakes.checker import Checker # First, compile into an AST and handle syntax errors. try: tree = compile(source_code, filename, "exec", _ast.PyCF_ONLY_AST) except SyntaxError as value: # If there's an encoding problem with the file, the text is None. if value.text is None: results = [] else: results = [(value.args[0], value.lineno)] except (ValueError, TypeError): # Example of ValueError: file contains invalid \x escape character # (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674797) # Example of TypeError: file contains null character # (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674796) results = [] else: # Okay, it's syntactically valid. Now check it. w = Checker(tree, filename) w.messages.sort(key=lambda x: x.lineno) results = [] coding = encoding.get_coding(source_code) lines = source_code.splitlines() for warning in w.messages: if 'analysis:ignore' not in \ to_text_string(lines[warning.lineno-1], coding): results.append((warning.message % warning.message_args, warning.lineno)) except Exception: # Never return None to avoid lock in spyder/widgets/editor.py # See Issue 1547 results = [] if DEBUG_EDITOR: traceback.print_exc() # Print exception in internal console return results
[ "def", "check_with_pyflakes", "(", "source_code", ",", "filename", "=", "None", ")", ":", "try", ":", "if", "filename", "is", "None", ":", "filename", "=", "'<string>'", "try", ":", "source_code", "+=", "'\\n'", "except", "TypeError", ":", "# Python 3\r", "source_code", "+=", "to_binary_string", "(", "'\\n'", ")", "import", "_ast", "from", "pyflakes", ".", "checker", "import", "Checker", "# First, compile into an AST and handle syntax errors.\r", "try", ":", "tree", "=", "compile", "(", "source_code", ",", "filename", ",", "\"exec\"", ",", "_ast", ".", "PyCF_ONLY_AST", ")", "except", "SyntaxError", "as", "value", ":", "# If there's an encoding problem with the file, the text is None.\r", "if", "value", ".", "text", "is", "None", ":", "results", "=", "[", "]", "else", ":", "results", "=", "[", "(", "value", ".", "args", "[", "0", "]", ",", "value", ".", "lineno", ")", "]", "except", "(", "ValueError", ",", "TypeError", ")", ":", "# Example of ValueError: file contains invalid \\x escape character\r", "# (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674797)\r", "# Example of TypeError: file contains null character\r", "# (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674796)\r", "results", "=", "[", "]", "else", ":", "# Okay, it's syntactically valid. Now check it.\r", "w", "=", "Checker", "(", "tree", ",", "filename", ")", "w", ".", "messages", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "lineno", ")", "results", "=", "[", "]", "coding", "=", "encoding", ".", "get_coding", "(", "source_code", ")", "lines", "=", "source_code", ".", "splitlines", "(", ")", "for", "warning", "in", "w", ".", "messages", ":", "if", "'analysis:ignore'", "not", "in", "to_text_string", "(", "lines", "[", "warning", ".", "lineno", "-", "1", "]", ",", "coding", ")", ":", "results", ".", "append", "(", "(", "warning", ".", "message", "%", "warning", ".", "message_args", ",", "warning", ".", "lineno", ")", ")", "except", "Exception", ":", "# Never return None to avoid lock in spyder/widgets/editor.py\r", "# See Issue 1547\r", "results", "=", "[", "]", "if", "DEBUG_EDITOR", ":", "traceback", ".", "print_exc", "(", ")", "# Print exception in internal console\r", "return", "results" ]
Check source code with pyflakes Returns an empty list if pyflakes is not installed
[ "Check", "source", "code", "with", "pyflakes", "Returns", "an", "empty", "list", "if", "pyflakes", "is", "not", "installed" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L41-L88
train
spyder-ide/spyder
spyder/utils/codeanalysis.py
get_checker_executable
def get_checker_executable(name): """Return checker executable in the form of a list of arguments for subprocess.Popen""" if programs.is_program_installed(name): # Checker is properly installed return [name] else: path1 = programs.python_script_exists(package=None, module=name+'_script') path2 = programs.python_script_exists(package=None, module=name) if path1 is not None: # checker_script.py is available # Checker script is available but has not been installed # (this may work with pyflakes) return [sys.executable, path1] elif path2 is not None: # checker.py is available # Checker package is available but its script has not been # installed (this works with pycodestyle but not with pyflakes) return [sys.executable, path2]
python
def get_checker_executable(name): """Return checker executable in the form of a list of arguments for subprocess.Popen""" if programs.is_program_installed(name): # Checker is properly installed return [name] else: path1 = programs.python_script_exists(package=None, module=name+'_script') path2 = programs.python_script_exists(package=None, module=name) if path1 is not None: # checker_script.py is available # Checker script is available but has not been installed # (this may work with pyflakes) return [sys.executable, path1] elif path2 is not None: # checker.py is available # Checker package is available but its script has not been # installed (this works with pycodestyle but not with pyflakes) return [sys.executable, path2]
[ "def", "get_checker_executable", "(", "name", ")", ":", "if", "programs", ".", "is_program_installed", "(", "name", ")", ":", "# Checker is properly installed\r", "return", "[", "name", "]", "else", ":", "path1", "=", "programs", ".", "python_script_exists", "(", "package", "=", "None", ",", "module", "=", "name", "+", "'_script'", ")", "path2", "=", "programs", ".", "python_script_exists", "(", "package", "=", "None", ",", "module", "=", "name", ")", "if", "path1", "is", "not", "None", ":", "# checker_script.py is available\r", "# Checker script is available but has not been installed\r", "# (this may work with pyflakes)\r", "return", "[", "sys", ".", "executable", ",", "path1", "]", "elif", "path2", "is", "not", "None", ":", "# checker.py is available\r", "# Checker package is available but its script has not been\r", "# installed (this works with pycodestyle but not with pyflakes)\r", "return", "[", "sys", ".", "executable", ",", "path2", "]" ]
Return checker executable in the form of a list of arguments for subprocess.Popen
[ "Return", "checker", "executable", "in", "the", "form", "of", "a", "list", "of", "arguments", "for", "subprocess", ".", "Popen" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L96-L113
train
spyder-ide/spyder
spyder/utils/codeanalysis.py
check
def check(args, source_code, filename=None, options=None): """Check source code with checker defined with *args* (list) Returns an empty list if checker is not installed""" if args is None: return [] if options is not None: args += options if any(['pyflakes' in arg for arg in args]): # Pyflakes requires an ending new line (pycodestyle don't! -- see Issue 1123) # Note: this code is not used right now as it is faster to invoke # pyflakes in current Python interpreter (see `check_with_pyflakes` # function above) than calling it through a subprocess source_code += '\n' if filename is None: # Creating a temporary file because file does not exist yet # or is not up-to-date tempfd = tempfile.NamedTemporaryFile(suffix=".py", delete=False) tempfd.write(source_code) tempfd.close() args.append(tempfd.name) else: args.append(filename) cmd = args[0] cmdargs = args[1:] proc = programs.run_program(cmd, cmdargs) output = proc.communicate()[0].strip().decode().splitlines() if filename is None: os.unlink(tempfd.name) results = [] coding = encoding.get_coding(source_code) lines = source_code.splitlines() for line in output: lineno = int(re.search(r'(\:[\d]+\:)', line).group()[1:-1]) try: text = to_text_string(lines[lineno-1], coding) except TypeError: text = to_text_string(lines[lineno-1]) except UnicodeDecodeError: # Needed to handle UnicodeDecodeError and force the use # of chardet to detect enconding. See issue 6970 coding = encoding.get_coding(source_code, force_chardet=True) text = to_text_string(lines[lineno-1], coding) if 'analysis:ignore' not in text: message = line[line.find(': ')+2:] results.append((message, lineno)) return results
python
def check(args, source_code, filename=None, options=None): """Check source code with checker defined with *args* (list) Returns an empty list if checker is not installed""" if args is None: return [] if options is not None: args += options if any(['pyflakes' in arg for arg in args]): # Pyflakes requires an ending new line (pycodestyle don't! -- see Issue 1123) # Note: this code is not used right now as it is faster to invoke # pyflakes in current Python interpreter (see `check_with_pyflakes` # function above) than calling it through a subprocess source_code += '\n' if filename is None: # Creating a temporary file because file does not exist yet # or is not up-to-date tempfd = tempfile.NamedTemporaryFile(suffix=".py", delete=False) tempfd.write(source_code) tempfd.close() args.append(tempfd.name) else: args.append(filename) cmd = args[0] cmdargs = args[1:] proc = programs.run_program(cmd, cmdargs) output = proc.communicate()[0].strip().decode().splitlines() if filename is None: os.unlink(tempfd.name) results = [] coding = encoding.get_coding(source_code) lines = source_code.splitlines() for line in output: lineno = int(re.search(r'(\:[\d]+\:)', line).group()[1:-1]) try: text = to_text_string(lines[lineno-1], coding) except TypeError: text = to_text_string(lines[lineno-1]) except UnicodeDecodeError: # Needed to handle UnicodeDecodeError and force the use # of chardet to detect enconding. See issue 6970 coding = encoding.get_coding(source_code, force_chardet=True) text = to_text_string(lines[lineno-1], coding) if 'analysis:ignore' not in text: message = line[line.find(': ')+2:] results.append((message, lineno)) return results
[ "def", "check", "(", "args", ",", "source_code", ",", "filename", "=", "None", ",", "options", "=", "None", ")", ":", "if", "args", "is", "None", ":", "return", "[", "]", "if", "options", "is", "not", "None", ":", "args", "+=", "options", "if", "any", "(", "[", "'pyflakes'", "in", "arg", "for", "arg", "in", "args", "]", ")", ":", "# Pyflakes requires an ending new line (pycodestyle don't! -- see Issue 1123)\r", "# Note: this code is not used right now as it is faster to invoke \r", "# pyflakes in current Python interpreter (see `check_with_pyflakes` \r", "# function above) than calling it through a subprocess\r", "source_code", "+=", "'\\n'", "if", "filename", "is", "None", ":", "# Creating a temporary file because file does not exist yet \r", "# or is not up-to-date\r", "tempfd", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".py\"", ",", "delete", "=", "False", ")", "tempfd", ".", "write", "(", "source_code", ")", "tempfd", ".", "close", "(", ")", "args", ".", "append", "(", "tempfd", ".", "name", ")", "else", ":", "args", ".", "append", "(", "filename", ")", "cmd", "=", "args", "[", "0", "]", "cmdargs", "=", "args", "[", "1", ":", "]", "proc", "=", "programs", ".", "run_program", "(", "cmd", ",", "cmdargs", ")", "output", "=", "proc", ".", "communicate", "(", ")", "[", "0", "]", ".", "strip", "(", ")", ".", "decode", "(", ")", ".", "splitlines", "(", ")", "if", "filename", "is", "None", ":", "os", ".", "unlink", "(", "tempfd", ".", "name", ")", "results", "=", "[", "]", "coding", "=", "encoding", ".", "get_coding", "(", "source_code", ")", "lines", "=", "source_code", ".", "splitlines", "(", ")", "for", "line", "in", "output", ":", "lineno", "=", "int", "(", "re", ".", "search", "(", "r'(\\:[\\d]+\\:)'", ",", "line", ")", ".", "group", "(", ")", "[", "1", ":", "-", "1", "]", ")", "try", ":", "text", "=", "to_text_string", "(", "lines", "[", "lineno", "-", "1", "]", ",", "coding", ")", "except", "TypeError", ":", "text", "=", "to_text_string", "(", "lines", "[", "lineno", "-", "1", "]", ")", "except", "UnicodeDecodeError", ":", "# Needed to handle UnicodeDecodeError and force the use\r", "# of chardet to detect enconding. See issue 6970\r", "coding", "=", "encoding", ".", "get_coding", "(", "source_code", ",", "force_chardet", "=", "True", ")", "text", "=", "to_text_string", "(", "lines", "[", "lineno", "-", "1", "]", ",", "coding", ")", "if", "'analysis:ignore'", "not", "in", "text", ":", "message", "=", "line", "[", "line", ".", "find", "(", "': '", ")", "+", "2", ":", "]", "results", ".", "append", "(", "(", "message", ",", "lineno", ")", ")", "return", "results" ]
Check source code with checker defined with *args* (list) Returns an empty list if checker is not installed
[ "Check", "source", "code", "with", "checker", "defined", "with", "*", "args", "*", "(", "list", ")", "Returns", "an", "empty", "list", "if", "checker", "is", "not", "installed" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L116-L161
train
spyder-ide/spyder
spyder/utils/codeanalysis.py
check_with_pep8
def check_with_pep8(source_code, filename=None): """Check source code with pycodestyle""" try: args = get_checker_executable('pycodestyle') results = check(args, source_code, filename=filename, options=['-r']) except Exception: # Never return None to avoid lock in spyder/widgets/editor.py # See Issue 1547 results = [] if DEBUG_EDITOR: traceback.print_exc() # Print exception in internal console return results
python
def check_with_pep8(source_code, filename=None): """Check source code with pycodestyle""" try: args = get_checker_executable('pycodestyle') results = check(args, source_code, filename=filename, options=['-r']) except Exception: # Never return None to avoid lock in spyder/widgets/editor.py # See Issue 1547 results = [] if DEBUG_EDITOR: traceback.print_exc() # Print exception in internal console return results
[ "def", "check_with_pep8", "(", "source_code", ",", "filename", "=", "None", ")", ":", "try", ":", "args", "=", "get_checker_executable", "(", "'pycodestyle'", ")", "results", "=", "check", "(", "args", ",", "source_code", ",", "filename", "=", "filename", ",", "options", "=", "[", "'-r'", "]", ")", "except", "Exception", ":", "# Never return None to avoid lock in spyder/widgets/editor.py\r", "# See Issue 1547\r", "results", "=", "[", "]", "if", "DEBUG_EDITOR", ":", "traceback", ".", "print_exc", "(", ")", "# Print exception in internal console\r", "return", "results" ]
Check source code with pycodestyle
[ "Check", "source", "code", "with", "pycodestyle" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/codeanalysis.py#L164-L175
train
spyder-ide/spyder
spyder/utils/qthelpers.py
get_image_label
def get_image_label(name, default="not_found.png"): """Return image inside a QLabel object""" label = QLabel() label.setPixmap(QPixmap(get_image_path(name, default))) return label
python
def get_image_label(name, default="not_found.png"): """Return image inside a QLabel object""" label = QLabel() label.setPixmap(QPixmap(get_image_path(name, default))) return label
[ "def", "get_image_label", "(", "name", ",", "default", "=", "\"not_found.png\"", ")", ":", "label", "=", "QLabel", "(", ")", "label", ".", "setPixmap", "(", "QPixmap", "(", "get_image_path", "(", "name", ",", "default", ")", ")", ")", "return", "label" ]
Return image inside a QLabel object
[ "Return", "image", "inside", "a", "QLabel", "object" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L44-L48
train
spyder-ide/spyder
spyder/utils/qthelpers.py
qapplication
def qapplication(translate=True, test_time=3): """ Return QApplication instance Creates it if it doesn't already exist test_time: Time to maintain open the application when testing. It's given in seconds """ if running_in_mac_app(): SpyderApplication = MacApplication else: SpyderApplication = QApplication app = SpyderApplication.instance() if app is None: # Set Application name for Gnome 3 # https://groups.google.com/forum/#!topic/pyside/24qxvwfrRDs app = SpyderApplication(['Spyder']) # Set application name for KDE (See issue 2207) app.setApplicationName('Spyder') if translate: install_translator(app) test_ci = os.environ.get('TEST_CI_WIDGETS', None) if test_ci is not None: timer_shutdown = QTimer(app) timer_shutdown.timeout.connect(app.quit) timer_shutdown.start(test_time*1000) return app
python
def qapplication(translate=True, test_time=3): """ Return QApplication instance Creates it if it doesn't already exist test_time: Time to maintain open the application when testing. It's given in seconds """ if running_in_mac_app(): SpyderApplication = MacApplication else: SpyderApplication = QApplication app = SpyderApplication.instance() if app is None: # Set Application name for Gnome 3 # https://groups.google.com/forum/#!topic/pyside/24qxvwfrRDs app = SpyderApplication(['Spyder']) # Set application name for KDE (See issue 2207) app.setApplicationName('Spyder') if translate: install_translator(app) test_ci = os.environ.get('TEST_CI_WIDGETS', None) if test_ci is not None: timer_shutdown = QTimer(app) timer_shutdown.timeout.connect(app.quit) timer_shutdown.start(test_time*1000) return app
[ "def", "qapplication", "(", "translate", "=", "True", ",", "test_time", "=", "3", ")", ":", "if", "running_in_mac_app", "(", ")", ":", "SpyderApplication", "=", "MacApplication", "else", ":", "SpyderApplication", "=", "QApplication", "app", "=", "SpyderApplication", ".", "instance", "(", ")", "if", "app", "is", "None", ":", "# Set Application name for Gnome 3\r", "# https://groups.google.com/forum/#!topic/pyside/24qxvwfrRDs\r", "app", "=", "SpyderApplication", "(", "[", "'Spyder'", "]", ")", "# Set application name for KDE (See issue 2207)\r", "app", ".", "setApplicationName", "(", "'Spyder'", ")", "if", "translate", ":", "install_translator", "(", "app", ")", "test_ci", "=", "os", ".", "environ", ".", "get", "(", "'TEST_CI_WIDGETS'", ",", "None", ")", "if", "test_ci", "is", "not", "None", ":", "timer_shutdown", "=", "QTimer", "(", "app", ")", "timer_shutdown", ".", "timeout", ".", "connect", "(", "app", ".", "quit", ")", "timer_shutdown", ".", "start", "(", "test_time", "*", "1000", ")", "return", "app" ]
Return QApplication instance Creates it if it doesn't already exist test_time: Time to maintain open the application when testing. It's given in seconds
[ "Return", "QApplication", "instance", "Creates", "it", "if", "it", "doesn", "t", "already", "exist", "test_time", ":", "Time", "to", "maintain", "open", "the", "application", "when", "testing", ".", "It", "s", "given", "in", "seconds" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L65-L94
train
spyder-ide/spyder
spyder/utils/qthelpers.py
file_uri
def file_uri(fname): """Select the right file uri scheme according to the operating system""" if os.name == 'nt': # Local file if re.search(r'^[a-zA-Z]:', fname): return 'file:///' + fname # UNC based path else: return 'file://' + fname else: return 'file://' + fname
python
def file_uri(fname): """Select the right file uri scheme according to the operating system""" if os.name == 'nt': # Local file if re.search(r'^[a-zA-Z]:', fname): return 'file:///' + fname # UNC based path else: return 'file://' + fname else: return 'file://' + fname
[ "def", "file_uri", "(", "fname", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "# Local file\r", "if", "re", ".", "search", "(", "r'^[a-zA-Z]:'", ",", "fname", ")", ":", "return", "'file:///'", "+", "fname", "# UNC based path\r", "else", ":", "return", "'file://'", "+", "fname", "else", ":", "return", "'file://'", "+", "fname" ]
Select the right file uri scheme according to the operating system
[ "Select", "the", "right", "file", "uri", "scheme", "according", "to", "the", "operating", "system" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L97-L107
train
spyder-ide/spyder
spyder/utils/qthelpers.py
install_translator
def install_translator(qapp): """Install Qt translator to the QApplication instance""" global QT_TRANSLATOR if QT_TRANSLATOR is None: qt_translator = QTranslator() if qt_translator.load("qt_"+QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)): QT_TRANSLATOR = qt_translator # Keep reference alive if QT_TRANSLATOR is not None: qapp.installTranslator(QT_TRANSLATOR)
python
def install_translator(qapp): """Install Qt translator to the QApplication instance""" global QT_TRANSLATOR if QT_TRANSLATOR is None: qt_translator = QTranslator() if qt_translator.load("qt_"+QLocale.system().name(), QLibraryInfo.location(QLibraryInfo.TranslationsPath)): QT_TRANSLATOR = qt_translator # Keep reference alive if QT_TRANSLATOR is not None: qapp.installTranslator(QT_TRANSLATOR)
[ "def", "install_translator", "(", "qapp", ")", ":", "global", "QT_TRANSLATOR", "if", "QT_TRANSLATOR", "is", "None", ":", "qt_translator", "=", "QTranslator", "(", ")", "if", "qt_translator", ".", "load", "(", "\"qt_\"", "+", "QLocale", ".", "system", "(", ")", ".", "name", "(", ")", ",", "QLibraryInfo", ".", "location", "(", "QLibraryInfo", ".", "TranslationsPath", ")", ")", ":", "QT_TRANSLATOR", "=", "qt_translator", "# Keep reference alive\r", "if", "QT_TRANSLATOR", "is", "not", "None", ":", "qapp", ".", "installTranslator", "(", "QT_TRANSLATOR", ")" ]
Install Qt translator to the QApplication instance
[ "Install", "Qt", "translator", "to", "the", "QApplication", "instance" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L111-L120
train
spyder-ide/spyder
spyder/utils/qthelpers.py
keybinding
def keybinding(attr): """Return keybinding""" ks = getattr(QKeySequence, attr) return from_qvariant(QKeySequence.keyBindings(ks)[0], str)
python
def keybinding(attr): """Return keybinding""" ks = getattr(QKeySequence, attr) return from_qvariant(QKeySequence.keyBindings(ks)[0], str)
[ "def", "keybinding", "(", "attr", ")", ":", "ks", "=", "getattr", "(", "QKeySequence", ",", "attr", ")", "return", "from_qvariant", "(", "QKeySequence", ".", "keyBindings", "(", "ks", ")", "[", "0", "]", ",", "str", ")" ]
Return keybinding
[ "Return", "keybinding" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L123-L126
train
spyder-ide/spyder
spyder/utils/qthelpers.py
mimedata2url
def mimedata2url(source, extlist=None): """ Extract url list from MIME data extlist: for example ('.py', '.pyw') """ pathlist = [] if source.hasUrls(): for url in source.urls(): path = _process_mime_path(to_text_string(url.toString()), extlist) if path is not None: pathlist.append(path) elif source.hasText(): for rawpath in to_text_string(source.text()).splitlines(): path = _process_mime_path(rawpath, extlist) if path is not None: pathlist.append(path) if pathlist: return pathlist
python
def mimedata2url(source, extlist=None): """ Extract url list from MIME data extlist: for example ('.py', '.pyw') """ pathlist = [] if source.hasUrls(): for url in source.urls(): path = _process_mime_path(to_text_string(url.toString()), extlist) if path is not None: pathlist.append(path) elif source.hasText(): for rawpath in to_text_string(source.text()).splitlines(): path = _process_mime_path(rawpath, extlist) if path is not None: pathlist.append(path) if pathlist: return pathlist
[ "def", "mimedata2url", "(", "source", ",", "extlist", "=", "None", ")", ":", "pathlist", "=", "[", "]", "if", "source", ".", "hasUrls", "(", ")", ":", "for", "url", "in", "source", ".", "urls", "(", ")", ":", "path", "=", "_process_mime_path", "(", "to_text_string", "(", "url", ".", "toString", "(", ")", ")", ",", "extlist", ")", "if", "path", "is", "not", "None", ":", "pathlist", ".", "append", "(", "path", ")", "elif", "source", ".", "hasText", "(", ")", ":", "for", "rawpath", "in", "to_text_string", "(", "source", ".", "text", "(", ")", ")", ".", "splitlines", "(", ")", ":", "path", "=", "_process_mime_path", "(", "rawpath", ",", "extlist", ")", "if", "path", "is", "not", "None", ":", "pathlist", ".", "append", "(", "path", ")", "if", "pathlist", ":", "return", "pathlist" ]
Extract url list from MIME data extlist: for example ('.py', '.pyw')
[ "Extract", "url", "list", "from", "MIME", "data", "extlist", ":", "for", "example", "(", ".", "py", ".", "pyw", ")" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L146-L163
train
spyder-ide/spyder
spyder/utils/qthelpers.py
keyevent2tuple
def keyevent2tuple(event): """Convert QKeyEvent instance into a tuple""" return (event.type(), event.key(), event.modifiers(), event.text(), event.isAutoRepeat(), event.count())
python
def keyevent2tuple(event): """Convert QKeyEvent instance into a tuple""" return (event.type(), event.key(), event.modifiers(), event.text(), event.isAutoRepeat(), event.count())
[ "def", "keyevent2tuple", "(", "event", ")", ":", "return", "(", "event", ".", "type", "(", ")", ",", "event", ".", "key", "(", ")", ",", "event", ".", "modifiers", "(", ")", ",", "event", ".", "text", "(", ")", ",", "event", ".", "isAutoRepeat", "(", ")", ",", "event", ".", "count", "(", ")", ")" ]
Convert QKeyEvent instance into a tuple
[ "Convert", "QKeyEvent", "instance", "into", "a", "tuple" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L166-L169
train
spyder-ide/spyder
spyder/utils/qthelpers.py
create_toolbutton
def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, autoraise=True, text_beside_icon=False): """Create a QToolButton""" button = QToolButton(parent) if text is not None: button.setText(text) if icon is not None: if is_text_string(icon): icon = get_icon(icon) button.setIcon(icon) if text is not None or tip is not None: button.setToolTip(text if tip is None else tip) if text_beside_icon: button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) button.setAutoRaise(autoraise) if triggered is not None: button.clicked.connect(triggered) if toggled is not None: button.toggled.connect(toggled) button.setCheckable(True) if shortcut is not None: button.setShortcut(shortcut) return button
python
def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, autoraise=True, text_beside_icon=False): """Create a QToolButton""" button = QToolButton(parent) if text is not None: button.setText(text) if icon is not None: if is_text_string(icon): icon = get_icon(icon) button.setIcon(icon) if text is not None or tip is not None: button.setToolTip(text if tip is None else tip) if text_beside_icon: button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) button.setAutoRaise(autoraise) if triggered is not None: button.clicked.connect(triggered) if toggled is not None: button.toggled.connect(toggled) button.setCheckable(True) if shortcut is not None: button.setShortcut(shortcut) return button
[ "def", "create_toolbutton", "(", "parent", ",", "text", "=", "None", ",", "shortcut", "=", "None", ",", "icon", "=", "None", ",", "tip", "=", "None", ",", "toggled", "=", "None", ",", "triggered", "=", "None", ",", "autoraise", "=", "True", ",", "text_beside_icon", "=", "False", ")", ":", "button", "=", "QToolButton", "(", "parent", ")", "if", "text", "is", "not", "None", ":", "button", ".", "setText", "(", "text", ")", "if", "icon", "is", "not", "None", ":", "if", "is_text_string", "(", "icon", ")", ":", "icon", "=", "get_icon", "(", "icon", ")", "button", ".", "setIcon", "(", "icon", ")", "if", "text", "is", "not", "None", "or", "tip", "is", "not", "None", ":", "button", ".", "setToolTip", "(", "text", "if", "tip", "is", "None", "else", "tip", ")", "if", "text_beside_icon", ":", "button", ".", "setToolButtonStyle", "(", "Qt", ".", "ToolButtonTextBesideIcon", ")", "button", ".", "setAutoRaise", "(", "autoraise", ")", "if", "triggered", "is", "not", "None", ":", "button", ".", "clicked", ".", "connect", "(", "triggered", ")", "if", "toggled", "is", "not", "None", ":", "button", ".", "toggled", ".", "connect", "(", "toggled", ")", "button", ".", "setCheckable", "(", "True", ")", "if", "shortcut", "is", "not", "None", ":", "button", ".", "setShortcut", "(", "shortcut", ")", "return", "button" ]
Create a QToolButton
[ "Create", "a", "QToolButton" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L190-L213
train
spyder-ide/spyder
spyder/utils/qthelpers.py
action2button
def action2button(action, autoraise=True, text_beside_icon=False, parent=None): """Create a QToolButton directly from a QAction object""" if parent is None: parent = action.parent() button = QToolButton(parent) button.setDefaultAction(action) button.setAutoRaise(autoraise) if text_beside_icon: button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) return button
python
def action2button(action, autoraise=True, text_beside_icon=False, parent=None): """Create a QToolButton directly from a QAction object""" if parent is None: parent = action.parent() button = QToolButton(parent) button.setDefaultAction(action) button.setAutoRaise(autoraise) if text_beside_icon: button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) return button
[ "def", "action2button", "(", "action", ",", "autoraise", "=", "True", ",", "text_beside_icon", "=", "False", ",", "parent", "=", "None", ")", ":", "if", "parent", "is", "None", ":", "parent", "=", "action", ".", "parent", "(", ")", "button", "=", "QToolButton", "(", "parent", ")", "button", ".", "setDefaultAction", "(", "action", ")", "button", ".", "setAutoRaise", "(", "autoraise", ")", "if", "text_beside_icon", ":", "button", ".", "setToolButtonStyle", "(", "Qt", ".", "ToolButtonTextBesideIcon", ")", "return", "button" ]
Create a QToolButton directly from a QAction object
[ "Create", "a", "QToolButton", "directly", "from", "a", "QAction", "object" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L216-L225
train
spyder-ide/spyder
spyder/utils/qthelpers.py
toggle_actions
def toggle_actions(actions, enable): """Enable/disable actions""" if actions is not None: for action in actions: if action is not None: action.setEnabled(enable)
python
def toggle_actions(actions, enable): """Enable/disable actions""" if actions is not None: for action in actions: if action is not None: action.setEnabled(enable)
[ "def", "toggle_actions", "(", "actions", ",", "enable", ")", ":", "if", "actions", "is", "not", "None", ":", "for", "action", "in", "actions", ":", "if", "action", "is", "not", "None", ":", "action", ".", "setEnabled", "(", "enable", ")" ]
Enable/disable actions
[ "Enable", "/", "disable", "actions" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L228-L233
train
spyder-ide/spyder
spyder/utils/qthelpers.py
create_action
def create_action(parent, text, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, data=None, menurole=None, context=Qt.WindowShortcut): """Create a QAction""" action = SpyderAction(text, parent) if triggered is not None: action.triggered.connect(triggered) if toggled is not None: action.toggled.connect(toggled) action.setCheckable(True) if icon is not None: if is_text_string(icon): icon = get_icon(icon) action.setIcon(icon) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if data is not None: action.setData(to_qvariant(data)) if menurole is not None: action.setMenuRole(menurole) # Workround for Mac because setting context=Qt.WidgetShortcut # there doesn't have any effect if sys.platform == 'darwin': action._shown_shortcut = None if context == Qt.WidgetShortcut: if shortcut is not None: action._shown_shortcut = shortcut else: # This is going to be filled by # main.register_shortcut action._shown_shortcut = 'missing' else: if shortcut is not None: action.setShortcut(shortcut) action.setShortcutContext(context) else: if shortcut is not None: action.setShortcut(shortcut) action.setShortcutContext(context) return action
python
def create_action(parent, text, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, data=None, menurole=None, context=Qt.WindowShortcut): """Create a QAction""" action = SpyderAction(text, parent) if triggered is not None: action.triggered.connect(triggered) if toggled is not None: action.toggled.connect(toggled) action.setCheckable(True) if icon is not None: if is_text_string(icon): icon = get_icon(icon) action.setIcon(icon) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if data is not None: action.setData(to_qvariant(data)) if menurole is not None: action.setMenuRole(menurole) # Workround for Mac because setting context=Qt.WidgetShortcut # there doesn't have any effect if sys.platform == 'darwin': action._shown_shortcut = None if context == Qt.WidgetShortcut: if shortcut is not None: action._shown_shortcut = shortcut else: # This is going to be filled by # main.register_shortcut action._shown_shortcut = 'missing' else: if shortcut is not None: action.setShortcut(shortcut) action.setShortcutContext(context) else: if shortcut is not None: action.setShortcut(shortcut) action.setShortcutContext(context) return action
[ "def", "create_action", "(", "parent", ",", "text", ",", "shortcut", "=", "None", ",", "icon", "=", "None", ",", "tip", "=", "None", ",", "toggled", "=", "None", ",", "triggered", "=", "None", ",", "data", "=", "None", ",", "menurole", "=", "None", ",", "context", "=", "Qt", ".", "WindowShortcut", ")", ":", "action", "=", "SpyderAction", "(", "text", ",", "parent", ")", "if", "triggered", "is", "not", "None", ":", "action", ".", "triggered", ".", "connect", "(", "triggered", ")", "if", "toggled", "is", "not", "None", ":", "action", ".", "toggled", ".", "connect", "(", "toggled", ")", "action", ".", "setCheckable", "(", "True", ")", "if", "icon", "is", "not", "None", ":", "if", "is_text_string", "(", "icon", ")", ":", "icon", "=", "get_icon", "(", "icon", ")", "action", ".", "setIcon", "(", "icon", ")", "if", "tip", "is", "not", "None", ":", "action", ".", "setToolTip", "(", "tip", ")", "action", ".", "setStatusTip", "(", "tip", ")", "if", "data", "is", "not", "None", ":", "action", ".", "setData", "(", "to_qvariant", "(", "data", ")", ")", "if", "menurole", "is", "not", "None", ":", "action", ".", "setMenuRole", "(", "menurole", ")", "# Workround for Mac because setting context=Qt.WidgetShortcut\r", "# there doesn't have any effect\r", "if", "sys", ".", "platform", "==", "'darwin'", ":", "action", ".", "_shown_shortcut", "=", "None", "if", "context", "==", "Qt", ".", "WidgetShortcut", ":", "if", "shortcut", "is", "not", "None", ":", "action", ".", "_shown_shortcut", "=", "shortcut", "else", ":", "# This is going to be filled by\r", "# main.register_shortcut\r", "action", ".", "_shown_shortcut", "=", "'missing'", "else", ":", "if", "shortcut", "is", "not", "None", ":", "action", ".", "setShortcut", "(", "shortcut", ")", "action", ".", "setShortcutContext", "(", "context", ")", "else", ":", "if", "shortcut", "is", "not", "None", ":", "action", ".", "setShortcut", "(", "shortcut", ")", "action", ".", "setShortcutContext", "(", "context", ")", "return", "action" ]
Create a QAction
[ "Create", "a", "QAction" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L236-L278
train
spyder-ide/spyder
spyder/utils/qthelpers.py
add_shortcut_to_tooltip
def add_shortcut_to_tooltip(action, context, name): """Add the shortcut associated with a given action to its tooltip""" action.setToolTip(action.toolTip() + ' (%s)' % get_shortcut(context=context, name=name))
python
def add_shortcut_to_tooltip(action, context, name): """Add the shortcut associated with a given action to its tooltip""" action.setToolTip(action.toolTip() + ' (%s)' % get_shortcut(context=context, name=name))
[ "def", "add_shortcut_to_tooltip", "(", "action", ",", "context", ",", "name", ")", ":", "action", ".", "setToolTip", "(", "action", ".", "toolTip", "(", ")", "+", "' (%s)'", "%", "get_shortcut", "(", "context", "=", "context", ",", "name", "=", "name", ")", ")" ]
Add the shortcut associated with a given action to its tooltip
[ "Add", "the", "shortcut", "associated", "with", "a", "given", "action", "to", "its", "tooltip" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L281-L284
train
spyder-ide/spyder
spyder/utils/qthelpers.py
add_actions
def add_actions(target, actions, insert_before=None): """Add actions to a QMenu or a QToolBar.""" previous_action = None target_actions = list(target.actions()) if target_actions: previous_action = target_actions[-1] if previous_action.isSeparator(): previous_action = None for action in actions: if (action is None) and (previous_action is not None): if insert_before is None: target.addSeparator() else: target.insertSeparator(insert_before) elif isinstance(action, QMenu): if insert_before is None: target.addMenu(action) else: target.insertMenu(insert_before, action) elif isinstance(action, QAction): if isinstance(action, SpyderAction): if isinstance(target, QMenu) or not isinstance(target, QToolBar): try: action = action.no_icon_action except RuntimeError: continue if insert_before is None: # This is needed in order to ignore adding an action whose # wrapped C/C++ object has been deleted. See issue 5074 try: target.addAction(action) except RuntimeError: continue else: target.insertAction(insert_before, action) previous_action = action
python
def add_actions(target, actions, insert_before=None): """Add actions to a QMenu or a QToolBar.""" previous_action = None target_actions = list(target.actions()) if target_actions: previous_action = target_actions[-1] if previous_action.isSeparator(): previous_action = None for action in actions: if (action is None) and (previous_action is not None): if insert_before is None: target.addSeparator() else: target.insertSeparator(insert_before) elif isinstance(action, QMenu): if insert_before is None: target.addMenu(action) else: target.insertMenu(insert_before, action) elif isinstance(action, QAction): if isinstance(action, SpyderAction): if isinstance(target, QMenu) or not isinstance(target, QToolBar): try: action = action.no_icon_action except RuntimeError: continue if insert_before is None: # This is needed in order to ignore adding an action whose # wrapped C/C++ object has been deleted. See issue 5074 try: target.addAction(action) except RuntimeError: continue else: target.insertAction(insert_before, action) previous_action = action
[ "def", "add_actions", "(", "target", ",", "actions", ",", "insert_before", "=", "None", ")", ":", "previous_action", "=", "None", "target_actions", "=", "list", "(", "target", ".", "actions", "(", ")", ")", "if", "target_actions", ":", "previous_action", "=", "target_actions", "[", "-", "1", "]", "if", "previous_action", ".", "isSeparator", "(", ")", ":", "previous_action", "=", "None", "for", "action", "in", "actions", ":", "if", "(", "action", "is", "None", ")", "and", "(", "previous_action", "is", "not", "None", ")", ":", "if", "insert_before", "is", "None", ":", "target", ".", "addSeparator", "(", ")", "else", ":", "target", ".", "insertSeparator", "(", "insert_before", ")", "elif", "isinstance", "(", "action", ",", "QMenu", ")", ":", "if", "insert_before", "is", "None", ":", "target", ".", "addMenu", "(", "action", ")", "else", ":", "target", ".", "insertMenu", "(", "insert_before", ",", "action", ")", "elif", "isinstance", "(", "action", ",", "QAction", ")", ":", "if", "isinstance", "(", "action", ",", "SpyderAction", ")", ":", "if", "isinstance", "(", "target", ",", "QMenu", ")", "or", "not", "isinstance", "(", "target", ",", "QToolBar", ")", ":", "try", ":", "action", "=", "action", ".", "no_icon_action", "except", "RuntimeError", ":", "continue", "if", "insert_before", "is", "None", ":", "# This is needed in order to ignore adding an action whose\r", "# wrapped C/C++ object has been deleted. See issue 5074\r", "try", ":", "target", ".", "addAction", "(", "action", ")", "except", "RuntimeError", ":", "continue", "else", ":", "target", ".", "insertAction", "(", "insert_before", ",", "action", ")", "previous_action", "=", "action" ]
Add actions to a QMenu or a QToolBar.
[ "Add", "actions", "to", "a", "QMenu", "or", "a", "QToolBar", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L287-L322
train