Instruction:
Make a summary of the following Python 3 code
def close_left(self):
        current_widget = self.widget(self.tab_under_menu())
        index = self.indexOf(current_widget)
        if self._try_close_dirty_tabs(tab_range=range(index)):
            while True:
                widget = self.widget(0)
                if widget != current_widget:
                    self.remove_tab(0)
                else:
                    break

Response: Closes every editors tabs on the left of the current one.


Instruction:
Create a Python 3 function for
closing every editors tabs on the left of the current one.

Response:
def close_right(self):
        """
        Closes every editors tabs on the left of the current one.
        """
        current_widget = self.widget(self.tab_under_menu())
        index = self.indexOf(current_widget)
        if self._try_close_dirty_tabs(tab_range=range(index + 1, self.count())):
            while True:
                widget = self.widget(self.count() - 1)
                if widget != current_widget:
                    self.remove_tab(self.count() - 1)
                else:
                    break


Instruction:
Here you have a function in Python 3, explain what it does
def close_all(self):
        if self._try_close_dirty_tabs():
            while self.count():
                widget = self.widget(0)
                self.remove_tab(0)
                self.tab_closed.emit(widget)
            return True
        return False

Response: Closes all editors and tabs.


Instruction:
How would you explain what the following Python 3 function does
def _collect_dirty_tabs(self, skip=None, tab_range=None):
        widgets = []
        filenames = []
        if tab_range is None:
            tab_range = range(self.count())
        for i in tab_range:
            widget = self.widget(i)
            try:
                if widget.dirty and widget != skip:
                    widgets.append(widget)
                    if widget.file.path:
                        filenames.append(widget.file.path)
                    else:
                        filenames.append(widget.documentTitle())
            except AttributeError:
                pass
        return widgets, filenames

Response: Collects the list of dirty tabs and their filenames.


Instruction:
Can you write a function in Python 3 where it
closes the given widgets and handles cases where the widget has been cloned or is a clone of another widget.

Response:
def _close_widget(widget):
        """
        Closes the given widgets and handles cases where the widget has been
        clone or is a clone of another widget
        """
        if widget is None:
            return
        try:
            widget.document().setParent(None)
            widget.syntax_highlighter.setParent(None)
        except AttributeError:
            pass  # not a QPlainTextEdit subclass
        # handled cloned widgets
        clones = []
        if hasattr(widget, 'original') and widget.original:
            # cloned widget needs to be removed from the original
            widget.original.clones.remove(widget)
            try:
                widget.setDocument(None)
            except AttributeError:
                # not a QTextEdit/QPlainTextEdit
                pass
        elif hasattr(widget, 'clones'):
            clones = widget.clones
        try:
            # only clear current editor if it does not have any other clones
            widget.close(clear=len(clones) == 0)
        except (AttributeError, TypeError):
            # not a CodeEdit
            widget.close()
        return clones


Instruction:
Create a Python 3 function to
remove a tab from the tab list.

Response:
def remove_tab(self, index):
        """
        Overrides removeTab to emit tab_closed and last_tab_closed signals.

        :param index: index of the tab to remove.
        """
        widget = self.widget(index)
        try:
            document = widget.document()
        except AttributeError:
            document = None  # not a QPlainTextEdit
        clones = self._close_widget(widget)
        self.tab_closed.emit(widget)
        self.removeTab(index)
        self._restore_original(clones)
        widget._original_tab_widget._tabs.remove(widget)
        if self.count() == 0:
            self.last_tab_closed.emit()
        if SplittableTabWidget.tab_under_menu == widget:
            SplittableTabWidget.tab_under_menu = None
        if not clones:
            widget.setParent(None)
        else:
            try:
                clones[0].syntax_highlighter.setDocument(document)
            except AttributeError:
                pass


Instruction:
Explain what the following Python 3 code does
def _on_split_requested(self):
        orientation = self.sender().text()
        widget = self.widget(self.tab_under_menu())
        if 'horizontally' in orientation:
            self.split_requested.emit(
                widget, QtCore.Qt.Horizontal)
        else:
            self.split_requested.emit(
                widget, QtCore.Qt.Vertical)

Response: Emits the split requested signal with the desired orientation.


Instruction:
Can you tell what is the following Python 3 function doing
def addTab(self, tab, *args):
        tab.parent_tab_widget = self
        super(BaseTabWidget, self).addTab(tab, *args)

Response: Add a tab to the tab widget.


Instruction:
Implement a function in Python 3 to
add a custom context menu action to the main tab widget.

Response:
def add_context_action(self, action):
        """
        Adds a custom context menu action

        :param action: action to add.
        """
        self.main_tab_widget.context_actions.append(action)
        for child_splitter in self.child_splitters:
            child_splitter.add_context_action(action)


Instruction:
Create a Python 3 function for
adding a tab to the main tab widget.

Response:
def add_tab(self, tab, title='', icon=None):
        """
        Adds a tab to main tab widget.

        :param tab: Widget to add as a new tab of the main tab widget.
        :param title: Tab title
        :param icon: Tab icon
        """
        if icon:
            tab._icon = icon
        if not hasattr(tab, 'clones'):
            tab.clones = []
        if not hasattr(tab, 'original'):
            tab.original = None
        if icon:
            self.main_tab_widget.addTab(tab, icon, title)
        else:
            self.main_tab_widget.addTab(tab, title)
        self.main_tab_widget.setCurrentIndex(
            self.main_tab_widget.indexOf(tab))
        self.main_tab_widget.show()
        tab._uuid = self._uuid
        try:
            scroll_bar = tab.horizontalScrollBar()
        except AttributeError:
            # not a QPlainTextEdit class
            pass
        else:
            scroll_bar.setValue(0)
        tab.setFocus()
        tab._original_tab_widget = self
        self._tabs.append(tab)
        self._on_focus_changed(None, tab)


Instruction:
Write a Python 3 script to
split the current widget in new SplittableTabWidget.

Response:
def split(self, widget, orientation):
        """
        Split the the current widget in new SplittableTabWidget.

        :param widget: widget to split
        :param orientation: orientation of the splitter
        :return: the new splitter
        """
        if widget.original:
            base = widget.original
        else:
            base = widget
        clone = base.split()
        if not clone:
            return
        if orientation == int(QtCore.Qt.Horizontal):
            orientation = QtCore.Qt.Horizontal
        else:
            orientation = QtCore.Qt.Vertical
        self.setOrientation(orientation)
        splitter = self._make_splitter()
        splitter.show()
        self.addWidget(splitter)
        self.child_splitters.append(splitter)
        if clone not in base.clones:
            # code editors maintain the list of clones internally but some
            # other widgets (user widgets) might not.
            base.clones.append(clone)
        clone.original = base
        splitter._parent_splitter = self
        splitter.last_tab_closed.connect(self._on_last_child_tab_closed)
        splitter.tab_detached.connect(self.tab_detached.emit)
        if hasattr(base, '_icon'):
            icon = base._icon
        else:
            icon = None
        # same group of tab splitter (user might have a group for editors and
        # another group for consoles or whatever).
        splitter._uuid = self._uuid
        splitter.add_tab(clone, title=self.main_tab_widget.tabText(
            self.main_tab_widget.indexOf(widget)), icon=icon)
        self.setSizes([1 for i in range(self.count())])
        return splitter


Instruction:
Make a summary of the following Python 3 code
def has_children(self):
        for splitter in self.child_splitters:
            if splitter.has_children():
                return splitter
        return self.main_tab_widget.count() != 0

Response: Checks if there are children tab widgets.


Instruction:
Given the following Python 3 function, write the documentation
def widgets(self, include_clones=False):
        widgets = []
        for i in range(self.main_tab_widget.count()):
            widget = self.main_tab_widget.widget(i)
            try:
                if widget.original is None or include_clones:
                    widgets.append(widget)
            except AttributeError:
                pass
        for child in self.child_splitters:
            widgets += child.widgets(include_clones=include_clones)
        return widgets

Response: Recursively gets the list of widgets.


Instruction:
Given the following Python 3 function, write the documentation
def count(self):
        c = self.main_tab_widget.count()
        for child in self.child_splitters:
            c += child.count()
        return c

Response: Returns the number of widgets currently displayed in this tab.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_filter(cls, mimetype):
        filters = ' '.join(
            ['*%s' % ext for ext in mimetypes.guess_all_extensions(mimetype)])
        return '%s (%s)' % (mimetype, filters)

Response:
Returns a filter string for the file dialog. The filter is based
        on the mime type.


Instruction:
How would you explain what the following Python 3 function does
def addTab(self, widget, *args):
        widget.dirty_changed.connect(self._on_dirty_changed)
        super(CodeEditTabWidget, self).addTab(widget, *args)

Response:
Re - implements addTab to connect to the dirty changed signal and setup
        some helper attributes.


Instruction:
How would you code a function in Python 3 to
call when the dirty flag is set to True.

Response:
def _on_dirty_changed(self, dirty):
        """
        Adds a star in front of a dirtt tab and emits dirty_changed.
        """
        widget = self.sender()
        if isinstance(widget, DraggableTabBar):
            return
        parent = widget.parent_tab_widget
        index = parent.indexOf(widget)
        title = parent.tabText(index)
        title = title.replace('* ', '')
        if dirty:
            parent.setTabText(index, "* " + title)
        else:
            parent.setTabText(index, title)
        parent.dirty_changed.emit(dirty)


Instruction:
Make a summary of the following Python 3 code
def _ask_path(cls, editor):
        try:
            filter = cls.get_filter(editor.mimetypes[0])
        except IndexError:
            filter = _('All files (*)')
        return QtWidgets.QFileDialog.getSaveFileName(
            editor, _('Save file as'), cls.default_directory, filter)

Response: Shows a QFileDialog and ask for a save filename.


Instruction:
Can you implement a function in Python 3 that
implements SplittableTabWidget. save_widget to actually save the current language of the current language of the current language of the current language of the current language.

Response:
def save_widget(cls, editor):
        """
        Implements SplittableTabWidget.save_widget to actually save the
        code editor widget.

        If the editor.file.path is None or empty or the file does not exist,
        a save as dialog is shown (save as).

        :param editor: editor widget to save.
        :return: False if there was a problem saving the editor (e.g. the save
        as dialog has been canceled by the user, or a permission error,...)
        """
        if editor.original:
            editor = editor.original
        if editor.file.path is None or not os.path.exists(editor.file.path):
            # save as
            path, filter = cls._ask_path(editor)
            if not path:
                return False
            if not os.path.splitext(path)[1]:
                if len(editor.mimetypes):
                    path += mimetypes.guess_extension(editor.mimetypes[0])
            try:
                _logger().debug('saving %r as %r', editor.file._old_path, path)
            except AttributeError:
                _logger().debug('saving %r as %r', editor.file.path, path)
            editor.file._path = path
        else:
            path = editor.file.path
        try:
            editor.file.save(path)
        except Exception as e:
            QtWidgets.QMessageBox.warning(editor, "Failed to save file", 'Failed to save %r.\n\nError="%s"' %
                                          (path, e))
        else:
            tw = editor.parent_tab_widget
            text = tw.tabText(tw.indexOf(editor)).replace('*', '')
            tw.setTabText(tw.indexOf(editor), text)
            for clone in [editor] + editor.clones:
                if clone != editor:
                    tw = clone.parent_tab_widget
                    tw.setTabText(tw.indexOf(clone), text)
        return True


Instruction:
How would you explain what the following Python 3 function does
def register_code_edit(cls, code_edit_class):
        if not inspect.isclass(code_edit_class):
            raise TypeError('must be a class, not an instance.')
        for mimetype in code_edit_class.mimetypes:
            if mimetype in cls.editors:
                _logger().warn('editor for mimetype already registered, '
                               'skipping')
            cls.editors[mimetype] = code_edit_class
        _logger().log(5, 'registered editors: %r', cls.editors)

Response: Register an additional code edit class.


Instruction:
Create a Python 3 function for
saving current widget as.

Response:
def save_current_as(self):
        """
        Save current widget as.
        """
        if not self.current_widget():
            return
        mem = self.current_widget().file.path
        self.current_widget().file._path = None
        self.current_widget().file._old_path = mem
        CodeEditTabWidget.default_directory = os.path.dirname(mem)
        widget = self.current_widget()
        try:
            success = self.main_tab_widget.save_widget(widget)
        except Exception as e:
            QtWidgets.QMessageBox.warning(
                self, _('Failed to save file as'),
                _('Failed to save file as %s\nError=%s') % (
                    widget.file.path, str(e)))
            widget.file._path = mem
        else:
            if not success:
                widget.file._path = mem
            else:
                CodeEditTabWidget.default_directory = os.path.expanduser('~')
                self.document_saved.emit(widget.file.path, '')

                # rename tab
                tw = widget.parent_tab_widget
                tw.setTabText(tw.indexOf(widget),
                              os.path.split(widget.file.path)[1])

        return self.current_widget().file.path


Instruction:
How would you explain what the following Python 3 function does
def save_current(self):
        if self.current_widget() is not None:
            editor = self.current_widget()
            self._save(editor)

Response:
Save current editor. If the editor.file.path is None, a save as dialog
        will be shown.


Instruction:
Write a Python 3 script to
save all widgets in the system.

Response:
def save_all(self):
        """
        Save all editors.
        """
        for w in self.widgets():
            try:
                self._save(w)
            except OSError:
                _logger().exception('failed to save %s', w.file.path)


Instruction:
Here you have a function in Python 3, explain what it does
def _create_code_edit(self, mimetype, *args, **kwargs):
        if mimetype in self.editors.keys():
            return self.editors[mimetype](
                *args, parent=self.main_tab_widget, **kwargs)
        editor = self.fallback_editor(*args, parent=self.main_tab_widget,
                                      **kwargs)
        return editor

Response: Create a code edit instance based on the mimetype.


Instruction:
Implement a function in Python 3 to
create a new document and returns a tab widget instance.

Response:
def create_new_document(self, base_name='New Document',
                            extension='.txt', preferred_eol=0,
                            autodetect_eol=True, **kwargs):
        """
        Creates a new document.

        The document name will be ``base_name + count + extension``

        :param base_name: Base name of the document. An int will be appended.
        :param extension: Document extension (dotted)
        :param args: Positional arguments that must be forwarded to the editor
            widget constructor.
        :param preferred_eol: Preferred EOL convention. This setting will be
            used for saving the document unless autodetect_eol is True.
        :param autodetect_eol: If true, automatically detects file EOL and
            use it instead of the preferred EOL when saving files.
        :param kwargs: Keyworded arguments that must be forwarded to the editor
            widget constructor.
        :return: Code editor widget instance.
        """
        SplittableCodeEditTabWidget._new_count += 1
        name = '%s%d%s' % (base_name, self._new_count, extension)
        tab = self._create_code_edit(
            self.guess_mimetype(name), **kwargs)
        self.editor_created.emit(tab)
        tab.file.autodetect_eol = autodetect_eol
        tab.file.preferred_eol = preferred_eol
        tab.setDocumentTitle(name)
        self.add_tab(tab, title=name, icon=self._icon(name))
        self.document_opened.emit(tab)
        return tab


Instruction:
Can you write a function in Python 3 where it
opens a document and returns a CodeEditor object.

Response:
def open_document(self, path, encoding=None, replace_tabs_by_spaces=True,
                      clean_trailing_whitespaces=True, safe_save=True,
                      restore_cursor_position=True, preferred_eol=0,
                      autodetect_eol=True, show_whitespaces=False, **kwargs):
        """
        Opens a document.

        :param path: Path of the document to open
        :param encoding: The encoding to use to open the file. Default is
            locale.getpreferredencoding().
        :param replace_tabs_by_spaces: Enable/Disable replace tabs by spaces.
            Default is true.
        :param clean_trailing_whitespaces: Enable/Disable clean trailing
            whitespaces (on save). Default is True.
        :param safe_save: If True, the file is saved to a temporary file first.
            If the save went fine, the temporary file is renamed to the final
            filename.
        :param restore_cursor_position: If true, last cursor position will be
            restored. Default is True.
        :param preferred_eol: Preferred EOL convention. This setting will be
            used for saving the document unless autodetect_eol is True.
        :param autodetect_eol: If true, automatically detects file EOL and
            use it instead of the preferred EOL when saving files.
        :param show_whitespaces: True to show white spaces.
        :param kwargs: addtional keyword args to pass to the widget
                       constructor.
        :return: The created code editor
        """
        original_path = os.path.normpath(path)
        path = os.path.normcase(original_path)
        paths = []
        widgets = []
        for w in self.widgets(include_clones=False):
            if os.path.exists(w.file.path):
                # skip new docs
                widgets.append(w)
                paths.append(os.path.normcase(w.file.path))
        if path in paths:
            i = paths.index(path)
            w = widgets[i]
            tw = w.parent_tab_widget
            tw.setCurrentIndex(tw.indexOf(w))
            return w
        else:
            assert os.path.exists(original_path)
            name = os.path.split(original_path)[1]

            use_parent_dir = False
            for tab in self.widgets():
                title = QtCore.QFileInfo(tab.file.path).fileName()
                if title == name:
                    tw = tab.parent_tab_widget
                    new_name = os.path.join(os.path.split(os.path.dirname(
                        tab.file.path))[1], title)
                    tw.setTabText(tw.indexOf(tab), new_name)
                    use_parent_dir = True

            if use_parent_dir:
                name = os.path.join(
                    os.path.split(os.path.dirname(path))[1], name)
                use_parent_dir = False

            tab = self._create_code_edit(self.guess_mimetype(path), **kwargs)
            self.editor_created.emit(tab)

            tab.open_parameters = {
                'encoding': encoding,
                'replace_tabs_by_spaces': replace_tabs_by_spaces,
                'clean_trailing_whitespaces': clean_trailing_whitespaces,
                'safe_save': safe_save,
                'restore_cursor_position': restore_cursor_position,
                'preferred_eol': preferred_eol,
                'autodetect_eol': autodetect_eol,
                'show_whitespaces': show_whitespaces,
                'kwargs': kwargs
            }
            tab.file.clean_trailing_whitespaces = clean_trailing_whitespaces
            tab.file.safe_save = safe_save
            tab.file.restore_cursor = restore_cursor_position
            tab.file.replace_tabs_by_spaces = replace_tabs_by_spaces
            tab.file.autodetect_eol = autodetect_eol
            tab.file.preferred_eol = preferred_eol
            tab.show_whitespaces = show_whitespaces
            try:
                tab.file.open(original_path, encoding=encoding)
            except Exception as e:
                _logger().exception('exception while opening file')
                tab.close()
                tab.setParent(None)
                tab.deleteLater()
                raise e
            else:
                tab.setDocumentTitle(name)
                tab.file._path = original_path
                icon = self._icon(path)
                self.add_tab(tab, title=name, icon=icon)
                self.document_opened.emit(tab)

                for action in self.closed_tabs_menu.actions():
                    if action.toolTip() == original_path:
                        self.closed_tabs_menu.removeAction(action)
                        break
                self.closed_tabs_history_btn.setEnabled(
                    len(self.closed_tabs_menu.actions()) > 0)

                return tab


Instruction:
How would you explain what the following Python 3 function does
def close_document(self, path):
        to_close = []
        for widget in self.widgets(include_clones=True):
            p = os.path.normpath(os.path.normcase(widget.file.path))
            path = os.path.normpath(os.path.normcase(path))
            if p == path:
                to_close.append(widget)
        for widget in to_close:
            tw = widget.parent_tab_widget
            tw.remove_tab(tw.indexOf(widget))

Response: Closes a text document.


Instruction:
Write a Python 3 script to
rename an already opened document.

Response:
def rename_document(self, old_path, new_path):
        """
        Renames an already opened document (this will not rename the file,
        just update the file path and tab title).

        Use that function to update a file that has been renamed externally.

        :param old_path: old path (path of the widget to rename with
            ``new_path``
        :param new_path: new path that will be used to rename the tab.
        """
        to_rename = []
        title = os.path.split(new_path)[1]
        for widget in self.widgets(include_clones=True):
            p = os.path.normpath(os.path.normcase(widget.file.path))
            old_path = os.path.normpath(os.path.normcase(old_path))
            if p == old_path:
                to_rename.append(widget)
        for widget in to_rename:
            tw = widget.parent_tab_widget
            widget.file._path = new_path
            tw.setTabText(tw.indexOf(widget), title)


Instruction:
Write a Python 3 function for
saving dirty editors on close and cancel the event if the user choosed to continue to work.

Response:
def closeEvent(self, event):
        """
        Saves dirty editors on close and cancel the event if the user choosed
        to continue to work.

        :param event: close event
        """
        dirty_widgets = []
        for w in self.widgets(include_clones=False):
            if w.dirty:
                dirty_widgets.append(w)
        filenames = []
        for w in dirty_widgets:
            if os.path.exists(w.file.path):
                filenames.append(w.file.path)
            else:
                filenames.append(w.documentTitle())
        if len(filenames) == 0:
            self.close_all()
            return
        dlg = DlgUnsavedFiles(self, files=filenames)
        if dlg.exec_() == dlg.Accepted:
            if not dlg.discarded:
                for item in dlg.listWidget.selectedItems():
                    filename = item.text()
                    widget = None
                    for widget in dirty_widgets:
                        if widget.file.path == filename or \
                                widget.documentTitle() == filename:
                            break
                    tw = widget.parent_tab_widget
                    tw.save_widget(widget)
                    tw.remove_tab(tw.indexOf(widget))
            self.close_all()
        else:
            event.ignore()


Instruction:
How would you explain what the following Python 3 function does
def _is_shortcut(self, event):
        modifier = (QtCore.Qt.MetaModifier if sys.platform == 'darwin' else
                    QtCore.Qt.ControlModifier)
        valid_modifier = int(event.modifiers() & modifier) == modifier
        valid_key = event.key() == self._trigger_key
        return valid_key and valid_modifier

Response: Checks if the event s key and modifiers make the completion shortcut


Instruction:
Can you tell what is the following Python 3 function doing
def _hide_popup(self):
        debug('hide popup')
        if (self._completer.popup() is not None and
                self._completer.popup().isVisible()):
            self._completer.popup().hide()
            self._last_cursor_column = -1
            self._last_cursor_line = -1
            QtWidgets.QToolTip.hideText()

Response: Hides the completer popup


Instruction:
Create a Python 3 function to
show the popup at the specified index.

Response:
def _show_popup(self, index=0):
        """
        Shows the popup at the specified index.
        :param index: index
        :return:
        """
        full_prefix = self._helper.word_under_cursor(
            select_whole_word=False).selectedText()
        if self._case_sensitive:
            self._completer.setCaseSensitivity(QtCore.Qt.CaseSensitive)
        else:
            self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        # set prefix
        self._completer.setCompletionPrefix(self.completion_prefix)
        cnt = self._completer.completionCount()
        selected = self._completer.currentCompletion()
        if (full_prefix == selected) and cnt == 1:
            debug('user already typed the only completion that we '
                            'have')
            self._hide_popup()
        else:
            # show the completion list
            if self.editor.isVisible():
                if self._completer.widget() != self.editor:
                    self._completer.setWidget(self.editor)
                self._completer.complete(self._get_popup_rect())
                self._completer.popup().setCurrentIndex(
                    self._completer.completionModel().index(index, 0))
                debug(
                    "popup shown: %r" % self._completer.popup().isVisible())
            else:
                debug('cannot show popup, editor is not visible')


Instruction:
Write a Python 3 script to
update the completion model for the current locale.

Response:
def _update_model(self, completions):
        """
        Creates a QStandardModel that holds the suggestion from the completion
        models for the QCompleter

        :param completionPrefix:
        """
        # build the completion model
        cc_model = QtGui.QStandardItemModel()
        self._tooltips.clear()
        for completion in completions:
            name = completion['name']
            item = QtGui.QStandardItem()
            item.setData(name, QtCore.Qt.DisplayRole)
            if 'tooltip' in completion and completion['tooltip']:
                self._tooltips[name] = completion['tooltip']
            if 'icon' in completion:
                icon = completion['icon']
                if isinstance(icon, list):
                    icon = QtGui.QIcon.fromTheme(icon[0], QtGui.QIcon(icon[1]))
                else:
                    icon = QtGui.QIcon(icon)
                item.setData(QtGui.QIcon(icon),
                             QtCore.Qt.DecorationRole)
            cc_model.appendRow(item)
        try:
            self._completer.setModel(cc_model)
        except RuntimeError:
            self._create_completer()
            self._completer.setModel(cc_model)
        return cc_model


Instruction:
Write a Python 3 function that can
create a suds object of the requested _type.

Response:
def create(client, _type, **kwargs):
    """Create a suds object of the requested _type."""
    obj = client.factory.create("ns0:%s" % _type)
    for key, value in kwargs.items():
        setattr(obj, key, value)
    return obj


Instruction:
Can you tell what is the following Python 3 function doing
def invoke(client, method, **kwargs):
    try:
        # Proxy the method to the suds service
        result = getattr(client.service, method)(**kwargs)
    except AttributeError:
        logger.critical("Unknown method: %s", method)
        raise
    except URLError as e:
        logger.debug(pprint(e))
        logger.debug("A URL related error occurred while invoking the '%s' "
              "method on the VIM server, this can be caused by "
              "name resolution or connection problems.", method)
        logger.debug("The underlying error is: %s", e.reason[1])
        raise
    except suds.client.TransportError as e:
        logger.debug(pprint(e))
        logger.debug("TransportError: %s", e)
    except suds.WebFault as e:
        # Get the type of fault
        logger.critical("SUDS Fault: %s" % e.fault.faultstring)
        if len(e.fault.faultstring) > 0:
            raise

        detail = e.document.childAtPath("/Envelope/Body/Fault/detail")
        fault_type = detail.getChildren()[0].name
        fault = create(fault_type)
        if isinstance(e.fault.detail[0], list):
            for attr in e.fault.detail[0]:
                setattr(fault, attr[0], attr[1])
        else:
            fault["text"] = e.fault.detail[0]

        raise VimFault(fault)

    return result

Response: Invoke a method on the underlying soap service.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def prettydate(date):
    now = datetime.now(timezone.utc)
    """
    Return the relative timeframe between the given date and now.

    e.g. 'Just now', 'x days ago', 'x hours ago', ...

    When the difference is greater than 7 days, the timestamp will be returned
    instead.
    """
    diff = now - date
    # Show the timestamp rather than the relative timeframe when the difference
    # is greater than 7 days
    if diff.days > 7:
        return date.strftime("%d. %b %Y")
    return arrow.get(date).humanize()

Response: Return a pretty date string for the given date.


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_app_auth_headers(self):
        now = datetime.now(timezone.utc)
        expiry = now + timedelta(minutes=5)

        data = {"iat": now, "exp": expiry, "iss": self.app_id}
        app_token = jwt.encode(data, self.app_key, algorithm="RS256").decode("utf-8")

        headers = {
            "Accept": PREVIEW_JSON_ACCEPT,
            "Authorization": "Bearer {}".format(app_token),
        }

        return headers

Response: Set the correct auth headers to authenticate against GitHub.


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_installation_key(
        self, project, user_id=None, install_id=None, reprime=False
    ):
        """Get the auth token for a project or installation id."""
        installation_id = install_id
        if project is not None:
            installation_id = self.installation_map.get(project, {}).get(
                "installation_id"
            )

        if not installation_id:
            if reprime:
                # prime installation map and try again without refreshing
                self._prime_install_map()
                return self._get_installation_key(
                    project, user_id=user_id, install_id=install_id, reprime=False
                )
            LOGGER.debug("No installation ID available for project %s", project)
            return ""

        # Look up the token from cache
        now = datetime.now(timezone.utc)
        token, expiry = self.installation_token_cache.get(installation_id, (None, None))

        # Request new token if the available one is expired or could not be found
        if (not expiry) or (not token) or (now >= expiry):
            LOGGER.debug("Requesting new token for installation %s", installation_id)
            headers = self._get_app_auth_headers()
            url = "{}/installations/{}/access_tokens".format(
                self.api_url, installation_id
            )

            json_data = {"user_id": user_id} if user_id else None

            response = requests.post(url, headers=headers, json=json_data)
            response.raise_for_status()

            data = response.json()

            token = data["token"]
            expiry = datetime.strptime(data["expires_at"], "%Y-%m-%dT%H:%M:%SZ")
            # Update time zone of expiration date to make it comparable with now()
            expiry = expiry.replace(tzinfo=timezone.utc)

            # Assume, that the token expires two minutes earlier, to not
            # get lost during the checkout/scraping?
            expiry -= timedelta(minutes=2)

            self.installation_token_cache[installation_id] = (token, expiry)

        return token

Response: Get the auth token for a project or installation id.


Instruction:
Can you tell what is the following Python 3 function doing
def _prime_install_map(self):
        url = "{}/app/installations".format(self.api_url)
        headers = self._get_app_auth_headers()
        LOGGER.debug("Fetching installations for GitHub app")

        response = requests.get(url, headers=headers)
        response.raise_for_status()

        data = response.json()

        for install in data:
            install_id = install.get("id")
            token = self._get_installation_key(project=None, install_id=install_id)
            headers = {
                "Accept": PREVIEW_JSON_ACCEPT,
                "Authorization": "token {}".format(token),
            }

            url = "{}/installation/repositories?per_page=100".format(self.api_url)
            while url:
                LOGGER.debug("Fetching repos for installation %s", install_id)
                response = requests.get(url, headers=headers)
                response.raise_for_status()
                repos = response.json()

                # Store all projects in the installation map
                for repo in repos.get("repositories", []):
                    # TODO (fschmidt): Store the installation's
                    # permissions (could come in handy for later features)
                    project_name = repo["full_name"]
                    self.installation_map[project_name] = {
                        "installation_id": install_id,
                        "default_branch": repo["default_branch"],
                    }

                # Check if we need to do further page calls
                url = response.links.get("next", {}).get("url")

Response: Fetch all installations and look up the ID for each.


Instruction:
How would you explain what the following Python 3 function does
def create_github_client(self, project):
        token = self._get_installation_key(project=project)
        if not token:
            LOGGER.warning(
                "Could not find an authentication token for '%s'. Do you "
                "have access to this repository?",
                project,
            )
            return
        gh = github3.GitHubEnterprise(self.base_url)
        gh.login(token=token)
        return gh

Response: Create a github3 client per project.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def refresh(self):
        if self.enabled and self.line:
            self._clear_deco()
            brush = QtGui.QBrush(self._color)
            self._decoration = TextDecoration(
                self.editor.textCursor(), start_line=self.line)
            self._decoration.set_background(brush)
            self._decoration.set_full_width()
            self._decoration.draw_order = 255
            self.editor.decorations.append(self._decoration)

Response: Updates the current line decoration


Instruction:
Implement a function in Python 3 to
close every editors tabs except the current one.

Response:
def close_others(self):
        """
        Closes every editors tabs except the current one.
        """
        current_widget = self.currentWidget()
        self._try_close_dirty_tabs(exept=current_widget)
        i = 0
        while self.count() > 1:
            widget = self.widget(i)
            if widget != current_widget:
                self.removeTab(i)
            else:
                i = 1


Instruction:
Explain what the following Python 3 code does
def save_current(self, path=None):
        try:
            if not path and not self._current.file.path:
                path, filter = QtWidgets.QFileDialog.getSaveFileName(
                    self, _('Choose destination path'))
                if not path:
                    return False
            old_path = self._current.file.path
            code_edit = self._current
            self._save_editor(code_edit, path)
            path = code_edit.file.path
            # path (and icon) may have changed
            if path and old_path != path:
                self._ensure_unique_name(code_edit, code_edit.file.name)
                self.setTabText(self.currentIndex(), code_edit._tab_name)
                ext = os.path.splitext(path)[1]
                old_ext = os.path.splitext(old_path)[1]
                if ext != old_ext or not old_path:
                    icon = QtWidgets.QFileIconProvider().icon(
                        QtCore.QFileInfo(code_edit.file.path))
                    self.setTabIcon(self.currentIndex(), icon)
            return True
        except AttributeError:  # not an editor widget
            pass
        return False

Response: Save the current editor content.


Instruction:
Can you tell what is the following Python 3 function doing
def index_from_filename(self, path):
        if path:
            for i in range(self.count()):
                widget = self.widget(i)
                try:
                    if widget.file.path == path:
                        return i
                except AttributeError:
                    pass  # not an editor widget
        return -1

Response: Checks if the path is already open in an editor tab. If not returns - 1.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_code_edit(self, code_edit, name=None):
        # new empty editor widget (no path set)
        if code_edit.file.path == '':
            cnt = 0
            for i in range(self.count()):
                tab = self.widget(i)
                if tab.file.path.startswith(name[:name.find('%')]):
                    cnt += 1
            name %= (cnt + 1)
            code_edit.file._path = name
        index = self.index_from_filename(code_edit.file.path)
        if index != -1:
            # already open, just show it
            self.setCurrentIndex(index)
            # no need to keep this instance
            self._del_code_edit(code_edit)
            return -1
        self._ensure_unique_name(code_edit, name)
        index = self.addTab(code_edit, code_edit.file.icon,
                            code_edit._tab_name)
        self.setCurrentIndex(index)
        self.setTabText(index, code_edit._tab_name)
        try:
            code_edit.setFocus()
        except TypeError:
            # PySide
            code_edit.setFocus()
        try:
            file_watcher = code_edit.modes.get(FileWatcherMode)
        except (KeyError, AttributeError):
            # not installed
            pass
        else:
            file_watcher.file_deleted.connect(self._on_file_deleted)
        return index

Response: Adds a code edit tab to the editor tab set its text as the editor. file. name and sets it as the active tab.


Instruction:
Here you have a function in Python 3, explain what it does
def addTab(self, elem, icon, name):
        self._widgets.append(elem)
        return super(TabWidget, self).addTab(elem, icon, name)

Response: Extends QTabWidget. addTab to keep an internal list of added tabs.


Instruction:
Make a summary of the following Python 3 code
def _name_exists(self, name):
        for i in range(self.count()):
            if self.tabText(i) == name:
                return True
        return False

Response: Checks if a tab with the given name already exists.


Instruction:
Make a summary of the following Python 3 code
def _rename_duplicate_tabs(self, current, name, path):
        for i in range(self.count()):
            if self.widget(i)._tab_name == name and self.widget(i) != current:
                file_path = self.widget(i).file.path
                if file_path:
                    parent_dir = os.path.split(os.path.abspath(
                        os.path.join(file_path, os.pardir)))[1]
                    new_name = os.path.join(parent_dir, name)
                    self.setTabText(i, new_name)
                    self.widget(i)._tab_name = new_name
                break
        if path:
            parent_dir = os.path.split(os.path.abspath(
                os.path.join(path, os.pardir)))[1]
            return os.path.join(parent_dir, name)
        else:
            return name

Response: Rename tabs whose title is the same as the name.


Instruction:
Create a Python 3 function for
removing the tab at index index.

Response:
def removeTab(self, index):
        """
        Removes tab at index ``index``.

        This method will emits tab_closed for the removed tab.

        :param index: index of the tab to remove.
        """
        widget = self.widget(index)
        try:
            self._widgets.remove(widget)
        except ValueError:
            pass
        self.tab_closed.emit(widget)
        self._del_code_edit(widget)
        QTabWidget.removeTab(self, index)
        if widget == self._current:
            self._current = None


Instruction:
How would you code a function in Python 3 to
collect the list of dirty tabs and their filenames.

Response:
def _collect_dirty_tabs(self, exept=None):
        """
        Collects the list of dirty tabs
        """
        widgets = []
        filenames = []
        for i in range(self.count()):
            widget = self.widget(i)
            try:
                if widget.dirty and widget != exept:
                    widgets.append(widget)
                    filenames.append(widget.file.path)
            except AttributeError:
                pass
        return widgets, filenames


Instruction:
Here you have a function in Python 3, explain what it does
def _on_dirty_changed(self, dirty):
        try:
            title = self._current._tab_name
            index = self.indexOf(self._current)
            if dirty:
                self.setTabText(index, "* " + title)
            else:
                self.setTabText(index, title)
        except AttributeError:
            pass
        self.dirty_changed.emit(dirty)

Response: Called when the dirty attribute of the class attribute is changed.


Instruction:
Make a summary of the following Python 3 code
def get_preferred_encodings(self):
        encodings = []
        for row in range(self.ui.tableWidgetPreferred.rowCount()):
            item = self.ui.tableWidgetPreferred.item(row, 0)
            encodings.append(item.data(QtCore.Qt.UserRole))
        return encodings

Response: Gets the list of preferred encodings.


Instruction:
Given the following Python 3 function, write the documentation
def edit_encoding(cls, parent):
        dlg = cls(parent)
        if dlg.exec_() == dlg.Accepted:
            settings = Cache()
            settings.preferred_encodings = dlg.get_preferred_encodings()
            return True
        return False

Response: Static helper method that shows the encoding editor dialog and adds the new encodings to the settings.


Instruction:
Implement a Python 3 function for
showing the encodings dialog and returns the user choice.

Response:
def choose_encoding(cls, parent, path, encoding):
        """
        Show the encodings dialog and returns the user choice.

        :param parent: parent widget.
        :param path: file path
        :param encoding: current file encoding
        :return: selected encoding
        """
        dlg = cls(parent, path, encoding)
        dlg.exec_()
        return dlg.ui.comboBoxEncodings.current_encoding


Instruction:
Can you tell what is the following Python 3 function doing
def background(self):
        if self._color or not self.editor:
            return self._color
        else:
            return drift_color(self.editor.background, 110)

Response: Get the color of the caret line.


Instruction:
Write a Python 3 script to
update the current line decoration with the current line color.

Response:
def refresh(self):
        """
        Updates the current line decoration
        """
        if self.enabled:
            self._clear_deco()
            if self._color:
                color = self._color
            else:
                color = drift_color(self.editor.background, 110)
            brush = QtGui.QBrush(color)
            self._decoration = TextDecoration(self.editor.textCursor())
            self._decoration.set_background(brush)
            self._decoration.set_full_width()
            self.editor.decorations.append(self._decoration)


Instruction:
Create a Python 3 function to
create the extended selection menu.

Response:
def create_menu(self):
        """
        Creates the extended selection menu.
        """
        # setup menu
        menu = QtWidgets.QMenu(self.editor)
        menu.setTitle(_('Select'))
        menu.menuAction().setIcon(QtGui.QIcon.fromTheme('edit-select'))
        # setup actions
        menu.addAction(self.action_select_word)
        menu.addAction(self.action_select_extended_word)
        menu.addAction(self.action_select_matched)
        menu.addAction(self.action_select_line)
        menu.addSeparator()
        menu.addAction(self.editor.action_select_all)
        icon = QtGui.QIcon.fromTheme(
            'edit-select-all', QtGui.QIcon(
                ':/pyqode-icons/rc/edit-select-all.png'))
        self.editor.action_select_all.setIcon(icon)
        return menu


Instruction:
How would you code a function in Python 3 to
perform word selection :param event: QMouseEvent

Response:
def perform_word_selection(self, event=None):
        """
        Performs word selection
        :param event: QMouseEvent
        """
        self.editor.setTextCursor(
            TextHelper(self.editor).word_under_cursor(True))
        if event:
            event.accept()


Instruction:
Implement a Python 3 function for
performing extended word selection.

Response:
def perform_extended_selection(self, event=None):
        """
        Performs extended word selection.
        :param event: QMouseEvent
        """
        TextHelper(self.editor).select_extended_word(
            continuation_chars=self.continuation_characters)
        if event:
            event.accept()


Instruction:
Can you tell what is the following Python 3 function doing
def perform_matched_selection(self, event):
        selected = TextHelper(self.editor).match_select()
        if selected and event:
            event.accept()

Response:
Performs matched selection.
        :param event: QMouseEvent


Instruction:
Implement a Python 3 function for
serializing a definition to a dictionary ready for json.

Response:
def to_dict(self):
        """
        Serializes a definition to a dictionary, ready for json.

        Children are serialised recursively.
        """
        ddict = {'name': self.name, 'icon': self.icon,
                 'line': self.line, 'column': self.column,
                 'children': [], 'description': self.description,
                 'user_data': self.user_data, 'path': self.file_path}
        for child in self.children:
            ddict['children'].append(child.to_dict())
        return ddict


Instruction:
Can you generate the documentation for the following Python 3 function
def from_dict(ddict):
        d = Definition(ddict['name'], ddict['line'], ddict['column'],
                       ddict['icon'], ddict['description'],
                       ddict['user_data'], ddict['path'])
        for child_dict in ddict['children']:
            d.children.append(Definition.from_dict(child_dict))
        return d

Response: Deserializes a definition from a simple dict.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def indent_selection(self, cursor):
        doc = self.editor.document()
        tab_len = self.editor.tab_length
        cursor.beginEditBlock()
        nb_lines = len(cursor.selection().toPlainText().splitlines())
        c = self.editor.textCursor()
        if c.atBlockStart() and c.position() == c.selectionEnd():
            nb_lines += 1
        block = doc.findBlock(cursor.selectionStart())
        i = 0
        # indent every lines
        while i < nb_lines:
            nb_space_to_add = tab_len
            cursor = QtGui.QTextCursor(block)
            cursor.movePosition(cursor.StartOfLine, cursor.MoveAnchor)
            if self.editor.use_spaces_instead_of_tabs:
                for _ in range(nb_space_to_add):
                    cursor.insertText(" ")
            else:
                cursor.insertText('\t')
            block = block.next()
            i += 1
        cursor.endEditBlock()

Response:
Indent selected text

        :param cursor: QTextCursor


Instruction:
Given the following Python 3 function, write the documentation
def indent(self):
        cursor = self.editor.textCursor()
        assert isinstance(cursor, QtGui.QTextCursor)
        if cursor.hasSelection():
            self.indent_selection(cursor)
        else:
            # simply insert indentation at the cursor position
            tab_len = self.editor.tab_length
            cursor.beginEditBlock()
            if self.editor.use_spaces_instead_of_tabs:
                nb_space_to_add = tab_len - cursor.positionInBlock() % tab_len
                cursor.insertText(nb_space_to_add * " ")
            else:
                cursor.insertText('\t')
            cursor.endEditBlock()

Response: Indents text at cursor position.


Instruction:
Write a Python 3 script for
splitting the code editor widget into two text documents and link them with the new one.

Response:
def split(self):
        """
        Split the code editor widget, return a clone of the widget ready to
        be used (and synchronised with its original).

        Splitting the widget is done in 2 steps:
            - first we clone the widget, you can override ``clone`` if your
              widget needs additional arguments.

            - then we link the two text document and disable some modes on the
                cloned instance (such as the watcher mode).
        """
        # cache cursor position so that the clone open at the current cursor
        # pos
        l, c = TextHelper(self).cursor_position()
        clone = self.clone()
        self.link(clone)
        TextHelper(clone).goto_line(l, c)
        self.clones.append(clone)
        return clone


Instruction:
Can you generate a brief explanation for the following Python 3 code
def link(self, clone):
        clone.file._path = self.file.path
        clone.file._encoding = self.file.encoding
        clone.file._mimetype = self.file.mimetype
        clone.setDocument(self.document())
        for original_mode, mode in zip(list(self.modes), list(clone.modes)):
            mode.enabled = original_mode.enabled
            mode.clone_settings(original_mode)
        for original_panel, panel in zip(
                list(self.panels), list(clone.panels)):
            panel.enabled = original_panel.isEnabled()
            panel.clone_settings(original_panel)
            if not original_panel.isVisible():
                panel.setVisible(False)
        clone.use_spaces_instead_of_tabs = self.use_spaces_instead_of_tabs
        clone.tab_length = self.tab_length
        clone._save_on_focus_out = self._save_on_focus_out
        clone.show_whitespaces = self.show_whitespaces
        clone.font_name = self.font_name
        clone.font_size = self.font_size
        clone.zoom_level = self.zoom_level
        clone.background = self.background
        clone.foreground = self.foreground
        clone.whitespaces_foreground = self.whitespaces_foreground
        clone.selection_background = self.selection_background
        clone.selection_foreground = self.selection_foreground
        clone.word_separators = self.word_separators
        clone.file.clone_settings(self.file)

Response: Links the clone with its original.


Instruction:
Make a summary of the following Python 3 code
def close(self, clear=True):
        if self._tooltips_runner:
            self._tooltips_runner.cancel_requests()
            self._tooltips_runner = None
        self.decorations.clear()
        self.modes.clear()
        self.panels.clear()
        self.backend.stop()
        Cache().set_cursor_position(
            self.file.path, self.textCursor().position())
        super(CodeEdit, self).close()

Response: Closes the editor and clears any installed version of the editor.


Instruction:
Can you create a Python 3 function that
shows a tool tip at the specified position.

Response:
def show_tooltip(self, pos, tooltip, _sender_deco=None):
        """
        Show a tool tip at the specified position

        :param pos: Tooltip position
        :param tooltip: Tooltip text

        :param _sender_deco: TextDecoration which is the sender of the show
            tooltip request. (for internal use only).
        """
        if _sender_deco is not None and _sender_deco not in self.decorations:
            return
        QtWidgets.QToolTip.showText(pos, tooltip[0: 1024], self)


Instruction:
How would you explain what the following Python 3 function does
def setPlainText(self, txt, mime_type, encoding):
        self.file.mimetype = mime_type
        self.file._encoding = encoding
        self._original_text = txt
        self._modified_lines.clear()
        import time
        t = time.time()
        super(CodeEdit, self).setPlainText(txt)
        _logger().log(5, 'setPlainText duration: %fs' % (time.time() - t))
        self.new_text_set.emit()
        self.redoAvailable.emit(False)
        self.undoAvailable.emit(False)

Response: Sets the plain text for the current locale.


Instruction:
Can you implement a function in Python 3 that
adds an action to the editor s context menu.

Response:
def add_action(self, action, sub_menu='Advanced'):
        """
        Adds an action to the editor's context menu.

        :param action: QAction to add to the context menu.
        :param sub_menu: The name of a sub menu where to put the action.
            'Advanced' by default. If None or empty, the action will be added
            at the root of the submenu.
        """
        if sub_menu:
            try:
                mnu = self._sub_menus[sub_menu]
            except KeyError:
                mnu = QtWidgets.QMenu(sub_menu)
                self.add_menu(mnu)
                self._sub_menus[sub_menu] = mnu
            finally:
                mnu.addAction(action)
        else:
            self._actions.append(action)
        action.setShortcutContext(QtCore.Qt.WidgetShortcut)
        self.addAction(action)


Instruction:
Explain what the following Python 3 code does
def insert_action(self, action, prev_action):
        if isinstance(prev_action, QtWidgets.QAction):
            index = self._actions.index(prev_action)
        else:
            index = prev_action
        action.setShortcutContext(QtCore.Qt.WidgetShortcut)
        self._actions.insert(index, action)

Response: Inserts an action to the editor s context menu.


Instruction:
Can you generate the documentation for the following Python 3 function
def add_separator(self, sub_menu='Advanced'):
        action = QtWidgets.QAction(self)
        action.setSeparator(True)
        if sub_menu:
            try:
                mnu = self._sub_menus[sub_menu]
            except KeyError:
                pass
            else:
                mnu.addAction(action)
        else:
            self._actions.append(action)
        return action

Response: Adds a sepqrator to the editor s context menu.


Instruction:
Can you implement a function in Python 3 that
removes an action from the context menu.

Response:
def remove_action(self, action, sub_menu='Advanced'):
        """
        Removes an action/separator from the editor's context menu.

        :param action: Action/seprator to remove.
        :param advanced: True to remove the action from the advanced submenu.
        """
        if sub_menu:
            try:
                mnu = self._sub_menus[sub_menu]
            except KeyError:
                pass
            else:
                mnu.removeAction(action)
        else:
            try:
                self._actions.remove(action)
            except ValueError:
                pass
        self.removeAction(action)


Instruction:
Can you generate the documentation for the following Python 3 function
def add_menu(self, menu):
        self._menus.append(menu)
        self._menus = sorted(list(set(self._menus)), key=lambda x: x.title())
        for action in menu.actions():
            action.setShortcutContext(QtCore.Qt.WidgetShortcut)
        self.addActions(menu.actions())

Response: Adds a sub - menu to the editor context menu.


Instruction:
Given the following Python 3 function, write the documentation
def remove_menu(self, menu):
        self._menus.remove(menu)
        for action in menu.actions():
            self.removeAction(action)

Response: Removes a sub - menu from the context menu.


Instruction:
Explain what the following Python 3 code does
def goto_line(self):
        helper = TextHelper(self)
        line, result = DlgGotoLine.get_line(
            self, helper.current_line_nbr(), helper.line_count())
        if not result:
            return
        return helper.goto_line(line, move=True)

Response: Shows the * go to line dialog* and go to the selected line.


Instruction:
How would you code a function in Python 3 to
zoom in the editor

Response:
def zoom_in(self, increment=1):
        """
        Zooms in the editor (makes the font bigger).

        :param increment: zoom level increment. Default is 1.
        """
        self.zoom_level += increment
        TextHelper(self).mark_whole_doc_dirty()
        self._reset_stylesheet()


Instruction:
How would you implement a function in Python 3 that
zooms out the editor.

Response:
def zoom_out(self, decrement=1):
        """
        Zooms out the editor (makes the font smaller).

        :param decrement: zoom level decrement. Default is 1. The value is
            given as an absolute value.
        """
        self.zoom_level -= decrement
        # make sure font size remains > 0
        if self.font_size + self.zoom_level <= 0:
            self.zoom_level = -self._font_size + 1
        TextHelper(self).mark_whole_doc_dirty()
        self._reset_stylesheet()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def duplicate_line(self):
        cursor = self.textCursor()
        assert isinstance(cursor, QtGui.QTextCursor)
        has_selection = True
        if not cursor.hasSelection():
            cursor.select(cursor.LineUnderCursor)
            has_selection = False
        line = cursor.selectedText()
        line = '\n'.join(line.split('\u2029'))
        end = cursor.selectionEnd()
        cursor.setPosition(end)
        cursor.beginEditBlock()
        cursor.insertText('\n')
        cursor.insertText(line)
        cursor.endEditBlock()
        if has_selection:
            pos = cursor.position()
            cursor.setPosition(end + 1)
            cursor.setPosition(pos, cursor.KeepAnchor)
        self.setTextCursor(cursor)

Response: Duplicates the line under the cursor.


Instruction:
Write a Python 3 script for
cutting the selected text or the whole line if no text was selected.

Response:
def cut(self):
        """
        Cuts the selected text or the whole line if no text was selected.
        """
        tc = self.textCursor()
        helper = TextHelper(self)
        tc.beginEditBlock()
        no_selection = False
        sText = tc.selection().toPlainText()
        if not helper.current_line_text() and sText.count("\n") > 1:
            tc.deleteChar()
        else:
            if not self.textCursor().hasSelection():
                no_selection = True
                TextHelper(self).select_whole_line()
            super(CodeEdit, self).cut()
            if no_selection:
                tc.deleteChar()
        tc.endEditBlock()
        self.setTextCursor(tc)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def copy(self):
        if self.select_line_on_copy_empty and not self.textCursor().hasSelection():
            TextHelper(self).select_whole_line()
        super(CodeEdit, self).copy()

Response: Copy the selected text to the clipboard.


Instruction:
Implement a Python 3 function for
overriding resize event to resize the editor s panels.

Response:
def resizeEvent(self, e):
        """
        Overrides resize event to resize the editor's panels.

        :param e: resize event
        """
        super(CodeEdit, self).resizeEvent(e)
        self.panels.resize()


Instruction:
Explain what the following Python 3 code does
def paintEvent(self, e):
        self._update_visible_blocks(e)
        super(CodeEdit, self).paintEvent(e)
        self.painted.emit(e)

Response: Overrides paintEvent to update the list of visible blocks and emit the painted event.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def keyPressEvent(self, event):
        if self.isReadOnly():
            return
        initial_state = event.isAccepted()
        event.ignore()
        self.key_pressed.emit(event)
        state = event.isAccepted()
        if not event.isAccepted():
            if event.key() == QtCore.Qt.Key_Tab and event.modifiers() == \
                    QtCore.Qt.NoModifier:
                self.indent()
                event.accept()
            elif event.key() == QtCore.Qt.Key_Backtab and \
                    event.modifiers() == QtCore.Qt.NoModifier:
                self.un_indent()
                event.accept()
            elif event.key() == QtCore.Qt.Key_Home and \
                    int(event.modifiers()) & QtCore.Qt.ControlModifier == 0:
                self._do_home_key(
                    event, int(event.modifiers()) & QtCore.Qt.ShiftModifier)
            if not event.isAccepted():
                event.setAccepted(initial_state)
                super(CodeEdit, self).keyPressEvent(event)
        new_state = event.isAccepted()
        event.setAccepted(state)
        self.post_key_pressed.emit(event)
        event.setAccepted(new_state)

Response: Overrides the keyPressEvent to emit the key_pressed signal.


Instruction:
How would you explain what the following Python 3 function does
def keyReleaseEvent(self, event):
        if self.isReadOnly():
            return
        initial_state = event.isAccepted()
        event.ignore()
        self.key_released.emit(event)
        if not event.isAccepted():
            event.setAccepted(initial_state)
            super(CodeEdit, self).keyReleaseEvent(event)

Response: Overrides keyReleaseEvent to emit the key_released signal.


Instruction:
Can you create a Python 3 function that
overrides focusInEvent to emits the focused_in signal.

Response:
def focusInEvent(self, event):
        """
        Overrides focusInEvent to emits the focused_in signal

        :param event: QFocusEvent
        """
        self.focused_in.emit(event)
        super(CodeEdit, self).focusInEvent(event)


Instruction:
Write a Python 3 function for
overriding mousePressEvent to emits mouse_pressed signal which is a list of related objects.

Response:
def mousePressEvent(self, event):
        """
        Overrides mousePressEvent to emits mouse_pressed signal

        :param event: QMouseEvent
        """
        initial_state = event.isAccepted()
        event.ignore()
        self.mouse_pressed.emit(event)
        if event.button() == QtCore.Qt.LeftButton:
            cursor = self.cursorForPosition(event.pos())
            for sel in self.decorations:
                if sel.cursor.blockNumber() == cursor.blockNumber():
                    if sel.contains_cursor(cursor):
                        sel.signals.clicked.emit(sel)
        if not event.isAccepted():
            event.setAccepted(initial_state)
            super(CodeEdit, self).mousePressEvent(event)


Instruction:
Write a Python 3 function that can
emit mouse_released signal. :param event: QMouseEvent

Response:
def mouseReleaseEvent(self, event):
        """
        Emits mouse_released signal.

        :param event: QMouseEvent
        """
        initial_state = event.isAccepted()
        event.ignore()
        self.mouse_released.emit(event)
        if not event.isAccepted():
            event.setAccepted(initial_state)
            super(CodeEdit, self).mouseReleaseEvent(event)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def wheelEvent(self, event):
        initial_state = event.isAccepted()
        event.ignore()
        self.mouse_wheel_activated.emit(event)
        if not event.isAccepted():
            event.setAccepted(initial_state)
            super(CodeEdit, self).wheelEvent(event)

Response: Emits the mouse_wheel_activated signal.


Instruction:
Implement a Python 3 function for
overriding mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event.

Response:
def mouseMoveEvent(self, event):
        """
        Overrides mouseMovedEvent to display any decoration tooltip and emits
        the mouse_moved event.

        :param event: QMouseEvent
        """
        cursor = self.cursorForPosition(event.pos())
        self._last_mouse_pos = event.pos()
        block_found = False
        for sel in self.decorations:
            if sel.contains_cursor(cursor) and sel.tooltip:
                if (self._prev_tooltip_block_nbr != cursor.blockNumber() or
                        not QtWidgets.QToolTip.isVisible()):
                    pos = event.pos()
                    # add left margin
                    pos.setX(pos.x() + self.panels.margin_size())
                    # add top margin
                    pos.setY(pos.y() + self.panels.margin_size(0))
                    self._tooltips_runner.request_job(
                        self.show_tooltip,
                        self.mapToGlobal(pos), sel.tooltip[0: 1024], sel)
                    self._prev_tooltip_block_nbr = cursor.blockNumber()
                block_found = True
                break
        if not block_found and self._prev_tooltip_block_nbr != -1:
            QtWidgets.QToolTip.hideText()
            self._prev_tooltip_block_nbr = -1
            self._tooltips_runner.cancel_requests()
        self.mouse_moved.emit(event)
        super(CodeEdit, self).mouseMoveEvent(event)


Instruction:
Implement a Python 3 function for
overriding showEvent to update the viewport margins

Response:
def showEvent(self, event):
        """ Overrides showEvent to update the viewport margins """
        super(CodeEdit, self).showEvent(event)
        self.panels.refresh()


Instruction:
How would you explain what the following Python 3 function does
def get_context_menu(self):
        mnu = QtWidgets.QMenu()
        mnu.addActions(self._actions)
        mnu.addSeparator()
        for menu in self._menus:
            mnu.addMenu(menu)
        return mnu

Response: Gets the editor context menu.


Instruction:
Implement a function in Python 3 to
show the context menu

Response:
def _show_context_menu(self, point):
        """ Shows the context menu """
        tc = self.textCursor()
        nc = self.cursorForPosition(point)
        if not nc.position() in range(tc.selectionStart(), tc.selectionEnd()):
            self.setTextCursor(nc)
        self._mnu = self.get_context_menu()
        if len(self._mnu.actions()) > 1 and self.show_context_menu:
            self._mnu.popup(self.mapToGlobal(point))


Instruction:
Implement a Python 3 function for
setting show white spaces flag

Response:
def _set_whitespaces_flags(self, show):
        """ Sets show white spaces flag """
        doc = self.document()
        options = doc.defaultTextOption()
        if show:
            options.setFlags(options.flags() |
                             QtGui.QTextOption.ShowTabsAndSpaces)
        else:
            options.setFlags(
                options.flags() & ~QtGui.QTextOption.ShowTabsAndSpaces)
        doc.setDefaultTextOption(options)


Instruction:
Can you implement a function in Python 3 that
initializes the context menu action

Response:
def _init_actions(self, create_standard_actions):
        """ Init context menu action """
        menu_advanced = QtWidgets.QMenu(_('Advanced'))
        self.add_menu(menu_advanced)
        self._sub_menus = {
            'Advanced': menu_advanced
        }
        if create_standard_actions:
            # Undo
            action = QtWidgets.QAction(_('Undo'), self)
            action.setShortcut('Ctrl+Z')
            action.setIcon(icons.icon(
                'edit-undo', ':/pyqode-icons/rc/edit-undo.png', 'fa.undo'))
            action.triggered.connect(self.undo)
            self.undoAvailable.connect(action.setVisible)
            action.setVisible(False)
            self.add_action(action, sub_menu=None)
            self.action_undo = action
            # Redo
            action = QtWidgets.QAction(_('Redo'), self)
            action.setShortcut('Ctrl+Y')
            action.setIcon(icons.icon(
                'edit-redo', ':/pyqode-icons/rc/edit-redo.png', 'fa.repeat'))
            action.triggered.connect(self.redo)
            self.redoAvailable.connect(action.setVisible)
            action.setVisible(False)
            self.add_action(action, sub_menu=None)
            self.action_redo = action
            # Copy
            action = QtWidgets.QAction(_('Copy'), self)
            action.setShortcut(QtGui.QKeySequence.Copy)
            action.setIcon(icons.icon(
                'edit-copy', ':/pyqode-icons/rc/edit-copy.png', 'fa.copy'))
            action.triggered.connect(self.copy)
            self.add_action(action, sub_menu=None)
            self.action_copy = action
            # cut
            action = QtWidgets.QAction(_('Cut'), self)
            action.setShortcut(QtGui.QKeySequence.Cut)
            action.setIcon(icons.icon(
                'edit-cut', ':/pyqode-icons/rc/edit-cut.png', 'fa.cut'))
            action.triggered.connect(self.cut)
            self.add_action(action, sub_menu=None)
            self.action_cut = action
            # paste
            action = QtWidgets.QAction(_('Paste'), self)
            action.setShortcut(QtGui.QKeySequence.Paste)
            action.setIcon(icons.icon(
                'edit-paste', ':/pyqode-icons/rc/edit-paste.png',
                'fa.paste'))
            action.triggered.connect(self.paste)
            self.add_action(action, sub_menu=None)
            self.action_paste = action
        # duplicate line
        action = QtWidgets.QAction(_('Duplicate line'), self)
        action.setShortcut('Ctrl+D')
        action.triggered.connect(self.duplicate_line)
        self.add_action(action, sub_menu=None)
        self.action_duplicate_line = action
        # swap line up
        action = QtWidgets.QAction(_('Swap line up'), self)
        action.setShortcut("Alt++")
        action.triggered.connect(self.swapLineUp)
        self.add_action(action, sub_menu=None)
        self.action_swap_line_up = action
        # swap line down
        action = QtWidgets.QAction(_('Swap line down'), self)
        action.setShortcut("Alt+-")
        action.triggered.connect(self.swapLineDown)
        self.add_action(action, sub_menu=None)
        self.action_swap_line_down = action
        # select all
        action = QtWidgets.QAction(_('Select all'), self)
        action.setShortcut(QtGui.QKeySequence.SelectAll)
        action.triggered.connect(self.selectAll)
        self.action_select_all = action
        self.add_action(self.action_select_all, sub_menu=None)
        self.add_separator(sub_menu=None)
        if create_standard_actions:
            # indent
            action = QtWidgets.QAction(_('Indent'), self)
            action.setShortcut('Tab')
            action.setIcon(icons.icon(
                'format-indent-more',
                ':/pyqode-icons/rc/format-indent-more.png', 'fa.indent'))
            action.triggered.connect(self.indent)
            self.add_action(action)
            self.action_indent = action
            # unindent
            action = QtWidgets.QAction(_('Un-indent'), self)
            action.setShortcut('Shift+Tab')
            action.setIcon(icons.icon(
                'format-indent-less',
                ':/pyqode-icons/rc/format-indent-less.png', 'fa.dedent'))
            action.triggered.connect(self.un_indent)
            self.add_action(action)
            self.action_un_indent = action
            self.add_separator()
        # goto
        action = QtWidgets.QAction(_('Go to line'), self)
        action.setShortcut('Ctrl+G')
        action.setIcon(icons.icon(
            'go-jump', ':/pyqode-icons/rc/goto-line.png', 'fa.share'))
        action.triggered.connect(self.goto_line)
        self.add_action(action)
        self.action_goto_line = action


Instruction:
Can you generate the documentation for the following Python 3 function
def _init_settings(self):
        self._show_whitespaces = False
        self._tab_length = 4
        self._use_spaces_instead_of_tabs = True
        self.setTabStopWidth(self._tab_length *
                             self.fontMetrics().width(" "))
        self._set_whitespaces_flags(self._show_whitespaces)

Response: Init settings for the current locale


Instruction:
Given the following Python 3 function, write the documentation
def _update_visible_blocks(self, *args):
        self._visible_blocks[:] = []
        block = self.firstVisibleBlock()
        block_nbr = block.blockNumber()
        top = int(self.blockBoundingGeometry(block).translated(
            self.contentOffset()).top())
        bottom = top + int(self.blockBoundingRect(block).height())
        ebottom_top = 0
        ebottom_bottom = self.height()
        while block.isValid():
            visible = (top >= ebottom_top and bottom <= ebottom_bottom)
            if not visible:
                break
            if block.isVisible():
                self._visible_blocks.append((top, block_nbr, block))
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            block_nbr = block.blockNumber()

Response: Updates the list of visible blocks in the archive.


Instruction:
Implement a function in Python 3 to
adjust dirty flag depending on editor s content

Response:
def _on_text_changed(self):
        """ Adjust dirty flag depending on editor's content """
        if not self._cleaning:
            ln = TextHelper(self).cursor_position()[0]
            self._modified_lines.add(ln)


Instruction:
Can you generate the documentation for the following Python 3 function
def _reset_stylesheet(self):
        self.setFont(QtGui.QFont(self._font_family,
                                 self._font_size + self._zoom_level))
        flg_stylesheet = hasattr(self, '_flg_stylesheet')
        if QtWidgets.QApplication.instance().styleSheet() or flg_stylesheet:
            self._flg_stylesheet = True
            # On Window, if the application once had a stylesheet, we must
            # keep on using a stylesheet otherwise strange colors appear
            # see https://github.com/OpenCobolIDE/OpenCobolIDE/issues/65
            # Also happen on plasma 5
            try:
                plasma = os.environ['DESKTOP_SESSION'] == 'plasma'
            except KeyError:
                plasma = False
            if sys.platform == 'win32' or plasma:
                self.setStyleSheet('''QPlainTextEdit
                {
                    background-color: %s;
                    color: %s;
                }
                ''' % (self.background.name(), self.foreground.name()))
            else:
                # on linux/osx we just have to set an empty stylesheet to
                # cancel any previous stylesheet and still keep a correct
                # style for scrollbars
                self.setStyleSheet('')
        else:
            p = self.palette()
            p.setColor(QtGui.QPalette.Base, self.background)
            p.setColor(QtGui.QPalette.Text, self.foreground)
            p.setColor(QtGui.QPalette.Highlight,
                       self.selection_background)
            p.setColor(QtGui.QPalette.HighlightedText,
                       self.selection_foreground)
            self.setPalette(p)
        self.repaint()

Response: Resets the current stylesheet to the default one.


Instruction:
Can you tell what is the following Python 3 function doing
def _do_home_key(self, event=None, select=False):
        # get nb char to first significative char
        delta = (self.textCursor().positionInBlock() -
                 TextHelper(self).line_indent())
        cursor = self.textCursor()
        move = QtGui.QTextCursor.MoveAnchor
        if select:
            move = QtGui.QTextCursor.KeepAnchor
        if delta > 0:
            cursor.movePosition(QtGui.QTextCursor.Left, move, delta)
        else:
            cursor.movePosition(QtGui.QTextCursor.StartOfBlock, move)
        self.setTextCursor(cursor)
        if event:
            event.accept()

Response: Handles the home key action.


Instruction:
How would you explain what the following Python 3 function does
def cached(key, timeout=3600):

    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            cache = get_cache()
            # Check if key is a function
            if callable(key):
                cache_key = key(*args, **kwargs)
            else:
                cache_key = key
            # Try to get the value from cache
            cached_val = cache.get(cache_key)
            if cached_val is None:
                # Call the original function and cache the result
                cached_val = f(*args, **kwargs)
                cache.set(cache_key, cached_val, timeout)
            return cached_val

        return wrapped

    return decorator

Response: A decorator that caches the return value of the decorated function with the given key.


Instruction:
Here you have a function in Python 3, explain what it does
def _copy_cell_text(self):
        txt = self.currentItem().text()
        QtWidgets.QApplication.clipboard().setText(txt)

Response: Copies the text of the selected message to the clipboard


Instruction:
Given the following Python 3 function, write the documentation
def clear(self):
        QtWidgets.QTableWidget.clear(self)
        self.setRowCount(0)
        self.setColumnCount(4)
        self.setHorizontalHeaderLabels(
            ["Type", "File name", "Line", "Description"])

Response: Clears the tables and the message list.


Instruction:
Write a Python 3 script to
make icon from icon filename or tuple

Response:
def _make_icon(cls, status):
        """
        Make icon from icon filename/tuple (if you want to use a theme)
        """
        icon = cls.ICONS[status]
        if isinstance(icon, tuple):
            return QtGui.QIcon.fromTheme(
                icon[0], QtGui.QIcon(icon[1]))
        elif isinstance(icon, str):
            return QtGui.QIcon(icon)
        elif isinstance(icon, QtGui.QIcon):
            return icon
        else:
            return None


Instruction:
How would you explain what the following Python 3 function does
def add_message(self, msg):
        row = self.rowCount()
        self.insertRow(row)

        # type
        item = QtWidgets.QTableWidgetItem(
            self._make_icon(msg.status), msg.status_string)
        item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        item.setData(QtCore.Qt.UserRole, msg)
        self.setItem(row, COL_TYPE, item)

        # filename
        item = QtWidgets.QTableWidgetItem(
            QtCore.QFileInfo(msg.path).fileName())
        item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        item.setData(QtCore.Qt.UserRole, msg)
        self.setItem(row, COL_FILE_NAME, item)

        # line
        if msg.line < 0:
            item = QtWidgets.QTableWidgetItem("-")
        else:
            item = QtWidgets.QTableWidgetItem(str(msg.line + 1))
        item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        item.setData(QtCore.Qt.UserRole, msg)
        self.setItem(row, COL_LINE_NBR, item)

        # desc
        item = QtWidgets.QTableWidgetItem(msg.description)
        item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        item.setData(QtCore.Qt.UserRole, msg)
        self.setItem(row, COL_MSG, item)

Response: Adds a checker message to the table.


Instruction:
Explain what the following Python 3 code does
def _on_item_activated(self, item):
        msg = item.data(QtCore.Qt.UserRole)
        self.msg_activated.emit(msg)

Response: Emits the message activated signal


Instruction:
Explain what the following Python 3 code does
def showDetails(self):
        msg = self.currentItem().data(QtCore.Qt.UserRole)
        desc = msg.description
        desc = desc.replace('\r\n', '\n').replace('\r', '\n')
        desc = desc.replace('\n', '
')
        QtWidgets.QMessageBox.information(
            self, _('Message details'),
            _("""
Description:
%s

File:
%s

Line:
%d

            """) % (desc, msg.path, msg.line + 1, ))

Response: Shows the error details.


Instruction:
Make a summary of the following Python 3 code
def get_line(cls, parent, current_line, line_count):
        dlg = DlgGotoLine(parent, current_line + 1, line_count)
        if dlg.exec_() == dlg.Accepted:
            return dlg.spinBox.value() - 1, True
        return current_line, False

Response: Gets user selected line.


Instruction:
Can you create a Python 3 function that
closes the current panel.

Response:
def close_panel(self):
        """
        Closes the panel
        """
        self.hide()
        self.lineEditReplace.clear()
        self.lineEditSearch.clear()


Instruction:
Implement a Python 3 function for
requesting a search operation.

Response:
def request_search(self, txt=None):
        """
        Requests a search operation.

        :param txt: The text to replace. If None, the content of lineEditSearch
                    is used instead.
        """
        if self.checkBoxRegex.isChecked():
            try:
                re.compile(self.lineEditSearch.text(), re.DOTALL)
            except sre_constants.error as e:
                self._show_error(e)
                return
            else:
                self._show_error(None)

        if txt is None or isinstance(txt, int):
            txt = self.lineEditSearch.text()
        if txt:
            self.job_runner.request_job(
                self._exec_search, txt, self._search_flags())
        else:
            self.job_runner.cancel_requests()
            self._clear_occurrences()
            self._on_search_finished()


Instruction:
Write a Python 3 function that can
change the base color of a widget.

Response:
def _set_widget_background_color(widget, color):
        """
        Changes the base color of a widget (background).
        :param widget: widget to modify
        :param color: the color to apply
        """
        pal = widget.palette()
        pal.setColor(pal.Base, color)
        widget.setPalette(pal)


Instruction:
Can you implement a function in Python 3 that
selects the next occurrence in the list.

Response:
def select_next(self):
        """
        Selects the next occurrence.

        :return: True in case of success, false if no occurrence could be
                 selected.
        """
        current_occurence = self._current_occurrence()
        occurrences = self.get_occurences()
        if not occurrences:
            return
        current = self._occurrences[current_occurence]
        cursor_pos = self.editor.textCursor().position()
        if cursor_pos not in range(current[0], current[1] + 1) or \
                current_occurence == -1:
            # search first occurrence that occurs after the cursor position
            current_occurence = 0
            for i, (start, end) in enumerate(self._occurrences):
                if end > cursor_pos:
                    current_occurence = i
                    break
        else:
            if (current_occurence == -1 or
                    current_occurence >= len(occurrences) - 1):
                current_occurence = 0
            else:
                current_occurence += 1
        self._set_current_occurrence(current_occurence)
        try:
            cursor = self.editor.textCursor()
            cursor.setPosition(occurrences[current_occurence][0])
            cursor.setPosition(occurrences[current_occurence][1],
                               cursor.KeepAnchor)
            self.editor.setTextCursor(cursor)
            return True
        except IndexError:
            return False


Instruction:
How would you explain what the following Python 3 function does
def replace(self, text=None):
        if text is None or isinstance(text, bool):
            text = self.lineEditReplace.text()
        current_occurences = self._current_occurrence()
        occurrences = self.get_occurences()
        if current_occurences == -1:
            self.select_next()
            current_occurences = self._current_occurrence()
        try:
            # prevent search request due to editor textChanged
            try:
                self.editor.textChanged.disconnect(self.request_search)
            except (RuntimeError, TypeError):
                # already disconnected
                pass
            occ = occurrences[current_occurences]
            cursor = self.editor.textCursor()
            cursor.setPosition(occ[0])
            cursor.setPosition(occ[1], cursor.KeepAnchor)
            len_to_replace = len(cursor.selectedText())
            len_replacement = len(text)
            offset = len_replacement - len_to_replace
            cursor.insertText(text)
            self.editor.setTextCursor(cursor)
            self._remove_occurrence(current_occurences, offset)
            current_occurences -= 1
            self._set_current_occurrence(current_occurences)
            self.select_next()
            self.cpt_occurences = len(self.get_occurences())
            self._update_label_matches()
            self._update_buttons()
            return True
        except IndexError:
            return False
        finally:
            self.editor.textChanged.connect(self.request_search)

Response: Replaces the selected occurrence with the given text.


Instruction:
How would you code a function in Python 3 to
replace all occurrences of the lineEdit with the given text.

Response:
def replace_all(self, text=None):
        """
        Replaces all occurrences in the editor's document.

        :param text: The replacement text. If None, the content of the lineEdit
                     replace will be used instead
        """
        cursor = self.editor.textCursor()
        cursor.beginEditBlock()
        remains = self.replace(text=text)
        while remains:
            remains = self.replace(text=text)
        cursor.endEditBlock()


Instruction:
Explain what the following Python 3 code does
def _search_flags(self):
        return (self.checkBoxRegex.isChecked(),
                self.checkBoxCase.isChecked(),
                self.checkBoxWholeWords.isChecked(),
                self.checkBoxInSelection.isChecked())

Response: Returns the user search flags.


Instruction:
How would you explain what the following Python 3 function does
def _create_decoration(self, selection_start, selection_end):
        deco = TextDecoration(self.editor.document(), selection_start,
                              selection_end)
        deco.set_background(QtGui.QBrush(self.background))
        deco.set_outline(self._outline)
        deco.set_foreground(QtCore.Qt.black)
        deco.draw_order = 1
        return deco

Response: Creates the text occurences decoration


Instruction:
Can you create a Python 3 function that
sends the request to the backend.

Response:
def _send_request(self):
        """
        Sends the request to the backend.
        """
        if isinstance(self._worker, str):
            classname = self._worker
        else:
            classname = '%s.%s' % (self._worker.__module__,
                                   self._worker.__name__)
        self.request_id = str(uuid.uuid4())
        self.send({'request_id': self.request_id, 'worker': classname,
                   'data': self._args})


Instruction:
How would you explain what the following Python 3 function does
def send(self, obj, encoding='utf-8'):
        comm('sending request: %r', obj)
        msg = json.dumps(obj)
        msg = msg.encode(encoding)
        header = struct.pack('=I', len(msg))
        self.write(header)
        self.write(msg)

Response: Send a python object to the backend.


Instruction:
How would you explain what the following Python 3 function does
def _connect(self):
        if self is None:
            return
        comm('connecting to 127.0.0.1:%d', self._port)
        address = QtNetwork.QHostAddress('127.0.0.1')
        self.connectToHost(address, self._port)
        if sys.platform == 'darwin':
            self.waitForConnected()

Response: Connects to the backend socket


Instruction:
Can you tell what is the following Python 3 function doing
def _read_payload(self):
        comm('reading payload data')
        comm('remaining bytes to read: %d', self._to_read)
        data_read = self.read(self._to_read)
        nb_bytes_read = len(data_read)
        comm('%d bytes read', nb_bytes_read)
        self._data_buf += data_read
        self._to_read -= nb_bytes_read
        if self._to_read <= 0:
            try:
                data = self._data_buf.decode('utf-8')
            except AttributeError:
                data = bytes(self._data_buf.data()).decode('utf-8')
            comm('payload read: %r', data)
            comm('payload length: %r', len(self._data_buf))
            comm('decoding payload as json object')
            obj = json.loads(data)
            comm('response received: %r', obj)
            try:
                results = obj['results']
            except (KeyError, TypeError):
                results = None
            # possible callback
            if self._callback and self._callback():
                self._callback()(results)
            self._header_complete = False
            self._data_buf = bytes()
            self.finished.emit(self)

Response: Reads the payload from the file and calls the callback function if it has been set.


Instruction:
Can you write a function in Python 3 where it
reads bytes when ready read

Response:
def _on_ready_read(self):
        """ Read bytes when ready read """
        while self.bytesAvailable():
            if not self._header_complete:
                self._read_header()
            else:
                self._read_payload()


Instruction:
Write a Python 3 script for
calling when the backend process is started.

Response:
def _on_process_started(self):
        """ Logs process started """
        comm('backend process started')
        if self is None:
            return
        self.starting = False
        self.running = True


Instruction:
Write a Python 3 function for
logging process output ready

Response:
def _on_process_stderr_ready(self):
        """ Logs process output (stderr) """
        try:
            o = self.readAllStandardError()
        except (TypeError, RuntimeError):
            # widget already deleted
            return
        try:
            output = bytes(o).decode(self._encoding)
        except TypeError:
            output = bytes(o.data()).decode(self._encoding)
        for line in output.splitlines():
            self._srv_logger.error(line)


Instruction:
Can you implement a function in Python 3 that
gives a dictionary of RegexLexer token dictionary tokens replace all patterns that match the token specified in new_pattern with new_pattern.

Response:
def replace_pattern(tokens, new_pattern):
    """ Given a RegexLexer token dictionary 'tokens', replace all patterns that
        match the token specified in 'new_pattern' with 'new_pattern'.
    """
    for state in tokens.values():
        for index, pattern in enumerate(state):
            if isinstance(pattern, tuple) and pattern[1] == new_pattern[1]:
                state[index] = new_pattern


Instruction:
Write a Python 3 function for
calling when the package is installed.

Response:
def on_install(self, editor):
        """
        :type editor: pyqode.code.api.CodeEdit
        """
        self._clear_caches()
        self._update_style()
        super(PygmentsSH, self).on_install(editor)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_mime_type(self, mime_type):
        try:
            self.set_lexer_from_mime_type(mime_type)
        except ClassNotFound:
            _logger().exception('failed to get lexer from mimetype')
            self._lexer = TextLexer()
            return False
        except ImportError:
            # import error while loading some pygments plugins, the editor
            # should not crash
            _logger().warning('failed to get lexer from mimetype (%s)' %
                              mime_type)
            self._lexer = TextLexer()
            return False
        else:
            return True

Response: Set the highlighter lexer based on a mime type.


Instruction:
Implement a function in Python 3 to
change the lexer based on the filename or extension.

Response:
def set_lexer_from_filename(self, filename):
        """
        Change the lexer based on the filename (actually only the extension is
        needed)

        :param filename: Filename or extension
        """
        self._lexer = None
        if filename.endswith("~"):
            filename = filename[0:len(filename) - 1]
        try:
            self._lexer = get_lexer_for_filename(filename)
        except (ClassNotFound, ImportError):
            print('class not found for url', filename)
            try:
                m = mimetypes.guess_type(filename)
                print(m)
                self._lexer = get_lexer_for_mimetype(m[0])
            except (ClassNotFound, IndexError, ImportError):
                self._lexer = get_lexer_for_mimetype('text/plain')
        if self._lexer is None:
            _logger().warning('failed to get lexer from filename: %s, using '
                              'plain text instead...', filename)
            self._lexer = TextLexer()


Instruction:
Implement a function in Python 3 to
set the pygments lexer from mime type.

Response:
def set_lexer_from_mime_type(self, mime, **options):
        """
        Sets the pygments lexer from mime type.

        :param mime: mime type
        :param options: optional addtional options.
        """
        self._lexer = get_lexer_for_mimetype(mime, **options)
        _logger().debug('lexer for mimetype (%s): %r', mime, self._lexer)