{
    "file_diffs": [
        {
            "old_file_content": "from numbers import Number, Integral\nfrom math import isnan, isinf\n\nimport operator\nfrom collections import namedtuple, Sequence, defaultdict\nfrom contextlib import contextmanager\nfrom functools import reduce, partial, lru_cache, wraps\nfrom itertools import chain\nfrom warnings import warn\nfrom xml.sax.saxutils import escape\n\nfrom AnyQt.QtCore import (\n    Qt, QObject, QAbstractListModel, QModelIndex,\n    QItemSelectionModel, QItemSelection)\nfrom AnyQt.QtCore import pyqtSignal as Signal\nfrom AnyQt.QtGui import QColor\nfrom AnyQt.QtWidgets import (\n    QWidget, QBoxLayout, QToolButton, QAbstractButton, QAction\n)\n\nimport numpy\n\nfrom orangewidget.utils.itemmodels import (\n    PyListModel, AbstractSortTableModel as _AbstractSortTableModel\n)\n\nfrom Orange.widgets.utils.colorpalettes import ContinuousPalettes, ContinuousPalette\nfrom Orange.data import Variable, Storage, DiscreteVariable, ContinuousVariable\nfrom Orange.data.domain import filter_visible\nfrom Orange.widgets import gui\nfrom Orange.widgets.utils import datacaching\nfrom Orange.statistics import basic_stats\nfrom Orange.util import deprecated\n\n__all__ = [\n    \"PyListModel\", \"VariableListModel\", \"PyListModelTooltip\", \"DomainModel\",\n    \"AbstractSortTableModel\", \"PyTableModel\", \"TableModel\",\n    \"ModelActionsWidget\", \"ListSingleSelectionModel\"\n]\n\n@contextmanager\ndef signal_blocking(obj):\n    blocked = obj.signalsBlocked()\n    obj.blockSignals(True)\n    try:\n        yield\n    finally:\n        obj.blockSignals(blocked)\n\n\ndef _as_contiguous_range(the_slice, length):\n    start, stop, step = the_slice.indices(length)\n    if step == -1:\n        # Equivalent range with positive step\n        start, stop, step = stop + 1, start + 1, 1\n    elif not (step == 1 or step is None):\n        raise IndexError(\"Non-contiguous range.\")\n    return start, stop, step\n\n\nclass AbstractSortTableModel(_AbstractSortTableModel):\n    # these were defined on TableModel below. When the AbstractSortTableModel\n    # was extracted and made a base of TableModel these deprecations were\n    # misplaced, they belong in TableModel.\n    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapFromSourceRows')\n    def mapFromTableRows(self, rows):\n        return self.mapFromSourceRows(rows)\n\n    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapToSourceRows')\n    def mapToTableRows(self, rows):\n        return self.mapToSourceRows(rows)\n\n\nclass PyTableModel(AbstractSortTableModel):\n    \"\"\" A model for displaying python tables (sequences of sequences) in\n    QTableView objects.\n\n    Parameters\n    ----------\n    sequence : list\n        The initial list to wrap.\n    parent : QObject\n        Parent QObject.\n    editable: bool or sequence\n        If True, all items are flagged editable. If sequence, the True-ish\n        fields mark their respective columns editable.\n\n    Notes\n    -----\n    The model rounds numbers to human readable precision, e.g.:\n    1.23e-04, 1.234, 1234.5, 12345, 1.234e06.\n\n    To set additional item roles, use setData().\n    \"\"\"\n\n    @staticmethod\n    def _RoleData():\n        return defaultdict(lambda: defaultdict(dict))\n\n    # All methods are either necessary overrides of super methods, or\n    # methods likened to the Python list's. Hence, docstrings aren't.\n    # pylint: disable=missing-docstring\n    def __init__(self, sequence=None, parent=None, editable=False):\n        super().__init__(parent)\n        self._rows = self._cols = 0\n        self._headers = {}\n        self._editable = editable\n        self._table = None\n        self._roleData = {}\n        self.wrap(sequence or [])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._rows\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._cols\n\n    def flags(self, index):\n        flags = super().flags(index)\n        if not self._editable or not index.isValid():\n            return flags\n        if isinstance(self._editable, Sequence):\n            return flags | Qt.ItemIsEditable if self._editable[index.column()] else flags\n        return flags | Qt.ItemIsEditable\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            self[row][index.column()] = value\n            self.dataChanged.emit(index, index)\n        else:\n            self._roleData[row][index.column()][role] = value\n        return True\n\n    def data(self, index, role=Qt.DisplayRole):\n        if not index.isValid():\n            return\n\n        row, column = self.mapToSourceRows(index.row()), index.column()\n\n        role_value = self._roleData.get(row, {}).get(column, {}).get(role)\n        if role_value is not None:\n            return role_value\n\n        try:\n            value = self[row][column]\n        except IndexError:\n            return\n        if role == Qt.EditRole:\n            return value\n        if role == Qt.DecorationRole and isinstance(value, Variable):\n            return gui.attributeIconDict[value]\n        if role == Qt.DisplayRole:\n            if (isinstance(value, Number) and\n                    not (isnan(value) or isinf(value) or isinstance(value, Integral))):\n                absval = abs(value)\n                strlen = len(str(int(absval)))\n                value = '{:.{}{}}'.format(value,\n                                          2 if absval < .001 else\n                                          3 if strlen < 2 else\n                                          1 if strlen < 5 else\n                                          0 if strlen < 6 else\n                                          3,\n                                          'f' if (absval == 0 or\n                                                  absval >= .001 and\n                                                  strlen < 6)\n                                          else 'e')\n            return str(value)\n        if role == Qt.TextAlignmentRole and isinstance(value, Number):\n            return Qt.AlignRight | Qt.AlignVCenter\n        if role == Qt.ToolTipRole:\n            return str(value)\n\n    def sortColumnData(self, column):\n        return [row[column] for row in self._table]\n\n    def setHorizontalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Horizontal] = tuple(labels)\n\n    def setVerticalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Vertical] = tuple(labels)\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        headers = self._headers.get(orientation)\n\n        if headers and section < len(headers):\n            section = self.mapToSourceRows(section) if orientation == Qt.Vertical else section\n            value = headers[section]\n\n            if role == Qt.ToolTipRole:\n                role = Qt.DisplayRole\n\n            if role == Qt.DisplayRole:\n                return value.name if isinstance(value, Variable) else value\n\n            if role == Qt.DecorationRole:\n                if isinstance(value, Variable):\n                    return gui.attributeIconDict[value]\n\n        # Use QAbstractItemModel default for non-existent header/sections\n        return super().headerData(section, orientation, role)\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        if not parent.isValid():\n            del self[row:row + count]\n            for rowidx in range(row, row + count):\n                self._roleData.pop(rowidx, None)\n            self._rows = self._table_dim()[0]\n            return True\n        return False\n\n    def removeColumns(self, column, count, parent=QModelIndex()):\n        self.beginRemoveColumns(parent, column, column + count - 1)\n        for row in self._table:\n            del row[column:column + count]\n        for cols in self._roleData.values():\n            for col in range(column, column + count):\n                cols.pop(col, None)\n        del self._headers.get(Qt.Horizontal, [])[column:column + count]\n        self._cols = self._table_dim()[1]\n        self.endRemoveColumns()\n        return True\n\n    def _table_dim(self):\n        return len(self._table), max(map(len, self), default=0)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        self.beginInsertRows(parent, row, row + count - 1)\n        self._table[row:row] = [[''] * self.columnCount() for _ in range(count)]\n        self._rows = self._table_dim()[0]\n        self.endInsertRows()\n        return True\n\n    def insertColumns(self, column, count, parent=QModelIndex()):\n        self.beginInsertColumns(parent, column, column + count - 1)\n        for row in self._table:\n            row[column:column] = [''] * count\n        self._rows = self._table_dim()[0]\n        self.endInsertColumns()\n        return True\n\n    def __len__(self):\n        return len(self._table)\n\n    def __bool__(self):\n        return len(self) != 0\n\n    def __iter__(self):\n        return iter(self._table)\n\n    def __getitem__(self, item):\n        return self._table[item]\n\n    def __delitem__(self, i):\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            stop -= 1\n        else:\n            start = stop = i = i if i >= 0 else len(self) + i\n        self._check_sort_order()\n        self.beginRemoveRows(QModelIndex(), start, stop)\n        del self._table[i]\n        rows = self._table_dim()[0]\n        self._rows = rows\n        self.endRemoveRows()\n        self._update_column_count()\n\n    def __setitem__(self, i, value):\n        self._check_sort_order()\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            self.removeRows(start, stop - start)\n            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)\n            self._table[start:start + len(value)] = value\n            self._rows = self._table_dim()[0]\n            self.endInsertRows()\n            self._update_column_count()\n        else:\n            self._table[i] = value\n            self.dataChanged.emit(self.index(i, 0),\n                                  self.index(i, self.columnCount() - 1))\n\n    def _update_column_count(self):\n        cols_before = self._cols\n        cols_after = self._table_dim()[1]\n        if cols_before < cols_after:\n            self.beginInsertColumns(QModelIndex(), cols_before, cols_after - 1)\n            self._cols = cols_after\n            self.endInsertColumns()\n        elif cols_before > cols_after:\n            self.beginRemoveColumns(QModelIndex(), cols_after, cols_before - 1)\n            self._cols = cols_after\n            self.endRemoveColumns()\n\n    def _check_sort_order(self):\n        if self.mapToSourceRows(Ellipsis) is not Ellipsis:\n            warn(\"Can't modify PyTableModel when it's sorted\",\n                 RuntimeWarning, stacklevel=3)\n            raise RuntimeError(\"Can't modify PyTableModel when it's sorted\")\n\n    def wrap(self, table):\n        self.beginResetModel()\n        self._table = table\n        self._roleData = self._RoleData()\n        self._rows, self._cols = self._table_dim()\n        self.resetSorting()\n        self.endResetModel()\n\n    def tolist(self):\n        return self._table\n\n    def clear(self):\n        self.beginResetModel()\n        self._table.clear()\n        self.resetSorting()\n        self._roleData.clear()\n        self._rows, self._cols = self._table_dim()\n        self.endResetModel()\n\n    def append(self, row):\n        self.extend([row])\n\n    def _insertColumns(self, rows):\n        n_max = max(map(len, rows))\n        if self.columnCount() < n_max:\n            self.insertColumns(self.columnCount(), n_max - self.columnCount())\n\n    def extend(self, rows):\n        i, rows = len(self), list(rows)\n        self.insertRows(i, len(rows))\n        self._insertColumns(rows)\n        self[i:] = rows\n\n    def insert(self, i, row):\n        self.insertRows(i, 1)\n        self._insertColumns((row,))\n        self[i] = row\n\n    def remove(self, val):\n        del self[self._table.index(val)]\n\n\nclass PyListModelTooltip(PyListModel):\n    def __init__(self):\n        super().__init__()\n        self.tooltips = []\n\n    def data(self, index, role=Qt.DisplayRole):\n        if role == Qt.ToolTipRole:\n            return self.tooltips[index.row()]\n        else:\n            return super().data(index, role)\n\n\nclass VariableListModel(PyListModel):\n    MIME_TYPE = \"application/x-Orange-VariableList\"\n\n    def __init__(self, *args, placeholder=None, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.placeholder = placeholder\n\n    def data(self, index, role=Qt.DisplayRole):\n        if self._is_index_valid(index):\n            var = self[index.row()]\n            if var is None and role == Qt.DisplayRole:\n                return self.placeholder or \"None\"\n            if not isinstance(var, Variable):\n                return super().data(index, role)\n            elif role == Qt.DisplayRole:\n                return var.name\n            elif role == Qt.DecorationRole:\n                return gui.attributeIconDict[var]\n            elif role == Qt.ToolTipRole:\n                return self.variable_tooltip(var)\n            elif role == gui.TableVariable:\n                return var\n            else:\n                return PyListModel.data(self, index, role)\n\n    def variable_tooltip(self, var):\n        if var.is_discrete:\n            return self.discrete_variable_tooltip(var)\n        elif var.is_time:\n            return self.time_variable_toltip(var)\n        elif var.is_continuous:\n            return self.continuous_variable_toltip(var)\n        elif var.is_string:\n            return self.string_variable_tooltip(var)\n\n    def variable_labels_tooltip(self, var):\n        text = \"\"\n        if var.attributes:\n            items = [(safe_text(key), safe_text(value))\n                     for key, value in var.attributes.items()]\n            labels = list(map(\"%s = %s\".__mod__, items))\n            text += \"<br/>Variable Labels:<br/>\"\n            text += \"<br/>\".join(labels)\n        return text\n\n    def discrete_variable_tooltip(self, var):\n        text = \"<b>%s</b><br/>Categorical with %i values: \" %\\\n               (safe_text(var.name), len(var.values))\n        text += \", \".join(\"%r\" % safe_text(v) for v in var.values)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def time_variable_toltip(self, var):\n        text = \"<b>%s</b><br/>Time\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def continuous_variable_toltip(self, var):\n        text = \"<b>%s</b><br/>Numeric\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def string_variable_tooltip(self, var):\n        text = \"<b>%s</b><br/>Text\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n\nclass DomainModel(VariableListModel):\n    ATTRIBUTES, CLASSES, METAS = 1, 2, 4\n    MIXED = ATTRIBUTES | CLASSES | METAS\n    SEPARATED = (CLASSES, PyListModel.Separator,\n                 METAS, PyListModel.Separator,\n                 ATTRIBUTES)\n    PRIMITIVE = (DiscreteVariable, ContinuousVariable)\n\n    def __init__(self, order=SEPARATED, separators=True, placeholder=None,\n                 valid_types=None, alphabetical=False, skip_hidden_vars=True, **kwargs):\n        \"\"\"\n\n        Parameters\n        ----------\n        order: tuple or int\n            Order of attributes, metas, classes, separators and other options\n        separators: bool\n            If False, remove separators from `order`.\n        placeholder: str\n            The text that is shown when no variable is selected\n        valid_types: tuple\n            (Sub)types of `Variable` that are included in the model\n        alphabetical: bool\n            If true, variables are sorted alphabetically.\n        skip_hidden_vars: bool\n            If true, variables marked as \"hidden\" are skipped.\n        \"\"\"\n        super().__init__(placeholder=placeholder, **kwargs)\n        if isinstance(order, int):\n            order = (order,)\n        if placeholder is not None and None not in order:\n            # Add None for the placeholder if it's not already there\n            # Include separator if the current order uses them\n            order = (None,) + \\\n                    (self.Separator, ) * (self.Separator in order) + \\\n                    order\n        if not separators:\n            order = [e for e in order if e is not self.Separator]\n        self.order = order\n        self.valid_types = valid_types\n        self.alphabetical = alphabetical\n        self.skip_hidden_vars = skip_hidden_vars\n        self._within_set_domain = False\n        self.set_domain(None)\n\n    def set_domain(self, domain):\n        self.beginResetModel()\n        content = []\n        # The logic related to separators is a bit complicated: it ensures that\n        # even when a section is empty we don't have two separators in a row\n        # or a separator at the end\n        add_separator = False\n        for section in self.order:\n            if section is self.Separator:\n                add_separator = True\n                continue\n            if isinstance(section, int):\n                if domain is None:\n                    continue\n                to_add = list(chain(\n                    *(vars for i, vars in enumerate(\n                        (domain.attributes, domain.class_vars, domain.metas))\n                      if (1 << i) & section)))\n                if self.skip_hidden_vars:\n                    to_add = list(filter_visible(to_add))\n                if self.valid_types is not None:\n                    to_add = [var for var in to_add\n                              if isinstance(var, self.valid_types)]\n                if self.alphabetical:\n                    to_add = sorted(to_add, key=lambda x: x.name)\n            elif isinstance(section, list):\n                to_add = section\n            else:\n                to_add = [section]\n            if to_add:\n                if add_separator and content:\n                    content.append(self.Separator)\n                    add_separator = False\n                content += to_add\n        try:\n            self._within_set_domain = True\n            self[:] = content\n        finally:\n            self._within_set_domain = False\n        self.endResetModel()\n\n    def prevent_modification(method):  # pylint: disable=no-self-argument\n        @wraps(method)\n        # pylint: disable=protected-access\n        def e(self, *args, **kwargs):\n            if self._within_set_domain:\n                method(self, *args, **kwargs)\n            else:\n                raise TypeError(\n                    \"{} can be modified only by calling 'set_domain'\".\n                    format(type(self).__name__))\n        return e\n\n    @prevent_modification\n    def extend(self, iterable):\n        return super().extend(iterable)\n\n    @prevent_modification\n    def append(self, item):\n        return super().append(item)\n\n    @prevent_modification\n    def insert(self, i, val):\n        return super().insert(i, val)\n\n    @prevent_modification\n    def remove(self, val):\n        return super().remove(val)\n\n    @prevent_modification\n    def pop(self, i):\n        return super().pop(i)\n\n    @prevent_modification\n    def clear(self):\n        return super().clear()\n\n    @prevent_modification\n    def __delitem__(self, s):\n        return super().__delitem__(s)\n\n    @prevent_modification\n    def __setitem__(self, s, value):\n        return super().__setitem__(s, value)\n\n    @prevent_modification\n    def reverse(self):\n        return super().reverse()\n\n    @prevent_modification\n    def sort(self, *args, **kwargs):\n        return super().sort(*args, **kwargs)\n\n    def setData(self, index, value, role=Qt.EditRole):\n        # reimplemented\n        if role == Qt.EditRole:\n            return False\n        else:\n            return super().setData(index, value, role)\n\n    def setItemData(self, index, data):\n        # reimplemented\n        if Qt.EditRole in data:\n            return False\n        else:\n            return super().setItemData(index, data)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        # reimplemented\n        return False\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        # reimplemented\n        return False\n\n_html_replace = [(\"<\", \"&lt;\"), (\">\", \"&gt;\")]\n\n\ndef safe_text(text):\n    for old, new in _html_replace:\n        text = str(text).replace(old, new)\n    return text\n\n\nclass ContinuousPalettesModel(QAbstractListModel):\n    \"\"\"\n    Model for combo boxes\n    \"\"\"\n    def __init__(self, parent=None, categories=None, icon_width=64):\n        super().__init__(parent)\n        self.icon_width = icon_width\n\n        palettes = list(ContinuousPalettes.values())\n        if categories is None:\n            # Use dict, not set, to keep order of categories\n            categories = dict.fromkeys(palette.category for palette in palettes)\n\n        self.items = []\n        for category in categories:\n            self.items.append(category)\n            self.items += [palette for palette in palettes\n                           if palette.category == category]\n        if len(categories) == 1:\n            del self.items[0]\n\n    def rowCount(self, parent):\n        return 0 if parent.isValid() else len(self.items)\n\n    @staticmethod\n    def columnCount(parent):\n        return 0 if parent.isValid() else 1\n\n    def data(self, index, role):\n        item = self.items[index.row()]\n        if isinstance(item, str):\n            if role in [Qt.EditRole, Qt.DisplayRole]:\n                return item\n        else:\n            if role in [Qt.EditRole, Qt.DisplayRole]:\n                return item.friendly_name\n            if role == Qt.DecorationRole:\n                return item.color_strip(self.icon_width, 16)\n            if role == Qt.UserRole:\n                return item\n        return None\n\n    def flags(self, index):\n        item = self.items[index.row()]\n        if isinstance(item, ContinuousPalette):\n            return Qt.ItemIsEnabled | Qt.ItemIsSelectable\n        else:\n            return Qt.NoItemFlags\n\n    def indexOf(self, x):\n        if isinstance(x, str):\n            for i, item in enumerate(self.items):\n                if not isinstance(item, str) \\\n                        and x in (item.name, item.friendly_name):\n                    return i\n        elif isinstance(x, ContinuousPalette):\n            return self.items.index(x)\n        return None\n\n\nclass ListSingleSelectionModel(QItemSelectionModel):\n    \"\"\" Item selection model for list item models with single selection.\n\n    Defines signal:\n        - selectedIndexChanged(QModelIndex)\n\n    \"\"\"\n    selectedIndexChanged = Signal(QModelIndex)\n\n    def __init__(self, model, parent=None):\n        QItemSelectionModel.__init__(self, model, parent)\n        self.selectionChanged.connect(self.onSelectionChanged)\n\n    def onSelectionChanged(self, new, _):\n        index = list(new.indexes())\n        if index:\n            index = index.pop()\n        else:\n            index = QModelIndex()\n\n        self.selectedIndexChanged.emit(index)\n\n    def selectedRow(self):\n        \"\"\" Return QModelIndex of the selected row or invalid if no selection.\n        \"\"\"\n        rows = self.selectedRows()\n        if rows:\n            return rows[0]\n        else:\n            return QModelIndex()\n\n    def select(self, index, flags=QItemSelectionModel.ClearAndSelect):\n        if isinstance(index, int):\n            index = self.model().index(index)\n        return QItemSelectionModel.select(self, index, flags)\n\n\ndef select_row(view, row):\n    \"\"\"\n    Select a `row` in an item view.\n    \"\"\"\n    selmodel = view.selectionModel()\n    selmodel.select(view.model().index(row, 0),\n                    QItemSelectionModel.ClearAndSelect |\n                    QItemSelectionModel.Rows)\n\n\ndef select_rows(view, row_indices, command=QItemSelectionModel.ClearAndSelect):\n    \"\"\"\n    Select several rows in view.\n\n    :param QAbstractItemView view:\n    :param row_indices: Integer indices of rows to select.\n    :param command: QItemSelectionModel.SelectionFlags\n    \"\"\"\n    selmodel = view.selectionModel()\n    model = view.model()\n    selection = QItemSelection()\n    for row in row_indices:\n        index = model.index(row, 0)\n        selection.select(index, index)\n    selmodel.select(selection, command | QItemSelectionModel.Rows)\n\n\nclass ModelActionsWidget(QWidget):\n    def __init__(self, actions=None, parent=None,\n                 direction=QBoxLayout.LeftToRight):\n        QWidget.__init__(self, parent)\n        self.actions = []\n        self.buttons = []\n        layout = QBoxLayout(direction)\n        layout.setContentsMargins(0, 0, 0, 0)\n        self.setContentsMargins(0, 0, 0, 0)\n        self.setLayout(layout)\n        if actions is not None:\n            for action in actions:\n                self.addAction(action)\n        self.setLayout(layout)\n\n    def actionButton(self, action):\n        if isinstance(action, QAction):\n            button = QToolButton(self)\n            button.setDefaultAction(action)\n            return button\n        elif isinstance(action, QAbstractButton):\n            return action\n\n    def insertAction(self, ind, action, *args):\n        button = self.actionButton(action)\n        self.layout().insertWidget(ind, button, *args)\n        self.buttons.insert(ind, button)\n        self.actions.insert(ind, action)\n        return button\n\n    def addAction(self, action, *args):\n        return self.insertAction(-1, action, *args)\n\n\nclass TableModel(AbstractSortTableModel):\n    \"\"\"\n    An adapter for using Orange.data.Table within Qt's Item View Framework.\n\n    :param Orange.data.Table sourcedata: Source data table.\n    :param QObject parent:\n    \"\"\"\n    #: Orange.data.Value for the index.\n    ValueRole = gui.TableValueRole  # next(gui.OrangeUserRole)\n    #: Orange.data.Value of the row's class.\n    ClassValueRole = gui.TableClassValueRole  # next(gui.OrangeUserRole)\n    #: Orange.data.Variable of the column.\n    VariableRole = gui.TableVariable  # next(gui.OrangeUserRole)\n    #: Basic statistics of the column\n    VariableStatsRole = next(gui.OrangeUserRole)\n    #: The column's role (position) in the domain.\n    #: One of Attribute, ClassVar or Meta\n    DomainRole = next(gui.OrangeUserRole)\n\n    #: Column domain roles\n    ClassVar, Meta, Attribute = range(3)\n\n    #: Default background color for domain roles\n    ColorForRole = {\n        ClassVar: QColor(160, 160, 160),\n        Meta: QColor(220, 220, 200),\n        Attribute: None,\n    }\n\n    #: Standard column descriptor\n    Column = namedtuple(\n        \"Column\", [\"var\", \"role\", \"background\", \"format\"])\n    #: Basket column descriptor (i.e. sparse X/Y/metas/ compressed into\n    #: a single column).\n    Basket = namedtuple(\n        \"Basket\", [\"vars\", \"role\", \"background\", \"density\", \"format\"])\n\n    # The class uses the same names (X_density etc) as Table\n    # pylint: disable=invalid-name\n    def __init__(self, sourcedata, parent=None):\n        super().__init__(parent)\n        self.source = sourcedata\n        self.domain = domain = sourcedata.domain\n\n        self.X_density = sourcedata.X_density()\n        self.Y_density = sourcedata.Y_density()\n        self.M_density = sourcedata.metas_density()\n\n        def format_sparse(vars, datagetter, instance):\n            data = datagetter(instance)\n            return \", \".join(\"{}={}\".format(vars[i].name, vars[i].repr_val(v))\n                             for i, v in zip(data.indices, data.data))\n\n        def format_sparse_bool(vars, datagetter, instance):\n            data = datagetter(instance)\n            return \", \".join(vars[i].name for i in data.indices)\n\n        def format_dense(var, instance):\n            return str(instance[var])\n\n        def make_basket_formater(vars, density, role):\n            formater = (format_sparse if density == Storage.SPARSE\n                        else format_sparse_bool)\n            if role == TableModel.Attribute:\n                getter = operator.attrgetter(\"sparse_x\")\n            elif role == TableModel.ClassVar:\n                getter = operator.attrgetter(\"sparse_y\")\n            elif role == TableModel.Meta:\n                getter = operator.attrgetter(\"sparse_metas\")\n            return partial(formater, vars, getter)\n\n        def make_basket(vars, density, role):\n            return TableModel.Basket(\n                vars, TableModel.Attribute, self.ColorForRole[role], density,\n                make_basket_formater(vars, density, role)\n            )\n\n        def make_column(var, role):\n            return TableModel.Column(\n                var, role, self.ColorForRole[role],\n                partial(format_dense, var)\n            )\n\n        columns = []\n\n        if self.Y_density != Storage.DENSE and domain.class_vars:\n            coldesc = make_basket(domain.class_vars, self.Y_density,\n                                  TableModel.ClassVar)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.ClassVar)\n                        for var in domain.class_vars]\n\n        if self.M_density != Storage.DENSE and domain.metas:\n            coldesc = make_basket(domain.metas, self.M_density,\n                                  TableModel.Meta)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.Meta)\n                        for var in domain.metas]\n\n        if self.X_density != Storage.DENSE and domain.attributes:\n            coldesc = make_basket(domain.attributes, self.X_density,\n                                  TableModel.Attribute)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.Attribute)\n                        for var in domain.attributes]\n\n        #: list of all domain variables (class_vars + metas + attrs)\n        self.vars = domain.class_vars + domain.metas + domain.attributes\n        self.columns = columns\n\n        #: A list of all unique attribute labels (in all variables)\n        self._labels = sorted(\n            reduce(operator.ior,\n                   [set(var.attributes) for var in self.vars],\n                   set()))\n\n        @lru_cache(maxsize=1000)\n        def row_instance(index):\n            return self.source[int(index)]\n        self._row_instance = row_instance\n\n        # column basic statistics (VariableStatsRole), computed when\n        # first needed.\n        self.__stats = None\n        self.__rowCount = sourcedata.approx_len()\n        self.__columnCount = len(self.columns)\n\n        if self.__rowCount > (2 ** 31 - 1):\n            raise ValueError(\"len(sourcedata) > 2 ** 31 - 1\")\n\n    def sortColumnData(self, column):\n        return self._columnSortKeyData(column, TableModel.ValueRole)\n\n    @deprecated('Orange.widgets.utils.itemmodels.TableModel.sortColumnData')\n    def columnSortKeyData(self, column, role):\n        return self._columnSortKeyData(column, role)\n\n    def _columnSortKeyData(self, column, role):\n        \"\"\"\n        Return a sequence of source table objects which can be used as\n        `keys` for sorting.\n\n        :param int column: Sort column.\n        :param Qt.ItemRole role: Sort item role.\n\n        \"\"\"\n        coldesc = self.columns[column]\n        if isinstance(coldesc, TableModel.Column) \\\n                and role == TableModel.ValueRole:\n            col_data = numpy.asarray(self.source.get_column_view(coldesc.var)[0])\n\n            if coldesc.var.is_continuous:\n                # continuous from metas have dtype object; cast it to float\n                col_data = col_data.astype(float)\n            return col_data\n        else:\n            return numpy.asarray([self.index(i, column).data(role)\n                                  for i in range(self.rowCount())])\n\n    def data(self, index, role,\n             # For optimizing out LOAD_GLOBAL byte code instructions in\n             # the item role tests.\n             _str=str,\n             _Qt_DisplayRole=Qt.DisplayRole,\n             _Qt_EditRole=Qt.EditRole,\n             _Qt_BackgroundRole=Qt.BackgroundRole,\n             _ValueRole=ValueRole,\n             _ClassValueRole=ClassValueRole,\n             _VariableRole=VariableRole,\n             _DomainRole=DomainRole,\n             _VariableStatsRole=VariableStatsRole,\n             # Some cached local precomputed values.\n             # All of the above roles we respond to\n             _recognizedRoles=frozenset([Qt.DisplayRole,\n                                         Qt.EditRole,\n                                         Qt.BackgroundRole,\n                                         ValueRole,\n                                         ClassValueRole,\n                                         VariableRole,\n                                         DomainRole,\n                                         VariableStatsRole])):\n        \"\"\"\n        Reimplemented from `QAbstractItemModel.data`\n        \"\"\"\n        if role not in _recognizedRoles:\n            return None\n\n        row, col = index.row(), index.column()\n        if  not 0 <= row <= self.__rowCount:\n            return None\n\n        row = self.mapToSourceRows(row)\n\n        try:\n            instance = self._row_instance(row)\n        except IndexError:\n            self.layoutAboutToBeChanged.emit()\n            self.beginRemoveRows(self.parent(), row, max(self.rowCount(), row))\n            self.__rowCount = min(row, self.__rowCount)\n            self.endRemoveRows()\n            self.layoutChanged.emit()\n            return None\n        coldesc = self.columns[col]\n\n        if role == _Qt_DisplayRole:\n            return coldesc.format(instance)\n        elif role == _Qt_EditRole and isinstance(coldesc, TableModel.Column):\n            return instance[coldesc.var]\n        elif role == _Qt_BackgroundRole:\n            return coldesc.background\n        elif role == _ValueRole and isinstance(coldesc, TableModel.Column):\n            return instance[coldesc.var]\n        elif role == _ClassValueRole:\n            try:\n                return instance.get_class()\n            except TypeError:\n                return None\n        elif role == _VariableRole and isinstance(coldesc, TableModel.Column):\n            return coldesc.var\n        elif role == _DomainRole:\n            return coldesc.role\n        elif role == _VariableStatsRole:\n            return self._stats_for_column(col)\n        else:\n            return None\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            try:\n                self.source[row, index.column()] = value\n            except (TypeError, IndexError):\n                return False\n            else:\n                self.dataChanged.emit(index, index)\n                return True\n        else:\n            return False\n\n    def parent(self, index=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.parent`.\"\"\"\n        return QModelIndex()\n\n    def rowCount(self, parent=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.rowCount`.\"\"\"\n        return 0 if parent.isValid() else self.__rowCount\n\n    def columnCount(self, parent=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.columnCount`.\"\"\"\n        return 0 if parent.isValid() else self.__columnCount\n\n    def headerData(self, section, orientation, role):\n        \"\"\"Reimplemented from `QAbstractTableModel.headerData`.\"\"\"\n        if orientation == Qt.Vertical:\n            if role == Qt.DisplayRole:\n                return int(self.mapToSourceRows(section) + 1)\n            return None\n\n        coldesc = self.columns[section]\n        if role == Qt.DisplayRole:\n            if isinstance(coldesc, TableModel.Basket):\n                return \"{...}\"\n            else:\n                return coldesc.var.name\n        elif role == Qt.ToolTipRole:\n            return self._tooltip(coldesc)\n        elif role == TableModel.VariableRole \\\n                and isinstance(coldesc, TableModel.Column):\n            return coldesc.var\n        elif role == TableModel.VariableStatsRole:\n            return self._stats_for_column(section)\n        elif role == TableModel.DomainRole:\n            return coldesc.role\n        else:\n            return None\n\n    def _tooltip(self, coldesc):\n        \"\"\"\n        Return an header tool tip text for an `column` descriptor.\n        \"\"\"\n        if isinstance(coldesc, TableModel.Basket):\n            return None\n\n        labels = self._labels\n        variable = coldesc.var\n        pairs = [(escape(key), escape(str(variable.attributes[key])))\n                 for key in labels if key in variable.attributes]\n        tip = \"<b>%s</b>\" % escape(variable.name)\n        tip = \"<br/>\".join([tip] + [\"%s = %s\" % pair for pair in pairs])\n        return tip\n\n    def _stats_for_column(self, column):\n        \"\"\"\n        Return BasicStats for `column` index.\n        \"\"\"\n        coldesc = self.columns[column]\n        if isinstance(coldesc, TableModel.Basket):\n            return None\n\n        if self.__stats is None:\n            self.__stats = datacaching.getCached(\n                self.source, basic_stats.DomainBasicStats,\n                (self.source, True)\n            )\n\n        return self.__stats[coldesc.var]\n",
            "new_file_content": "from numbers import Number, Integral\nfrom math import isnan, isinf\n\nimport operator\nfrom collections import namedtuple, Sequence, defaultdict\nfrom contextlib import contextmanager\nfrom functools import reduce, partial, lru_cache, wraps\nfrom itertools import chain\nfrom warnings import warn\nfrom xml.sax.saxutils import escape\n\nfrom AnyQt.QtCore import (\n    Qt, QObject, QAbstractListModel, QModelIndex,\n    QItemSelectionModel, QItemSelection)\nfrom AnyQt.QtCore import pyqtSignal as Signal\nfrom AnyQt.QtGui import QColor\nfrom AnyQt.QtWidgets import (\n    QWidget, QBoxLayout, QToolButton, QAbstractButton, QAction\n)\n\nimport numpy\n\nfrom orangewidget.utils.itemmodels import (\n    PyListModel, AbstractSortTableModel as _AbstractSortTableModel\n)\n\nfrom Orange.widgets.utils.colorpalettes import ContinuousPalettes, ContinuousPalette\nfrom Orange.data import Variable, Storage, DiscreteVariable, ContinuousVariable\nfrom Orange.data.domain import filter_visible\nfrom Orange.widgets import gui\nfrom Orange.widgets.utils import datacaching\nfrom Orange.statistics import basic_stats\nfrom Orange.util import deprecated\n\n__all__ = [\n    \"PyListModel\", \"VariableListModel\", \"PyListModelTooltip\", \"DomainModel\",\n    \"AbstractSortTableModel\", \"PyTableModel\", \"TableModel\",\n    \"ModelActionsWidget\", \"ListSingleSelectionModel\"\n]\n\n@contextmanager\ndef signal_blocking(obj):\n    blocked = obj.signalsBlocked()\n    obj.blockSignals(True)\n    try:\n        yield\n    finally:\n        obj.blockSignals(blocked)\n\n\ndef _as_contiguous_range(the_slice, length):\n    start, stop, step = the_slice.indices(length)\n    if step == -1:\n        # Equivalent range with positive step\n        start, stop, step = stop + 1, start + 1, 1\n    elif not (step == 1 or step is None):\n        raise IndexError(\"Non-contiguous range.\")\n    return start, stop, step\n\n\nclass AbstractSortTableModel(_AbstractSortTableModel):\n    # these were defined on TableModel below. When the AbstractSortTableModel\n    # was extracted and made a base of TableModel these deprecations were\n    # misplaced, they belong in TableModel.\n    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapFromSourceRows')\n    def mapFromTableRows(self, rows):\n        return self.mapFromSourceRows(rows)\n\n    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapToSourceRows')\n    def mapToTableRows(self, rows):\n        return self.mapToSourceRows(rows)\n\n\nclass PyTableModel(AbstractSortTableModel):\n    \"\"\" A model for displaying python tables (sequences of sequences) in\n    QTableView objects.\n\n    Parameters\n    ----------\n    sequence : list\n        The initial list to wrap.\n    parent : QObject\n        Parent QObject.\n    editable: bool or sequence\n        If True, all items are flagged editable. If sequence, the True-ish\n        fields mark their respective columns editable.\n\n    Notes\n    -----\n    The model rounds numbers to human readable precision, e.g.:\n    1.23e-04, 1.234, 1234.5, 12345, 1.234e06.\n\n    To set additional item roles, use setData().\n    \"\"\"\n\n    @staticmethod\n    def _RoleData():\n        return defaultdict(lambda: defaultdict(dict))\n\n    # All methods are either necessary overrides of super methods, or\n    # methods likened to the Python list's. Hence, docstrings aren't.\n    # pylint: disable=missing-docstring\n    def __init__(self, sequence=None, parent=None, editable=False):\n        super().__init__(parent)\n        self._rows = self._cols = 0\n        self._headers = {}\n        self._editable = editable\n        self._table = None\n        self._roleData = {}\n        self.wrap(sequence or [])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._rows\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._cols\n\n    def flags(self, index):\n        flags = super().flags(index)\n        if not self._editable or not index.isValid():\n            return flags\n        if isinstance(self._editable, Sequence):\n            return flags | Qt.ItemIsEditable if self._editable[index.column()] else flags\n        return flags | Qt.ItemIsEditable\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            self[row][index.column()] = value\n            self.dataChanged.emit(index, index)\n        else:\n            self._roleData[row][index.column()][role] = value\n        return True\n\n    def data(self, index, role=Qt.DisplayRole):\n        if not index.isValid():\n            return\n\n        row, column = self.mapToSourceRows(index.row()), index.column()\n\n        role_value = self._roleData.get(row, {}).get(column, {}).get(role)\n        if role_value is not None:\n            return role_value\n\n        try:\n            value = self[row][column]\n        except IndexError:\n            return\n        if role == Qt.EditRole:\n            return value\n        if role == Qt.DecorationRole and isinstance(value, Variable):\n            return gui.attributeIconDict[value]\n        if role == Qt.DisplayRole:\n            if (isinstance(value, Number) and\n                    not (isnan(value) or isinf(value) or isinstance(value, Integral))):\n                absval = abs(value)\n                strlen = len(str(int(absval)))\n                value = '{:.{}{}}'.format(value,\n                                          2 if absval < .001 else\n                                          3 if strlen < 2 else\n                                          1 if strlen < 5 else\n                                          0 if strlen < 6 else\n                                          3,\n                                          'f' if (absval == 0 or\n                                                  absval >= .001 and\n                                                  strlen < 6)\n                                          else 'e')\n            return str(value)\n        if role == Qt.TextAlignmentRole and isinstance(value, Number):\n            return Qt.AlignRight | Qt.AlignVCenter\n        if role == Qt.ToolTipRole:\n            return str(value)\n\n    def sortColumnData(self, column):\n        return [row[column] for row in self._table]\n\n    def setHorizontalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Horizontal] = tuple(labels)\n\n    def setVerticalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Vertical] = tuple(labels)\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        headers = self._headers.get(orientation)\n\n        if headers and section < len(headers):\n            section = self.mapToSourceRows(section) if orientation == Qt.Vertical else section\n            value = headers[section]\n\n            if role == Qt.ToolTipRole:\n                role = Qt.DisplayRole\n\n            if role == Qt.DisplayRole:\n                return value.name if isinstance(value, Variable) else value\n\n            if role == Qt.DecorationRole:\n                if isinstance(value, Variable):\n                    return gui.attributeIconDict[value]\n\n        # Use QAbstractItemModel default for non-existent header/sections\n        return super().headerData(section, orientation, role)\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        if not parent.isValid():\n            del self[row:row + count]\n            for rowidx in range(row, row + count):\n                self._roleData.pop(rowidx, None)\n            self._rows = self._table_dim()[0]\n            return True\n        return False\n\n    def removeColumns(self, column, count, parent=QModelIndex()):\n        self.beginRemoveColumns(parent, column, column + count - 1)\n        for row in self._table:\n            del row[column:column + count]\n        for cols in self._roleData.values():\n            for col in range(column, column + count):\n                cols.pop(col, None)\n        del self._headers.get(Qt.Horizontal, [])[column:column + count]\n        self._cols = self._table_dim()[1]\n        self.endRemoveColumns()\n        return True\n\n    def _table_dim(self):\n        return len(self._table), max(map(len, self), default=0)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        self.beginInsertRows(parent, row, row + count - 1)\n        self._table[row:row] = [[''] * self.columnCount() for _ in range(count)]\n        self._rows = self._table_dim()[0]\n        self.endInsertRows()\n        return True\n\n    def insertColumns(self, column, count, parent=QModelIndex()):\n        self.beginInsertColumns(parent, column, column + count - 1)\n        for row in self._table:\n            row[column:column] = [''] * count\n        self._rows = self._table_dim()[0]\n        self.endInsertColumns()\n        return True\n\n    def __len__(self):\n        return len(self._table)\n\n    def __bool__(self):\n        return len(self) != 0\n\n    def __iter__(self):\n        return iter(self._table)\n\n    def __getitem__(self, item):\n        return self._table[item]\n\n    def __delitem__(self, i):\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            stop -= 1\n        else:\n            start = stop = i = i if i >= 0 else len(self) + i\n        self._check_sort_order()\n        self.beginRemoveRows(QModelIndex(), start, stop)\n        del self._table[i]\n        rows = self._table_dim()[0]\n        self._rows = rows\n        self.endRemoveRows()\n        self._update_column_count()\n\n    def __setitem__(self, i, value):\n        self._check_sort_order()\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            self.removeRows(start, stop - start)\n            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)\n            self._table[start:start] = value\n            self._rows = self._table_dim()[0]\n            self.endInsertRows()\n            self._update_column_count()\n        else:\n            self._table[i] = value\n            self.dataChanged.emit(self.index(i, 0),\n                                  self.index(i, self.columnCount() - 1))\n\n    def _update_column_count(self):\n        cols_before = self._cols\n        cols_after = self._table_dim()[1]\n        if cols_before < cols_after:\n            self.beginInsertColumns(QModelIndex(), cols_before, cols_after - 1)\n            self._cols = cols_after\n            self.endInsertColumns()\n        elif cols_before > cols_after:\n            self.beginRemoveColumns(QModelIndex(), cols_after, cols_before - 1)\n            self._cols = cols_after\n            self.endRemoveColumns()\n\n    def _check_sort_order(self):\n        if self.mapToSourceRows(Ellipsis) is not Ellipsis:\n            warn(\"Can't modify PyTableModel when it's sorted\",\n                 RuntimeWarning, stacklevel=3)\n            raise RuntimeError(\"Can't modify PyTableModel when it's sorted\")\n\n    def wrap(self, table):\n        self.beginResetModel()\n        self._table = table\n        self._roleData = self._RoleData()\n        self._rows, self._cols = self._table_dim()\n        self.resetSorting()\n        self.endResetModel()\n\n    def tolist(self):\n        return self._table\n\n    def clear(self):\n        self.beginResetModel()\n        self._table.clear()\n        self.resetSorting()\n        self._roleData.clear()\n        self._rows, self._cols = self._table_dim()\n        self.endResetModel()\n\n    def append(self, row):\n        self.extend([row])\n\n    def _insertColumns(self, rows):\n        n_max = max(map(len, rows))\n        if self.columnCount() < n_max:\n            self.insertColumns(self.columnCount(), n_max - self.columnCount())\n\n    def extend(self, rows):\n        i, rows = len(self), list(rows)\n        self.insertRows(i, len(rows))\n        self._insertColumns(rows)\n        self[i:] = rows\n\n    def insert(self, i, row):\n        self.insertRows(i, 1)\n        self._insertColumns((row,))\n        self[i] = row\n\n    def remove(self, val):\n        del self[self._table.index(val)]\n\n\nclass PyListModelTooltip(PyListModel):\n    def __init__(self):\n        super().__init__()\n        self.tooltips = []\n\n    def data(self, index, role=Qt.DisplayRole):\n        if role == Qt.ToolTipRole:\n            return self.tooltips[index.row()]\n        else:\n            return super().data(index, role)\n\n\nclass VariableListModel(PyListModel):\n    MIME_TYPE = \"application/x-Orange-VariableList\"\n\n    def __init__(self, *args, placeholder=None, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.placeholder = placeholder\n\n    def data(self, index, role=Qt.DisplayRole):\n        if self._is_index_valid(index):\n            var = self[index.row()]\n            if var is None and role == Qt.DisplayRole:\n                return self.placeholder or \"None\"\n            if not isinstance(var, Variable):\n                return super().data(index, role)\n            elif role == Qt.DisplayRole:\n                return var.name\n            elif role == Qt.DecorationRole:\n                return gui.attributeIconDict[var]\n            elif role == Qt.ToolTipRole:\n                return self.variable_tooltip(var)\n            elif role == gui.TableVariable:\n                return var\n            else:\n                return PyListModel.data(self, index, role)\n\n    def variable_tooltip(self, var):\n        if var.is_discrete:\n            return self.discrete_variable_tooltip(var)\n        elif var.is_time:\n            return self.time_variable_toltip(var)\n        elif var.is_continuous:\n            return self.continuous_variable_toltip(var)\n        elif var.is_string:\n            return self.string_variable_tooltip(var)\n\n    def variable_labels_tooltip(self, var):\n        text = \"\"\n        if var.attributes:\n            items = [(safe_text(key), safe_text(value))\n                     for key, value in var.attributes.items()]\n            labels = list(map(\"%s = %s\".__mod__, items))\n            text += \"<br/>Variable Labels:<br/>\"\n            text += \"<br/>\".join(labels)\n        return text\n\n    def discrete_variable_tooltip(self, var):\n        text = \"<b>%s</b><br/>Categorical with %i values: \" %\\\n               (safe_text(var.name), len(var.values))\n        text += \", \".join(\"%r\" % safe_text(v) for v in var.values)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def time_variable_toltip(self, var):\n        text = \"<b>%s</b><br/>Time\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def continuous_variable_toltip(self, var):\n        text = \"<b>%s</b><br/>Numeric\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def string_variable_tooltip(self, var):\n        text = \"<b>%s</b><br/>Text\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n\nclass DomainModel(VariableListModel):\n    ATTRIBUTES, CLASSES, METAS = 1, 2, 4\n    MIXED = ATTRIBUTES | CLASSES | METAS\n    SEPARATED = (CLASSES, PyListModel.Separator,\n                 METAS, PyListModel.Separator,\n                 ATTRIBUTES)\n    PRIMITIVE = (DiscreteVariable, ContinuousVariable)\n\n    def __init__(self, order=SEPARATED, separators=True, placeholder=None,\n                 valid_types=None, alphabetical=False, skip_hidden_vars=True, **kwargs):\n        \"\"\"\n\n        Parameters\n        ----------\n        order: tuple or int\n            Order of attributes, metas, classes, separators and other options\n        separators: bool\n            If False, remove separators from `order`.\n        placeholder: str\n            The text that is shown when no variable is selected\n        valid_types: tuple\n            (Sub)types of `Variable` that are included in the model\n        alphabetical: bool\n            If true, variables are sorted alphabetically.\n        skip_hidden_vars: bool\n            If true, variables marked as \"hidden\" are skipped.\n        \"\"\"\n        super().__init__(placeholder=placeholder, **kwargs)\n        if isinstance(order, int):\n            order = (order,)\n        if placeholder is not None and None not in order:\n            # Add None for the placeholder if it's not already there\n            # Include separator if the current order uses them\n            order = (None,) + \\\n                    (self.Separator, ) * (self.Separator in order) + \\\n                    order\n        if not separators:\n            order = [e for e in order if e is not self.Separator]\n        self.order = order\n        self.valid_types = valid_types\n        self.alphabetical = alphabetical\n        self.skip_hidden_vars = skip_hidden_vars\n        self._within_set_domain = False\n        self.set_domain(None)\n\n    def set_domain(self, domain):\n        self.beginResetModel()\n        content = []\n        # The logic related to separators is a bit complicated: it ensures that\n        # even when a section is empty we don't have two separators in a row\n        # or a separator at the end\n        add_separator = False\n        for section in self.order:\n            if section is self.Separator:\n                add_separator = True\n                continue\n            if isinstance(section, int):\n                if domain is None:\n                    continue\n                to_add = list(chain(\n                    *(vars for i, vars in enumerate(\n                        (domain.attributes, domain.class_vars, domain.metas))\n                      if (1 << i) & section)))\n                if self.skip_hidden_vars:\n                    to_add = list(filter_visible(to_add))\n                if self.valid_types is not None:\n                    to_add = [var for var in to_add\n                              if isinstance(var, self.valid_types)]\n                if self.alphabetical:\n                    to_add = sorted(to_add, key=lambda x: x.name)\n            elif isinstance(section, list):\n                to_add = section\n            else:\n                to_add = [section]\n            if to_add:\n                if add_separator and content:\n                    content.append(self.Separator)\n                    add_separator = False\n                content += to_add\n        try:\n            self._within_set_domain = True\n            self[:] = content\n        finally:\n            self._within_set_domain = False\n        self.endResetModel()\n\n    def prevent_modification(method):  # pylint: disable=no-self-argument\n        @wraps(method)\n        # pylint: disable=protected-access\n        def e(self, *args, **kwargs):\n            if self._within_set_domain:\n                method(self, *args, **kwargs)\n            else:\n                raise TypeError(\n                    \"{} can be modified only by calling 'set_domain'\".\n                    format(type(self).__name__))\n        return e\n\n    @prevent_modification\n    def extend(self, iterable):\n        return super().extend(iterable)\n\n    @prevent_modification\n    def append(self, item):\n        return super().append(item)\n\n    @prevent_modification\n    def insert(self, i, val):\n        return super().insert(i, val)\n\n    @prevent_modification\n    def remove(self, val):\n        return super().remove(val)\n\n    @prevent_modification\n    def pop(self, i):\n        return super().pop(i)\n\n    @prevent_modification\n    def clear(self):\n        return super().clear()\n\n    @prevent_modification\n    def __delitem__(self, s):\n        return super().__delitem__(s)\n\n    @prevent_modification\n    def __setitem__(self, s, value):\n        return super().__setitem__(s, value)\n\n    @prevent_modification\n    def reverse(self):\n        return super().reverse()\n\n    @prevent_modification\n    def sort(self, *args, **kwargs):\n        return super().sort(*args, **kwargs)\n\n    def setData(self, index, value, role=Qt.EditRole):\n        # reimplemented\n        if role == Qt.EditRole:\n            return False\n        else:\n            return super().setData(index, value, role)\n\n    def setItemData(self, index, data):\n        # reimplemented\n        if Qt.EditRole in data:\n            return False\n        else:\n            return super().setItemData(index, data)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        # reimplemented\n        return False\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        # reimplemented\n        return False\n\n_html_replace = [(\"<\", \"&lt;\"), (\">\", \"&gt;\")]\n\n\ndef safe_text(text):\n    for old, new in _html_replace:\n        text = str(text).replace(old, new)\n    return text\n\n\nclass ContinuousPalettesModel(QAbstractListModel):\n    \"\"\"\n    Model for combo boxes\n    \"\"\"\n    def __init__(self, parent=None, categories=None, icon_width=64):\n        super().__init__(parent)\n        self.icon_width = icon_width\n\n        palettes = list(ContinuousPalettes.values())\n        if categories is None:\n            # Use dict, not set, to keep order of categories\n            categories = dict.fromkeys(palette.category for palette in palettes)\n\n        self.items = []\n        for category in categories:\n            self.items.append(category)\n            self.items += [palette for palette in palettes\n                           if palette.category == category]\n        if len(categories) == 1:\n            del self.items[0]\n\n    def rowCount(self, parent):\n        return 0 if parent.isValid() else len(self.items)\n\n    @staticmethod\n    def columnCount(parent):\n        return 0 if parent.isValid() else 1\n\n    def data(self, index, role):\n        item = self.items[index.row()]\n        if isinstance(item, str):\n            if role in [Qt.EditRole, Qt.DisplayRole]:\n                return item\n        else:\n            if role in [Qt.EditRole, Qt.DisplayRole]:\n                return item.friendly_name\n            if role == Qt.DecorationRole:\n                return item.color_strip(self.icon_width, 16)\n            if role == Qt.UserRole:\n                return item\n        return None\n\n    def flags(self, index):\n        item = self.items[index.row()]\n        if isinstance(item, ContinuousPalette):\n            return Qt.ItemIsEnabled | Qt.ItemIsSelectable\n        else:\n            return Qt.NoItemFlags\n\n    def indexOf(self, x):\n        if isinstance(x, str):\n            for i, item in enumerate(self.items):\n                if not isinstance(item, str) \\\n                        and x in (item.name, item.friendly_name):\n                    return i\n        elif isinstance(x, ContinuousPalette):\n            return self.items.index(x)\n        return None\n\n\nclass ListSingleSelectionModel(QItemSelectionModel):\n    \"\"\" Item selection model for list item models with single selection.\n\n    Defines signal:\n        - selectedIndexChanged(QModelIndex)\n\n    \"\"\"\n    selectedIndexChanged = Signal(QModelIndex)\n\n    def __init__(self, model, parent=None):\n        QItemSelectionModel.__init__(self, model, parent)\n        self.selectionChanged.connect(self.onSelectionChanged)\n\n    def onSelectionChanged(self, new, _):\n        index = list(new.indexes())\n        if index:\n            index = index.pop()\n        else:\n            index = QModelIndex()\n\n        self.selectedIndexChanged.emit(index)\n\n    def selectedRow(self):\n        \"\"\" Return QModelIndex of the selected row or invalid if no selection.\n        \"\"\"\n        rows = self.selectedRows()\n        if rows:\n            return rows[0]\n        else:\n            return QModelIndex()\n\n    def select(self, index, flags=QItemSelectionModel.ClearAndSelect):\n        if isinstance(index, int):\n            index = self.model().index(index)\n        return QItemSelectionModel.select(self, index, flags)\n\n\ndef select_row(view, row):\n    \"\"\"\n    Select a `row` in an item view.\n    \"\"\"\n    selmodel = view.selectionModel()\n    selmodel.select(view.model().index(row, 0),\n                    QItemSelectionModel.ClearAndSelect |\n                    QItemSelectionModel.Rows)\n\n\ndef select_rows(view, row_indices, command=QItemSelectionModel.ClearAndSelect):\n    \"\"\"\n    Select several rows in view.\n\n    :param QAbstractItemView view:\n    :param row_indices: Integer indices of rows to select.\n    :param command: QItemSelectionModel.SelectionFlags\n    \"\"\"\n    selmodel = view.selectionModel()\n    model = view.model()\n    selection = QItemSelection()\n    for row in row_indices:\n        index = model.index(row, 0)\n        selection.select(index, index)\n    selmodel.select(selection, command | QItemSelectionModel.Rows)\n\n\nclass ModelActionsWidget(QWidget):\n    def __init__(self, actions=None, parent=None,\n                 direction=QBoxLayout.LeftToRight):\n        QWidget.__init__(self, parent)\n        self.actions = []\n        self.buttons = []\n        layout = QBoxLayout(direction)\n        layout.setContentsMargins(0, 0, 0, 0)\n        self.setContentsMargins(0, 0, 0, 0)\n        self.setLayout(layout)\n        if actions is not None:\n            for action in actions:\n                self.addAction(action)\n        self.setLayout(layout)\n\n    def actionButton(self, action):\n        if isinstance(action, QAction):\n            button = QToolButton(self)\n            button.setDefaultAction(action)\n            return button\n        elif isinstance(action, QAbstractButton):\n            return action\n\n    def insertAction(self, ind, action, *args):\n        button = self.actionButton(action)\n        self.layout().insertWidget(ind, button, *args)\n        self.buttons.insert(ind, button)\n        self.actions.insert(ind, action)\n        return button\n\n    def addAction(self, action, *args):\n        return self.insertAction(-1, action, *args)\n\n\nclass TableModel(AbstractSortTableModel):\n    \"\"\"\n    An adapter for using Orange.data.Table within Qt's Item View Framework.\n\n    :param Orange.data.Table sourcedata: Source data table.\n    :param QObject parent:\n    \"\"\"\n    #: Orange.data.Value for the index.\n    ValueRole = gui.TableValueRole  # next(gui.OrangeUserRole)\n    #: Orange.data.Value of the row's class.\n    ClassValueRole = gui.TableClassValueRole  # next(gui.OrangeUserRole)\n    #: Orange.data.Variable of the column.\n    VariableRole = gui.TableVariable  # next(gui.OrangeUserRole)\n    #: Basic statistics of the column\n    VariableStatsRole = next(gui.OrangeUserRole)\n    #: The column's role (position) in the domain.\n    #: One of Attribute, ClassVar or Meta\n    DomainRole = next(gui.OrangeUserRole)\n\n    #: Column domain roles\n    ClassVar, Meta, Attribute = range(3)\n\n    #: Default background color for domain roles\n    ColorForRole = {\n        ClassVar: QColor(160, 160, 160),\n        Meta: QColor(220, 220, 200),\n        Attribute: None,\n    }\n\n    #: Standard column descriptor\n    Column = namedtuple(\n        \"Column\", [\"var\", \"role\", \"background\", \"format\"])\n    #: Basket column descriptor (i.e. sparse X/Y/metas/ compressed into\n    #: a single column).\n    Basket = namedtuple(\n        \"Basket\", [\"vars\", \"role\", \"background\", \"density\", \"format\"])\n\n    # The class uses the same names (X_density etc) as Table\n    # pylint: disable=invalid-name\n    def __init__(self, sourcedata, parent=None):\n        super().__init__(parent)\n        self.source = sourcedata\n        self.domain = domain = sourcedata.domain\n\n        self.X_density = sourcedata.X_density()\n        self.Y_density = sourcedata.Y_density()\n        self.M_density = sourcedata.metas_density()\n\n        def format_sparse(vars, datagetter, instance):\n            data = datagetter(instance)\n            return \", \".join(\"{}={}\".format(vars[i].name, vars[i].repr_val(v))\n                             for i, v in zip(data.indices, data.data))\n\n        def format_sparse_bool(vars, datagetter, instance):\n            data = datagetter(instance)\n            return \", \".join(vars[i].name for i in data.indices)\n\n        def format_dense(var, instance):\n            return str(instance[var])\n\n        def make_basket_formater(vars, density, role):\n            formater = (format_sparse if density == Storage.SPARSE\n                        else format_sparse_bool)\n            if role == TableModel.Attribute:\n                getter = operator.attrgetter(\"sparse_x\")\n            elif role == TableModel.ClassVar:\n                getter = operator.attrgetter(\"sparse_y\")\n            elif role == TableModel.Meta:\n                getter = operator.attrgetter(\"sparse_metas\")\n            return partial(formater, vars, getter)\n\n        def make_basket(vars, density, role):\n            return TableModel.Basket(\n                vars, TableModel.Attribute, self.ColorForRole[role], density,\n                make_basket_formater(vars, density, role)\n            )\n\n        def make_column(var, role):\n            return TableModel.Column(\n                var, role, self.ColorForRole[role],\n                partial(format_dense, var)\n            )\n\n        columns = []\n\n        if self.Y_density != Storage.DENSE and domain.class_vars:\n            coldesc = make_basket(domain.class_vars, self.Y_density,\n                                  TableModel.ClassVar)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.ClassVar)\n                        for var in domain.class_vars]\n\n        if self.M_density != Storage.DENSE and domain.metas:\n            coldesc = make_basket(domain.metas, self.M_density,\n                                  TableModel.Meta)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.Meta)\n                        for var in domain.metas]\n\n        if self.X_density != Storage.DENSE and domain.attributes:\n            coldesc = make_basket(domain.attributes, self.X_density,\n                                  TableModel.Attribute)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.Attribute)\n                        for var in domain.attributes]\n\n        #: list of all domain variables (class_vars + metas + attrs)\n        self.vars = domain.class_vars + domain.metas + domain.attributes\n        self.columns = columns\n\n        #: A list of all unique attribute labels (in all variables)\n        self._labels = sorted(\n            reduce(operator.ior,\n                   [set(var.attributes) for var in self.vars],\n                   set()))\n\n        @lru_cache(maxsize=1000)\n        def row_instance(index):\n            return self.source[int(index)]\n        self._row_instance = row_instance\n\n        # column basic statistics (VariableStatsRole), computed when\n        # first needed.\n        self.__stats = None\n        self.__rowCount = sourcedata.approx_len()\n        self.__columnCount = len(self.columns)\n\n        if self.__rowCount > (2 ** 31 - 1):\n            raise ValueError(\"len(sourcedata) > 2 ** 31 - 1\")\n\n    def sortColumnData(self, column):\n        return self._columnSortKeyData(column, TableModel.ValueRole)\n\n    @deprecated('Orange.widgets.utils.itemmodels.TableModel.sortColumnData')\n    def columnSortKeyData(self, column, role):\n        return self._columnSortKeyData(column, role)\n\n    def _columnSortKeyData(self, column, role):\n        \"\"\"\n        Return a sequence of source table objects which can be used as\n        `keys` for sorting.\n\n        :param int column: Sort column.\n        :param Qt.ItemRole role: Sort item role.\n\n        \"\"\"\n        coldesc = self.columns[column]\n        if isinstance(coldesc, TableModel.Column) \\\n                and role == TableModel.ValueRole:\n            col_data = numpy.asarray(self.source.get_column_view(coldesc.var)[0])\n\n            if coldesc.var.is_continuous:\n                # continuous from metas have dtype object; cast it to float\n                col_data = col_data.astype(float)\n            return col_data\n        else:\n            return numpy.asarray([self.index(i, column).data(role)\n                                  for i in range(self.rowCount())])\n\n    def data(self, index, role,\n             # For optimizing out LOAD_GLOBAL byte code instructions in\n             # the item role tests.\n             _str=str,\n             _Qt_DisplayRole=Qt.DisplayRole,\n             _Qt_EditRole=Qt.EditRole,\n             _Qt_BackgroundRole=Qt.BackgroundRole,\n             _ValueRole=ValueRole,\n             _ClassValueRole=ClassValueRole,\n             _VariableRole=VariableRole,\n             _DomainRole=DomainRole,\n             _VariableStatsRole=VariableStatsRole,\n             # Some cached local precomputed values.\n             # All of the above roles we respond to\n             _recognizedRoles=frozenset([Qt.DisplayRole,\n                                         Qt.EditRole,\n                                         Qt.BackgroundRole,\n                                         ValueRole,\n                                         ClassValueRole,\n                                         VariableRole,\n                                         DomainRole,\n                                         VariableStatsRole])):\n        \"\"\"\n        Reimplemented from `QAbstractItemModel.data`\n        \"\"\"\n        if role not in _recognizedRoles:\n            return None\n\n        row, col = index.row(), index.column()\n        if  not 0 <= row <= self.__rowCount:\n            return None\n\n        row = self.mapToSourceRows(row)\n\n        try:\n            instance = self._row_instance(row)\n        except IndexError:\n            self.layoutAboutToBeChanged.emit()\n            self.beginRemoveRows(self.parent(), row, max(self.rowCount(), row))\n            self.__rowCount = min(row, self.__rowCount)\n            self.endRemoveRows()\n            self.layoutChanged.emit()\n            return None\n        coldesc = self.columns[col]\n\n        if role == _Qt_DisplayRole:\n            return coldesc.format(instance)\n        elif role == _Qt_EditRole and isinstance(coldesc, TableModel.Column):\n            return instance[coldesc.var]\n        elif role == _Qt_BackgroundRole:\n            return coldesc.background\n        elif role == _ValueRole and isinstance(coldesc, TableModel.Column):\n            return instance[coldesc.var]\n        elif role == _ClassValueRole:\n            try:\n                return instance.get_class()\n            except TypeError:\n                return None\n        elif role == _VariableRole and isinstance(coldesc, TableModel.Column):\n            return coldesc.var\n        elif role == _DomainRole:\n            return coldesc.role\n        elif role == _VariableStatsRole:\n            return self._stats_for_column(col)\n        else:\n            return None\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            try:\n                self.source[row, index.column()] = value\n            except (TypeError, IndexError):\n                return False\n            else:\n                self.dataChanged.emit(index, index)\n                return True\n        else:\n            return False\n\n    def parent(self, index=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.parent`.\"\"\"\n        return QModelIndex()\n\n    def rowCount(self, parent=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.rowCount`.\"\"\"\n        return 0 if parent.isValid() else self.__rowCount\n\n    def columnCount(self, parent=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.columnCount`.\"\"\"\n        return 0 if parent.isValid() else self.__columnCount\n\n    def headerData(self, section, orientation, role):\n        \"\"\"Reimplemented from `QAbstractTableModel.headerData`.\"\"\"\n        if orientation == Qt.Vertical:\n            if role == Qt.DisplayRole:\n                return int(self.mapToSourceRows(section) + 1)\n            return None\n\n        coldesc = self.columns[section]\n        if role == Qt.DisplayRole:\n            if isinstance(coldesc, TableModel.Basket):\n                return \"{...}\"\n            else:\n                return coldesc.var.name\n        elif role == Qt.ToolTipRole:\n            return self._tooltip(coldesc)\n        elif role == TableModel.VariableRole \\\n                and isinstance(coldesc, TableModel.Column):\n            return coldesc.var\n        elif role == TableModel.VariableStatsRole:\n            return self._stats_for_column(section)\n        elif role == TableModel.DomainRole:\n            return coldesc.role\n        else:\n            return None\n\n    def _tooltip(self, coldesc):\n        \"\"\"\n        Return an header tool tip text for an `column` descriptor.\n        \"\"\"\n        if isinstance(coldesc, TableModel.Basket):\n            return None\n\n        labels = self._labels\n        variable = coldesc.var\n        pairs = [(escape(key), escape(str(variable.attributes[key])))\n                 for key in labels if key in variable.attributes]\n        tip = \"<b>%s</b>\" % escape(variable.name)\n        tip = \"<br/>\".join([tip] + [\"%s = %s\" % pair for pair in pairs])\n        return tip\n\n    def _stats_for_column(self, column):\n        \"\"\"\n        Return BasicStats for `column` index.\n        \"\"\"\n        coldesc = self.columns[column]\n        if isinstance(coldesc, TableModel.Basket):\n            return None\n\n        if self.__stats is None:\n            self.__stats = datacaching.getCached(\n                self.source, basic_stats.DomainBasicStats,\n                (self.source, True)\n            )\n\n        return self.__stats[coldesc.var]\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/utils/itemmodels.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "cc94e18fb",
                "new_commit_hash": "9d15f776f",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/utils/itemmodels.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/utils/itemmodels.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 281,
                            "length": 7
                        },
                        "new_range": {
                            "start": 281,
                            "length": 7
                        },
                        "section": "class PyTableModel(AbstractSortTableModel):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            start, stop, _ = _as_contiguous_range(i, len(self))",
                                "type": "context"
                            },
                            {
                                "content": "            self.removeRows(start, stop - start)",
                                "type": "context"
                            },
                            {
                                "content": "            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)",
                                "type": "context"
                            },
                            {
                                "content": "            self._table[start:start + len(value)] = value",
                                "type": "deleted"
                            },
                            {
                                "content": "            self._table[start:start] = value",
                                "type": "added"
                            },
                            {
                                "content": "            self._rows = self._table_dim()[0]",
                                "type": "context"
                            },
                            {
                                "content": "            self.endInsertRows()",
                                "type": "context"
                            },
                            {
                                "content": "            self._update_column_count()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/utils/itemmodels.py",
                            "type": "method",
                            "name": "PyTableModel.__setitem__",
                            "content": "class PyTableModel(AbstractSortTableModel):\n    \"\"\" A model for displaying python tables (sequences of sequences) in\n    QTableView objects.\n\n    Parameters\n    ----------\n    sequence : list\n        The initial list to wrap.\n    parent : QObject\n        Parent QObject.\n    editable: bool or sequence\n        If True, all items are flagged editable. If sequence, the True-ish\n        fields mark their respective columns editable.\n\n    Notes\n    -----\n    The model rounds numbers to human readable precision, e.g.:\n    1.23e-04, 1.234, 1234.5, 12345, 1.234e06.\n\n    To set additional item roles, use setData().\n    \"\"\"\n\n    @staticmethod\n    def _RoleData():\n        return defaultdict(lambda: defaultdict(dict))\n\n    # All methods are either necessary overrides of super methods, or\n    # methods likened to the Python list's. Hence, docstrings aren't.\n    # pylint: disable=missing-docstring\n    def __init__(self, sequence=None, parent=None, editable=False):\n        super().__init__(parent)\n        self._rows = self._cols = 0\n        self._headers = {}\n        self._editable = editable\n        self._table = None\n        self._roleData = {}\n        self.wrap(sequence or [])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._rows\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._cols\n\n    def flags(self, index):\n        flags = super().flags(index)\n        if not self._editable or not index.isValid():\n            return flags\n        if isinstance(self._editable, Sequence):\n            return flags | Qt.ItemIsEditable if self._editable[index.column()] else flags\n        return flags | Qt.ItemIsEditable\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            self[row][index.column()] = value\n            self.dataChanged.emit(index, index)\n        else:\n            self._roleData[row][index.column()][role] = value\n        return True\n\n    def data(self, index, role=Qt.DisplayRole):\n        if not index.isValid():\n            return\n\n        row, column = self.mapToSourceRows(index.row()), index.column()\n\n        role_value = self._roleData.get(row, {}).get(column, {}).get(role)\n        if role_value is not None:\n            return role_value\n\n        try:\n            value = self[row][column]\n        except IndexError:\n            return\n        if role == Qt.EditRole:\n            return value\n        if role == Qt.DecorationRole and isinstance(value, Variable):\n            return gui.attributeIconDict[value]\n        if role == Qt.DisplayRole:\n            if (isinstance(value, Number) and\n                    not (isnan(value) or isinf(value) or isinstance(value, Integral))):\n                absval = abs(value)\n                strlen = len(str(int(absval)))\n                value = '{:.{}{}}'.format(value,\n                                          2 if absval < .001 else\n                                          3 if strlen < 2 else\n                                          1 if strlen < 5 else\n                                          0 if strlen < 6 else\n                                          3,\n                                          'f' if (absval == 0 or\n                                                  absval >= .001 and\n                                                  strlen < 6)\n                                          else 'e')\n            return str(value)\n        if role == Qt.TextAlignmentRole and isinstance(value, Number):\n            return Qt.AlignRight | Qt.AlignVCenter\n        if role == Qt.ToolTipRole:\n            return str(value)\n\n    def sortColumnData(self, column):\n        return [row[column] for row in self._table]\n\n    def setHorizontalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Horizontal] = tuple(labels)\n\n    def setVerticalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Vertical] = tuple(labels)\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        headers = self._headers.get(orientation)\n\n        if headers and section < len(headers):\n            section = self.mapToSourceRows(section) if orientation == Qt.Vertical else section\n            value = headers[section]\n\n            if role == Qt.ToolTipRole:\n                role = Qt.DisplayRole\n\n            if role == Qt.DisplayRole:\n                return value.name if isinstance(value, Variable) else value\n\n            if role == Qt.DecorationRole:\n                if isinstance(value, Variable):\n                    return gui.attributeIconDict[value]\n\n        # Use QAbstractItemModel default for non-existent header/sections\n        return super().headerData(section, orientation, role)\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        if not parent.isValid():\n            del self[row:row + count]\n            for rowidx in range(row, row + count):\n                self._roleData.pop(rowidx, None)\n            self._rows = self._table_dim()[0]\n            return True\n        return False\n\n    def removeColumns(self, column, count, parent=QModelIndex()):\n        self.beginRemoveColumns(parent, column, column + count - 1)\n        for row in self._table:\n            del row[column:column + count]\n        for cols in self._roleData.values():\n            for col in range(column, column + count):\n                cols.pop(col, None)\n        del self._headers.get(Qt.Horizontal, [])[column:column + count]\n        self._cols = self._table_dim()[1]\n        self.endRemoveColumns()\n        return True\n\n    def _table_dim(self):\n        return len(self._table), max(map(len, self), default=0)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        self.beginInsertRows(parent, row, row + count - 1)\n        self._table[row:row] = [[''] * self.columnCount() for _ in range(count)]\n        self._rows = self._table_dim()[0]\n        self.endInsertRows()\n        return True\n\n    def insertColumns(self, column, count, parent=QModelIndex()):\n        self.beginInsertColumns(parent, column, column + count - 1)\n        for row in self._table:\n            row[column:column] = [''] * count\n        self._rows = self._table_dim()[0]\n        self.endInsertColumns()\n        return True\n\n    def __len__(self):\n        return len(self._table)\n\n    def __bool__(self):\n        return len(self) != 0\n\n    def __iter__(self):\n        return iter(self._table)\n\n    def __getitem__(self, item):\n        return self._table[item]\n\n    def __delitem__(self, i):\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            stop -= 1\n        else:\n            start = stop = i = i if i >= 0 else len(self) + i\n        self._check_sort_order()\n        self.beginRemoveRows(QModelIndex(), start, stop)\n        del self._table[i]\n        rows = self._table_dim()[0]\n        self._rows = rows\n        self.endRemoveRows()\n        self._update_column_count()\n\n    def __setitem__(self, i, value):\n        self._check_sort_order()\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            self.removeRows(start, stop - start)\n            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)\n            self._table[start:start + len(value)] = value\n            self._rows = self._table_dim()[0]\n            self.endInsertRows()\n            self._update_column_count()\n        else:\n            self._table[i] = value\n            self.dataChanged.emit(self.index(i, 0),\n                                  self.index(i, self.columnCount() - 1))\n\n    def _update_column_count(self):\n        cols_before = self._cols\n        cols_after = self._table_dim()[1]\n        if cols_before < cols_after:\n            self.beginInsertColumns(QModelIndex(), cols_before, cols_after - 1)\n            self._cols = cols_after\n            self.endInsertColumns()\n        elif cols_before > cols_after:\n            self.beginRemoveColumns(QModelIndex(), cols_after, cols_before - 1)\n            self._cols = cols_after\n            self.endRemoveColumns()\n\n    def _check_sort_order(self):\n        if self.mapToSourceRows(Ellipsis) is not Ellipsis:\n            warn(\"Can't modify PyTableModel when it's sorted\",\n                 RuntimeWarning, stacklevel=3)\n            raise RuntimeError(\"Can't modify PyTableModel when it's sorted\")\n\n    def wrap(self, table):\n        self.beginResetModel()\n        self._table = table\n        self._roleData = self._RoleData()\n        self._rows, self._cols = self._table_dim()\n        self.resetSorting()\n        self.endResetModel()\n\n    def tolist(self):\n        return self._table\n\n    def clear(self):\n        self.beginResetModel()\n        self._table.clear()\n        self.resetSorting()\n        self._roleData.clear()\n        self._rows, self._cols = self._table_dim()\n        self.endResetModel()\n\n    def append(self, row):\n        self.extend([row])\n\n    def _insertColumns(self, rows):\n        n_max = max(map(len, rows))\n        if self.columnCount() < n_max:\n            self.insertColumns(self.columnCount(), n_max - self.columnCount())\n\n    def extend(self, rows):\n        i, rows = len(self), list(rows)\n        self.insertRows(i, len(rows))\n        self._insertColumns(rows)\n        self[i:] = rows\n\n    def insert(self, i, row):\n        self.insertRows(i, 1)\n        self._insertColumns((row,))\n        self[i] = row\n\n    def remove(self, val):\n        del self[self._table.index(val)]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 278,
                            "end_lineno": 291,
                            "parent": {
                                "file_name": "Orange/widgets/utils/itemmodels.py",
                                "type": "class",
                                "name": "PyTableModel",
                                "content": "class PyTableModel(AbstractSortTableModel):\n    \"\"\" A model for displaying python tables (sequences of sequences) in\n    QTableView objects.\n\n    Parameters\n    ----------\n    sequence : list\n        The initial list to wrap.\n    parent : QObject\n        Parent QObject.\n    editable: bool or sequence\n        If True, all items are flagged editable. If sequence, the True-ish\n        fields mark their respective columns editable.\n\n    Notes\n    -----\n    The model rounds numbers to human readable precision, e.g.:\n    1.23e-04, 1.234, 1234.5, 12345, 1.234e06.\n\n    To set additional item roles, use setData().\n    \"\"\"\n\n    @staticmethod\n    def _RoleData():\n        return defaultdict(lambda: defaultdict(dict))\n\n    # All methods are either necessary overrides of super methods, or\n    # methods likened to the Python list's. Hence, docstrings aren't.\n    # pylint: disable=missing-docstring\n    def __init__(self, sequence=None, parent=None, editable=False):\n        super().__init__(parent)\n        self._rows = self._cols = 0\n        self._headers = {}\n        self._editable = editable\n        self._table = None\n        self._roleData = {}\n        self.wrap(sequence or [])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._rows\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._cols\n\n    def flags(self, index):\n        flags = super().flags(index)\n        if not self._editable or not index.isValid():\n            return flags\n        if isinstance(self._editable, Sequence):\n            return flags | Qt.ItemIsEditable if self._editable[index.column()] else flags\n        return flags | Qt.ItemIsEditable\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            self[row][index.column()] = value\n            self.dataChanged.emit(index, index)\n        else:\n            self._roleData[row][index.column()][role] = value\n        return True\n\n    def data(self, index, role=Qt.DisplayRole):\n        if not index.isValid():\n            return\n\n        row, column = self.mapToSourceRows(index.row()), index.column()\n\n        role_value = self._roleData.get(row, {}).get(column, {}).get(role)\n        if role_value is not None:\n            return role_value\n\n        try:\n            value = self[row][column]\n        except IndexError:\n            return\n        if role == Qt.EditRole:\n            return value\n        if role == Qt.DecorationRole and isinstance(value, Variable):\n            return gui.attributeIconDict[value]\n        if role == Qt.DisplayRole:\n            if (isinstance(value, Number) and\n                    not (isnan(value) or isinf(value) or isinstance(value, Integral))):\n                absval = abs(value)\n                strlen = len(str(int(absval)))\n                value = '{:.{}{}}'.format(value,\n                                          2 if absval < .001 else\n                                          3 if strlen < 2 else\n                                          1 if strlen < 5 else\n                                          0 if strlen < 6 else\n                                          3,\n                                          'f' if (absval == 0 or\n                                                  absval >= .001 and\n                                                  strlen < 6)\n                                          else 'e')\n            return str(value)\n        if role == Qt.TextAlignmentRole and isinstance(value, Number):\n            return Qt.AlignRight | Qt.AlignVCenter\n        if role == Qt.ToolTipRole:\n            return str(value)\n\n    def sortColumnData(self, column):\n        return [row[column] for row in self._table]\n\n    def setHorizontalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Horizontal] = tuple(labels)\n\n    def setVerticalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Vertical] = tuple(labels)\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        headers = self._headers.get(orientation)\n\n        if headers and section < len(headers):\n            section = self.mapToSourceRows(section) if orientation == Qt.Vertical else section\n            value = headers[section]\n\n            if role == Qt.ToolTipRole:\n                role = Qt.DisplayRole\n\n            if role == Qt.DisplayRole:\n                return value.name if isinstance(value, Variable) else value\n\n            if role == Qt.DecorationRole:\n                if isinstance(value, Variable):\n                    return gui.attributeIconDict[value]\n\n        # Use QAbstractItemModel default for non-existent header/sections\n        return super().headerData(section, orientation, role)\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        if not parent.isValid():\n            del self[row:row + count]\n            for rowidx in range(row, row + count):\n                self._roleData.pop(rowidx, None)\n            self._rows = self._table_dim()[0]\n            return True\n        return False\n\n    def removeColumns(self, column, count, parent=QModelIndex()):\n        self.beginRemoveColumns(parent, column, column + count - 1)\n        for row in self._table:\n            del row[column:column + count]\n        for cols in self._roleData.values():\n            for col in range(column, column + count):\n                cols.pop(col, None)\n        del self._headers.get(Qt.Horizontal, [])[column:column + count]\n        self._cols = self._table_dim()[1]\n        self.endRemoveColumns()\n        return True\n\n    def _table_dim(self):\n        return len(self._table), max(map(len, self), default=0)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        self.beginInsertRows(parent, row, row + count - 1)\n        self._table[row:row] = [[''] * self.columnCount() for _ in range(count)]\n        self._rows = self._table_dim()[0]\n        self.endInsertRows()\n        return True\n\n    def insertColumns(self, column, count, parent=QModelIndex()):\n        self.beginInsertColumns(parent, column, column + count - 1)\n        for row in self._table:\n            row[column:column] = [''] * count\n        self._rows = self._table_dim()[0]\n        self.endInsertColumns()\n        return True\n\n    def __len__(self):\n        return len(self._table)\n\n    def __bool__(self):\n        return len(self) != 0\n\n    def __iter__(self):\n        return iter(self._table)\n\n    def __getitem__(self, item):\n        return self._table[item]\n\n    def __delitem__(self, i):\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            stop -= 1\n        else:\n            start = stop = i = i if i >= 0 else len(self) + i\n        self._check_sort_order()\n        self.beginRemoveRows(QModelIndex(), start, stop)\n        del self._table[i]\n        rows = self._table_dim()[0]\n        self._rows = rows\n        self.endRemoveRows()\n        self._update_column_count()\n\n    def __setitem__(self, i, value):\n        self._check_sort_order()\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            self.removeRows(start, stop - start)\n            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)\n            self._table[start:start + len(value)] = value\n            self._rows = self._table_dim()[0]\n            self.endInsertRows()\n            self._update_column_count()\n        else:\n            self._table[i] = value\n            self.dataChanged.emit(self.index(i, 0),\n                                  self.index(i, self.columnCount() - 1))\n\n    def _update_column_count(self):\n        cols_before = self._cols\n        cols_after = self._table_dim()[1]\n        if cols_before < cols_after:\n            self.beginInsertColumns(QModelIndex(), cols_before, cols_after - 1)\n            self._cols = cols_after\n            self.endInsertColumns()\n        elif cols_before > cols_after:\n            self.beginRemoveColumns(QModelIndex(), cols_after, cols_before - 1)\n            self._cols = cols_after\n            self.endRemoveColumns()\n\n    def _check_sort_order(self):\n        if self.mapToSourceRows(Ellipsis) is not Ellipsis:\n            warn(\"Can't modify PyTableModel when it's sorted\",\n                 RuntimeWarning, stacklevel=3)\n            raise RuntimeError(\"Can't modify PyTableModel when it's sorted\")\n\n    def wrap(self, table):\n        self.beginResetModel()\n        self._table = table\n        self._roleData = self._RoleData()\n        self._rows, self._cols = self._table_dim()\n        self.resetSorting()\n        self.endResetModel()\n\n    def tolist(self):\n        return self._table\n\n    def clear(self):\n        self.beginResetModel()\n        self._table.clear()\n        self.resetSorting()\n        self._roleData.clear()\n        self._rows, self._cols = self._table_dim()\n        self.endResetModel()\n\n    def append(self, row):\n        self.extend([row])\n\n    def _insertColumns(self, rows):\n        n_max = max(map(len, rows))\n        if self.columnCount() < n_max:\n            self.insertColumns(self.columnCount(), n_max - self.columnCount())\n\n    def extend(self, rows):\n        i, rows = len(self), list(rows)\n        self.insertRows(i, len(rows))\n        self._insertColumns(rows)\n        self[i:] = rows\n\n    def insert(self, i, row):\n        self.insertRows(i, 1)\n        self._insertColumns((row,))\n        self[i] = row\n\n    def remove(self, val):\n        del self[self._table.index(val)]",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 74,
                                "end_lineno": 350,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/utils/itemmodels.py",
                            "type": "class",
                            "name": "PyTableModel",
                            "content": "class PyTableModel(AbstractSortTableModel):\n    \"\"\" A model for displaying python tables (sequences of sequences) in\n    QTableView objects.\n\n    Parameters\n    ----------\n    sequence : list\n        The initial list to wrap.\n    parent : QObject\n        Parent QObject.\n    editable: bool or sequence\n        If True, all items are flagged editable. If sequence, the True-ish\n        fields mark their respective columns editable.\n\n    Notes\n    -----\n    The model rounds numbers to human readable precision, e.g.:\n    1.23e-04, 1.234, 1234.5, 12345, 1.234e06.\n\n    To set additional item roles, use setData().\n    \"\"\"\n\n    @staticmethod\n    def _RoleData():\n        return defaultdict(lambda: defaultdict(dict))\n\n    # All methods are either necessary overrides of super methods, or\n    # methods likened to the Python list's. Hence, docstrings aren't.\n    # pylint: disable=missing-docstring\n    def __init__(self, sequence=None, parent=None, editable=False):\n        super().__init__(parent)\n        self._rows = self._cols = 0\n        self._headers = {}\n        self._editable = editable\n        self._table = None\n        self._roleData = {}\n        self.wrap(sequence or [])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._rows\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._cols\n\n    def flags(self, index):\n        flags = super().flags(index)\n        if not self._editable or not index.isValid():\n            return flags\n        if isinstance(self._editable, Sequence):\n            return flags | Qt.ItemIsEditable if self._editable[index.column()] else flags\n        return flags | Qt.ItemIsEditable\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            self[row][index.column()] = value\n            self.dataChanged.emit(index, index)\n        else:\n            self._roleData[row][index.column()][role] = value\n        return True\n\n    def data(self, index, role=Qt.DisplayRole):\n        if not index.isValid():\n            return\n\n        row, column = self.mapToSourceRows(index.row()), index.column()\n\n        role_value = self._roleData.get(row, {}).get(column, {}).get(role)\n        if role_value is not None:\n            return role_value\n\n        try:\n            value = self[row][column]\n        except IndexError:\n            return\n        if role == Qt.EditRole:\n            return value\n        if role == Qt.DecorationRole and isinstance(value, Variable):\n            return gui.attributeIconDict[value]\n        if role == Qt.DisplayRole:\n            if (isinstance(value, Number) and\n                    not (isnan(value) or isinf(value) or isinstance(value, Integral))):\n                absval = abs(value)\n                strlen = len(str(int(absval)))\n                value = '{:.{}{}}'.format(value,\n                                          2 if absval < .001 else\n                                          3 if strlen < 2 else\n                                          1 if strlen < 5 else\n                                          0 if strlen < 6 else\n                                          3,\n                                          'f' if (absval == 0 or\n                                                  absval >= .001 and\n                                                  strlen < 6)\n                                          else 'e')\n            return str(value)\n        if role == Qt.TextAlignmentRole and isinstance(value, Number):\n            return Qt.AlignRight | Qt.AlignVCenter\n        if role == Qt.ToolTipRole:\n            return str(value)\n\n    def sortColumnData(self, column):\n        return [row[column] for row in self._table]\n\n    def setHorizontalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Horizontal] = tuple(labels)\n\n    def setVerticalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Vertical] = tuple(labels)\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        headers = self._headers.get(orientation)\n\n        if headers and section < len(headers):\n            section = self.mapToSourceRows(section) if orientation == Qt.Vertical else section\n            value = headers[section]\n\n            if role == Qt.ToolTipRole:\n                role = Qt.DisplayRole\n\n            if role == Qt.DisplayRole:\n                return value.name if isinstance(value, Variable) else value\n\n            if role == Qt.DecorationRole:\n                if isinstance(value, Variable):\n                    return gui.attributeIconDict[value]\n\n        # Use QAbstractItemModel default for non-existent header/sections\n        return super().headerData(section, orientation, role)\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        if not parent.isValid():\n            del self[row:row + count]\n            for rowidx in range(row, row + count):\n                self._roleData.pop(rowidx, None)\n            self._rows = self._table_dim()[0]\n            return True\n        return False\n\n    def removeColumns(self, column, count, parent=QModelIndex()):\n        self.beginRemoveColumns(parent, column, column + count - 1)\n        for row in self._table:\n            del row[column:column + count]\n        for cols in self._roleData.values():\n            for col in range(column, column + count):\n                cols.pop(col, None)\n        del self._headers.get(Qt.Horizontal, [])[column:column + count]\n        self._cols = self._table_dim()[1]\n        self.endRemoveColumns()\n        return True\n\n    def _table_dim(self):\n        return len(self._table), max(map(len, self), default=0)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        self.beginInsertRows(parent, row, row + count - 1)\n        self._table[row:row] = [[''] * self.columnCount() for _ in range(count)]\n        self._rows = self._table_dim()[0]\n        self.endInsertRows()\n        return True\n\n    def insertColumns(self, column, count, parent=QModelIndex()):\n        self.beginInsertColumns(parent, column, column + count - 1)\n        for row in self._table:\n            row[column:column] = [''] * count\n        self._rows = self._table_dim()[0]\n        self.endInsertColumns()\n        return True\n\n    def __len__(self):\n        return len(self._table)\n\n    def __bool__(self):\n        return len(self) != 0\n\n    def __iter__(self):\n        return iter(self._table)\n\n    def __getitem__(self, item):\n        return self._table[item]\n\n    def __delitem__(self, i):\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            stop -= 1\n        else:\n            start = stop = i = i if i >= 0 else len(self) + i\n        self._check_sort_order()\n        self.beginRemoveRows(QModelIndex(), start, stop)\n        del self._table[i]\n        rows = self._table_dim()[0]\n        self._rows = rows\n        self.endRemoveRows()\n        self._update_column_count()\n\n    def __setitem__(self, i, value):\n        self._check_sort_order()\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            self.removeRows(start, stop - start)\n            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)\n            self._table[start:start + len(value)] = value\n            self._rows = self._table_dim()[0]\n            self.endInsertRows()\n            self._update_column_count()\n        else:\n            self._table[i] = value\n            self.dataChanged.emit(self.index(i, 0),\n                                  self.index(i, self.columnCount() - 1))\n\n    def _update_column_count(self):\n        cols_before = self._cols\n        cols_after = self._table_dim()[1]\n        if cols_before < cols_after:\n            self.beginInsertColumns(QModelIndex(), cols_before, cols_after - 1)\n            self._cols = cols_after\n            self.endInsertColumns()\n        elif cols_before > cols_after:\n            self.beginRemoveColumns(QModelIndex(), cols_after, cols_before - 1)\n            self._cols = cols_after\n            self.endRemoveColumns()\n\n    def _check_sort_order(self):\n        if self.mapToSourceRows(Ellipsis) is not Ellipsis:\n            warn(\"Can't modify PyTableModel when it's sorted\",\n                 RuntimeWarning, stacklevel=3)\n            raise RuntimeError(\"Can't modify PyTableModel when it's sorted\")\n\n    def wrap(self, table):\n        self.beginResetModel()\n        self._table = table\n        self._roleData = self._RoleData()\n        self._rows, self._cols = self._table_dim()\n        self.resetSorting()\n        self.endResetModel()\n\n    def tolist(self):\n        return self._table\n\n    def clear(self):\n        self.beginResetModel()\n        self._table.clear()\n        self.resetSorting()\n        self._roleData.clear()\n        self._rows, self._cols = self._table_dim()\n        self.endResetModel()\n\n    def append(self, row):\n        self.extend([row])\n\n    def _insertColumns(self, rows):\n        n_max = max(map(len, rows))\n        if self.columnCount() < n_max:\n            self.insertColumns(self.columnCount(), n_max - self.columnCount())\n\n    def extend(self, rows):\n        i, rows = len(self), list(rows)\n        self.insertRows(i, len(rows))\n        self._insertColumns(rows)\n        self[i:] = rows\n\n    def insert(self, i, row):\n        self.insertRows(i, 1)\n        self._insertColumns((row,))\n        self[i] = row\n\n    def remove(self, val):\n        del self[self._table.index(val)]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 74,
                            "end_lineno": 350,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "# Test methods with long descriptive names can omit docstrings\n# pylint: disable=missing-docstring\n\nimport unittest\nfrom unittest.mock import patch\n\nimport numpy as np\n\nfrom AnyQt.QtCore import Qt, QModelIndex\nfrom AnyQt.QtTest import QSignalSpy\n\nfrom Orange.data import \\\n    Domain, \\\n    ContinuousVariable, DiscreteVariable, StringVariable, TimeVariable\nfrom Orange.widgets.utils import colorpalettes\nfrom Orange.widgets.utils.itemmodels import \\\n    AbstractSortTableModel, PyTableModel,\\\n    PyListModel, VariableListModel, DomainModel, ContinuousPalettesModel, \\\n    _as_contiguous_range\nfrom Orange.widgets.gui import TableVariable\nfrom orangewidget.tests.base import GuiTest\n\n\nclass TestUtils(unittest.TestCase):\n    def test_as_contiguous_range(self):\n        self.assertEqual(_as_contiguous_range(slice(1, 8), 20), (1, 8, 1))\n        self.assertEqual(_as_contiguous_range(slice(1, 8), 6), (1, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8, 1, -1), 6), (2, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8), 6), (0, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8, None, -1), 6), (0, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(7, None, -1), 9), (0, 8, 1))\n        self.assertEqual(_as_contiguous_range(slice(None, None, -1), 9),\n                         (0, 9, 1))\n\n\nclass TestPyTableModel(unittest.TestCase):\n    def setUp(self):\n        self.model = PyTableModel([[1, 4],\n                                   [2, 3]])\n\n    def test_init(self):\n        self.model = PyTableModel()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_rowCount(self):\n        self.assertEqual(self.model.rowCount(), 2)\n        self.assertEqual(len(self.model), 2)\n\n    def test_columnCount(self):\n        self.assertEqual(self.model.columnCount(), 2)\n\n    def test_data(self):\n        mi = self.model.index(0, 0)\n        self.assertEqual(self.model.data(mi), '1')\n        self.assertEqual(self.model.data(mi, Qt.EditRole), 1)\n\n    def test_editable(self):\n        editable_model = PyTableModel([[0]], editable=True)\n        self.assertFalse(int(self.model.flags(self.model.index(0, 0)) & Qt.ItemIsEditable))\n        self.assertTrue(int(editable_model.flags(editable_model.index(0, 0)) & Qt.ItemIsEditable))\n\n    def test_sort(self):\n        self.model.sort(1)\n        self.assertEqual(self.model.index(0, 0).data(Qt.EditRole), 2)\n\n    def test_setHeaderLabels(self):\n        self.model.setHorizontalHeaderLabels(['Col 1', 'Col 2'])\n        self.assertEqual(self.model.headerData(1, Qt.Horizontal), 'Col 2')\n        self.assertEqual(self.model.headerData(1, Qt.Vertical), 2)\n\n    def test_removeRows(self):\n        self.model.removeRows(0, 1)\n        self.assertEqual(len(self.model), 1)\n        self.assertEqual(self.model[0][1], 3)\n\n    def test_removeColumns(self):\n        self.model.removeColumns(0, 1)\n        self.assertEqual(self.model.columnCount(), 1)\n        self.assertEqual(self.model[1][0], 3)\n\n    def test_insertRows(self):\n        self.model.insertRows(0, 1)\n        self.assertEqual(self.model[1][0], 1)\n\n    def test_insertColumns(self):\n        self.model.insertColumns(0, 1)\n        self.assertEqual(self.model[0], ['', 1, 4])\n\n    def test_wrap(self):\n        self.model.wrap([[0]])\n        self.assertEqual(self.model.rowCount(), 1)\n        self.assertEqual(self.model.columnCount(), 1)\n\n    def test_clear(self):\n        self.model.clear()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_append(self):\n        self.model.append([5, 6])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_extend(self):\n        self.model.extend([[5, 6]])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_insert(self):\n        self.model.insert(0, [5, 6])\n        self.assertEqual(self.model[0][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_remove(self):\n        self.model.remove([2, 3])\n        self.assertEqual(self.model.rowCount(), 1)\n\n    def test_other_roles(self):\n        self.model.append([2, 3])\n        self.model.setData(self.model.index(2, 0),\n                           Qt.AlignCenter,\n                           Qt.TextAlignmentRole)\n        del self.model[1]\n        self.assertTrue(Qt.AlignCenter &\n                        self.model.data(self.model.index(1, 0),\n                                        Qt.TextAlignmentRole))\n\n    def test_emits_column_changes_on_row_insert(self):\n        inserted = []\n        removed = []\n        model = PyTableModel()\n        model.columnsInserted.connect(inserted.append)\n        model.columnsRemoved.connect(removed.append)\n        inserted = QSignalSpy(model.columnsInserted)\n        removed = QSignalSpy(model.columnsRemoved)\n        model.append([2])\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n        model.append([2, 3])\n        self.assertEqual(list(inserted)[-1][1:], [1, 1])\n        del model[:]\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model.extend([[0, 1], [0, 2]])\n        self.assertEqual(list(inserted)[-1][1:], [0, 1])\n        model.clear()\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model[:] = [[1], [2]]\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n\n\nclass TestVariableListModel(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.disc = DiscreteVariable(\"gender\", values=(\"M\", \"F\"))\n        cls.cont = ContinuousVariable(\"age\")\n        cls.string = StringVariable(\"name\")\n        cls.time = TimeVariable(\"birth\")\n        cls.model = VariableListModel([\n            cls.cont, None, \"Foo\", cls.disc, cls.string, cls.time])\n\n    def test_placeholder(self):\n        model = self.model\n        self.assertEqual(model.data(model.index(1)), \"None\")\n        model.placeholder = \"Bar\"\n        self.assertEqual(model.data(model.index(1)), \"Bar\")\n        model.placeholder = \"None\"\n\n    def test_displayrole(self):\n        data, index = self.model.data, self.model.index\n        self.assertEqual(data(index(0)), \"age\")\n        self.assertEqual(data(index(1)), \"None\")\n        self.assertEqual(data(index(2)), \"Foo\")\n        self.assertEqual(data(index(3)), \"gender\")\n        self.assertEqual(data(index(4)), \"name\")\n        self.assertEqual(data(index(5)), \"birth\")\n\n    def test_tooltip(self):\n        def get_tooltip(i):\n            return self.model.data(self.model.index(i), Qt.ToolTipRole)\n\n        text = get_tooltip(0)\n        self.assertIn(\"age\", text)\n        self.assertIn(\"Numeric\", text)\n\n        self.assertIsNone(get_tooltip(1))\n        self.assertIsNone(get_tooltip(2))\n\n        text = get_tooltip(3)\n        self.assertIn(\"gender\", text)\n        self.assertIn(\"M\", text)\n        self.assertIn(\"F\", text)\n        self.assertIn(\"2\", text)\n        self.assertIn(\"Categorical\", text)\n\n        text = get_tooltip(4)\n        self.assertIn(\"name\", text)\n        self.assertIn(\"Text\", text)\n\n        text = get_tooltip(5)\n        self.assertIn(\"birth\", text)\n        self.assertIn(\"Time\", text)\n\n        self.cont.attributes = {\"foo\": \"bar\"}\n        text = get_tooltip(0)\n        self.assertIn(\"foo\", text)\n        self.assertIn(\"bar\", text)\n\n    def test_table_variable(self):\n        self.assertEqual(\n            [self.model.data(self.model.index(i), TableVariable)\n             for i in range(self.model.rowCount())],\n            [self.cont, None, None, self.disc, self.string, self.time])\n\n    def test_other_roles(self):\n        with patch.object(PyListModel, \"data\") as data:\n            index = self.model.index(0)\n            _ = self.model.data(index, Qt.BackgroundRole)\n            self.assertEqual(data.call_args[0][1:], (index, Qt.BackgroundRole))\n\n    def test_invalid_index(self):\n        self.assertIsNone(self.model.data(self.model.index(0).parent()))\n\n\nclass TestDomainModel(unittest.TestCase):\n    def test_init_with_single_section(self):\n        model = DomainModel(order=DomainModel.CLASSES)\n        self.assertEqual(model.order, (DomainModel.CLASSES, ))\n\n    def test_separators(self):\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        model = DomainModel()\n        sep = [model.Separator]\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), classes + sep + metas + sep + attrs)\n\n        model = DomainModel()\n        model.set_domain(Domain(attrs, [], metas))\n        self.assertEqual(list(model), metas + sep + attrs)\n\n        model = DomainModel()\n        model.set_domain(Domain([], [], metas))\n        self.assertEqual(list(model), metas)\n\n        model = DomainModel(placeholder=\"foo\")\n        model.set_domain(Domain([], [], metas))\n        self.assertEqual(list(model), [None] + sep + metas)\n\n        model = DomainModel(placeholder=\"foo\")\n        model.set_domain(Domain(attrs, [], metas))\n        self.assertEqual(list(model), [None] + sep + metas + sep + attrs)\n\n    def test_placeholder_placement(self):\n        model = DomainModel(placeholder=\"foo\")\n        sep = model.Separator\n        self.assertEqual(model.order, (None, sep) + model.SEPARATED)\n\n        model = DomainModel(order=(\"bar\", ), placeholder=\"foo\")\n        self.assertEqual(model.order, (None, \"bar\"))\n\n        model = DomainModel(order=(\"bar\", None, \"baz\"), placeholder=\"foo\")\n        self.assertEqual(model.order, (\"bar\", None, \"baz\"))\n\n        model = DomainModel(order=(\"bar\", sep, \"baz\"),\n                            placeholder=\"foo\")\n        self.assertEqual(model.order, (None, sep, \"bar\", sep, \"baz\"))\n\n    def test_subparts(self):\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        m = DomainModel\n        sep = m.Separator\n        model = DomainModel(\n            order=(m.ATTRIBUTES | m.METAS, sep, m.CLASSES))\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), attrs + metas + [sep] + classes)\n\n        m = DomainModel\n        sep = m.Separator\n        model = DomainModel(\n            order=(m.ATTRIBUTES | m.METAS, sep, m.CLASSES),\n            alphabetical=True)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model),\n                         sorted(attrs + metas, key=lambda x: x.name) +\n                         [sep] +\n                         sorted(classes, key=lambda x: x.name))\n\n    def test_filtering(self):\n        cont = [ContinuousVariable(n) for n in \"abc\"]\n        disc = [DiscreteVariable(n) for n in \"def\"]\n        attrs = cont + disc\n\n        model = DomainModel(valid_types=(ContinuousVariable, ))\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), cont)\n\n        model = DomainModel(valid_types=(DiscreteVariable, ))\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc)\n\n        disc[0].attributes[\"hidden\"] = True\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc[1:])\n\n        model = DomainModel(valid_types=(DiscreteVariable, ),\n                            skip_hidden_vars=False)\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc)\n\n    def test_no_separators(self):\n        \"\"\"\n        GH-2697\n        \"\"\"\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        model = DomainModel(order=DomainModel.SEPARATED, separators=False)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), classes + metas + attrs)\n\n        model = DomainModel(order=DomainModel.SEPARATED, separators=True)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(\n            list(model),\n            classes + [PyListModel.Separator] + metas + [PyListModel.Separator] + attrs)\n\n    def test_read_only(self):\n        model = DomainModel()\n        domain = Domain([ContinuousVariable(x) for x in \"abc\"])\n        model.set_domain(domain)\n        index = model.index(0, 0)\n\n        self.assertRaises(TypeError, model.append, 42)\n        self.assertRaises(TypeError, model.extend, [42])\n        self.assertRaises(TypeError, model.insert, 0, 42)\n        self.assertRaises(TypeError, model.remove, 0)\n        self.assertRaises(TypeError, model.pop)\n        self.assertRaises(TypeError, model.clear)\n        self.assertRaises(TypeError, model.reverse)\n        self.assertRaises(TypeError, model.sort)\n        with self.assertRaises(TypeError):\n            model[0] = 1\n        with self.assertRaises(TypeError):\n            del model[0]\n\n        self.assertFalse(model.setData(index, domain[0], Qt.EditRole))\n        self.assertTrue(model.setData(index, \"foo\", Qt.ToolTipRole))\n\n        self.assertFalse(model.setItemData(index, {Qt.EditRole: domain[0],\n                                                   Qt.ToolTipRole: \"foo\"}))\n        self.assertTrue(model.setItemData(index, {Qt.ToolTipRole: \"foo\"}))\n\n        self.assertFalse(model.insertRows(0, 1))\n        self.assertSequenceEqual(model, domain)\n        self.assertFalse(model.removeRows(0, 1))\n        self.assertSequenceEqual(model, domain)\n\n\nclass TestContinuousPalettesModel(GuiTest):\n    def setUp(self):\n        self.palette1, self.palette2 = \\\n            list(colorpalettes.ContinuousPalettes.values())[:2]\n\n    def test_all_categories(self):\n        model = ContinuousPalettesModel()\n        shown = {palette.name for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()}\n        self.assertEqual(expected, shown)\n\n        shown = {name for name in model.items if isinstance(name, str)}\n        expected = {palette.category\n                    for palette in colorpalettes.ContinuousPalettes.values()}\n        self.assertEqual(expected, shown)\n\n    def test_category_selection(self):\n        categories = ('Diverging', 'Linear')\n        model = ContinuousPalettesModel(categories=categories)\n        shown = {palette.name\n                 for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()\n                    if palette.category in categories}\n        self.assertEqual(expected, shown)\n        self.assertIn(\"Diverging\", model.items)\n        self.assertIn(\"Linear\", model.items)\n\n    def test_single_category(self):\n        category = 'Diverging'\n        model = ContinuousPalettesModel(categories=(category, ))\n        shown = {palette.name\n                 for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()\n                    if palette.category == category}\n        self.assertEqual(expected, shown)\n        self.assertEqual(len(model.items), len(shown))\n\n    def test_count(self):\n        model = ContinuousPalettesModel()\n        model.items = [self.palette1, self.palette1]\n        self.assertEqual(model.rowCount(QModelIndex()), 2)\n        self.assertEqual(model.columnCount(QModelIndex()), 1)\n\n    def test_data(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        data = model.data\n        index = model.index\n\n        self.assertEqual(data(index(0, 0), Qt.EditRole), \"Palettes\")\n        self.assertEqual(data(index(1, 0), Qt.EditRole),\n                         self.palette1.friendly_name)\n        self.assertEqual(data(index(2, 0), Qt.EditRole),\n                         self.palette2.friendly_name)\n\n        self.assertEqual(data(index(0, 0), Qt.DisplayRole), \"Palettes\")\n        self.assertEqual(data(index(1, 0), Qt.DisplayRole),\n                         self.palette1.friendly_name)\n        self.assertEqual(data(index(2, 0), Qt.DisplayRole),\n                         self.palette2.friendly_name)\n\n        self.assertIsNone(data(index(0, 0), Qt.DecorationRole))\n        with patch.object(self.palette1, \"color_strip\") as color_strip:\n            self.assertIs(data(index(1, 0), Qt.DecorationRole),\n                          color_strip.return_value)\n        with patch.object(self.palette2, \"color_strip\") as color_strip:\n            self.assertIs(data(index(2, 0), Qt.DecorationRole),\n                          color_strip.return_value)\n\n        self.assertIsNone(data(index(0, 0), Qt.UserRole))\n        self.assertIs(data(index(1, 0), Qt.UserRole), self.palette1)\n        self.assertIs(data(index(2, 0), Qt.UserRole), self.palette2)\n\n        self.assertIsNone(data(index(2, 0), Qt.FontRole))\n\n    def test_select_flags(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        self.assertFalse(model.flags(model.index(0, 0)) & Qt.ItemIsSelectable)\n        self.assertTrue(model.flags(model.index(1, 0)) & Qt.ItemIsSelectable)\n        self.assertTrue(model.flags(model.index(2, 0)) & Qt.ItemIsSelectable)\n\n    def testIndexOf(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        self.assertEqual(model.indexOf(self.palette1), 1)\n        self.assertEqual(model.indexOf(self.palette1.name), 1)\n        self.assertEqual(model.indexOf(self.palette1.friendly_name), 1)\n        self.assertEqual(model.indexOf(self.palette2), 2)\n        self.assertEqual(model.indexOf(self.palette2.name), 2)\n        self.assertEqual(model.indexOf(self.palette2.friendly_name), 2)\n        self.assertIsNone(model.indexOf(42))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "new_file_content": "# Test methods with long descriptive names can omit docstrings\n# pylint: disable=missing-docstring\n\nimport unittest\nfrom unittest.mock import patch\n\nimport numpy as np\n\nfrom AnyQt.QtCore import Qt, QModelIndex\nfrom AnyQt.QtTest import QSignalSpy\n\nfrom Orange.data import \\\n    Domain, \\\n    ContinuousVariable, DiscreteVariable, StringVariable, TimeVariable\nfrom Orange.widgets.utils import colorpalettes\nfrom Orange.widgets.utils.itemmodels import \\\n    AbstractSortTableModel, PyTableModel,\\\n    PyListModel, VariableListModel, DomainModel, ContinuousPalettesModel, \\\n    _as_contiguous_range\nfrom Orange.widgets.gui import TableVariable\nfrom orangewidget.tests.base import GuiTest\n\n\nclass TestUtils(unittest.TestCase):\n    def test_as_contiguous_range(self):\n        self.assertEqual(_as_contiguous_range(slice(1, 8), 20), (1, 8, 1))\n        self.assertEqual(_as_contiguous_range(slice(1, 8), 6), (1, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8, 1, -1), 6), (2, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8), 6), (0, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8, None, -1), 6), (0, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(7, None, -1), 9), (0, 8, 1))\n        self.assertEqual(_as_contiguous_range(slice(None, None, -1), 9),\n                         (0, 9, 1))\n\n\nclass TestPyTableModel(unittest.TestCase):\n    def setUp(self):\n        self.model = PyTableModel([[1, 4],\n                                   [2, 3]])\n\n    def test_init(self):\n        self.model = PyTableModel()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_rowCount(self):\n        self.assertEqual(self.model.rowCount(), 2)\n        self.assertEqual(len(self.model), 2)\n\n    def test_columnCount(self):\n        self.assertEqual(self.model.columnCount(), 2)\n\n    def test_data(self):\n        mi = self.model.index(0, 0)\n        self.assertEqual(self.model.data(mi), '1')\n        self.assertEqual(self.model.data(mi, Qt.EditRole), 1)\n\n    def test_editable(self):\n        editable_model = PyTableModel([[0]], editable=True)\n        self.assertFalse(int(self.model.flags(self.model.index(0, 0)) & Qt.ItemIsEditable))\n        self.assertTrue(int(editable_model.flags(editable_model.index(0, 0)) & Qt.ItemIsEditable))\n\n    def test_sort(self):\n        self.model.sort(1)\n        self.assertEqual(self.model.index(0, 0).data(Qt.EditRole), 2)\n\n    def test_setHeaderLabels(self):\n        self.model.setHorizontalHeaderLabels(['Col 1', 'Col 2'])\n        self.assertEqual(self.model.headerData(1, Qt.Horizontal), 'Col 2')\n        self.assertEqual(self.model.headerData(1, Qt.Vertical), 2)\n\n    def test_removeRows(self):\n        self.model.removeRows(0, 1)\n        self.assertEqual(len(self.model), 1)\n        self.assertEqual(self.model[0][1], 3)\n\n    def test_removeColumns(self):\n        self.model.removeColumns(0, 1)\n        self.assertEqual(self.model.columnCount(), 1)\n        self.assertEqual(self.model[1][0], 3)\n\n    def test_insertRows(self):\n        self.model.insertRows(0, 1)\n        self.assertEqual(self.model[1][0], 1)\n\n    def test_insertColumns(self):\n        self.model.insertColumns(0, 1)\n        self.assertEqual(self.model[0], ['', 1, 4])\n\n    def test_wrap(self):\n        self.model.wrap([[0]])\n        self.assertEqual(self.model.rowCount(), 1)\n        self.assertEqual(self.model.columnCount(), 1)\n\n    def test_clear(self):\n        self.model.clear()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_append(self):\n        self.model.append([5, 6])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_extend(self):\n        self.model.extend([[5, 6]])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_insert(self):\n        self.model.insert(0, [5, 6])\n        self.assertEqual(self.model[0][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_remove(self):\n        self.model.remove([2, 3])\n        self.assertEqual(self.model.rowCount(), 1)\n\n    def test_other_roles(self):\n        self.model.append([2, 3])\n        self.model.setData(self.model.index(2, 0),\n                           Qt.AlignCenter,\n                           Qt.TextAlignmentRole)\n        del self.model[1]\n        self.assertTrue(Qt.AlignCenter &\n                        self.model.data(self.model.index(1, 0),\n                                        Qt.TextAlignmentRole))\n\n    def test_set_iten_slice(self):\n        self.model[:1] = [[10, 11], [12, 13], [14, 15]]\n        self.assertEqual(list(self.model), [[10, 11], [12, 13], [14, 15], [2, 3]])\n\n        self.model[1:3] = []\n        self.assertEqual(list(self.model), [[10, 11], [2, 3]])\n\n        self.model[:] = [[20, 21]]\n        self.assertEqual(list(self.model), [[20, 21]])\n\n        self.model[1:] = [[10, 11], [2, 3]]\n        self.assertEqual(list(self.model), [[20, 21], [10, 11], [2, 3]])\n\n    def test_emits_column_changes_on_row_insert(self):\n        inserted = []\n        removed = []\n        model = PyTableModel()\n        model.columnsInserted.connect(inserted.append)\n        model.columnsRemoved.connect(removed.append)\n        inserted = QSignalSpy(model.columnsInserted)\n        removed = QSignalSpy(model.columnsRemoved)\n        model.append([2])\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n        model.append([2, 3])\n        self.assertEqual(list(inserted)[-1][1:], [1, 1])\n        del model[:]\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model.extend([[0, 1], [0, 2]])\n        self.assertEqual(list(inserted)[-1][1:], [0, 1])\n        model.clear()\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model[:] = [[1], [2]]\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n\n\nclass TestVariableListModel(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.disc = DiscreteVariable(\"gender\", values=(\"M\", \"F\"))\n        cls.cont = ContinuousVariable(\"age\")\n        cls.string = StringVariable(\"name\")\n        cls.time = TimeVariable(\"birth\")\n        cls.model = VariableListModel([\n            cls.cont, None, \"Foo\", cls.disc, cls.string, cls.time])\n\n    def test_placeholder(self):\n        model = self.model\n        self.assertEqual(model.data(model.index(1)), \"None\")\n        model.placeholder = \"Bar\"\n        self.assertEqual(model.data(model.index(1)), \"Bar\")\n        model.placeholder = \"None\"\n\n    def test_displayrole(self):\n        data, index = self.model.data, self.model.index\n        self.assertEqual(data(index(0)), \"age\")\n        self.assertEqual(data(index(1)), \"None\")\n        self.assertEqual(data(index(2)), \"Foo\")\n        self.assertEqual(data(index(3)), \"gender\")\n        self.assertEqual(data(index(4)), \"name\")\n        self.assertEqual(data(index(5)), \"birth\")\n\n    def test_tooltip(self):\n        def get_tooltip(i):\n            return self.model.data(self.model.index(i), Qt.ToolTipRole)\n\n        text = get_tooltip(0)\n        self.assertIn(\"age\", text)\n        self.assertIn(\"Numeric\", text)\n\n        self.assertIsNone(get_tooltip(1))\n        self.assertIsNone(get_tooltip(2))\n\n        text = get_tooltip(3)\n        self.assertIn(\"gender\", text)\n        self.assertIn(\"M\", text)\n        self.assertIn(\"F\", text)\n        self.assertIn(\"2\", text)\n        self.assertIn(\"Categorical\", text)\n\n        text = get_tooltip(4)\n        self.assertIn(\"name\", text)\n        self.assertIn(\"Text\", text)\n\n        text = get_tooltip(5)\n        self.assertIn(\"birth\", text)\n        self.assertIn(\"Time\", text)\n\n        self.cont.attributes = {\"foo\": \"bar\"}\n        text = get_tooltip(0)\n        self.assertIn(\"foo\", text)\n        self.assertIn(\"bar\", text)\n\n    def test_table_variable(self):\n        self.assertEqual(\n            [self.model.data(self.model.index(i), TableVariable)\n             for i in range(self.model.rowCount())],\n            [self.cont, None, None, self.disc, self.string, self.time])\n\n    def test_other_roles(self):\n        with patch.object(PyListModel, \"data\") as data:\n            index = self.model.index(0)\n            _ = self.model.data(index, Qt.BackgroundRole)\n            self.assertEqual(data.call_args[0][1:], (index, Qt.BackgroundRole))\n\n    def test_invalid_index(self):\n        self.assertIsNone(self.model.data(self.model.index(0).parent()))\n\n\nclass TestDomainModel(unittest.TestCase):\n    def test_init_with_single_section(self):\n        model = DomainModel(order=DomainModel.CLASSES)\n        self.assertEqual(model.order, (DomainModel.CLASSES, ))\n\n    def test_separators(self):\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        model = DomainModel()\n        sep = [model.Separator]\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), classes + sep + metas + sep + attrs)\n\n        model = DomainModel()\n        model.set_domain(Domain(attrs, [], metas))\n        self.assertEqual(list(model), metas + sep + attrs)\n\n        model = DomainModel()\n        model.set_domain(Domain([], [], metas))\n        self.assertEqual(list(model), metas)\n\n        model = DomainModel(placeholder=\"foo\")\n        model.set_domain(Domain([], [], metas))\n        self.assertEqual(list(model), [None] + sep + metas)\n\n        model = DomainModel(placeholder=\"foo\")\n        model.set_domain(Domain(attrs, [], metas))\n        self.assertEqual(list(model), [None] + sep + metas + sep + attrs)\n\n    def test_placeholder_placement(self):\n        model = DomainModel(placeholder=\"foo\")\n        sep = model.Separator\n        self.assertEqual(model.order, (None, sep) + model.SEPARATED)\n\n        model = DomainModel(order=(\"bar\", ), placeholder=\"foo\")\n        self.assertEqual(model.order, (None, \"bar\"))\n\n        model = DomainModel(order=(\"bar\", None, \"baz\"), placeholder=\"foo\")\n        self.assertEqual(model.order, (\"bar\", None, \"baz\"))\n\n        model = DomainModel(order=(\"bar\", sep, \"baz\"),\n                            placeholder=\"foo\")\n        self.assertEqual(model.order, (None, sep, \"bar\", sep, \"baz\"))\n\n    def test_subparts(self):\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        m = DomainModel\n        sep = m.Separator\n        model = DomainModel(\n            order=(m.ATTRIBUTES | m.METAS, sep, m.CLASSES))\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), attrs + metas + [sep] + classes)\n\n        m = DomainModel\n        sep = m.Separator\n        model = DomainModel(\n            order=(m.ATTRIBUTES | m.METAS, sep, m.CLASSES),\n            alphabetical=True)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model),\n                         sorted(attrs + metas, key=lambda x: x.name) +\n                         [sep] +\n                         sorted(classes, key=lambda x: x.name))\n\n    def test_filtering(self):\n        cont = [ContinuousVariable(n) for n in \"abc\"]\n        disc = [DiscreteVariable(n) for n in \"def\"]\n        attrs = cont + disc\n\n        model = DomainModel(valid_types=(ContinuousVariable, ))\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), cont)\n\n        model = DomainModel(valid_types=(DiscreteVariable, ))\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc)\n\n        disc[0].attributes[\"hidden\"] = True\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc[1:])\n\n        model = DomainModel(valid_types=(DiscreteVariable, ),\n                            skip_hidden_vars=False)\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc)\n\n    def test_no_separators(self):\n        \"\"\"\n        GH-2697\n        \"\"\"\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        model = DomainModel(order=DomainModel.SEPARATED, separators=False)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), classes + metas + attrs)\n\n        model = DomainModel(order=DomainModel.SEPARATED, separators=True)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(\n            list(model),\n            classes + [PyListModel.Separator] + metas + [PyListModel.Separator] + attrs)\n\n    def test_read_only(self):\n        model = DomainModel()\n        domain = Domain([ContinuousVariable(x) for x in \"abc\"])\n        model.set_domain(domain)\n        index = model.index(0, 0)\n\n        self.assertRaises(TypeError, model.append, 42)\n        self.assertRaises(TypeError, model.extend, [42])\n        self.assertRaises(TypeError, model.insert, 0, 42)\n        self.assertRaises(TypeError, model.remove, 0)\n        self.assertRaises(TypeError, model.pop)\n        self.assertRaises(TypeError, model.clear)\n        self.assertRaises(TypeError, model.reverse)\n        self.assertRaises(TypeError, model.sort)\n        with self.assertRaises(TypeError):\n            model[0] = 1\n        with self.assertRaises(TypeError):\n            del model[0]\n\n        self.assertFalse(model.setData(index, domain[0], Qt.EditRole))\n        self.assertTrue(model.setData(index, \"foo\", Qt.ToolTipRole))\n\n        self.assertFalse(model.setItemData(index, {Qt.EditRole: domain[0],\n                                                   Qt.ToolTipRole: \"foo\"}))\n        self.assertTrue(model.setItemData(index, {Qt.ToolTipRole: \"foo\"}))\n\n        self.assertFalse(model.insertRows(0, 1))\n        self.assertSequenceEqual(model, domain)\n        self.assertFalse(model.removeRows(0, 1))\n        self.assertSequenceEqual(model, domain)\n\n\nclass TestContinuousPalettesModel(GuiTest):\n    def setUp(self):\n        self.palette1, self.palette2 = \\\n            list(colorpalettes.ContinuousPalettes.values())[:2]\n\n    def test_all_categories(self):\n        model = ContinuousPalettesModel()\n        shown = {palette.name for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()}\n        self.assertEqual(expected, shown)\n\n        shown = {name for name in model.items if isinstance(name, str)}\n        expected = {palette.category\n                    for palette in colorpalettes.ContinuousPalettes.values()}\n        self.assertEqual(expected, shown)\n\n    def test_category_selection(self):\n        categories = ('Diverging', 'Linear')\n        model = ContinuousPalettesModel(categories=categories)\n        shown = {palette.name\n                 for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()\n                    if palette.category in categories}\n        self.assertEqual(expected, shown)\n        self.assertIn(\"Diverging\", model.items)\n        self.assertIn(\"Linear\", model.items)\n\n    def test_single_category(self):\n        category = 'Diverging'\n        model = ContinuousPalettesModel(categories=(category, ))\n        shown = {palette.name\n                 for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()\n                    if palette.category == category}\n        self.assertEqual(expected, shown)\n        self.assertEqual(len(model.items), len(shown))\n\n    def test_count(self):\n        model = ContinuousPalettesModel()\n        model.items = [self.palette1, self.palette1]\n        self.assertEqual(model.rowCount(QModelIndex()), 2)\n        self.assertEqual(model.columnCount(QModelIndex()), 1)\n\n    def test_data(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        data = model.data\n        index = model.index\n\n        self.assertEqual(data(index(0, 0), Qt.EditRole), \"Palettes\")\n        self.assertEqual(data(index(1, 0), Qt.EditRole),\n                         self.palette1.friendly_name)\n        self.assertEqual(data(index(2, 0), Qt.EditRole),\n                         self.palette2.friendly_name)\n\n        self.assertEqual(data(index(0, 0), Qt.DisplayRole), \"Palettes\")\n        self.assertEqual(data(index(1, 0), Qt.DisplayRole),\n                         self.palette1.friendly_name)\n        self.assertEqual(data(index(2, 0), Qt.DisplayRole),\n                         self.palette2.friendly_name)\n\n        self.assertIsNone(data(index(0, 0), Qt.DecorationRole))\n        with patch.object(self.palette1, \"color_strip\") as color_strip:\n            self.assertIs(data(index(1, 0), Qt.DecorationRole),\n                          color_strip.return_value)\n        with patch.object(self.palette2, \"color_strip\") as color_strip:\n            self.assertIs(data(index(2, 0), Qt.DecorationRole),\n                          color_strip.return_value)\n\n        self.assertIsNone(data(index(0, 0), Qt.UserRole))\n        self.assertIs(data(index(1, 0), Qt.UserRole), self.palette1)\n        self.assertIs(data(index(2, 0), Qt.UserRole), self.palette2)\n\n        self.assertIsNone(data(index(2, 0), Qt.FontRole))\n\n    def test_select_flags(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        self.assertFalse(model.flags(model.index(0, 0)) & Qt.ItemIsSelectable)\n        self.assertTrue(model.flags(model.index(1, 0)) & Qt.ItemIsSelectable)\n        self.assertTrue(model.flags(model.index(2, 0)) & Qt.ItemIsSelectable)\n\n    def testIndexOf(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        self.assertEqual(model.indexOf(self.palette1), 1)\n        self.assertEqual(model.indexOf(self.palette1.name), 1)\n        self.assertEqual(model.indexOf(self.palette1.friendly_name), 1)\n        self.assertEqual(model.indexOf(self.palette2), 2)\n        self.assertEqual(model.indexOf(self.palette2.name), 2)\n        self.assertEqual(model.indexOf(self.palette2.friendly_name), 2)\n        self.assertIsNone(model.indexOf(42))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/utils/tests/test_itemmodels.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "15f6372ce",
                "new_commit_hash": "b716fe402",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/utils/tests/test_itemmodels.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/utils/tests/test_itemmodels.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 124,
                            "length": 6
                        },
                        "new_range": {
                            "start": 124,
                            "length": 19
                        },
                        "section": "class TestPyTableModel(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                        self.model.data(self.model.index(1, 0),",
                                "type": "context"
                            },
                            {
                                "content": "                                        Qt.TextAlignmentRole))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_set_iten_slice(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.model[:1] = [[10, 11], [12, 13], [14, 15]]",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(list(self.model), [[10, 11], [12, 13], [14, 15], [2, 3]])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        self.model[1:3] = []",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(list(self.model), [[10, 11], [2, 3]])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        self.model[:] = [[20, 21]]",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(list(self.model), [[20, 21]])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        self.model[1:] = [[10, 11], [2, 3]]",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(list(self.model), [[20, 21], [10, 11], [2, 3]])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_emits_column_changes_on_row_insert(self):",
                                "type": "context"
                            },
                            {
                                "content": "        inserted = []",
                                "type": "context"
                            },
                            {
                                "content": "        removed = []",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/utils/tests/test_itemmodels.py",
                            "type": "class",
                            "name": "TestPyTableModel",
                            "content": "class TestPyTableModel(unittest.TestCase):\n    def setUp(self):\n        self.model = PyTableModel([[1, 4],\n                                   [2, 3]])\n\n    def test_init(self):\n        self.model = PyTableModel()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_rowCount(self):\n        self.assertEqual(self.model.rowCount(), 2)\n        self.assertEqual(len(self.model), 2)\n\n    def test_columnCount(self):\n        self.assertEqual(self.model.columnCount(), 2)\n\n    def test_data(self):\n        mi = self.model.index(0, 0)\n        self.assertEqual(self.model.data(mi), '1')\n        self.assertEqual(self.model.data(mi, Qt.EditRole), 1)\n\n    def test_editable(self):\n        editable_model = PyTableModel([[0]], editable=True)\n        self.assertFalse(int(self.model.flags(self.model.index(0, 0)) & Qt.ItemIsEditable))\n        self.assertTrue(int(editable_model.flags(editable_model.index(0, 0)) & Qt.ItemIsEditable))\n\n    def test_sort(self):\n        self.model.sort(1)\n        self.assertEqual(self.model.index(0, 0).data(Qt.EditRole), 2)\n\n    def test_setHeaderLabels(self):\n        self.model.setHorizontalHeaderLabels(['Col 1', 'Col 2'])\n        self.assertEqual(self.model.headerData(1, Qt.Horizontal), 'Col 2')\n        self.assertEqual(self.model.headerData(1, Qt.Vertical), 2)\n\n    def test_removeRows(self):\n        self.model.removeRows(0, 1)\n        self.assertEqual(len(self.model), 1)\n        self.assertEqual(self.model[0][1], 3)\n\n    def test_removeColumns(self):\n        self.model.removeColumns(0, 1)\n        self.assertEqual(self.model.columnCount(), 1)\n        self.assertEqual(self.model[1][0], 3)\n\n    def test_insertRows(self):\n        self.model.insertRows(0, 1)\n        self.assertEqual(self.model[1][0], 1)\n\n    def test_insertColumns(self):\n        self.model.insertColumns(0, 1)\n        self.assertEqual(self.model[0], ['', 1, 4])\n\n    def test_wrap(self):\n        self.model.wrap([[0]])\n        self.assertEqual(self.model.rowCount(), 1)\n        self.assertEqual(self.model.columnCount(), 1)\n\n    def test_clear(self):\n        self.model.clear()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_append(self):\n        self.model.append([5, 6])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_extend(self):\n        self.model.extend([[5, 6]])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_insert(self):\n        self.model.insert(0, [5, 6])\n        self.assertEqual(self.model[0][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_remove(self):\n        self.model.remove([2, 3])\n        self.assertEqual(self.model.rowCount(), 1)\n\n    def test_other_roles(self):\n        self.model.append([2, 3])\n        self.model.setData(self.model.index(2, 0),\n                           Qt.AlignCenter,\n                           Qt.TextAlignmentRole)\n        del self.model[1]\n        self.assertTrue(Qt.AlignCenter &\n                        self.model.data(self.model.index(1, 0),\n                                        Qt.TextAlignmentRole))\n\n    def test_set_iten_slice(self):\n        self.model[:1] = [[10, 11], [12, 13], [14, 15]]\n        self.assertEqual(list(self.model), [[10, 11], [12, 13], [14, 15], [2, 3]])\n\n        self.model[1:3] = []\n        self.assertEqual(list(self.model), [[10, 11], [2, 3]])\n\n        self.model[:] = [[20, 21]]\n        self.assertEqual(list(self.model), [[20, 21]])\n\n        self.model[1:] = [[10, 11], [2, 3]]\n        self.assertEqual(list(self.model), [[20, 21], [10, 11], [2, 3]])\n\n    def test_emits_column_changes_on_row_insert(self):\n        inserted = []\n        removed = []\n        model = PyTableModel()\n        model.columnsInserted.connect(inserted.append)\n        model.columnsRemoved.connect(removed.append)\n        inserted = QSignalSpy(model.columnsInserted)\n        removed = QSignalSpy(model.columnsRemoved)\n        model.append([2])\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n        model.append([2, 3])\n        self.assertEqual(list(inserted)[-1][1:], [1, 1])\n        del model[:]\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model.extend([[0, 1], [0, 2]])\n        self.assertEqual(list(inserted)[-1][1:], [0, 1])\n        model.clear()\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model[:] = [[1], [2]]\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 36,
                            "end_lineno": 159,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/utils/tests/test_itemmodels.py",
                            "type": "method",
                            "name": "TestPyTableModel.test_set_iten_slice",
                            "content": "class TestPyTableModel(unittest.TestCase):\n    def setUp(self):\n        self.model = PyTableModel([[1, 4],\n                                   [2, 3]])\n\n    def test_init(self):\n        self.model = PyTableModel()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_rowCount(self):\n        self.assertEqual(self.model.rowCount(), 2)\n        self.assertEqual(len(self.model), 2)\n\n    def test_columnCount(self):\n        self.assertEqual(self.model.columnCount(), 2)\n\n    def test_data(self):\n        mi = self.model.index(0, 0)\n        self.assertEqual(self.model.data(mi), '1')\n        self.assertEqual(self.model.data(mi, Qt.EditRole), 1)\n\n    def test_editable(self):\n        editable_model = PyTableModel([[0]], editable=True)\n        self.assertFalse(int(self.model.flags(self.model.index(0, 0)) & Qt.ItemIsEditable))\n        self.assertTrue(int(editable_model.flags(editable_model.index(0, 0)) & Qt.ItemIsEditable))\n\n    def test_sort(self):\n        self.model.sort(1)\n        self.assertEqual(self.model.index(0, 0).data(Qt.EditRole), 2)\n\n    def test_setHeaderLabels(self):\n        self.model.setHorizontalHeaderLabels(['Col 1', 'Col 2'])\n        self.assertEqual(self.model.headerData(1, Qt.Horizontal), 'Col 2')\n        self.assertEqual(self.model.headerData(1, Qt.Vertical), 2)\n\n    def test_removeRows(self):\n        self.model.removeRows(0, 1)\n        self.assertEqual(len(self.model), 1)\n        self.assertEqual(self.model[0][1], 3)\n\n    def test_removeColumns(self):\n        self.model.removeColumns(0, 1)\n        self.assertEqual(self.model.columnCount(), 1)\n        self.assertEqual(self.model[1][0], 3)\n\n    def test_insertRows(self):\n        self.model.insertRows(0, 1)\n        self.assertEqual(self.model[1][0], 1)\n\n    def test_insertColumns(self):\n        self.model.insertColumns(0, 1)\n        self.assertEqual(self.model[0], ['', 1, 4])\n\n    def test_wrap(self):\n        self.model.wrap([[0]])\n        self.assertEqual(self.model.rowCount(), 1)\n        self.assertEqual(self.model.columnCount(), 1)\n\n    def test_clear(self):\n        self.model.clear()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_append(self):\n        self.model.append([5, 6])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_extend(self):\n        self.model.extend([[5, 6]])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_insert(self):\n        self.model.insert(0, [5, 6])\n        self.assertEqual(self.model[0][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_remove(self):\n        self.model.remove([2, 3])\n        self.assertEqual(self.model.rowCount(), 1)\n\n    def test_other_roles(self):\n        self.model.append([2, 3])\n        self.model.setData(self.model.index(2, 0),\n                           Qt.AlignCenter,\n                           Qt.TextAlignmentRole)\n        del self.model[1]\n        self.assertTrue(Qt.AlignCenter &\n                        self.model.data(self.model.index(1, 0),\n                                        Qt.TextAlignmentRole))\n\n    def test_set_iten_slice(self):\n        self.model[:1] = [[10, 11], [12, 13], [14, 15]]\n        self.assertEqual(list(self.model), [[10, 11], [12, 13], [14, 15], [2, 3]])\n\n        self.model[1:3] = []\n        self.assertEqual(list(self.model), [[10, 11], [2, 3]])\n\n        self.model[:] = [[20, 21]]\n        self.assertEqual(list(self.model), [[20, 21]])\n\n        self.model[1:] = [[10, 11], [2, 3]]\n        self.assertEqual(list(self.model), [[20, 21], [10, 11], [2, 3]])\n\n    def test_emits_column_changes_on_row_insert(self):\n        inserted = []\n        removed = []\n        model = PyTableModel()\n        model.columnsInserted.connect(inserted.append)\n        model.columnsRemoved.connect(removed.append)\n        inserted = QSignalSpy(model.columnsInserted)\n        removed = QSignalSpy(model.columnsRemoved)\n        model.append([2])\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n        model.append([2, 3])\n        self.assertEqual(list(inserted)[-1][1:], [1, 1])\n        del model[:]\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model.extend([[0, 1], [0, 2]])\n        self.assertEqual(list(inserted)[-1][1:], [0, 1])\n        model.clear()\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model[:] = [[1], [2]]\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 127,
                            "end_lineno": 138,
                            "parent": {
                                "file_name": "Orange/widgets/utils/tests/test_itemmodels.py",
                                "type": "class",
                                "name": "TestPyTableModel",
                                "content": "class TestPyTableModel(unittest.TestCase):\n    def setUp(self):\n        self.model = PyTableModel([[1, 4],\n                                   [2, 3]])\n\n    def test_init(self):\n        self.model = PyTableModel()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_rowCount(self):\n        self.assertEqual(self.model.rowCount(), 2)\n        self.assertEqual(len(self.model), 2)\n\n    def test_columnCount(self):\n        self.assertEqual(self.model.columnCount(), 2)\n\n    def test_data(self):\n        mi = self.model.index(0, 0)\n        self.assertEqual(self.model.data(mi), '1')\n        self.assertEqual(self.model.data(mi, Qt.EditRole), 1)\n\n    def test_editable(self):\n        editable_model = PyTableModel([[0]], editable=True)\n        self.assertFalse(int(self.model.flags(self.model.index(0, 0)) & Qt.ItemIsEditable))\n        self.assertTrue(int(editable_model.flags(editable_model.index(0, 0)) & Qt.ItemIsEditable))\n\n    def test_sort(self):\n        self.model.sort(1)\n        self.assertEqual(self.model.index(0, 0).data(Qt.EditRole), 2)\n\n    def test_setHeaderLabels(self):\n        self.model.setHorizontalHeaderLabels(['Col 1', 'Col 2'])\n        self.assertEqual(self.model.headerData(1, Qt.Horizontal), 'Col 2')\n        self.assertEqual(self.model.headerData(1, Qt.Vertical), 2)\n\n    def test_removeRows(self):\n        self.model.removeRows(0, 1)\n        self.assertEqual(len(self.model), 1)\n        self.assertEqual(self.model[0][1], 3)\n\n    def test_removeColumns(self):\n        self.model.removeColumns(0, 1)\n        self.assertEqual(self.model.columnCount(), 1)\n        self.assertEqual(self.model[1][0], 3)\n\n    def test_insertRows(self):\n        self.model.insertRows(0, 1)\n        self.assertEqual(self.model[1][0], 1)\n\n    def test_insertColumns(self):\n        self.model.insertColumns(0, 1)\n        self.assertEqual(self.model[0], ['', 1, 4])\n\n    def test_wrap(self):\n        self.model.wrap([[0]])\n        self.assertEqual(self.model.rowCount(), 1)\n        self.assertEqual(self.model.columnCount(), 1)\n\n    def test_clear(self):\n        self.model.clear()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_append(self):\n        self.model.append([5, 6])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_extend(self):\n        self.model.extend([[5, 6]])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_insert(self):\n        self.model.insert(0, [5, 6])\n        self.assertEqual(self.model[0][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_remove(self):\n        self.model.remove([2, 3])\n        self.assertEqual(self.model.rowCount(), 1)\n\n    def test_other_roles(self):\n        self.model.append([2, 3])\n        self.model.setData(self.model.index(2, 0),\n                           Qt.AlignCenter,\n                           Qt.TextAlignmentRole)\n        del self.model[1]\n        self.assertTrue(Qt.AlignCenter &\n                        self.model.data(self.model.index(1, 0),\n                                        Qt.TextAlignmentRole))\n\n    def test_set_iten_slice(self):\n        self.model[:1] = [[10, 11], [12, 13], [14, 15]]\n        self.assertEqual(list(self.model), [[10, 11], [12, 13], [14, 15], [2, 3]])\n\n        self.model[1:3] = []\n        self.assertEqual(list(self.model), [[10, 11], [2, 3]])\n\n        self.model[:] = [[20, 21]]\n        self.assertEqual(list(self.model), [[20, 21]])\n\n        self.model[1:] = [[10, 11], [2, 3]]\n        self.assertEqual(list(self.model), [[20, 21], [10, 11], [2, 3]])\n\n    def test_emits_column_changes_on_row_insert(self):\n        inserted = []\n        removed = []\n        model = PyTableModel()\n        model.columnsInserted.connect(inserted.append)\n        model.columnsRemoved.connect(removed.append)\n        inserted = QSignalSpy(model.columnsInserted)\n        removed = QSignalSpy(model.columnsRemoved)\n        model.append([2])\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n        model.append([2, 3])\n        self.assertEqual(list(inserted)[-1][1:], [1, 1])\n        del model[:]\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model.extend([[0, 1], [0, 2]])\n        self.assertEqual(list(inserted)[-1][1:], [0, 1])\n        model.clear()\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model[:] = [[1], [2]]\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 36,
                                "end_lineno": 159,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "221f981ef0324c3101b02e9bab6aef48201fdf5b^",
    "new_commit_hash": "221f981ef0324c3101b02e9bab6aef48201fdf5b",
    "commit_message": "PyTableModel: Tests and a small fix for __setitem__",
    "commit_date": "2020-03-27T22:24:39+01:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "221f981ef0324c3101b02e9bab6aef48201fdf5b",
    "test_file_codes": [
        "# Test methods with long descriptive names can omit docstrings\n# pylint: disable=missing-docstring\n\nimport unittest\nfrom unittest.mock import patch\n\nimport numpy as np\n\nfrom AnyQt.QtCore import Qt, QModelIndex\nfrom AnyQt.QtTest import QSignalSpy\n\nfrom Orange.data import \\\n    Domain, \\\n    ContinuousVariable, DiscreteVariable, StringVariable, TimeVariable\nfrom Orange.widgets.utils import colorpalettes\nfrom Orange.widgets.utils.itemmodels import \\\n    AbstractSortTableModel, PyTableModel,\\\n    PyListModel, VariableListModel, DomainModel, ContinuousPalettesModel, \\\n    _as_contiguous_range\nfrom Orange.widgets.gui import TableVariable\nfrom orangewidget.tests.base import GuiTest\n\n\nclass TestUtils(unittest.TestCase):\n    def test_as_contiguous_range(self):\n        self.assertEqual(_as_contiguous_range(slice(1, 8), 20), (1, 8, 1))\n        self.assertEqual(_as_contiguous_range(slice(1, 8), 6), (1, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8, 1, -1), 6), (2, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8), 6), (0, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(8, None, -1), 6), (0, 6, 1))\n        self.assertEqual(_as_contiguous_range(slice(7, None, -1), 9), (0, 8, 1))\n        self.assertEqual(_as_contiguous_range(slice(None, None, -1), 9),\n                         (0, 9, 1))\n\n\nclass TestPyTableModel(unittest.TestCase):\n    def setUp(self):\n        self.model = PyTableModel([[1, 4],\n                                   [2, 3]])\n\n    def test_init(self):\n        self.model = PyTableModel()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_rowCount(self):\n        self.assertEqual(self.model.rowCount(), 2)\n        self.assertEqual(len(self.model), 2)\n\n    def test_columnCount(self):\n        self.assertEqual(self.model.columnCount(), 2)\n\n    def test_data(self):\n        mi = self.model.index(0, 0)\n        self.assertEqual(self.model.data(mi), '1')\n        self.assertEqual(self.model.data(mi, Qt.EditRole), 1)\n\n    def test_editable(self):\n        editable_model = PyTableModel([[0]], editable=True)\n        self.assertFalse(int(self.model.flags(self.model.index(0, 0)) & Qt.ItemIsEditable))\n        self.assertTrue(int(editable_model.flags(editable_model.index(0, 0)) & Qt.ItemIsEditable))\n\n    def test_sort(self):\n        self.model.sort(1)\n        self.assertEqual(self.model.index(0, 0).data(Qt.EditRole), 2)\n\n    def test_setHeaderLabels(self):\n        self.model.setHorizontalHeaderLabels(['Col 1', 'Col 2'])\n        self.assertEqual(self.model.headerData(1, Qt.Horizontal), 'Col 2')\n        self.assertEqual(self.model.headerData(1, Qt.Vertical), 2)\n\n    def test_removeRows(self):\n        self.model.removeRows(0, 1)\n        self.assertEqual(len(self.model), 1)\n        self.assertEqual(self.model[0][1], 3)\n\n    def test_removeColumns(self):\n        self.model.removeColumns(0, 1)\n        self.assertEqual(self.model.columnCount(), 1)\n        self.assertEqual(self.model[1][0], 3)\n\n    def test_insertRows(self):\n        self.model.insertRows(0, 1)\n        self.assertEqual(self.model[1][0], 1)\n\n    def test_insertColumns(self):\n        self.model.insertColumns(0, 1)\n        self.assertEqual(self.model[0], ['', 1, 4])\n\n    def test_wrap(self):\n        self.model.wrap([[0]])\n        self.assertEqual(self.model.rowCount(), 1)\n        self.assertEqual(self.model.columnCount(), 1)\n\n    def test_clear(self):\n        self.model.clear()\n        self.assertEqual(self.model.rowCount(), 0)\n\n    def test_append(self):\n        self.model.append([5, 6])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_extend(self):\n        self.model.extend([[5, 6]])\n        self.assertEqual(self.model[2][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_insert(self):\n        self.model.insert(0, [5, 6])\n        self.assertEqual(self.model[0][1], 6)\n        self.assertEqual(self.model.rowCount(), 3)\n\n    def test_remove(self):\n        self.model.remove([2, 3])\n        self.assertEqual(self.model.rowCount(), 1)\n\n    def test_other_roles(self):\n        self.model.append([2, 3])\n        self.model.setData(self.model.index(2, 0),\n                           Qt.AlignCenter,\n                           Qt.TextAlignmentRole)\n        del self.model[1]\n        self.assertTrue(Qt.AlignCenter &\n                        self.model.data(self.model.index(1, 0),\n                                        Qt.TextAlignmentRole))\n\n    def test_set_iten_slice(self):\n        self.model[:1] = [[10, 11], [12, 13], [14, 15]]\n        self.assertEqual(list(self.model), [[10, 11], [12, 13], [14, 15], [2, 3]])\n\n        self.model[1:3] = []\n        self.assertEqual(list(self.model), [[10, 11], [2, 3]])\n\n        self.model[:] = [[20, 21]]\n        self.assertEqual(list(self.model), [[20, 21]])\n\n        self.model[1:] = [[10, 11], [2, 3]]\n        self.assertEqual(list(self.model), [[20, 21], [10, 11], [2, 3]])\n\n    def test_emits_column_changes_on_row_insert(self):\n        inserted = []\n        removed = []\n        model = PyTableModel()\n        model.columnsInserted.connect(inserted.append)\n        model.columnsRemoved.connect(removed.append)\n        inserted = QSignalSpy(model.columnsInserted)\n        removed = QSignalSpy(model.columnsRemoved)\n        model.append([2])\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n        model.append([2, 3])\n        self.assertEqual(list(inserted)[-1][1:], [1, 1])\n        del model[:]\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model.extend([[0, 1], [0, 2]])\n        self.assertEqual(list(inserted)[-1][1:], [0, 1])\n        model.clear()\n        self.assertEqual(list(removed)[0][1:], [0, 1])\n        model[:] = [[1], [2]]\n        self.assertEqual(list(inserted)[-1][1:], [0, 0])\n\n\nclass TestVariableListModel(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.disc = DiscreteVariable(\"gender\", values=(\"M\", \"F\"))\n        cls.cont = ContinuousVariable(\"age\")\n        cls.string = StringVariable(\"name\")\n        cls.time = TimeVariable(\"birth\")\n        cls.model = VariableListModel([\n            cls.cont, None, \"Foo\", cls.disc, cls.string, cls.time])\n\n    def test_placeholder(self):\n        model = self.model\n        self.assertEqual(model.data(model.index(1)), \"None\")\n        model.placeholder = \"Bar\"\n        self.assertEqual(model.data(model.index(1)), \"Bar\")\n        model.placeholder = \"None\"\n\n    def test_displayrole(self):\n        data, index = self.model.data, self.model.index\n        self.assertEqual(data(index(0)), \"age\")\n        self.assertEqual(data(index(1)), \"None\")\n        self.assertEqual(data(index(2)), \"Foo\")\n        self.assertEqual(data(index(3)), \"gender\")\n        self.assertEqual(data(index(4)), \"name\")\n        self.assertEqual(data(index(5)), \"birth\")\n\n    def test_tooltip(self):\n        def get_tooltip(i):\n            return self.model.data(self.model.index(i), Qt.ToolTipRole)\n\n        text = get_tooltip(0)\n        self.assertIn(\"age\", text)\n        self.assertIn(\"Numeric\", text)\n\n        self.assertIsNone(get_tooltip(1))\n        self.assertIsNone(get_tooltip(2))\n\n        text = get_tooltip(3)\n        self.assertIn(\"gender\", text)\n        self.assertIn(\"M\", text)\n        self.assertIn(\"F\", text)\n        self.assertIn(\"2\", text)\n        self.assertIn(\"Categorical\", text)\n\n        text = get_tooltip(4)\n        self.assertIn(\"name\", text)\n        self.assertIn(\"Text\", text)\n\n        text = get_tooltip(5)\n        self.assertIn(\"birth\", text)\n        self.assertIn(\"Time\", text)\n\n        self.cont.attributes = {\"foo\": \"bar\"}\n        text = get_tooltip(0)\n        self.assertIn(\"foo\", text)\n        self.assertIn(\"bar\", text)\n\n    def test_table_variable(self):\n        self.assertEqual(\n            [self.model.data(self.model.index(i), TableVariable)\n             for i in range(self.model.rowCount())],\n            [self.cont, None, None, self.disc, self.string, self.time])\n\n    def test_other_roles(self):\n        with patch.object(PyListModel, \"data\") as data:\n            index = self.model.index(0)\n            _ = self.model.data(index, Qt.BackgroundRole)\n            self.assertEqual(data.call_args[0][1:], (index, Qt.BackgroundRole))\n\n    def test_invalid_index(self):\n        self.assertIsNone(self.model.data(self.model.index(0).parent()))\n\n\nclass TestDomainModel(unittest.TestCase):\n    def test_init_with_single_section(self):\n        model = DomainModel(order=DomainModel.CLASSES)\n        self.assertEqual(model.order, (DomainModel.CLASSES, ))\n\n    def test_separators(self):\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        model = DomainModel()\n        sep = [model.Separator]\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), classes + sep + metas + sep + attrs)\n\n        model = DomainModel()\n        model.set_domain(Domain(attrs, [], metas))\n        self.assertEqual(list(model), metas + sep + attrs)\n\n        model = DomainModel()\n        model.set_domain(Domain([], [], metas))\n        self.assertEqual(list(model), metas)\n\n        model = DomainModel(placeholder=\"foo\")\n        model.set_domain(Domain([], [], metas))\n        self.assertEqual(list(model), [None] + sep + metas)\n\n        model = DomainModel(placeholder=\"foo\")\n        model.set_domain(Domain(attrs, [], metas))\n        self.assertEqual(list(model), [None] + sep + metas + sep + attrs)\n\n    def test_placeholder_placement(self):\n        model = DomainModel(placeholder=\"foo\")\n        sep = model.Separator\n        self.assertEqual(model.order, (None, sep) + model.SEPARATED)\n\n        model = DomainModel(order=(\"bar\", ), placeholder=\"foo\")\n        self.assertEqual(model.order, (None, \"bar\"))\n\n        model = DomainModel(order=(\"bar\", None, \"baz\"), placeholder=\"foo\")\n        self.assertEqual(model.order, (\"bar\", None, \"baz\"))\n\n        model = DomainModel(order=(\"bar\", sep, \"baz\"),\n                            placeholder=\"foo\")\n        self.assertEqual(model.order, (None, sep, \"bar\", sep, \"baz\"))\n\n    def test_subparts(self):\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        m = DomainModel\n        sep = m.Separator\n        model = DomainModel(\n            order=(m.ATTRIBUTES | m.METAS, sep, m.CLASSES))\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), attrs + metas + [sep] + classes)\n\n        m = DomainModel\n        sep = m.Separator\n        model = DomainModel(\n            order=(m.ATTRIBUTES | m.METAS, sep, m.CLASSES),\n            alphabetical=True)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model),\n                         sorted(attrs + metas, key=lambda x: x.name) +\n                         [sep] +\n                         sorted(classes, key=lambda x: x.name))\n\n    def test_filtering(self):\n        cont = [ContinuousVariable(n) for n in \"abc\"]\n        disc = [DiscreteVariable(n) for n in \"def\"]\n        attrs = cont + disc\n\n        model = DomainModel(valid_types=(ContinuousVariable, ))\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), cont)\n\n        model = DomainModel(valid_types=(DiscreteVariable, ))\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc)\n\n        disc[0].attributes[\"hidden\"] = True\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc[1:])\n\n        model = DomainModel(valid_types=(DiscreteVariable, ),\n                            skip_hidden_vars=False)\n        model.set_domain(Domain(attrs))\n        self.assertEqual(list(model), disc)\n\n    def test_no_separators(self):\n        \"\"\"\n        GH-2697\n        \"\"\"\n        attrs = [ContinuousVariable(n) for n in \"abg\"]\n        classes = [ContinuousVariable(n) for n in \"deh\"]\n        metas = [ContinuousVariable(n) for n in \"ijf\"]\n\n        model = DomainModel(order=DomainModel.SEPARATED, separators=False)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(list(model), classes + metas + attrs)\n\n        model = DomainModel(order=DomainModel.SEPARATED, separators=True)\n        model.set_domain(Domain(attrs, classes, metas))\n        self.assertEqual(\n            list(model),\n            classes + [PyListModel.Separator] + metas + [PyListModel.Separator] + attrs)\n\n    def test_read_only(self):\n        model = DomainModel()\n        domain = Domain([ContinuousVariable(x) for x in \"abc\"])\n        model.set_domain(domain)\n        index = model.index(0, 0)\n\n        self.assertRaises(TypeError, model.append, 42)\n        self.assertRaises(TypeError, model.extend, [42])\n        self.assertRaises(TypeError, model.insert, 0, 42)\n        self.assertRaises(TypeError, model.remove, 0)\n        self.assertRaises(TypeError, model.pop)\n        self.assertRaises(TypeError, model.clear)\n        self.assertRaises(TypeError, model.reverse)\n        self.assertRaises(TypeError, model.sort)\n        with self.assertRaises(TypeError):\n            model[0] = 1\n        with self.assertRaises(TypeError):\n            del model[0]\n\n        self.assertFalse(model.setData(index, domain[0], Qt.EditRole))\n        self.assertTrue(model.setData(index, \"foo\", Qt.ToolTipRole))\n\n        self.assertFalse(model.setItemData(index, {Qt.EditRole: domain[0],\n                                                   Qt.ToolTipRole: \"foo\"}))\n        self.assertTrue(model.setItemData(index, {Qt.ToolTipRole: \"foo\"}))\n\n        self.assertFalse(model.insertRows(0, 1))\n        self.assertSequenceEqual(model, domain)\n        self.assertFalse(model.removeRows(0, 1))\n        self.assertSequenceEqual(model, domain)\n\n\nclass TestContinuousPalettesModel(GuiTest):\n    def setUp(self):\n        self.palette1, self.palette2 = \\\n            list(colorpalettes.ContinuousPalettes.values())[:2]\n\n    def test_all_categories(self):\n        model = ContinuousPalettesModel()\n        shown = {palette.name for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()}\n        self.assertEqual(expected, shown)\n\n        shown = {name for name in model.items if isinstance(name, str)}\n        expected = {palette.category\n                    for palette in colorpalettes.ContinuousPalettes.values()}\n        self.assertEqual(expected, shown)\n\n    def test_category_selection(self):\n        categories = ('Diverging', 'Linear')\n        model = ContinuousPalettesModel(categories=categories)\n        shown = {palette.name\n                 for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()\n                    if palette.category in categories}\n        self.assertEqual(expected, shown)\n        self.assertIn(\"Diverging\", model.items)\n        self.assertIn(\"Linear\", model.items)\n\n    def test_single_category(self):\n        category = 'Diverging'\n        model = ContinuousPalettesModel(categories=(category, ))\n        shown = {palette.name\n                 for palette in model.items\n                 if isinstance(palette, colorpalettes.Palette)}\n        expected = {palette.name\n                    for palette in colorpalettes.ContinuousPalettes.values()\n                    if palette.category == category}\n        self.assertEqual(expected, shown)\n        self.assertEqual(len(model.items), len(shown))\n\n    def test_count(self):\n        model = ContinuousPalettesModel()\n        model.items = [self.palette1, self.palette1]\n        self.assertEqual(model.rowCount(QModelIndex()), 2)\n        self.assertEqual(model.columnCount(QModelIndex()), 1)\n\n    def test_data(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        data = model.data\n        index = model.index\n\n        self.assertEqual(data(index(0, 0), Qt.EditRole), \"Palettes\")\n        self.assertEqual(data(index(1, 0), Qt.EditRole),\n                         self.palette1.friendly_name)\n        self.assertEqual(data(index(2, 0), Qt.EditRole),\n                         self.palette2.friendly_name)\n\n        self.assertEqual(data(index(0, 0), Qt.DisplayRole), \"Palettes\")\n        self.assertEqual(data(index(1, 0), Qt.DisplayRole),\n                         self.palette1.friendly_name)\n        self.assertEqual(data(index(2, 0), Qt.DisplayRole),\n                         self.palette2.friendly_name)\n\n        self.assertIsNone(data(index(0, 0), Qt.DecorationRole))\n        with patch.object(self.palette1, \"color_strip\") as color_strip:\n            self.assertIs(data(index(1, 0), Qt.DecorationRole),\n                          color_strip.return_value)\n        with patch.object(self.palette2, \"color_strip\") as color_strip:\n            self.assertIs(data(index(2, 0), Qt.DecorationRole),\n                          color_strip.return_value)\n\n        self.assertIsNone(data(index(0, 0), Qt.UserRole))\n        self.assertIs(data(index(1, 0), Qt.UserRole), self.palette1)\n        self.assertIs(data(index(2, 0), Qt.UserRole), self.palette2)\n\n        self.assertIsNone(data(index(2, 0), Qt.FontRole))\n\n    def test_select_flags(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        self.assertFalse(model.flags(model.index(0, 0)) & Qt.ItemIsSelectable)\n        self.assertTrue(model.flags(model.index(1, 0)) & Qt.ItemIsSelectable)\n        self.assertTrue(model.flags(model.index(2, 0)) & Qt.ItemIsSelectable)\n\n    def testIndexOf(self):\n        model = ContinuousPalettesModel()\n        model.items = [\"Palettes\", self.palette1, self.palette2]\n        self.assertEqual(model.indexOf(self.palette1), 1)\n        self.assertEqual(model.indexOf(self.palette1.name), 1)\n        self.assertEqual(model.indexOf(self.palette1.friendly_name), 1)\n        self.assertEqual(model.indexOf(self.palette2), 2)\n        self.assertEqual(model.indexOf(self.palette2.name), 2)\n        self.assertEqual(model.indexOf(self.palette2.friendly_name), 2)\n        self.assertIsNone(model.indexOf(42))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Orange installation attempts...\nAttempting installation with Python 3.7...\nrunning build_ext\nrunning build_src\nbuild_src\nbuilding extension \"Orange.classification._simple_tree\" sources\nbuilding extension \"Orange.classification._tree_scorers\" sources\nbuilding extension \"Orange.data._valuecount\" sources\nbuilding extension \"Orange.data._contingency\" sources\nbuilding extension \"Orange.data._io\" sources\nbuilding extension \"Orange.data._variable\" sources\nbuilding extension \"Orange.distance._distance\" sources\nbuilding extension \"Orange.preprocess._discretize\" sources\nbuilding extension \"Orange.preprocess._relieff\" sources\nbuilding extension \"Orange.projection._som\" sources\nbuilding extension \"Orange.widgets.utils._grid_density\" sources\nbuild_src: building npy-pkg config files\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmp29u57l8y/tmp\ncreating /tmp/tmp29u57l8y/tmp/tmp29u57l8y\ncompile options: '-MMD -MF /tmp/tmp29u57l8y/file.c.d -c'\ncc: /tmp/tmp29u57l8y/file.c\ncustomize UnixCCompiler using build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpb9zhd6dc/tmp\ncreating /tmp/tmpb9zhd6dc/tmp/tmpb9zhd6dc\ncompile options: '-MMD -MF /tmp/tmpb9zhd6dc/file.c.d -c'\ncc: /tmp/tmpb9zhd6dc/file.c\ncustomize UnixCCompiler using build_ext\nbuilding 'Orange.classification._simple_tree' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange\ncreating build/temp.linux-x86_64-3.7/Orange/classification\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/classification/_simple_tree.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_simple_tree.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.classification._tree_scorers' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/classification/_tree_scorers.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_tree_scorers.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._valuecount' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/data\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_valuecount.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_valuecount.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._contingency' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_contingency.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_contingency.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._io' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_io.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_io.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_io.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._variable' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_variable.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_variable.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.distance._distance' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/distance\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/distance/_distance.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/distance/_distance.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._discretize' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/preprocess\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/preprocess/_discretize.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_discretize.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._relieff' extension\ncompiling C++ sources\nC compiler: c++ -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\nc++: Orange/preprocess/_relieff.cpp\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_relieff.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.projection._som' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/projection\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/projection/_som.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/projection/_som.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/projection/_som.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.widgets.utils._grid_density' extension\ncompiling C++ sources\nC compiler: c++ -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/widgets\ncreating build/temp.linux-x86_64-3.7/Orange/widgets/utils\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\nc++: Orange/widgets/utils/_grid_density.cpp\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so\nrunning develop\nrunning build_scripts\nrunning egg_info\nrunning build_src\nbuild_src\nbuilding extension \"Orange.classification._simple_tree\" sources\nbuilding extension \"Orange.classification._tree_scorers\" sources\nbuilding extension \"Orange.data._valuecount\" sources\nbuilding extension \"Orange.data._contingency\" sources\nbuilding extension \"Orange.data._io\" sources\nbuilding extension \"Orange.data._variable\" sources\nbuilding extension \"Orange.distance._distance\" sources\nbuilding extension \"Orange.preprocess._discretize\" sources\nbuilding extension \"Orange.preprocess._relieff\" sources\nbuilding extension \"Orange.projection._som\" sources\nbuilding extension \"Orange.widgets.utils._grid_density\" sources\nbuild_src: building npy-pkg config files\ncreating Orange3.egg-info\nwriting Orange3.egg-info/PKG-INFO\nwriting dependency_links to Orange3.egg-info/dependency_links.txt\nwriting entry points to Orange3.egg-info/entry_points.txt\nwriting requirements to Orange3.egg-info/requires.txt\nwriting top-level names to Orange3.egg-info/top_level.txt\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest template 'MANIFEST.in'\nwarning: no files found matching 'README*' under directory 'Orange'\nwarning: no files found matching 'LICENSE' under directory 'Orange'\nwarning: no files found matching '*.basket' under directory 'Orange/datasets'\nwarning: no files found matching '*.js' under directory 'Orange/widgets'\nwarning: no files found matching '*.css' under directory 'Orange/widgets'\nwarning: no files found matching '*.html' under directory 'Orange/widgets'\nwarning: no files found matching 'COPYING'\nadding license file 'LICENSE'\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nrunning build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpiir54qde/tmp\ncreating /tmp/tmpiir54qde/tmp/tmpiir54qde\ncompile options: '-MMD -MF /tmp/tmpiir54qde/file.c.d -c'\ncc: /tmp/tmpiir54qde/file.c\ncustomize UnixCCompiler using build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmp99nm_mtq/tmp\ncreating /tmp/tmp99nm_mtq/tmp/tmp99nm_mtq\ncompile options: '-MMD -MF /tmp/tmp99nm_mtq/file.c.d -c'\ncc: /tmp/tmp99nm_mtq/file.c\ncustomize UnixCCompiler using build_ext\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.25.0.dev0+221f981 to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b\nProcessing dependencies for Orange3==3.25.0.dev0+221f981\nSearching for XlsxWriter==3.2.0\nBest match: XlsxWriter 3.2.0\nAdding XlsxWriter 3.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for xlrd==2.0.1\nBest match: xlrd 2.0.1\nAdding xlrd 2.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for setuptools==59.8.0\nBest match: setuptools 59.8.0\nAdding setuptools 59.8.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for serverfiles==0.3.1\nBest match: serverfiles 0.3.1\nAdding serverfiles 0.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for scipy==1.7.3\nBest match: scipy 1.7.3\nAdding scipy 1.7.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for scikit-learn==1.0.2\nBest match: scikit-learn 1.0.2\nAdding scikit-learn 1.0.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for requests==2.31.0\nBest match: requests 2.31.0\nAdding requests 2.31.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for PyYAML==6.0.1\nBest match: PyYAML 6.0.1\nAdding PyYAML 6.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for python-louvain==0.16\nBest match: python-louvain 0.16\nAdding python-louvain 0.16 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for pyqtgraph==0.10.0\nBest match: pyqtgraph 0.10.0\nAdding pyqtgraph 0.10.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for pip==24.0\nBest match: pip 24.0\nAdding pip 24.0 to easy-install.pth file\nInstalling pip script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for pandas==1.3.5\nBest match: pandas 1.3.5\nAdding pandas 1.3.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for orange-widget-base==4.22.0\nBest match: orange-widget-base 4.22.0\nAdding orange-widget-base 4.22.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for orange-canvas-core==0.1.35\nBest match: orange-canvas-core 0.1.35\nAdding orange-canvas-core 0.1.35 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for openpyxl==3.1.3\nBest match: openpyxl 3.1.3\nAdding openpyxl 3.1.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for openTSNE==1.0.1\nBest match: openTSNE 1.0.1\nAdding openTSNE 1.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for numpy==1.17.5\nBest match: numpy 1.17.5\nAdding numpy 1.17.5 to easy-install.pth file\nInstalling f2py script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for networkx==2.6.3\nBest match: networkx 2.6.3\nAdding networkx 2.6.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for matplotlib==3.5.3\nBest match: matplotlib 3.5.3\nAdding matplotlib 3.5.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for keyrings.alt==4.2.0\nBest match: keyrings.alt 4.2.0\nAdding keyrings.alt 4.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for keyring==24.1.1\nBest match: keyring 24.1.1\nAdding keyring 24.1.1 to easy-install.pth file\nInstalling keyring script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for joblib==1.3.2\nBest match: joblib 1.3.2\nAdding joblib 1.3.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for httpx==0.24.1\nBest match: httpx 0.24.1\nAdding httpx 0.24.1 to easy-install.pth file\nInstalling httpx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for docutils==0.20.1\nBest match: docutils 0.20.1\nAdding docutils 0.20.1 to easy-install.pth file\nInstalling docutils script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for chardet==5.2.0\nBest match: chardet 5.2.0\nAdding chardet 5.2.0 to easy-install.pth file\nInstalling chardetect script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for Bottleneck==1.4.0\nBest match: Bottleneck 1.4.0\nAdding Bottleneck 1.4.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for baycomp==1.0.3\nBest match: baycomp 1.0.3\nAdding baycomp 1.0.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for AnyQt==0.2.0\nBest match: AnyQt 0.2.0\nAdding AnyQt 0.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for threadpoolctl==3.1.0\nBest match: threadpoolctl 3.1.0\nAdding threadpoolctl 3.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for idna==3.10\nBest match: idna 3.10\nAdding idna 3.10 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for certifi==2024.12.14\nBest match: certifi 2024.12.14\nAdding certifi 2024.12.14 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for charset-normalizer==3.4.1\nBest match: charset-normalizer 3.4.1\nAdding charset-normalizer 3.4.1 to easy-install.pth file\nInstalling normalizer script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for urllib3==2.0.7\nBest match: urllib3 2.0.7\nAdding urllib3 2.0.7 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for python-dateutil==2.9.0.post0\nBest match: python-dateutil 2.9.0.post0\nAdding python-dateutil 2.9.0.post0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for pytz==2024.2\nBest match: pytz 2024.2\nAdding pytz 2024.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for typing-extensions==4.7.1\nBest match: typing-extensions 4.7.1\nAdding typing-extensions 4.7.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for commonmark==0.9.1\nBest match: commonmark 0.9.1\nAdding commonmark 0.9.1 to easy-install.pth file\nInstalling cmark script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for qasync==0.25.0\nBest match: qasync 0.25.0\nAdding qasync 0.25.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for dictdiffer==0.9.0\nBest match: dictdiffer 0.9.0\nAdding dictdiffer 0.9.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for requests-cache==1.1.1\nBest match: requests-cache 1.1.1\nAdding requests-cache 1.1.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for importlib-metadata==6.7.0\nBest match: importlib-metadata 6.7.0\nAdding importlib-metadata 6.7.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for packaging==24.0\nBest match: packaging 24.0\nAdding packaging 24.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for et-xmlfile==1.1.0\nBest match: et-xmlfile 1.1.0\nAdding et-xmlfile 1.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for pyparsing==3.1.4\nBest match: pyparsing 3.1.4\nAdding pyparsing 3.1.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for Pillow==9.5.0\nBest match: Pillow 9.5.0\nAdding Pillow 9.5.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for cycler==0.11.0\nBest match: cycler 0.11.0\nAdding cycler 0.11.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for kiwisolver==1.4.5\nBest match: kiwisolver 1.4.5\nAdding kiwisolver 1.4.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for fonttools==4.38.0\nBest match: fonttools 4.38.0\nAdding fonttools 4.38.0 to easy-install.pth file\nInstalling fonttools script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for jaraco.classes==3.2.3\nBest match: jaraco.classes 3.2.3\nAdding jaraco.classes 3.2.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for SecretStorage==3.3.3\nBest match: SecretStorage 3.3.3\nAdding SecretStorage 3.3.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for jeepney==0.8.0\nBest match: jeepney 0.8.0\nAdding jeepney 0.8.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for importlib-resources==5.12.0\nBest match: importlib-resources 5.12.0\nAdding importlib-resources 5.12.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for sniffio==1.3.1\nBest match: sniffio 1.3.1\nAdding sniffio 1.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for httpcore==0.17.3\nBest match: httpcore 0.17.3\nAdding httpcore 0.17.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for six==1.17.0\nBest match: six 1.17.0\nAdding six 1.17.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for url-normalize==1.4.3\nBest match: url-normalize 1.4.3\nAdding url-normalize 1.4.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for cattrs==23.1.2\nBest match: cattrs 23.1.2\nAdding cattrs 23.1.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for attrs==24.2.0\nBest match: attrs 24.2.0\nAdding attrs 24.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for platformdirs==4.0.0\nBest match: platformdirs 4.0.0\nAdding platformdirs 4.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for zipp==3.15.0\nBest match: zipp 3.15.0\nAdding zipp 3.15.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for more-itertools==9.1.0\nBest match: more-itertools 9.1.0\nAdding more-itertools 9.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for cryptography==44.0.0\nBest match: cryptography 44.0.0\nAdding cryptography 44.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for h11==0.14.0\nBest match: h11 0.14.0\nAdding h11 0.14.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for anyio==3.7.1\nBest match: anyio 3.7.1\nAdding anyio 3.7.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for exceptiongroup==1.2.2\nBest match: exceptiongroup 1.2.2\nAdding exceptiongroup 1.2.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for cffi==1.15.1\nBest match: cffi 1.15.1\nAdding cffi 1.15.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nSearching for pycparser==2.21\nBest match: pycparser 2.21\nAdding pycparser 2.21 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.25.0.dev0+221f981\nVerifying Orange installation...\n✅ Orange installation successful!\nSuccessfully installed orange using Python 3.7\n",
    "setup_res_stderr": "Using CPython 3.7.9\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 18 packages in 62ms\nPrepared 18 packages in 3ms\nInstalled 18 packages in 138ms\n + cython==0.29.37\n + exceptiongroup==1.2.2\n + importlib-metadata==6.7.0\n + iniconfig==2.0.0\n + numpy==1.17.5\n + packaging==24.0\n + pluggy==1.2.0\n + pyqt5==5.15.10\n + pyqt5-qt5==5.15.16\n + pyqt5-sip==12.13.0\n + pyqtwebengine==5.15.6\n + pyqtwebengine-qt5==5.15.16\n + pytest==7.4.4\n + setuptools==59.8.0\n + tomli==2.0.1\n + typing-extensions==4.7.1\n + wheel==0.42.0\n + zipp==3.15.0\nResolved 54 packages in 433ms\nInstalled 47 packages in 747ms\n + anyio==3.7.1\n + baycomp==1.0.3\n + bottleneck==1.4.0\n + certifi==2024.12.14\n + cffi==1.15.1\n + chardet==5.2.0\n + charset-normalizer==3.4.1\n + cryptography==44.0.0\n + cycler==0.11.0\n + et-xmlfile==1.1.0\n + fonttools==4.38.0\n + h11==0.14.0\n + httpcore==0.17.3\n + httpx==0.24.1\n + idna==3.10\n + importlib-resources==5.12.0\n + jaraco-classes==3.2.3\n + jeepney==0.8.0\n + joblib==1.3.2\n + keyring==24.1.1\n + keyrings-alt==4.2.0\n + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + more-itertools==9.1.0\n + networkx==2.6.3\n + openpyxl==3.1.3\n + opentsne==1.0.1\n + pandas==1.3.5\n + pillow==9.5.0\n + pip==24.0\n + pycparser==2.21\n + pyparsing==3.1.4\n + python-dateutil==2.9.0.post0\n + python-louvain==0.16\n + pytz==2024.2\n + pyyaml==6.0.1\n + requests==2.31.0\n + scikit-learn==1.0.2\n + scipy==1.7.3\n + secretstorage==3.3.3\n + serverfiles==0.3.1\n + six==1.17.0\n + sniffio==1.3.1\n + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\n + xlsxwriter==3.2.0\nResolved 34 packages in 97ms\nInstalled 13 packages in 188ms\n + anyqt==0.2.0\n + attrs==24.2.0\n + cattrs==23.1.2\n + commonmark==0.9.1\n + dictdiffer==0.9.0\n + docutils==0.20.1\n + orange-canvas-core==0.1.35\n + orange-widget-base==4.22.0\n + platformdirs==4.0.0\n + pyqtgraph==0.10.0\n + qasync==0.25.0\n + requests-cache==1.1.1\n + url-normalize==1.4.3\nResolved 2 packages in 3ms\nInstalled 2 packages in 37ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nAudited 1 package in 35ms\nAudited 2 packages in 35ms\nOrange/classification/_simple_tree.c: In function ‘gain_ratio_c’:\nOrange/classification/_simple_tree.c:63:9: warning: implicit declaration of function ‘qsort_r’; did you mean ‘qsort’? [-Wimplicit-function-declaration]\n   63 |         qsort_r(base, nel, size, compar, thunk)\n      |         ^~~~~~~\nOrange/classification/_simple_tree.c:147:9: note: in expansion of macro ‘QSORT_R_FUNC’\n  147 |         QSORT_R_FUNC(examples, size, sizeof(struct Example), (void*) &compar_attr, compar_examples);\n      |         ^~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/classification/_tree_scorers.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_2find_threshold_entropy’:\nOrange/classification/_tree_scorers.c:3115:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 3115 |   __pyx_t_7 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_6find_threshold_MSE’:\nOrange/classification/_tree_scorers.c:4619:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 4619 |   __pyx_t_1 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_8find_binarization_MSE’:\nOrange/classification/_tree_scorers.c:5396:43: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5396 |           for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) {\n      |                                           ^\nOrange/classification/_tree_scorers.c:5517:39: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5517 |           __pyx_t_27 = ((__pyx_v_left >= __pyx_v_min_leaf) != 0);\n      |                                       ^~\nOrange/classification/_tree_scorers.c:5523:53: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5523 |           __pyx_t_27 = (((__pyx_v_N - __pyx_v_left) >= __pyx_v_min_leaf) != 0);\n      |                                                     ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_14compute_predictions_csr’:\nOrange/classification/_tree_scorers.c:7051:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7051 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_16compute_predictions_csc’:\nOrange/classification/_tree_scorers.c:7741:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7741 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c:7801:143: warning: comparison of integer expressions of different signedness: ‘__pyx_t_5numpy_int32_t’ {aka ‘int’} and ‘unsigned int’ [-Wsign-compare]\n 7801 |               __pyx_t_17 = (((*((__pyx_t_5numpy_int32_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_18 * __pyx_v_indices.strides[0]) ))) != __pyx_v_i) != 0);\n      |                                                                                                                                               ^~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_valuecount.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/data/_io.c: In function ‘__pyx_pf_6Orange_4data_3_io_sparse_read_float.constprop’:\nOrange/data/_io.c:3881:24: warning: ‘__pyx_v_decs’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3881 |           __pyx_v_decs = (__pyx_v_decs / 10.0);\n      |           ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:4070:24: warning: ‘__pyx_v_value’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4070 |           __pyx_t_10 = PyFloat_FromDouble(__pyx_v_value); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 221, __pyx_L5_error)\n      |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:480:40: warning: ‘__pyx_v_attr_index’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n  480 |   #define PyInt_FromLong               PyLong_FromLong\n      |                                        ^~~~~~~~~~~~~~~\nOrange/data/_io.c:1301:7: note: ‘__pyx_v_attr_index’ was declared here\n 1301 |   int __pyx_v_attr_index;\n      |       ^~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:2935:25: warning: ‘__pyx_v_atomp’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2935 |           __pyx_v_atomp = (__pyx_v_atomp + 1);\n      |           ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_discretize.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_relieff.cpp:581:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/projection/_som.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_5update_hex’:\nOrange/projection/_som.c:3655:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3655 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:3654:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3654 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_7get_winners_sparse’:\nOrange/projection/_som.c:4547:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4547 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_38, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_39, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4114:7: note: ‘__pyx_v_win_y’ was declared here\n 4114 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4536:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4536 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_36, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_37, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4113:7: note: ‘__pyx_v_win_x’ was declared here\n 4113 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_8update_sparse.constprop’:\nOrange/projection/_som.c:4746:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4746 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4745:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4745 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_3update’:\nOrange/projection/_som.c:3141:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3141 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_1get_winners’:\nOrange/projection/_som.c:2964:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2964 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_28, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2665:7: note: ‘__pyx_v_win_y’ was declared here\n 2665 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:2953:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2953 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2664:7: note: ‘__pyx_v_win_x’ was declared here\n 2664 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_10update_sparse_hex.constprop’:\nOrange/projection/_som.c:5515:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5515 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:5514:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5514 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/setuptools/command/easy_install.py:159: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.\n  EasyInstallDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b/.venv/lib/python3.7/site-packages/setuptools/command/egg_info.py:628: SetuptoolsDeprecationWarning: Custom 'build_py' does not implement 'get_data_files_without_manifest'.\nPlease extend command classes from setuptools instead of distutils.\n  SetuptoolsDeprecationWarning\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b\nplugins: anyio-3.7.1\ncollected 41 items\n\nr2e_tests/test_1.py .........................................            [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestUtils::test_as_contiguous_range\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_append\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_clear\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_columnCount\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_data\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_editable\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_emits_column_changes_on_row_insert\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_extend\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_init\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_insert\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_insertColumns\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_insertRows\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_other_roles\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_remove\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_removeColumns\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_removeRows\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_rowCount\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_setHeaderLabels\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_set_iten_slice\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_sort\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_wrap\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_displayrole\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_invalid_index\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_other_roles\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_placeholder\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_table_variable\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_tooltip\nPASSED r2e_tests/test_1.py::TestDomainModel::test_filtering\nPASSED r2e_tests/test_1.py::TestDomainModel::test_init_with_single_section\nPASSED r2e_tests/test_1.py::TestDomainModel::test_no_separators\nPASSED r2e_tests/test_1.py::TestDomainModel::test_placeholder_placement\nPASSED r2e_tests/test_1.py::TestDomainModel::test_read_only\nPASSED r2e_tests/test_1.py::TestDomainModel::test_separators\nPASSED r2e_tests/test_1.py::TestDomainModel::test_subparts\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::testIndexOf\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_all_categories\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_category_selection\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_count\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_data\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_select_flags\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_single_category\n============================== 41 passed in 3.33s ==============================\nWidgets left: 0    Max widgets: 0 \n\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_221f981ef0324c3101b02e9bab6aef48201fdf5b\nplugins: anyio-3.7.1\ncollected 41 items\n\nr2e_tests/test_1.py ..................F......................            [100%]\n\n=================================== FAILURES ===================================\n_____________________ TestPyTableModel.test_set_iten_slice _____________________\n\nself = <r2e_tests.test_1.TestPyTableModel testMethod=test_set_iten_slice>\n\n    def test_set_iten_slice(self):\n        self.model[:1] = [[10, 11], [12, 13], [14, 15]]\n>       self.assertEqual(list(self.model), [[10, 11], [12, 13], [14, 15], [2, 3]])\nE       AssertionError: Lists differ: [[10, 11], [12, 13], [14, 15]] != [[10, 11], [12, 13], [14, 15], [2, 3]]\nE       \nE       Second list contains 1 additional elements.\nE       First extra element 3:\nE       [2, 3]\nE       \nE       - [[10, 11], [12, 13], [14, 15]]\nE       + [[10, 11], [12, 13], [14, 15], [2, 3]]\nE       ?                              +++++++ +\n\nr2e_tests/test_1.py:129: AssertionError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestUtils::test_as_contiguous_range\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_append\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_clear\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_columnCount\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_data\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_editable\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_emits_column_changes_on_row_insert\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_extend\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_init\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_insert\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_insertColumns\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_insertRows\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_other_roles\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_remove\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_removeColumns\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_removeRows\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_rowCount\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_setHeaderLabels\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_sort\nPASSED r2e_tests/test_1.py::TestPyTableModel::test_wrap\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_displayrole\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_invalid_index\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_other_roles\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_placeholder\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_table_variable\nPASSED r2e_tests/test_1.py::TestVariableListModel::test_tooltip\nPASSED r2e_tests/test_1.py::TestDomainModel::test_filtering\nPASSED r2e_tests/test_1.py::TestDomainModel::test_init_with_single_section\nPASSED r2e_tests/test_1.py::TestDomainModel::test_no_separators\nPASSED r2e_tests/test_1.py::TestDomainModel::test_placeholder_placement\nPASSED r2e_tests/test_1.py::TestDomainModel::test_read_only\nPASSED r2e_tests/test_1.py::TestDomainModel::test_separators\nPASSED r2e_tests/test_1.py::TestDomainModel::test_subparts\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::testIndexOf\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_all_categories\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_category_selection\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_count\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_data\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_select_flags\nPASSED r2e_tests/test_1.py::TestContinuousPalettesModel::test_single_category\nFAILED r2e_tests/test_1.py::TestPyTableModel::test_set_iten_slice - Assertion...\n========================= 1 failed, 40 passed in 2.23s =========================\nWidgets left: 0    Max widgets: 0 \n\n",
    "old_commit_res_stderr": ""
}
Orange/widgets/utils/itemmodels.py Orange/widgets/utils/tests/test_itemmodels.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Slice assignment in PyTableModel does not correctly update table rows

**Description:**
When assigning a list of items to a slice of the `PyTableModel`, the table does not update the rows as expected. This leads to an inconsistent state where the number of rows does not match the intended assignment.

**Example Code:**
```python
model = PyTableModel([[1, 4], [2, 3]])
model[:1] = [[10, 11], [12, 13], [14, 15]]
print(list(model))
# Expected output: [[10, 11], [12, 13], [14, 15], [2, 3]]
```

**Expected Behavior:**
After assigning to the slice, the model should correctly insert the new rows, resulting in four rows as specified:
```
[[10, 11], [12, 13], [14, 15], [2, 3]]
```

**Actual Behavior:**
Only three rows are present after the assignment, missing the last expected row:
```
[[10, 11], [12, 13], [14, 15]]
```
This discrepancy causes operations that rely on the correct number of rows to fail or behave unexpectedly.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### Orange/widgets/utils/itemmodels.py
from numbers import Number, Integral
from math import isnan, isinf

import operator
from collections import namedtuple, Sequence, defaultdict
from contextlib import contextmanager
from functools import reduce, partial, lru_cache, wraps
from itertools import chain
from warnings import warn
from xml.sax.saxutils import escape

from AnyQt.QtCore import (
    Qt, QObject, QAbstractListModel, QModelIndex,
    QItemSelectionModel, QItemSelection)
from AnyQt.QtCore import pyqtSignal as Signal
from AnyQt.QtGui import QColor
from AnyQt.QtWidgets import (
    QWidget, QBoxLayout, QToolButton, QAbstractButton, QAction
)

import numpy

from orangewidget.utils.itemmodels import (
    PyListModel, AbstractSortTableModel as _AbstractSortTableModel
)

from Orange.widgets.utils.colorpalettes import ContinuousPalettes, ContinuousPalette
from Orange.data import Variable, Storage, DiscreteVariable, ContinuousVariable
from Orange.data.domain import filter_visible
from Orange.widgets import gui
from Orange.widgets.utils import datacaching
from Orange.statistics import basic_stats
from Orange.util import deprecated

__all__ = [
    "PyListModel", "VariableListModel", "PyListModelTooltip", "DomainModel",
    "AbstractSortTableModel", "PyTableModel", "TableModel",
    "ModelActionsWidget", "ListSingleSelectionModel"
]

@contextmanager
def signal_blocking(obj):
    blocked = obj.signalsBlocked()
    obj.blockSignals(True)
    try:
        yield
    finally:
        obj.blockSignals(blocked)


def _as_contiguous_range(the_slice, length):
    start, stop, step = the_slice.indices(length)
    if step == -1:
        # Equivalent range with positive step
        start, stop, step = stop + 1, start + 1, 1
    elif not (step == 1 or step is None):
        raise IndexError("Non-contiguous range.")
    return start, stop, step


class AbstractSortTableModel(_AbstractSortTableModel):
    # these were defined on TableModel below. When the AbstractSortTableModel
    # was extracted and made a base of TableModel these deprecations were
    # misplaced, they belong in TableModel.
    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapFromSourceRows')
    def mapFromTableRows(self, rows):
        return self.mapFromSourceRows(rows)

    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapToSourceRows')
    def mapToTableRows(self, rows):
        return self.mapToSourceRows(rows)


class PyTableModel(AbstractSortTableModel):
    """ A model for displaying python tables (sequences of sequences) in
    QTableView objects.

    Parameters
    ----------
    sequence : list
        The initial list to wrap.
    parent : QObject
        Parent QObject.
    editable: bool or sequence
        If True, all items are flagged editable. If sequence, the True-ish
        fields mark their respective columns editable.

    Notes
    -----
    The model rounds numbers to human readable precision, e.g.:
    1.23e-04, 1.234, 1234.5, 12345, 1.234e06.

    To set additional item roles, use setData().
    """

    @staticmethod
    def _RoleData():
        return defaultdict(lambda: defaultdict(dict))

    # All methods are either necessary overrides of super methods, or
    # methods likened to the Python list's. Hence, docstrings aren't.
    # pylint: disable=missing-docstring
    def __init__(self, sequence=None, parent=None, editable=False):
        super().__init__(parent)
        self._rows = self._cols = 0
        self._headers = {}
        self._editable = editable
        self._table = None
        self._roleData = {}
        self.wrap(sequence or [])

    def rowCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else self._rows

    def columnCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else self._cols

    def flags(self, index):
        flags = super().flags(index)
        if not self._editable or not index.isValid():
            return flags
        if isinstance(self._editable, Sequence):
            return flags | Qt.ItemIsEditable if self._editable[index.column()] else flags
        return flags | Qt.ItemIsEditable

    def setData(self, index, value, role):
        row = self.mapFromSourceRows(index.row())
        if role == Qt.EditRole:
            self[row][index.column()] = value
            self.dataChanged.emit(index, index)
        else:
            self._roleData[row][index.column()][role] = value
        return True

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return

        row, column = self.mapToSourceRows(index.row()), index.column()

        role_value = self._roleData.get(row, {}).get(column, {}).get(role)
        if role_value is not None:
            return role_value

        try:
            value = self[row][column]
        except IndexError:
            return
        if role == Qt.EditRole:
            return value
        if role == Qt.DecorationRole and isinstance(value, Variable):
            return gui.attributeIconDict[value]
        if role == Qt.DisplayRole:
            if (isinstance(value, Number) and
                    not (isnan(value) or isinf(value) or isinstance(value, Integral))):
                absval = abs(value)
                strlen = len(str(int(absval)))
                value = '{:.{}{}}'.format(value,
                                          2 if absval < .001 else
                                          3 if strlen < 2 else
                                          1 if strlen < 5 else
                                          0 if strlen < 6 else
                                          3,
                                          'f' if (absval == 0 or
                                                  absval >= .001 and
                                                  strlen < 6)
                                          else 'e')
            return str(value)
        if role == Qt.TextAlignmentRole and isinstance(value, Number):
            return Qt.AlignRight | Qt.AlignVCenter
        if role == Qt.ToolTipRole:
            return str(value)

    def sortColumnData(self, column):
        return [row[column] for row in self._table]

    def setHorizontalHeaderLabels(self, labels):
        """
        Parameters
        ----------
        labels : list of str or list of Variable
        """
        self._headers[Qt.Horizontal] = tuple(labels)

    def setVerticalHeaderLabels(self, labels):
        """
        Parameters
        ----------
        labels : list of str or list of Variable
        """
        self._headers[Qt.Vertical] = tuple(labels)

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        headers = self._headers.get(orientation)

        if headers and section < len(headers):
            section = self.mapToSourceRows(section) if orientation == Qt.Vertical else section
            value = headers[section]

            if role == Qt.ToolTipRole:
                role = Qt.DisplayRole

            if role == Qt.DisplayRole:
                return value.name if isinstance(value, Variable) else value

            if role == Qt.DecorationRole:
                if isinstance(value, Variable):
                    return gui.attributeIconDict[value]

        # Use QAbstractItemModel default for non-existent header/sections
        return super().headerData(section, orientation, role)

    def removeRows(self, row, count, parent=QModelIndex()):
        if not parent.isValid():
            del self[row:row + count]
            for rowidx in range(row, row + count):
                self._roleData.pop(rowidx, None)
            self._rows = self._table_dim()[0]
            return True
        return False

    def removeColumns(self, column, count, parent=QModelIndex()):
        self.beginRemoveColumns(parent, column, column + count - 1)
        for row in self._table:
            del row[column:column + count]
        for cols in self._roleData.values():
            for col in range(column, column + count):
                cols.pop(col, None)
        del self._headers.get(Qt.Horizontal, [])[column:column + count]
        self._cols = self._table_dim()[1]
        self.endRemoveColumns()
        return True

    def _table_dim(self):
        return len(self._table), max(map(len, self), default=0)

    def insertRows(self, row, count, parent=QModelIndex()):
        self.beginInsertRows(parent, row, row + count - 1)
        self._table[row:row] = [[''] * self.columnCount() for _ in range(count)]
        self._rows = self._table_dim()[0]
        self.endInsertRows()
        return True

    def insertColumns(self, column, count, parent=QModelIndex()):
        self.beginInsertColumns(parent, column, column + count - 1)
        for row in self._table:
            row[column:column] = [''] * count
        self._rows = self._table_dim()[0]
        self.endInsertColumns()
        return True

    def __len__(self):
        return len(self._table)

    def __bool__(self):
        return len(self) != 0

    def __iter__(self):
        return iter(self._table)

    def __getitem__(self, item):
        return self._table[item]

    def __delitem__(self, i):
        if isinstance(i, slice):
            start, stop, _ = _as_contiguous_range(i, len(self))
            stop -= 1
        else:
            start = stop = i = i if i >= 0 else len(self) + i
        self._check_sort_order()
        self.beginRemoveRows(QModelIndex(), start, stop)
        del self._table[i]
        rows = self._table_dim()[0]
        self._rows = rows
        self.endRemoveRows()
        self._update_column_count()

    def __setitem__(self, i, value):
        self._check_sort_order()
        if isinstance(i, slice):
            start, stop, _ = _as_contiguous_range(i, len(self))
            self.removeRows(start, stop - start)
            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)
            self._table[start:start + len(value)] = value
            self._rows = self._table_dim()[0]
            self.endInsertRows()
            self._update_column_count()
        else:
            self._table[i] = value
            self.dataChanged.emit(self.index(i, 0),
                                  self.index(i, self.columnCount() - 1))

    def _update_column_count(self):
        cols_before = self._cols
        cols_after = self._table_dim()[1]
        if cols_before < cols_after:
            self.beginInsertColumns(QModelIndex(), cols_before, cols_after - 1)
            self._cols = cols_after
            self.endInsertColumns()
        elif cols_before > cols_after:
            self.beginRemoveColumns(QModelIndex(), cols_after, cols_before - 1)
            self._cols = cols_after
            self.endRemoveColumns()

    def _check_sort_order(self):
        if self.mapToSourceRows(Ellipsis) is not Ellipsis:
            warn("Can't modify PyTableModel when it's sorted",
                 RuntimeWarning, stacklevel=3)
            raise RuntimeError("Can't modify PyTableModel when it's sorted")

    def wrap(self, table):
        self.beginResetModel()
        self._table = table
        self._roleData = self._RoleData()
        self._rows, self._cols = self._table_dim()
        self.resetSorting()
        self.endResetModel()

    def tolist(self):
        return self._table

    def clear(self):
        self.beginResetModel()
        self._table.clear()
        self.resetSorting()
        self._roleData.clear()
        self._rows, self._cols = self._table_dim()
        self.endResetModel()

    def append(self, row):
        self.extend([row])

    def _insertColumns(self, rows):
        n_max = max(map(len, rows))
        if self.columnCount() < n_max:
            self.insertColumns(self.columnCount(), n_max - self.columnCount())

    def extend(self, rows):
        i, rows = len(self), list(rows)
        self.insertRows(i, len(rows))
        self._insertColumns(rows)
        self[i:] = rows

    def insert(self, i, row):
        self.insertRows(i, 1)
        self._insertColumns((row,))
        self[i] = row

    def remove(self, val):
        del self[self._table.index(val)]


class PyListModelTooltip(PyListModel):
    def __init__(self):
        super().__init__()
        self.tooltips = []

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.ToolTipRole:
            return self.tooltips[index.row()]
        else:
            return super().data(index, role)


class VariableListModel(PyListModel):
    MIME_TYPE = "application/x-Orange-VariableList"

    def __init__(self, *args, placeholder=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.placeholder = placeholder

    def data(self, index, role=Qt.DisplayRole):
        if self._is_index_valid(index):
            var = self[index.row()]
            if var is None and role == Qt.DisplayRole:
                return self.placeholder or "None"
            if not isinstance(var, Variable):
                return super().data(index, role)
            elif role == Qt.DisplayRole:
                return var.name
            elif role == Qt.DecorationRole:
                return gui.attributeIconDict[var]
            elif role == Qt.ToolTipRole:
                return self.variable_tooltip(var)
            elif role == gui.TableVariable:
                return var
            else:
                return PyListModel.data(self, index, role)

    def variable_tooltip(self, var):
        if var.is_discrete:
            return self.discrete_variable_tooltip(var)
        elif var.is_time:
            return self.time_variable_toltip(var)
        elif var.is_continuous:
            return self.continuous_variable_toltip(var)
        elif var.is_string:
            return self.string_variable_tooltip(var)

    def variable_labels_tooltip(self, var):
        text = ""
        if var.attributes:
            items = [(safe_text(key), safe_text(value))
                     for key, value in var.attributes.items()]
            labels = list(map("%s = %s".__mod__, items))
            text += "<br/>Variable Labels:<br/>"
            text += "<br/>".join(labels)
        return text

    def discrete_variable_tooltip(self, var):
        text = "<b>%s</b><br/>Categorical with %i values: " %\
               (safe_text(var.name), len(var.values))
        text += ", ".join("%r" % safe_text(v) for v in var.values)
        text += self.variable_labels_tooltip(var)
        return text

    def time_variable_toltip(self, var):
        text = "<b>%s</b><br/>Time" % safe_text(var.name)
        text += self.variable_labels_tooltip(var)
        return text

    def continuous_variable_toltip(self, var):
        text = "<b>%s</b><br/>Numeric" % safe_text(var.name)
        text += self.variable_labels_tooltip(var)
        return text

    def string_variable_tooltip(self, var):
        text = "<b>%s</b><br/>Text" % safe_text(var.name)
        text += self.variable_labels_tooltip(var)
        return text


class DomainModel(VariableListModel):
    ATTRIBUTES, CLASSES, METAS = 1, 2, 4
    MIXED = ATTRIBUTES | CLASSES | METAS
    SEPARATED = (CLASSES, PyListModel.Separator,
                 METAS, PyListModel.Separator,
                 ATTRIBUTES)
    PRIMITIVE = (DiscreteVariable, ContinuousVariable)

    def __init__(self, order=SEPARATED, separators=True, placeholder=None,
                 valid_types=None, alphabetical=False, skip_hidden_vars=True, **kwargs):
        """

        Parameters
        ----------
        order: tuple or int
            Order of attributes, metas, classes, separators and other options
        separators: bool
            If False, remove separators from `order`.
        placeholder: str
            The text that is shown when no variable is selected
        valid_types: tuple
            (Sub)types of `Variable` that are included in the model
        alphabetical: bool
            If true, variables are sorted alphabetically.
        skip_hidden_vars: bool
            If true, variables marked as "hidden" are skipped.
        """
        super().__init__(placeholder=placeholder, **kwargs)
        if isinstance(order, int):
            order = (order,)
        if placeholder is not None and None not in order:
            # Add None for the placeholder if it's not already there
            # Include separator if the current order uses them
            order = (None,) + \
                    (self.Separator, ) * (self.Separator in order) + \
                    order
        if not separators:
            order = [e for e in order if e is not self.Separator]
        self.order = order
        self.valid_types = valid_types
        self.alphabetical = alphabetical
        self.skip_hidden_vars = skip_hidden_vars
        self._within_set_domain = False
        self.set_domain(None)

    def set_domain(self, domain):
        self.beginResetModel()
        content = []
        # The logic related to separators is a bit complicated: it ensures that
        # even when a section is empty we don't have two separators in a row
        # or a separator at the end
        add_separator = False
        for section in self.order:
            if section is self.Separator:
                add_separator = True
                continue
            if isinstance(section, int):
                if domain is None:
                    continue
                to_add = list(chain(
                    *(vars for i, vars in enumerate(
                        (domain.attributes, domain.class_vars, domain.metas))
                      if (1 << i) & section)))
                if self.skip_hidden_vars:
                    to_add = list(filter_visible(to_add))
                if self.valid_types is not None:
                    to_add = [var for var in to_add
                              if isinstance(var, self.valid_types)]
                if self.alphabetical:
                    to_add = sorted(to_add, key=lambda x: x.name)
            elif isinstance(section, list):
                to_add = section
            else:
                to_add = [section]
            if to_add:
                if add_separator and content:
                    content.append(self.Separator)
                    add_separator = False
                content += to_add
        try:
            self._within_set_domain = True
            self[:] = content
        finally:
            self._within_set_domain = False
        self.endResetModel()

    def prevent_modification(method):  # pylint: disable=no-self-argument
        @wraps(method)
        # pylint: disable=protected-access
        def e(self, *args, **kwargs):
            if self._within_set_domain:
                method(self, *args, **kwargs)
            else:
                raise TypeError(
                    "{} can be modified only by calling 'set_domain'".
                    format(type(self).__name__))
        return e

    @prevent_modification
    def extend(self, iterable):
        return super().extend(iterable)

    @prevent_modification
    def append(self, item):
        return super().append(item)

    @prevent_modification
    def insert(self, i, val):
        return super().insert(i, val)

    @prevent_modification
    def remove(self, val):
        return super().remove(val)

    @prevent_modification
    def pop(self, i):
        return super().pop(i)

    @prevent_modification
    def clear(self):
        return super().clear()

    @prevent_modification
    def __delitem__(self, s):
        return super().__delitem__(s)

    @prevent_modification
    def __setitem__(self, s, value):
        return super().__setitem__(s, value)

    @prevent_modification
    def reverse(self):
        return super().reverse()

    @prevent_modification
    def sort(self, *args, **kwargs):
        return super().sort(*args, **kwargs)

    def setData(self, index, value, role=Qt.EditRole):
        # reimplemented
        if role == Qt.EditRole:
            return False
        else:
            return super().setData(index, value, role)

    def setItemData(self, index, data):
        # reimplemented
        if Qt.EditRole in data:
            return False
        else:
            return super().setItemData(index, data)

    def insertRows(self, row, count, parent=QModelIndex()):
        # reimplemented
        return False

    def removeRows(self, row, count, parent=QModelIndex()):
        # reimplemented
        return False

_html_replace = [("<", "&lt;"), (">", "&gt;")]


def safe_text(text):
    for old, new in _html_replace:
        text = str(text).replace(old, new)
    return text


class ContinuousPalettesModel(QAbstractListModel):
    """
    Model for combo boxes
    """
    def __init__(self, parent=None, categories=None, icon_width=64):
        super().__init__(parent)
        self.icon_width = icon_width

        palettes = list(ContinuousPalettes.values())
        if categories is None:
            # Use dict, not set, to keep order of categories
            categories = dict.fromkeys(palette.category for palette in palettes)

        self.items = []
        for category in categories:
            self.items.append(category)
            self.items += [palette for palette in palettes
                           if palette.category == category]
        if len(categories) == 1:
            del self.items[0]

    def rowCount(self, parent):
        return 0 if parent.isValid() else len(self.items)

    @staticmethod
    def columnCount(parent):
        return 0 if parent.isValid() else 1

    def data(self, index, role):
        item = self.items[index.row()]
        if isinstance(item, str):
            if role in [Qt.EditRole, Qt.DisplayRole]:
                return item
        else:
            if role in [Qt.EditRole, Qt.DisplayRole]:
                return item.friendly_name
            if role == Qt.DecorationRole:
                return item.color_strip(self.icon_width, 16)
            if role == Qt.UserRole:
                return item
        return None

    def flags(self, index):
        item = self.items[index.row()]
        if isinstance(item, ContinuousPalette):
            return Qt.ItemIsEnabled | Qt.ItemIsSelectable
        else:
            return Qt.NoItemFlags

    def indexOf(self, x):
        if isinstance(x, str):
            for i, item in enumerate(self.items):
                if not isinstance(item, str) \
                        and x in (item.name, item.friendly_name):
                    return i
        elif isinstance(x, ContinuousPalette):
            return self.items.index(x)
        return None


class ListSingleSelectionModel(QItemSelectionModel):
    """ Item selection model for list item models with single selection.

    Defines signal:
        - selectedIndexChanged(QModelIndex)

    """
    selectedIndexChanged = Signal(QModelIndex)

    def __init__(self, model, parent=None):
        QItemSelectionModel.__init__(self, model, parent)
        self.selectionChanged.connect(self.onSelectionChanged)

    def onSelectionChanged(self, new, _):
        index = list(new.indexes())
        if index:
            index = index.pop()
        else:
            index = QModelIndex()

        self.selectedIndexChanged.emit(index)

    def selectedRow(self):
        """ Return QModelIndex of the selected row or invalid if no selection.
        """
        rows = self.selectedRows()
        if rows:
            return rows[0]
        else:
            return QModelIndex()

    def select(self, index, flags=QItemSelectionModel.ClearAndSelect):
        if isinstance(index, int):
            index = self.model().index(index)
        return QItemSelectionModel.select(self, index, flags)


def select_row(view, row):
    """
    Select a `row` in an item view.
    """
    selmodel = view.selectionModel()
    selmodel.select(view.model().index(row, 0),
                    QItemSelectionModel.ClearAndSelect |
                    QItemSelectionModel.Rows)


def select_rows(view, row_indices, command=QItemSelectionModel.ClearAndSelect):
    """
    Select several rows in view.

    :param QAbstractItemView view:
    :param row_indices: Integer indices of rows to select.
    :param command: QItemSelectionModel.SelectionFlags
    """
    selmodel = view.selectionModel()
    model = view.model()
    selection = QItemSelection()
    for row in row_indices:
        index = model.index(row, 0)
        selection.select(index, index)
    selmodel.select(selection, command | QItemSelectionModel.Rows)


class ModelActionsWidget(QWidget):
    def __init__(self, actions=None, parent=None,
                 direction=QBoxLayout.LeftToRight):
        QWidget.__init__(self, parent)
        self.actions = []
        self.buttons = []
        layout = QBoxLayout(direction)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        if actions is not None:
            for action in actions:
                self.addAction(action)
        self.setLayout(layout)

    def actionButton(self, action):
        if isinstance(action, QAction):
            button = QToolButton(self)
            button.setDefaultAction(action)
            return button
        elif isinstance(action, QAbstractButton):
            return action

    def insertAction(self, ind, action, *args):
        button = self.actionButton(action)
        self.layout().insertWidget(ind, button, *args)
        self.buttons.insert(ind, button)
        self.actions.insert(ind, action)
        return button

    def addAction(self, action, *args):
        return self.insertAction(-1, action, *args)


class TableModel(AbstractSortTableModel):
    """
    An adapter for using Orange.data.Table within Qt's Item View Framework.

    :param Orange.data.Table sourcedata: Source data table.
    :param QObject parent:
    """
    #: Orange.data.Value for the index.
    ValueRole = gui.TableValueRole  # next(gui.OrangeUserRole)
    #: Orange.data.Value of the row's class.
    ClassValueRole = gui.TableClassValueRole  # next(gui.OrangeUserRole)
    #: Orange.data.Variable of the column.
    VariableRole = gui.TableVariable  # next(gui.OrangeUserRole)
    #: Basic statistics of the column
    VariableStatsRole = next(gui.OrangeUserRole)
    #: The column's role (position) in the domain.
    #: One of Attribute, ClassVar or Meta
    DomainRole = next(gui.OrangeUserRole)

    #: Column domain roles
    ClassVar, Meta, Attribute = range(3)

    #: Default background color for domain roles
    ColorForRole = {
        ClassVar: QColor(160, 160, 160),
        Meta: QColor(220, 220, 200),
        Attribute: None,
    }

    #: Standard column descriptor
    Column = namedtuple(
        "Column", ["var", "role", "background", "format"])
    #: Basket column descriptor (i.e. sparse X/Y/metas/ compressed into
    #: a single column).
    Basket = namedtuple(
        "Basket", ["vars", "role", "background", "density", "format"])

    # The class uses the same names (X_density etc) as Table
    # pylint: disable=invalid-name
    def __init__(self, sourcedata, parent=None):
        super().__init__(parent)
        self.source = sourcedata
        self.domain = domain = sourcedata.domain

        self.X_density = sourcedata.X_density()
        self.Y_density = sourcedata.Y_density()
        self.M_density = sourcedata.metas_density()

        def format_sparse(vars, datagetter, instance):
            data = datagetter(instance)
            return ", ".join("{}={}".format(vars[i].name, vars[i].repr_val(v))
                             for i, v in zip(data.indices, data.data))

        def format_sparse_bool(vars, datagetter, instance):
            data = datagetter(instance)
            return ", ".join(vars[i].name for i in data.indices)

        def format_dense(var, instance):
            return str(instance[var])

        def make_basket_formater(vars, density, role):
            formater = (format_sparse if density == Storage.SPARSE
                        else format_sparse_bool)
            if role == TableModel.Attribute:
                getter = operator.attrgetter("sparse_x")
            elif role == TableModel.ClassVar:
                getter = operator.attrgetter("sparse_y")
            elif role == TableModel.Meta:
                getter = operator.attrgetter("sparse_metas")
            return partial(formater, vars, getter)

        def make_basket(vars, density, role):
            return TableModel.Basket(
                vars, TableModel.Attribute, self.ColorForRole[role], density,
                make_basket_formater(vars, density, role)
            )

        def make_column(var, role):
            return TableModel.Column(
                var, role, self.ColorForRole[role],
                partial(format_dense, var)
            )

        columns = []

        if self.Y_density != Storage.DENSE and domain.class_vars:
            coldesc = make_basket(domain.class_vars, self.Y_density,
                                  TableModel.ClassVar)
            columns.append(coldesc)
        else:
            columns += [make_column(var, TableModel.ClassVar)
                        for var in domain.class_vars]

        if self.M_density != Storage.DENSE and domain.metas:
            coldesc = make_basket(domain.metas, self.M_density,
                                  TableModel.Meta)
            columns.append(coldesc)
        else:
            columns += [make_column(var, TableModel.Meta)
                        for var in domain.metas]

        if self.X_density != Storage.DENSE and domain.attributes:
            coldesc = make_basket(domain.attributes, self.X_density,
                                  TableModel.Attribute)
            columns.append(coldesc)
        else:
            columns += [make_column(var, TableModel.Attribute)
                        for var in domain.attributes]

        #: list of all domain variables (class_vars + metas + attrs)
        self.vars = domain.class_vars + domain.metas + domain.attributes
        self.columns = columns

        #: A list of all unique attribute labels (in all variables)
        self._labels = sorted(
            reduce(operator.ior,
                   [set(var.attributes) for var in self.vars],
                   set()))

        @lru_cache(maxsize=1000)
        def row_instance(index):
            return self.source[int(index)]
        self._row_instance = row_instance

        # column basic statistics (VariableStatsRole), computed when
        # first needed.
        self.__stats = None
        self.__rowCount = sourcedata.approx_len()
        self.__columnCount = len(self.columns)

        if self.__rowCount > (2 ** 31 - 1):
            raise ValueError("len(sourcedata) > 2 ** 31 - 1")

    def sortColumnData(self, column):
        return self._columnSortKeyData(column, TableModel.ValueRole)

    @deprecated('Orange.widgets.utils.itemmodels.TableModel.sortColumnData')
    def columnSortKeyData(self, column, role):
        return self._columnSortKeyData(column, role)

    def _columnSortKeyData(self, column, role):
        """
        Return a sequence of source table objects which can be used as
        `keys` for sorting.

        :param int column: Sort column.
        :param Qt.ItemRole role: Sort item role.

        """
        coldesc = self.columns[column]
        if isinstance(coldesc, TableModel.Column) \
                and role == TableModel.ValueRole:
            col_data = numpy.asarray(self.source.get_column_view(coldesc.var)[0])

            if coldesc.var.is_continuous:
                # continuous from metas have dtype object; cast it to float
                col_data = col_data.astype(float)
            return col_data
        else:
            return numpy.asarray([self.index(i, column).data(role)
                                  for i in range(self.rowCount())])

    def data(self, index, role,
             # For optimizing out LOAD_GLOBAL byte code instructions in
             # the item role tests.
             _str=str,
             _Qt_DisplayRole=Qt.DisplayRole,
             _Qt_EditRole=Qt.EditRole,
             _Qt_BackgroundRole=Qt.BackgroundRole,
             _ValueRole=ValueRole,
             _ClassValueRole=ClassValueRole,
             _VariableRole=VariableRole,
             _DomainRole=DomainRole,
             _VariableStatsRole=VariableStatsRole,
             # Some cached local precomputed values.
             # All of the above roles we respond to
             _recognizedRoles=frozenset([Qt.DisplayRole,
                                         Qt.EditRole,
                                         Qt.BackgroundRole,
                                         ValueRole,
                                         ClassValueRole,
                                         VariableRole,
                                         DomainRole,
                                         VariableStatsRole])):
        """
        Reimplemented from `QAbstractItemModel.data`
        """
        if role not in _recognizedRoles:
            return None

        row, col = index.row(), index.column()
        if  not 0 <= row <= self.__rowCount:
            return None

        row = self.mapToSourceRows(row)

        try:
            instance = self._row_instance(row)
        except IndexError:
            self.layoutAboutToBeChanged.emit()
            self.beginRemoveRows(self.parent(), row, max(self.rowCount(), row))
            self.__rowCount = min(row, self.__rowCount)
            self.endRemoveRows()
            self.layoutChanged.emit()
            return None
        coldesc = self.columns[col]

        if role == _Qt_DisplayRole:
            return coldesc.format(instance)
        elif role == _Qt_EditRole and isinstance(coldesc, TableModel.Column):
            return instance[coldesc.var]
        elif role == _Qt_BackgroundRole:
            return coldesc.background
        elif role == _ValueRole and isinstance(coldesc, TableModel.Column):
            return instance[coldesc.var]
        elif role == _ClassValueRole:
            try:
                return instance.get_class()
            except TypeError:
                return None
        elif role == _VariableRole and isinstance(coldesc, TableModel.Column):
            return coldesc.var
        elif role == _DomainRole:
            return coldesc.role
        elif role == _VariableStatsRole:
            return self._stats_for_column(col)
        else:
            return None

    def setData(self, index, value, role):
        row = self.mapFromSourceRows(index.row())
        if role == Qt.EditRole:
            try:
                self.source[row, index.column()] = value
            except (TypeError, IndexError):
                return False
            else:
                self.dataChanged.emit(index, index)
                return True
        else:
            return False

    def parent(self, index=QModelIndex()):
        """Reimplemented from `QAbstractTableModel.parent`."""
        return QModelIndex()

    def rowCount(self, parent=QModelIndex()):
        """Reimplemented from `QAbstractTableModel.rowCount`."""
        return 0 if parent.isValid() else self.__rowCount

    def columnCount(self, parent=QModelIndex()):
        """Reimplemented from `QAbstractTableModel.columnCount`."""
        return 0 if parent.isValid() else self.__columnCount

    def headerData(self, section, orientation, role):
        """Reimplemented from `QAbstractTableModel.headerData`."""
        if orientation == Qt.Vertical:
            if role == Qt.DisplayRole:
                return int(self.mapToSourceRows(section) + 1)
            return None

        coldesc = self.columns[section]
        if role == Qt.DisplayRole:
            if isinstance(coldesc, TableModel.Basket):
                return "{...}"
            else:
                return coldesc.var.name
        elif role == Qt.ToolTipRole:
            return self._tooltip(coldesc)
        elif role == TableModel.VariableRole \
                and isinstance(coldesc, TableModel.Column):
            return coldesc.var
        elif role == TableModel.VariableStatsRole:
            return self._stats_for_column(section)
        elif role == TableModel.DomainRole:
            return coldesc.role
        else:
            return None

    def _tooltip(self, coldesc):
        """
        Return an header tool tip text for an `column` descriptor.
        """
        if isinstance(coldesc, TableModel.Basket):
            return None

        labels = self._labels
        variable = coldesc.var
        pairs = [(escape(key), escape(str(variable.attributes[key])))
                 for key in labels if key in variable.attributes]
        tip = "<b>%s</b>" % escape(variable.name)
        tip = "<br/>".join([tip] + ["%s = %s" % pair for pair in pairs])
        return tip

    def _stats_for_column(self, column):
        """
        Return BasicStats for `column` index.
        """
        coldesc = self.columns[column]
        if isinstance(coldesc, TableModel.Basket):
            return None

        if self.__stats is None:
            self.__stats = datacaching.getCached(
                self.source, basic_stats.DomainBasicStats,
                (self.source, True)
            )

        return self.__stats[coldesc.var]

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** Slice assignment in PyTableModel does not correctly update table rows

**Description:**
When assigning a list of items to a slice of the `PyTableModel`, the table does not update the rows as expected. This leads to an inconsistent state where the number of rows does not match the intended assignment.

**Example Code:**
```python
model = PyTableModel([[1, 4], [2, 3]])
model[:1] = [[10, 11], [12, 13], [14, 15]]
print(list(model))
# Expected output: [[10, 11], [12, 13], [14, 15], [2, 3]]
```

**Expected Behavior:**
After assigning to the slice, the model should correctly insert the new rows, resulting in four rows as specified:
```
[[10, 11], [12, 13], [14, 15], [2, 3]]
```

**Actual Behavior:**
Only three rows are present after the assignment, missing the last expected row:
```
[[10, 11], [12, 13], [14, 15]]
```
This discrepancy causes operations that rely on the correct number of rows to fail or behave unexpectedly.

[/ISSUE]
{
    "TestUtils.test_as_contiguous_range": "PASSED",
    "TestPyTableModel.test_append": "PASSED",
    "TestPyTableModel.test_clear": "PASSED",
    "TestPyTableModel.test_columnCount": "PASSED",
    "TestPyTableModel.test_data": "PASSED",
    "TestPyTableModel.test_editable": "PASSED",
    "TestPyTableModel.test_emits_column_changes_on_row_insert": "PASSED",
    "TestPyTableModel.test_extend": "PASSED",
    "TestPyTableModel.test_init": "PASSED",
    "TestPyTableModel.test_insert": "PASSED",
    "TestPyTableModel.test_insertColumns": "PASSED",
    "TestPyTableModel.test_insertRows": "PASSED",
    "TestPyTableModel.test_other_roles": "PASSED",
    "TestPyTableModel.test_remove": "PASSED",
    "TestPyTableModel.test_removeColumns": "PASSED",
    "TestPyTableModel.test_removeRows": "PASSED",
    "TestPyTableModel.test_rowCount": "PASSED",
    "TestPyTableModel.test_setHeaderLabels": "PASSED",
    "TestPyTableModel.test_set_iten_slice": "PASSED",
    "TestPyTableModel.test_sort": "PASSED",
    "TestPyTableModel.test_wrap": "PASSED",
    "TestVariableListModel.test_displayrole": "PASSED",
    "TestVariableListModel.test_invalid_index": "PASSED",
    "TestVariableListModel.test_other_roles": "PASSED",
    "TestVariableListModel.test_placeholder": "PASSED",
    "TestVariableListModel.test_table_variable": "PASSED",
    "TestVariableListModel.test_tooltip": "PASSED",
    "TestDomainModel.test_filtering": "PASSED",
    "TestDomainModel.test_init_with_single_section": "PASSED",
    "TestDomainModel.test_no_separators": "PASSED",
    "TestDomainModel.test_placeholder_placement": "PASSED",
    "TestDomainModel.test_read_only": "PASSED",
    "TestDomainModel.test_separators": "PASSED",
    "TestDomainModel.test_subparts": "PASSED",
    "TestContinuousPalettesModel.testIndexOf": "PASSED",
    "TestContinuousPalettesModel.test_all_categories": "PASSED",
    "TestContinuousPalettesModel.test_category_selection": "PASSED",
    "TestContinuousPalettesModel.test_count": "PASSED",
    "TestContinuousPalettesModel.test_data": "PASSED",
    "TestContinuousPalettesModel.test_select_flags": "PASSED",
    "TestContinuousPalettesModel.test_single_category": "PASSED"
}
diff --git a/Orange/widgets/utils/itemmodels.py b/Orange/widgets/utils/itemmodels.py
index cc94e18fb..9d15f776f 100644
--- a/Orange/widgets/utils/itemmodels.py
+++ b/Orange/widgets/utils/itemmodels.py
@@ -281,7 +281,7 @@ class PyTableModel(AbstractSortTableModel):
             start, stop, _ = _as_contiguous_range(i, len(self))
             self.removeRows(start, stop - start)
             self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)
-            self._table[start:start + len(value)] = value
+            self._table[start:start] = value
             self._rows = self._table_dim()[0]
             self.endInsertRows()
             self._update_column_count()

{"Orange/widgets/utils/itemmodels.py": "from numbers import Number, Integral\nfrom math import isnan, isinf\n\nimport operator\nfrom collections import namedtuple, Sequence, defaultdict\nfrom contextlib import contextmanager\nfrom functools import reduce, partial, lru_cache, wraps\nfrom itertools import chain\nfrom warnings import warn\nfrom xml.sax.saxutils import escape\n\nfrom AnyQt.QtCore import (\n    Qt, QObject, QAbstractListModel, QModelIndex,\n    QItemSelectionModel, QItemSelection)\nfrom AnyQt.QtCore import pyqtSignal as Signal\nfrom AnyQt.QtGui import QColor\nfrom AnyQt.QtWidgets import (\n    QWidget, QBoxLayout, QToolButton, QAbstractButton, QAction\n)\n\nimport numpy\n\nfrom orangewidget.utils.itemmodels import (\n    PyListModel, AbstractSortTableModel as _AbstractSortTableModel\n)\n\nfrom Orange.widgets.utils.colorpalettes import ContinuousPalettes, ContinuousPalette\nfrom Orange.data import Variable, Storage, DiscreteVariable, ContinuousVariable\nfrom Orange.data.domain import filter_visible\nfrom Orange.widgets import gui\nfrom Orange.widgets.utils import datacaching\nfrom Orange.statistics import basic_stats\nfrom Orange.util import deprecated\n\n__all__ = [\n    \"PyListModel\", \"VariableListModel\", \"PyListModelTooltip\", \"DomainModel\",\n    \"AbstractSortTableModel\", \"PyTableModel\", \"TableModel\",\n    \"ModelActionsWidget\", \"ListSingleSelectionModel\"\n]\n\n@contextmanager\ndef signal_blocking(obj):\n    blocked = obj.signalsBlocked()\n    obj.blockSignals(True)\n    try:\n        yield\n    finally:\n        obj.blockSignals(blocked)\n\n\ndef _as_contiguous_range(the_slice, length):\n    start, stop, step = the_slice.indices(length)\n    if step == -1:\n        # Equivalent range with positive step\n        start, stop, step = stop + 1, start + 1, 1\n    elif not (step == 1 or step is None):\n        raise IndexError(\"Non-contiguous range.\")\n    return start, stop, step\n\n\nclass AbstractSortTableModel(_AbstractSortTableModel):\n    # these were defined on TableModel below. When the AbstractSortTableModel\n    # was extracted and made a base of TableModel these deprecations were\n    # misplaced, they belong in TableModel.\n    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapFromSourceRows')\n    def mapFromTableRows(self, rows):\n        return self.mapFromSourceRows(rows)\n\n    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapToSourceRows')\n    def mapToTableRows(self, rows):\n        return self.mapToSourceRows(rows)\n\n\nclass PyTableModel(AbstractSortTableModel):\n    \"\"\" A model for displaying python tables (sequences of sequences) in\n    QTableView objects.\n\n    Parameters\n    ----------\n    sequence : list\n        The initial list to wrap.\n    parent : QObject\n        Parent QObject.\n    editable: bool or sequence\n        If True, all items are flagged editable. If sequence, the True-ish\n        fields mark their respective columns editable.\n\n    Notes\n    -----\n    The model rounds numbers to human readable precision, e.g.:\n    1.23e-04, 1.234, 1234.5, 12345, 1.234e06.\n\n    To set additional item roles, use setData().\n    \"\"\"\n\n    @staticmethod\n    def _RoleData():\n        return defaultdict(lambda: defaultdict(dict))\n\n    # All methods are either necessary overrides of super methods, or\n    # methods likened to the Python list's. Hence, docstrings aren't.\n    # pylint: disable=missing-docstring\n    def __init__(self, sequence=None, parent=None, editable=False):\n        super().__init__(parent)\n        self._rows = self._cols = 0\n        self._headers = {}\n        self._editable = editable\n        self._table = None\n        self._roleData = {}\n        self.wrap(sequence or [])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._rows\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self._cols\n\n    def flags(self, index):\n        flags = super().flags(index)\n        if not self._editable or not index.isValid():\n            return flags\n        if isinstance(self._editable, Sequence):\n            return flags | Qt.ItemIsEditable if self._editable[index.column()] else flags\n        return flags | Qt.ItemIsEditable\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            self[row][index.column()] = value\n            self.dataChanged.emit(index, index)\n        else:\n            self._roleData[row][index.column()][role] = value\n        return True\n\n    def data(self, index, role=Qt.DisplayRole):\n        if not index.isValid():\n            return\n\n        row, column = self.mapToSourceRows(index.row()), index.column()\n\n        role_value = self._roleData.get(row, {}).get(column, {}).get(role)\n        if role_value is not None:\n            return role_value\n\n        try:\n            value = self[row][column]\n        except IndexError:\n            return\n        if role == Qt.EditRole:\n            return value\n        if role == Qt.DecorationRole and isinstance(value, Variable):\n            return gui.attributeIconDict[value]\n        if role == Qt.DisplayRole:\n            if (isinstance(value, Number) and\n                    not (isnan(value) or isinf(value) or isinstance(value, Integral))):\n                absval = abs(value)\n                strlen = len(str(int(absval)))\n                value = '{:.{}{}}'.format(value,\n                                          2 if absval < .001 else\n                                          3 if strlen < 2 else\n                                          1 if strlen < 5 else\n                                          0 if strlen < 6 else\n                                          3,\n                                          'f' if (absval == 0 or\n                                                  absval >= .001 and\n                                                  strlen < 6)\n                                          else 'e')\n            return str(value)\n        if role == Qt.TextAlignmentRole and isinstance(value, Number):\n            return Qt.AlignRight | Qt.AlignVCenter\n        if role == Qt.ToolTipRole:\n            return str(value)\n\n    def sortColumnData(self, column):\n        return [row[column] for row in self._table]\n\n    def setHorizontalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Horizontal] = tuple(labels)\n\n    def setVerticalHeaderLabels(self, labels):\n        \"\"\"\n        Parameters\n        ----------\n        labels : list of str or list of Variable\n        \"\"\"\n        self._headers[Qt.Vertical] = tuple(labels)\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        headers = self._headers.get(orientation)\n\n        if headers and section < len(headers):\n            section = self.mapToSourceRows(section) if orientation == Qt.Vertical else section\n            value = headers[section]\n\n            if role == Qt.ToolTipRole:\n                role = Qt.DisplayRole\n\n            if role == Qt.DisplayRole:\n                return value.name if isinstance(value, Variable) else value\n\n            if role == Qt.DecorationRole:\n                if isinstance(value, Variable):\n                    return gui.attributeIconDict[value]\n\n        # Use QAbstractItemModel default for non-existent header/sections\n        return super().headerData(section, orientation, role)\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        if not parent.isValid():\n            del self[row:row + count]\n            for rowidx in range(row, row + count):\n                self._roleData.pop(rowidx, None)\n            self._rows = self._table_dim()[0]\n            return True\n        return False\n\n    def removeColumns(self, column, count, parent=QModelIndex()):\n        self.beginRemoveColumns(parent, column, column + count - 1)\n        for row in self._table:\n            del row[column:column + count]\n        for cols in self._roleData.values():\n            for col in range(column, column + count):\n                cols.pop(col, None)\n        del self._headers.get(Qt.Horizontal, [])[column:column + count]\n        self._cols = self._table_dim()[1]\n        self.endRemoveColumns()\n        return True\n\n    def _table_dim(self):\n        return len(self._table), max(map(len, self), default=0)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        self.beginInsertRows(parent, row, row + count - 1)\n        self._table[row:row] = [[''] * self.columnCount() for _ in range(count)]\n        self._rows = self._table_dim()[0]\n        self.endInsertRows()\n        return True\n\n    def insertColumns(self, column, count, parent=QModelIndex()):\n        self.beginInsertColumns(parent, column, column + count - 1)\n        for row in self._table:\n            row[column:column] = [''] * count\n        self._rows = self._table_dim()[0]\n        self.endInsertColumns()\n        return True\n\n    def __len__(self):\n        return len(self._table)\n\n    def __bool__(self):\n        return len(self) != 0\n\n    def __iter__(self):\n        return iter(self._table)\n\n    def __getitem__(self, item):\n        return self._table[item]\n\n    def __delitem__(self, i):\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            stop -= 1\n        else:\n            start = stop = i = i if i >= 0 else len(self) + i\n        self._check_sort_order()\n        self.beginRemoveRows(QModelIndex(), start, stop)\n        del self._table[i]\n        rows = self._table_dim()[0]\n        self._rows = rows\n        self.endRemoveRows()\n        self._update_column_count()\n\n    def __setitem__(self, i, value):\n        self._check_sort_order()\n        if isinstance(i, slice):\n            start, stop, _ = _as_contiguous_range(i, len(self))\n            self.removeRows(start, stop - start)\n            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)\n            self._table[start:start + len(value)] = value\n            self._rows = self._table_dim()[0]\n            self.endInsertRows()\n            self._update_column_count()\n        else:\n            self._table[i] = value\n            self.dataChanged.emit(self.index(i, 0),\n                                  self.index(i, self.columnCount() - 1))\n\n    def _update_column_count(self):\n        cols_before = self._cols\n        cols_after = self._table_dim()[1]\n        if cols_before < cols_after:\n            self.beginInsertColumns(QModelIndex(), cols_before, cols_after - 1)\n            self._cols = cols_after\n            self.endInsertColumns()\n        elif cols_before > cols_after:\n            self.beginRemoveColumns(QModelIndex(), cols_after, cols_before - 1)\n            self._cols = cols_after\n            self.endRemoveColumns()\n\n    def _check_sort_order(self):\n        if self.mapToSourceRows(Ellipsis) is not Ellipsis:\n            warn(\"Can't modify PyTableModel when it's sorted\",\n                 RuntimeWarning, stacklevel=3)\n            raise RuntimeError(\"Can't modify PyTableModel when it's sorted\")\n\n    def wrap(self, table):\n        self.beginResetModel()\n        self._table = table\n        self._roleData = self._RoleData()\n        self._rows, self._cols = self._table_dim()\n        self.resetSorting()\n        self.endResetModel()\n\n    def tolist(self):\n        return self._table\n\n    def clear(self):\n        self.beginResetModel()\n        self._table.clear()\n        self.resetSorting()\n        self._roleData.clear()\n        self._rows, self._cols = self._table_dim()\n        self.endResetModel()\n\n    def append(self, row):\n        self.extend([row])\n\n    def _insertColumns(self, rows):\n        n_max = max(map(len, rows))\n        if self.columnCount() < n_max:\n            self.insertColumns(self.columnCount(), n_max - self.columnCount())\n\n    def extend(self, rows):\n        i, rows = len(self), list(rows)\n        self.insertRows(i, len(rows))\n        self._insertColumns(rows)\n        self[i:] = rows\n\n    def insert(self, i, row):\n        self.insertRows(i, 1)\n        self._insertColumns((row,))\n        self[i] = row\n\n    def remove(self, val):\n        del self[self._table.index(val)]\n\n\nclass PyListModelTooltip(PyListModel):\n    def __init__(self):\n        super().__init__()\n        self.tooltips = []\n\n    def data(self, index, role=Qt.DisplayRole):\n        if role == Qt.ToolTipRole:\n            return self.tooltips[index.row()]\n        else:\n            return super().data(index, role)\n\n\nclass VariableListModel(PyListModel):\n    MIME_TYPE = \"application/x-Orange-VariableList\"\n\n    def __init__(self, *args, placeholder=None, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.placeholder = placeholder\n\n    def data(self, index, role=Qt.DisplayRole):\n        if self._is_index_valid(index):\n            var = self[index.row()]\n            if var is None and role == Qt.DisplayRole:\n                return self.placeholder or \"None\"\n            if not isinstance(var, Variable):\n                return super().data(index, role)\n            elif role == Qt.DisplayRole:\n                return var.name\n            elif role == Qt.DecorationRole:\n                return gui.attributeIconDict[var]\n            elif role == Qt.ToolTipRole:\n                return self.variable_tooltip(var)\n            elif role == gui.TableVariable:\n                return var\n            else:\n                return PyListModel.data(self, index, role)\n\n    def variable_tooltip(self, var):\n        if var.is_discrete:\n            return self.discrete_variable_tooltip(var)\n        elif var.is_time:\n            return self.time_variable_toltip(var)\n        elif var.is_continuous:\n            return self.continuous_variable_toltip(var)\n        elif var.is_string:\n            return self.string_variable_tooltip(var)\n\n    def variable_labels_tooltip(self, var):\n        text = \"\"\n        if var.attributes:\n            items = [(safe_text(key), safe_text(value))\n                     for key, value in var.attributes.items()]\n            labels = list(map(\"%s = %s\".__mod__, items))\n            text += \"<br/>Variable Labels:<br/>\"\n            text += \"<br/>\".join(labels)\n        return text\n\n    def discrete_variable_tooltip(self, var):\n        text = \"<b>%s</b><br/>Categorical with %i values: \" %\\\n               (safe_text(var.name), len(var.values))\n        text += \", \".join(\"%r\" % safe_text(v) for v in var.values)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def time_variable_toltip(self, var):\n        text = \"<b>%s</b><br/>Time\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def continuous_variable_toltip(self, var):\n        text = \"<b>%s</b><br/>Numeric\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n    def string_variable_tooltip(self, var):\n        text = \"<b>%s</b><br/>Text\" % safe_text(var.name)\n        text += self.variable_labels_tooltip(var)\n        return text\n\n\nclass DomainModel(VariableListModel):\n    ATTRIBUTES, CLASSES, METAS = 1, 2, 4\n    MIXED = ATTRIBUTES | CLASSES | METAS\n    SEPARATED = (CLASSES, PyListModel.Separator,\n                 METAS, PyListModel.Separator,\n                 ATTRIBUTES)\n    PRIMITIVE = (DiscreteVariable, ContinuousVariable)\n\n    def __init__(self, order=SEPARATED, separators=True, placeholder=None,\n                 valid_types=None, alphabetical=False, skip_hidden_vars=True, **kwargs):\n        \"\"\"\n\n        Parameters\n        ----------\n        order: tuple or int\n            Order of attributes, metas, classes, separators and other options\n        separators: bool\n            If False, remove separators from `order`.\n        placeholder: str\n            The text that is shown when no variable is selected\n        valid_types: tuple\n            (Sub)types of `Variable` that are included in the model\n        alphabetical: bool\n            If true, variables are sorted alphabetically.\n        skip_hidden_vars: bool\n            If true, variables marked as \"hidden\" are skipped.\n        \"\"\"\n        super().__init__(placeholder=placeholder, **kwargs)\n        if isinstance(order, int):\n            order = (order,)\n        if placeholder is not None and None not in order:\n            # Add None for the placeholder if it's not already there\n            # Include separator if the current order uses them\n            order = (None,) + \\\n                    (self.Separator, ) * (self.Separator in order) + \\\n                    order\n        if not separators:\n            order = [e for e in order if e is not self.Separator]\n        self.order = order\n        self.valid_types = valid_types\n        self.alphabetical = alphabetical\n        self.skip_hidden_vars = skip_hidden_vars\n        self._within_set_domain = False\n        self.set_domain(None)\n\n    def set_domain(self, domain):\n        self.beginResetModel()\n        content = []\n        # The logic related to separators is a bit complicated: it ensures that\n        # even when a section is empty we don't have two separators in a row\n        # or a separator at the end\n        add_separator = False\n        for section in self.order:\n            if section is self.Separator:\n                add_separator = True\n                continue\n            if isinstance(section, int):\n                if domain is None:\n                    continue\n                to_add = list(chain(\n                    *(vars for i, vars in enumerate(\n                        (domain.attributes, domain.class_vars, domain.metas))\n                      if (1 << i) & section)))\n                if self.skip_hidden_vars:\n                    to_add = list(filter_visible(to_add))\n                if self.valid_types is not None:\n                    to_add = [var for var in to_add\n                              if isinstance(var, self.valid_types)]\n                if self.alphabetical:\n                    to_add = sorted(to_add, key=lambda x: x.name)\n            elif isinstance(section, list):\n                to_add = section\n            else:\n                to_add = [section]\n            if to_add:\n                if add_separator and content:\n                    content.append(self.Separator)\n                    add_separator = False\n                content += to_add\n        try:\n            self._within_set_domain = True\n            self[:] = content\n        finally:\n            self._within_set_domain = False\n        self.endResetModel()\n\n    def prevent_modification(method):  # pylint: disable=no-self-argument\n        @wraps(method)\n        # pylint: disable=protected-access\n        def e(self, *args, **kwargs):\n            if self._within_set_domain:\n                method(self, *args, **kwargs)\n            else:\n                raise TypeError(\n                    \"{} can be modified only by calling 'set_domain'\".\n                    format(type(self).__name__))\n        return e\n\n    @prevent_modification\n    def extend(self, iterable):\n        return super().extend(iterable)\n\n    @prevent_modification\n    def append(self, item):\n        return super().append(item)\n\n    @prevent_modification\n    def insert(self, i, val):\n        return super().insert(i, val)\n\n    @prevent_modification\n    def remove(self, val):\n        return super().remove(val)\n\n    @prevent_modification\n    def pop(self, i):\n        return super().pop(i)\n\n    @prevent_modification\n    def clear(self):\n        return super().clear()\n\n    @prevent_modification\n    def __delitem__(self, s):\n        return super().__delitem__(s)\n\n    @prevent_modification\n    def __setitem__(self, s, value):\n        return super().__setitem__(s, value)\n\n    @prevent_modification\n    def reverse(self):\n        return super().reverse()\n\n    @prevent_modification\n    def sort(self, *args, **kwargs):\n        return super().sort(*args, **kwargs)\n\n    def setData(self, index, value, role=Qt.EditRole):\n        # reimplemented\n        if role == Qt.EditRole:\n            return False\n        else:\n            return super().setData(index, value, role)\n\n    def setItemData(self, index, data):\n        # reimplemented\n        if Qt.EditRole in data:\n            return False\n        else:\n            return super().setItemData(index, data)\n\n    def insertRows(self, row, count, parent=QModelIndex()):\n        # reimplemented\n        return False\n\n    def removeRows(self, row, count, parent=QModelIndex()):\n        # reimplemented\n        return False\n\n_html_replace = [(\"<\", \"&lt;\"), (\">\", \"&gt;\")]\n\n\ndef safe_text(text):\n    for old, new in _html_replace:\n        text = str(text).replace(old, new)\n    return text\n\n\nclass ContinuousPalettesModel(QAbstractListModel):\n    \"\"\"\n    Model for combo boxes\n    \"\"\"\n    def __init__(self, parent=None, categories=None, icon_width=64):\n        super().__init__(parent)\n        self.icon_width = icon_width\n\n        palettes = list(ContinuousPalettes.values())\n        if categories is None:\n            # Use dict, not set, to keep order of categories\n            categories = dict.fromkeys(palette.category for palette in palettes)\n\n        self.items = []\n        for category in categories:\n            self.items.append(category)\n            self.items += [palette for palette in palettes\n                           if palette.category == category]\n        if len(categories) == 1:\n            del self.items[0]\n\n    def rowCount(self, parent):\n        return 0 if parent.isValid() else len(self.items)\n\n    @staticmethod\n    def columnCount(parent):\n        return 0 if parent.isValid() else 1\n\n    def data(self, index, role):\n        item = self.items[index.row()]\n        if isinstance(item, str):\n            if role in [Qt.EditRole, Qt.DisplayRole]:\n                return item\n        else:\n            if role in [Qt.EditRole, Qt.DisplayRole]:\n                return item.friendly_name\n            if role == Qt.DecorationRole:\n                return item.color_strip(self.icon_width, 16)\n            if role == Qt.UserRole:\n                return item\n        return None\n\n    def flags(self, index):\n        item = self.items[index.row()]\n        if isinstance(item, ContinuousPalette):\n            return Qt.ItemIsEnabled | Qt.ItemIsSelectable\n        else:\n            return Qt.NoItemFlags\n\n    def indexOf(self, x):\n        if isinstance(x, str):\n            for i, item in enumerate(self.items):\n                if not isinstance(item, str) \\\n                        and x in (item.name, item.friendly_name):\n                    return i\n        elif isinstance(x, ContinuousPalette):\n            return self.items.index(x)\n        return None\n\n\nclass ListSingleSelectionModel(QItemSelectionModel):\n    \"\"\" Item selection model for list item models with single selection.\n\n    Defines signal:\n        - selectedIndexChanged(QModelIndex)\n\n    \"\"\"\n    selectedIndexChanged = Signal(QModelIndex)\n\n    def __init__(self, model, parent=None):\n        QItemSelectionModel.__init__(self, model, parent)\n        self.selectionChanged.connect(self.onSelectionChanged)\n\n    def onSelectionChanged(self, new, _):\n        index = list(new.indexes())\n        if index:\n            index = index.pop()\n        else:\n            index = QModelIndex()\n\n        self.selectedIndexChanged.emit(index)\n\n    def selectedRow(self):\n        \"\"\" Return QModelIndex of the selected row or invalid if no selection.\n        \"\"\"\n        rows = self.selectedRows()\n        if rows:\n            return rows[0]\n        else:\n            return QModelIndex()\n\n    def select(self, index, flags=QItemSelectionModel.ClearAndSelect):\n        if isinstance(index, int):\n            index = self.model().index(index)\n        return QItemSelectionModel.select(self, index, flags)\n\n\ndef select_row(view, row):\n    \"\"\"\n    Select a `row` in an item view.\n    \"\"\"\n    selmodel = view.selectionModel()\n    selmodel.select(view.model().index(row, 0),\n                    QItemSelectionModel.ClearAndSelect |\n                    QItemSelectionModel.Rows)\n\n\ndef select_rows(view, row_indices, command=QItemSelectionModel.ClearAndSelect):\n    \"\"\"\n    Select several rows in view.\n\n    :param QAbstractItemView view:\n    :param row_indices: Integer indices of rows to select.\n    :param command: QItemSelectionModel.SelectionFlags\n    \"\"\"\n    selmodel = view.selectionModel()\n    model = view.model()\n    selection = QItemSelection()\n    for row in row_indices:\n        index = model.index(row, 0)\n        selection.select(index, index)\n    selmodel.select(selection, command | QItemSelectionModel.Rows)\n\n\nclass ModelActionsWidget(QWidget):\n    def __init__(self, actions=None, parent=None,\n                 direction=QBoxLayout.LeftToRight):\n        QWidget.__init__(self, parent)\n        self.actions = []\n        self.buttons = []\n        layout = QBoxLayout(direction)\n        layout.setContentsMargins(0, 0, 0, 0)\n        self.setContentsMargins(0, 0, 0, 0)\n        self.setLayout(layout)\n        if actions is not None:\n            for action in actions:\n                self.addAction(action)\n        self.setLayout(layout)\n\n    def actionButton(self, action):\n        if isinstance(action, QAction):\n            button = QToolButton(self)\n            button.setDefaultAction(action)\n            return button\n        elif isinstance(action, QAbstractButton):\n            return action\n\n    def insertAction(self, ind, action, *args):\n        button = self.actionButton(action)\n        self.layout().insertWidget(ind, button, *args)\n        self.buttons.insert(ind, button)\n        self.actions.insert(ind, action)\n        return button\n\n    def addAction(self, action, *args):\n        return self.insertAction(-1, action, *args)\n\n\nclass TableModel(AbstractSortTableModel):\n    \"\"\"\n    An adapter for using Orange.data.Table within Qt's Item View Framework.\n\n    :param Orange.data.Table sourcedata: Source data table.\n    :param QObject parent:\n    \"\"\"\n    #: Orange.data.Value for the index.\n    ValueRole = gui.TableValueRole  # next(gui.OrangeUserRole)\n    #: Orange.data.Value of the row's class.\n    ClassValueRole = gui.TableClassValueRole  # next(gui.OrangeUserRole)\n    #: Orange.data.Variable of the column.\n    VariableRole = gui.TableVariable  # next(gui.OrangeUserRole)\n    #: Basic statistics of the column\n    VariableStatsRole = next(gui.OrangeUserRole)\n    #: The column's role (position) in the domain.\n    #: One of Attribute, ClassVar or Meta\n    DomainRole = next(gui.OrangeUserRole)\n\n    #: Column domain roles\n    ClassVar, Meta, Attribute = range(3)\n\n    #: Default background color for domain roles\n    ColorForRole = {\n        ClassVar: QColor(160, 160, 160),\n        Meta: QColor(220, 220, 200),\n        Attribute: None,\n    }\n\n    #: Standard column descriptor\n    Column = namedtuple(\n        \"Column\", [\"var\", \"role\", \"background\", \"format\"])\n    #: Basket column descriptor (i.e. sparse X/Y/metas/ compressed into\n    #: a single column).\n    Basket = namedtuple(\n        \"Basket\", [\"vars\", \"role\", \"background\", \"density\", \"format\"])\n\n    # The class uses the same names (X_density etc) as Table\n    # pylint: disable=invalid-name\n    def __init__(self, sourcedata, parent=None):\n        super().__init__(parent)\n        self.source = sourcedata\n        self.domain = domain = sourcedata.domain\n\n        self.X_density = sourcedata.X_density()\n        self.Y_density = sourcedata.Y_density()\n        self.M_density = sourcedata.metas_density()\n\n        def format_sparse(vars, datagetter, instance):\n            data = datagetter(instance)\n            return \", \".join(\"{}={}\".format(vars[i].name, vars[i].repr_val(v))\n                             for i, v in zip(data.indices, data.data))\n\n        def format_sparse_bool(vars, datagetter, instance):\n            data = datagetter(instance)\n            return \", \".join(vars[i].name for i in data.indices)\n\n        def format_dense(var, instance):\n            return str(instance[var])\n\n        def make_basket_formater(vars, density, role):\n            formater = (format_sparse if density == Storage.SPARSE\n                        else format_sparse_bool)\n            if role == TableModel.Attribute:\n                getter = operator.attrgetter(\"sparse_x\")\n            elif role == TableModel.ClassVar:\n                getter = operator.attrgetter(\"sparse_y\")\n            elif role == TableModel.Meta:\n                getter = operator.attrgetter(\"sparse_metas\")\n            return partial(formater, vars, getter)\n\n        def make_basket(vars, density, role):\n            return TableModel.Basket(\n                vars, TableModel.Attribute, self.ColorForRole[role], density,\n                make_basket_formater(vars, density, role)\n            )\n\n        def make_column(var, role):\n            return TableModel.Column(\n                var, role, self.ColorForRole[role],\n                partial(format_dense, var)\n            )\n\n        columns = []\n\n        if self.Y_density != Storage.DENSE and domain.class_vars:\n            coldesc = make_basket(domain.class_vars, self.Y_density,\n                                  TableModel.ClassVar)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.ClassVar)\n                        for var in domain.class_vars]\n\n        if self.M_density != Storage.DENSE and domain.metas:\n            coldesc = make_basket(domain.metas, self.M_density,\n                                  TableModel.Meta)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.Meta)\n                        for var in domain.metas]\n\n        if self.X_density != Storage.DENSE and domain.attributes:\n            coldesc = make_basket(domain.attributes, self.X_density,\n                                  TableModel.Attribute)\n            columns.append(coldesc)\n        else:\n            columns += [make_column(var, TableModel.Attribute)\n                        for var in domain.attributes]\n\n        #: list of all domain variables (class_vars + metas + attrs)\n        self.vars = domain.class_vars + domain.metas + domain.attributes\n        self.columns = columns\n\n        #: A list of all unique attribute labels (in all variables)\n        self._labels = sorted(\n            reduce(operator.ior,\n                   [set(var.attributes) for var in self.vars],\n                   set()))\n\n        @lru_cache(maxsize=1000)\n        def row_instance(index):\n            return self.source[int(index)]\n        self._row_instance = row_instance\n\n        # column basic statistics (VariableStatsRole), computed when\n        # first needed.\n        self.__stats = None\n        self.__rowCount = sourcedata.approx_len()\n        self.__columnCount = len(self.columns)\n\n        if self.__rowCount > (2 ** 31 - 1):\n            raise ValueError(\"len(sourcedata) > 2 ** 31 - 1\")\n\n    def sortColumnData(self, column):\n        return self._columnSortKeyData(column, TableModel.ValueRole)\n\n    @deprecated('Orange.widgets.utils.itemmodels.TableModel.sortColumnData')\n    def columnSortKeyData(self, column, role):\n        return self._columnSortKeyData(column, role)\n\n    def _columnSortKeyData(self, column, role):\n        \"\"\"\n        Return a sequence of source table objects which can be used as\n        `keys` for sorting.\n\n        :param int column: Sort column.\n        :param Qt.ItemRole role: Sort item role.\n\n        \"\"\"\n        coldesc = self.columns[column]\n        if isinstance(coldesc, TableModel.Column) \\\n                and role == TableModel.ValueRole:\n            col_data = numpy.asarray(self.source.get_column_view(coldesc.var)[0])\n\n            if coldesc.var.is_continuous:\n                # continuous from metas have dtype object; cast it to float\n                col_data = col_data.astype(float)\n            return col_data\n        else:\n            return numpy.asarray([self.index(i, column).data(role)\n                                  for i in range(self.rowCount())])\n\n    def data(self, index, role,\n             # For optimizing out LOAD_GLOBAL byte code instructions in\n             # the item role tests.\n             _str=str,\n             _Qt_DisplayRole=Qt.DisplayRole,\n             _Qt_EditRole=Qt.EditRole,\n             _Qt_BackgroundRole=Qt.BackgroundRole,\n             _ValueRole=ValueRole,\n             _ClassValueRole=ClassValueRole,\n             _VariableRole=VariableRole,\n             _DomainRole=DomainRole,\n             _VariableStatsRole=VariableStatsRole,\n             # Some cached local precomputed values.\n             # All of the above roles we respond to\n             _recognizedRoles=frozenset([Qt.DisplayRole,\n                                         Qt.EditRole,\n                                         Qt.BackgroundRole,\n                                         ValueRole,\n                                         ClassValueRole,\n                                         VariableRole,\n                                         DomainRole,\n                                         VariableStatsRole])):\n        \"\"\"\n        Reimplemented from `QAbstractItemModel.data`\n        \"\"\"\n        if role not in _recognizedRoles:\n            return None\n\n        row, col = index.row(), index.column()\n        if  not 0 <= row <= self.__rowCount:\n            return None\n\n        row = self.mapToSourceRows(row)\n\n        try:\n            instance = self._row_instance(row)\n        except IndexError:\n            self.layoutAboutToBeChanged.emit()\n            self.beginRemoveRows(self.parent(), row, max(self.rowCount(), row))\n            self.__rowCount = min(row, self.__rowCount)\n            self.endRemoveRows()\n            self.layoutChanged.emit()\n            return None\n        coldesc = self.columns[col]\n\n        if role == _Qt_DisplayRole:\n            return coldesc.format(instance)\n        elif role == _Qt_EditRole and isinstance(coldesc, TableModel.Column):\n            return instance[coldesc.var]\n        elif role == _Qt_BackgroundRole:\n            return coldesc.background\n        elif role == _ValueRole and isinstance(coldesc, TableModel.Column):\n            return instance[coldesc.var]\n        elif role == _ClassValueRole:\n            try:\n                return instance.get_class()\n            except TypeError:\n                return None\n        elif role == _VariableRole and isinstance(coldesc, TableModel.Column):\n            return coldesc.var\n        elif role == _DomainRole:\n            return coldesc.role\n        elif role == _VariableStatsRole:\n            return self._stats_for_column(col)\n        else:\n            return None\n\n    def setData(self, index, value, role):\n        row = self.mapFromSourceRows(index.row())\n        if role == Qt.EditRole:\n            try:\n                self.source[row, index.column()] = value\n            except (TypeError, IndexError):\n                return False\n            else:\n                self.dataChanged.emit(index, index)\n                return True\n        else:\n            return False\n\n    def parent(self, index=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.parent`.\"\"\"\n        return QModelIndex()\n\n    def rowCount(self, parent=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.rowCount`.\"\"\"\n        return 0 if parent.isValid() else self.__rowCount\n\n    def columnCount(self, parent=QModelIndex()):\n        \"\"\"Reimplemented from `QAbstractTableModel.columnCount`.\"\"\"\n        return 0 if parent.isValid() else self.__columnCount\n\n    def headerData(self, section, orientation, role):\n        \"\"\"Reimplemented from `QAbstractTableModel.headerData`.\"\"\"\n        if orientation == Qt.Vertical:\n            if role == Qt.DisplayRole:\n                return int(self.mapToSourceRows(section) + 1)\n            return None\n\n        coldesc = self.columns[section]\n        if role == Qt.DisplayRole:\n            if isinstance(coldesc, TableModel.Basket):\n                return \"{...}\"\n            else:\n                return coldesc.var.name\n        elif role == Qt.ToolTipRole:\n            return self._tooltip(coldesc)\n        elif role == TableModel.VariableRole \\\n                and isinstance(coldesc, TableModel.Column):\n            return coldesc.var\n        elif role == TableModel.VariableStatsRole:\n            return self._stats_for_column(section)\n        elif role == TableModel.DomainRole:\n            return coldesc.role\n        else:\n            return None\n\n    def _tooltip(self, coldesc):\n        \"\"\"\n        Return an header tool tip text for an `column` descriptor.\n        \"\"\"\n        if isinstance(coldesc, TableModel.Basket):\n            return None\n\n        labels = self._labels\n        variable = coldesc.var\n        pairs = [(escape(key), escape(str(variable.attributes[key])))\n                 for key in labels if key in variable.attributes]\n        tip = \"<b>%s</b>\" % escape(variable.name)\n        tip = \"<br/>\".join([tip] + [\"%s = %s\" % pair for pair in pairs])\n        return tip\n\n    def _stats_for_column(self, column):\n        \"\"\"\n        Return BasicStats for `column` index.\n        \"\"\"\n        coldesc = self.columns[column]\n        if isinstance(coldesc, TableModel.Basket):\n            return None\n\n        if self.__stats is None:\n            self.__stats = datacaching.getCached(\n                self.source, basic_stats.DomainBasicStats,\n                (self.source, True)\n            )\n\n        return self.__stats[coldesc.var]\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Slice assignment in PyTableModel does not correctly update table rows

**Description:**
When assigning a list of items to a slice of the `PyTableModel`, the table does not update the rows as expected. This leads to an inconsistent state where the number of rows does not match the intended assignment.

**Example Code:**
```python
model = PyTableModel([[1, 4], [2, 3]])
model[:1] = [[10, 11], [12, 13], [14, 15]]
print(list(model))
# Expected output: [[10, 11], [12, 13], [14, 15], [2, 3]]
```

**Expected Behavior:**
After assigning to the slice, the model should correctly insert the new rows, resulting in four rows as specified:
```
[[10, 11], [12, 13], [14, 15], [2, 3]]
```

**Actual Behavior:**
Only three rows are present after the assignment, missing the last expected row:
```
[[10, 11], [12, 13], [14, 15]]
```
This discrepancy causes operations that rely on the correct number of rows to fail or behave unexpectedly.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### Orange/widgets/utils/itemmodels.py
from numbers import Number, Integral
from math import isnan, isinf

import operator
from collections import namedtuple, Sequence, defaultdict
from contextlib import contextmanager
from functools import reduce, partial, lru_cache, wraps
from itertools import chain
from warnings import warn
from xml.sax.saxutils import escape

from AnyQt.QtCore import (
    Qt, QObject, QAbstractListModel, QModelIndex,
    QItemSelectionModel, QItemSelection)
from AnyQt.QtCore import pyqtSignal as Signal
from AnyQt.QtGui import QColor
from AnyQt.QtWidgets import (
    QWidget, QBoxLayout, QToolButton, QAbstractButton, QAction
)

import numpy

from orangewidget.utils.itemmodels import (
    PyListModel, AbstractSortTableModel as _AbstractSortTableModel
)

from Orange.widgets.utils.colorpalettes import ContinuousPalettes, ContinuousPalette
from Orange.data import Variable, Storage, DiscreteVariable, ContinuousVariable
from Orange.data.domain import filter_visible
from Orange.widgets import gui
from Orange.widgets.utils import datacaching
from Orange.statistics import basic_stats
from Orange.util import deprecated

__all__ = [
    "PyListModel", "VariableListModel", "PyListModelTooltip", "DomainModel",
    "AbstractSortTableModel", "PyTableModel", "TableModel",
    "ModelActionsWidget", "ListSingleSelectionModel"
]

@contextmanager
def signal_blocking(obj):
    blocked = obj.signalsBlocked()
    obj.blockSignals(True)
    try:
        yield
    finally:
        obj.blockSignals(blocked)


def _as_contiguous_range(the_slice, length):
    start, stop, step = the_slice.indices(length)
    if step == -1:
        # Equivalent range with positive step
        start, stop, step = stop + 1, start + 1, 1
    elif not (step == 1 or step is None):
        raise IndexError("Non-contiguous range.")
    return start, stop, step


class AbstractSortTableModel(_AbstractSortTableModel):
    # these were defined on TableModel below. When the AbstractSortTableModel
    # was extracted and made a base of TableModel these deprecations were
    # misplaced, they belong in TableModel.
    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapFromSourceRows')
    def mapFromTableRows(self, rows):
        return self.mapFromSourceRows(rows)

    @deprecated('Orange.widgets.utils.itemmodels.AbstractSortTableModel.mapToSourceRows')
    def mapToTableRows(self, rows):
        return self.mapToSourceRows(rows)


class PyTableModel(AbstractSortTableModel):
    """ A model for displaying python tables (sequences of sequences) in
    QTableView objects.

    Parameters
    ----------
    sequence : list
        The initial list to wrap.
    parent : QObject
        Parent QObject.
    editable: bool or sequence
        If True, all items are flagged editable. If sequence, the True-ish
        fields mark their respective columns editable.

    Notes
    -----
    The model rounds numbers to human readable precision, e.g.:
    1.23e-04, 1.234, 1234.5, 12345, 1.234e06.

    To set additional item roles, use setData().
    """

    @staticmethod
    def _RoleData():
        return defaultdict(lambda: defaultdict(dict))

    # All methods are either necessary overrides of super methods, or
    # methods likened to the Python list's. Hence, docstrings aren't.
    # pylint: disable=missing-docstring
    def __init__(self, sequence=None, parent=None, editable=False):
        super().__init__(parent)
        self._rows = self._cols = 0
        self._headers = {}
        self._editable = editable
        self._table = None
        self._roleData = {}
        self.wrap(sequence or [])

    def rowCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else self._rows

    def columnCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else self._cols

    def flags(self, index):
        flags = super().flags(index)
        if not self._editable or not index.isValid():
            return flags
        if isinstance(self._editable, Sequence):
            return flags | Qt.ItemIsEditable if self._editable[index.column()] else flags
        return flags | Qt.ItemIsEditable

    def setData(self, index, value, role):
        row = self.mapFromSourceRows(index.row())
        if role == Qt.EditRole:
            self[row][index.column()] = value
            self.dataChanged.emit(index, index)
        else:
            self._roleData[row][index.column()][role] = value
        return True

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return

        row, column = self.mapToSourceRows(index.row()), index.column()

        role_value = self._roleData.get(row, {}).get(column, {}).get(role)
        if role_value is not None:
            return role_value

        try:
            value = self[row][column]
        except IndexError:
            return
        if role == Qt.EditRole:
            return value
        if role == Qt.DecorationRole and isinstance(value, Variable):
            return gui.attributeIconDict[value]
        if role == Qt.DisplayRole:
            if (isinstance(value, Number) and
                    not (isnan(value) or isinf(value) or isinstance(value, Integral))):
                absval = abs(value)
                strlen = len(str(int(absval)))
                value = '{:.{}{}}'.format(value,
                                          2 if absval < .001 else
                                          3 if strlen < 2 else
                                          1 if strlen < 5 else
                                          0 if strlen < 6 else
                                          3,
                                          'f' if (absval == 0 or
                                                  absval >= .001 and
                                                  strlen < 6)
                                          else 'e')
            return str(value)
        if role == Qt.TextAlignmentRole and isinstance(value, Number):
            return Qt.AlignRight | Qt.AlignVCenter
        if role == Qt.ToolTipRole:
            return str(value)

    def sortColumnData(self, column):
        return [row[column] for row in self._table]

    def setHorizontalHeaderLabels(self, labels):
        """
        Parameters
        ----------
        labels : list of str or list of Variable
        """
        self._headers[Qt.Horizontal] = tuple(labels)

    def setVerticalHeaderLabels(self, labels):
        """
        Parameters
        ----------
        labels : list of str or list of Variable
        """
        self._headers[Qt.Vertical] = tuple(labels)

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        headers = self._headers.get(orientation)

        if headers and section < len(headers):
            section = self.mapToSourceRows(section) if orientation == Qt.Vertical else section
            value = headers[section]

            if role == Qt.ToolTipRole:
                role = Qt.DisplayRole

            if role == Qt.DisplayRole:
                return value.name if isinstance(value, Variable) else value

            if role == Qt.DecorationRole:
                if isinstance(value, Variable):
                    return gui.attributeIconDict[value]

        # Use QAbstractItemModel default for non-existent header/sections
        return super().headerData(section, orientation, role)

    def removeRows(self, row, count, parent=QModelIndex()):
        if not parent.isValid():
            del self[row:row + count]
            for rowidx in range(row, row + count):
                self._roleData.pop(rowidx, None)
            self._rows = self._table_dim()[0]
            return True
        return False

    def removeColumns(self, column, count, parent=QModelIndex()):
        self.beginRemoveColumns(parent, column, column + count - 1)
        for row in self._table:
            del row[column:column + count]
        for cols in self._roleData.values():
            for col in range(column, column + count):
                cols.pop(col, None)
        del self._headers.get(Qt.Horizontal, [])[column:column + count]
        self._cols = self._table_dim()[1]
        self.endRemoveColumns()
        return True

    def _table_dim(self):
        return len(self._table), max(map(len, self), default=0)

    def insertRows(self, row, count, parent=QModelIndex()):
        self.beginInsertRows(parent, row, row + count - 1)
        self._table[row:row] = [[''] * self.columnCount() for _ in range(count)]
        self._rows = self._table_dim()[0]
        self.endInsertRows()
        return True

    def insertColumns(self, column, count, parent=QModelIndex()):
        self.beginInsertColumns(parent, column, column + count - 1)
        for row in self._table:
            row[column:column] = [''] * count
        self._rows = self._table_dim()[0]
        self.endInsertColumns()
        return True

    def __len__(self):
        return len(self._table)

    def __bool__(self):
        return len(self) != 0

    def __iter__(self):
        return iter(self._table)

    def __getitem__(self, item):
        return self._table[item]

    def __delitem__(self, i):
        if isinstance(i, slice):
            start, stop, _ = _as_contiguous_range(i, len(self))
            stop -= 1
        else:
            start = stop = i = i if i >= 0 else len(self) + i
        self._check_sort_order()
        self.beginRemoveRows(QModelIndex(), start, stop)
        del self._table[i]
        rows = self._table_dim()[0]
        self._rows = rows
        self.endRemoveRows()
        self._update_column_count()

    def __setitem__(self, i, value):
        self._check_sort_order()
        if isinstance(i, slice):
            start, stop, _ = _as_contiguous_range(i, len(self))
            self.removeRows(start, stop - start)
            self.beginInsertRows(QModelIndex(), start, start + len(value) - 1)
            self._table[start:start + len(value)] = value
            self._rows = self._table_dim()[0]
            self.endInsertRows()
            self._update_column_count()
        else:
            self._table[i] = value
            self.dataChanged.emit(self.index(i, 0),
                                  self.index(i, self.columnCount() - 1))

    def _update_column_count(self):
        cols_before = self._cols
        cols_after = self._table_dim()[1]
        if cols_before < cols_after:
            self.beginInsertColumns(QModelIndex(), cols_before, cols_after - 1)
            self._cols = cols_after
            self.endInsertColumns()
        elif cols_before > cols_after:
            self.beginRemoveColumns(QModelIndex(), cols_after, cols_before - 1)
            self._cols = cols_after
            self.endRemoveColumns()

    def _check_sort_order(self):
        if self.mapToSourceRows(Ellipsis) is not Ellipsis:
            warn("Can't modify PyTableModel when it's sorted",
                 RuntimeWarning, stacklevel=3)
            raise RuntimeError("Can't modify PyTableModel when it's sorted")

    def wrap(self, table):
        self.beginResetModel()
        self._table = table
        self._roleData = self._RoleData()
        self._rows, self._cols = self._table_dim()
        self.resetSorting()
        self.endResetModel()

    def tolist(self):
        return self._table

    def clear(self):
        self.beginResetModel()
        self._table.clear()
        self.resetSorting()
        self._roleData.clear()
        self._rows, self._cols = self._table_dim()
        self.endResetModel()

    def append(self, row):
        self.extend([row])

    def _insertColumns(self, rows):
        n_max = max(map(len, rows))
        if self.columnCount() < n_max:
            self.insertColumns(self.columnCount(), n_max - self.columnCount())

    def extend(self, rows):
        i, rows = len(self), list(rows)
        self.insertRows(i, len(rows))
        self._insertColumns(rows)
        self[i:] = rows

    def insert(self, i, row):
        self.insertRows(i, 1)
        self._insertColumns((row,))
        self[i] = row

    def remove(self, val):
        del self[self._table.index(val)]


class PyListModelTooltip(PyListModel):
    def __init__(self):
        super().__init__()
        self.tooltips = []

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.ToolTipRole:
            return self.tooltips[index.row()]
        else:
            return super().data(index, role)


class VariableListModel(PyListModel):
    MIME_TYPE = "application/x-Orange-VariableList"

    def __init__(self, *args, placeholder=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.placeholder = placeholder

    def data(self, index, role=Qt.DisplayRole):
        if self._is_index_valid(index):
            var = self[index.row()]
            if var is None and role == Qt.DisplayRole:
                return self.placeholder or "None"
            if not isinstance(var, Variable):
                return super().data(index, role)
            elif role == Qt.DisplayRole:
                return var.name
            elif role == Qt.DecorationRole:
                return gui.attributeIconDict[var]
            elif role == Qt.ToolTipRole:
                return self.variable_tooltip(var)
            elif role == gui.TableVariable:
                return var
            else:
                return PyListModel.data(self, index, role)

    def variable_tooltip(self, var):
        if var.is_discrete:
            return self.discrete_variable_tooltip(var)
        elif var.is_time:
            return self.time_variable_toltip(var)
        elif var.is_continuous:
            return self.continuous_variable_toltip(var)
        elif var.is_string:
            return self.string_variable_tooltip(var)

    def variable_labels_tooltip(self, var):
        text = ""
        if var.attributes:
            items = [(safe_text(key), safe_text(value))
                     for key, value in var.attributes.items()]
            labels = list(map("%s = %s".__mod__, items))
            text += "<br/>Variable Labels:<br/>"
            text += "<br/>".join(labels)
        return text

    def discrete_variable_tooltip(self, var):
        text = "<b>%s</b><br/>Categorical with %i values: " %\
               (safe_text(var.name), len(var.values))
        text += ", ".join("%r" % safe_text(v) for v in var.values)
        text += self.variable_labels_tooltip(var)
        return text

    def time_variable_toltip(self, var):
        text = "<b>%s</b><br/>Time" % safe_text(var.name)
        text += self.variable_labels_tooltip(var)
        return text

    def continuous_variable_toltip(self, var):
        text = "<b>%s</b><br/>Numeric" % safe_text(var.name)
        text += self.variable_labels_tooltip(var)
        return text

    def string_variable_tooltip(self, var):
        text = "<b>%s</b><br/>Text" % safe_text(var.name)
        text += self.variable_labels_tooltip(var)
        return text


class DomainModel(VariableListModel):
    ATTRIBUTES, CLASSES, METAS = 1, 2, 4
    MIXED = ATTRIBUTES | CLASSES | METAS
    SEPARATED = (CLASSES, PyListModel.Separator,
                 METAS, PyListModel.Separator,
                 ATTRIBUTES)
    PRIMITIVE = (DiscreteVariable, ContinuousVariable)

    def __init__(self, order=SEPARATED, separators=True, placeholder=None,
                 valid_types=None, alphabetical=False, skip_hidden_vars=True, **kwargs):
        """

        Parameters
        ----------
        order: tuple or int
            Order of attributes, metas, classes, separators and other options
        separators: bool
            If False, remove separators from `order`.
        placeholder: str
            The text that is shown when no variable is selected
        valid_types: tuple
            (Sub)types of `Variable` that are included in the model
        alphabetical: bool
            If true, variables are sorted alphabetically.
        skip_hidden_vars: bool
            If true, variables marked as "hidden" are skipped.
        """
        super().__init__(placeholder=placeholder, **kwargs)
        if isinstance(order, int):
            order = (order,)
        if placeholder is not None and None not in order:
            # Add None for the placeholder if it's not already there
            # Include separator if the current order uses them
            order = (None,) + \
                    (self.Separator, ) * (self.Separator in order) + \
                    order
        if not separators:
            order = [e for e in order if e is not self.Separator]
        self.order = order
        self.valid_types = valid_types
        self.alphabetical = alphabetical
        self.skip_hidden_vars = skip_hidden_vars
        self._within_set_domain = False
        self.set_domain(None)

    def set_domain(self, domain):
        self.beginResetModel()
        content = []
        # The logic related to separators is a bit complicated: it ensures that
        # even when a section is empty we don't have two separators in a row
        # or a separator at the end
        add_separator = False
        for section in self.order:
            if section is self.Separator:
                add_separator = True
                continue
            if isinstance(section, int):
                if domain is None:
                    continue
                to_add = list(chain(
                    *(vars for i, vars in enumerate(
                        (domain.attributes, domain.class_vars, domain.metas))
                      if (1 << i) & section)))
                if self.skip_hidden_vars:
                    to_add = list(filter_visible(to_add))
                if self.valid_types is not None:
                    to_add = [var for var in to_add
                              if isinstance(var, self.valid_types)]
                if self.alphabetical:
                    to_add = sorted(to_add, key=lambda x: x.name)
            elif isinstance(section, list):
                to_add = section
            else:
                to_add = [section]
            if to_add:
                if add_separator and content:
                    content.append(self.Separator)
                    add_separator = False
                content += to_add
        try:
            self._within_set_domain = True
            self[:] = content
        finally:
            self._within_set_domain = False
        self.endResetModel()

    def prevent_modification(method):  # pylint: disable=no-self-argument
        @wraps(method)
        # pylint: disable=protected-access
        def e(self, *args, **kwargs):
            if self._within_set_domain:
                method(self, *args, **kwargs)
            else:
                raise TypeError(
                    "{} can be modified only by calling 'set_domain'".
                    format(type(self).__name__))
        return e

    @prevent_modification
    def extend(self, iterable):
        return super().extend(iterable)

    @prevent_modification
    def append(self, item):
        return super().append(item)

    @prevent_modification
    def insert(self, i, val):
        return super().insert(i, val)

    @prevent_modification
    def remove(self, val):
        return super().remove(val)

    @prevent_modification
    def pop(self, i):
        return super().pop(i)

    @prevent_modification
    def clear(self):
        return super().clear()

    @prevent_modification
    def __delitem__(self, s):
        return super().__delitem__(s)

    @prevent_modification
    def __setitem__(self, s, value):
        return super().__setitem__(s, value)

    @prevent_modification
    def reverse(self):
        return super().reverse()

    @prevent_modification
    def sort(self, *args, **kwargs):
        return super().sort(*args, **kwargs)

    def setData(self, index, value, role=Qt.EditRole):
        # reimplemented
        if role == Qt.EditRole:
            return False
        else:
            return super().setData(index, value, role)

    def setItemData(self, index, data):
        # reimplemented
        if Qt.EditRole in data:
            return False
        else:
            return super().setItemData(index, data)

    def insertRows(self, row, count, parent=QModelIndex()):
        # reimplemented
        return False

    def removeRows(self, row, count, parent=QModelIndex()):
        # reimplemented
        return False

_html_replace = [("<", "&lt;"), (">", "&gt;")]


def safe_text(text):
    for old, new in _html_replace:
        text = str(text).replace(old, new)
    return text


class ContinuousPalettesModel(QAbstractListModel):
    """
    Model for combo boxes
    """
    def __init__(self, parent=None, categories=None, icon_width=64):
        super().__init__(parent)
        self.icon_width = icon_width

        palettes = list(ContinuousPalettes.values())
        if categories is None:
            # Use dict, not set, to keep order of categories
            categories = dict.fromkeys(palette.category for palette in palettes)

        self.items = []
        for category in categories:
            self.items.append(category)
            self.items += [palette for palette in palettes
                           if palette.category == category]
        if len(categories) == 1:
            del self.items[0]

    def rowCount(self, parent):
        return 0 if parent.isValid() else len(self.items)

    @staticmethod
    def columnCount(parent):
        return 0 if parent.isValid() else 1

    def data(self, index, role):
        item = self.items[index.row()]
        if isinstance(item, str):
            if role in [Qt.EditRole, Qt.DisplayRole]:
                return item
        else:
            if role in [Qt.EditRole, Qt.DisplayRole]:
                return item.friendly_name
            if role == Qt.DecorationRole:
                return item.color_strip(self.icon_width, 16)
            if role == Qt.UserRole:
                return item
        return None

    def flags(self, index):
        item = self.items[index.row()]
        if isinstance(item, ContinuousPalette):
            return Qt.ItemIsEnabled | Qt.ItemIsSelectable
        else:
            return Qt.NoItemFlags

    def indexOf(self, x):
        if isinstance(x, str):
            for i, item in enumerate(self.items):
                if not isinstance(item, str) \
                        and x in (item.name, item.friendly_name):
                    return i
        elif isinstance(x, ContinuousPalette):
            return self.items.index(x)
        return None


class ListSingleSelectionModel(QItemSelectionModel):
    """ Item selection model for list item models with single selection.

    Defines signal:
        - selectedIndexChanged(QModelIndex)

    """
    selectedIndexChanged = Signal(QModelIndex)

    def __init__(self, model, parent=None):
        QItemSelectionModel.__init__(self, model, parent)
        self.selectionChanged.connect(self.onSelectionChanged)

    def onSelectionChanged(self, new, _):
        index = list(new.indexes())
        if index:
            index = index.pop()
        else:
            index = QModelIndex()

        self.selectedIndexChanged.emit(index)

    def selectedRow(self):
        """ Return QModelIndex of the selected row or invalid if no selection.
        """
        rows = self.selectedRows()
        if rows:
            return rows[0]
        else:
            return QModelIndex()

    def select(self, index, flags=QItemSelectionModel.ClearAndSelect):
        if isinstance(index, int):
            index = self.model().index(index)
        return QItemSelectionModel.select(self, index, flags)


def select_row(view, row):
    """
    Select a `row` in an item view.
    """
    selmodel = view.selectionModel()
    selmodel.select(view.model().index(row, 0),
                    QItemSelectionModel.ClearAndSelect |
                    QItemSelectionModel.Rows)


def select_rows(view, row_indices, command=QItemSelectionModel.ClearAndSelect):
    """
    Select several rows in view.

    :param QAbstractItemView view:
    :param row_indices: Integer indices of rows to select.
    :param command: QItemSelectionModel.SelectionFlags
    """
    selmodel = view.selectionModel()
    model = view.model()
    selection = QItemSelection()
    for row in row_indices:
        index = model.index(row, 0)
        selection.select(index, index)
    selmodel.select(selection, command | QItemSelectionModel.Rows)


class ModelActionsWidget(QWidget):
    def __init__(self, actions=None, parent=None,
                 direction=QBoxLayout.LeftToRight):
        QWidget.__init__(self, parent)
        self.actions = []
        self.buttons = []
        layout = QBoxLayout(direction)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        if actions is not None:
            for action in actions:
                self.addAction(action)
        self.setLayout(layout)

    def actionButton(self, action):
        if isinstance(action, QAction):
            button = QToolButton(self)
            button.setDefaultAction(action)
            return button
        elif isinstance(action, QAbstractButton):
            return action

    def insertAction(self, ind, action, *args):
        button = self.actionButton(action)
        self.layout().insertWidget(ind, button, *args)
        self.buttons.insert(ind, button)
        self.actions.insert(ind, action)
        return button

    def addAction(self, action, *args):
        return self.insertAction(-1, action, *args)


class TableModel(AbstractSortTableModel):
    """
    An adapter for using Orange.data.Table within Qt's Item View Framework.

    :param Orange.data.Table sourcedata: Source data table.
    :param QObject parent:
    """
    #: Orange.data.Value for the index.
    ValueRole = gui.TableValueRole  # next(gui.OrangeUserRole)
    #: Orange.data.Value of the row's class.
    ClassValueRole = gui.TableClassValueRole  # next(gui.OrangeUserRole)
    #: Orange.data.Variable of the column.
    VariableRole = gui.TableVariable  # next(gui.OrangeUserRole)
    #: Basic statistics of the column
    VariableStatsRole = next(gui.OrangeUserRole)
    #: The column's role (position) in the domain.
    #: One of Attribute, ClassVar or Meta
    DomainRole = next(gui.OrangeUserRole)

    #: Column domain roles
    ClassVar, Meta, Attribute = range(3)

    #: Default background color for domain roles
    ColorForRole = {
        ClassVar: QColor(160, 160, 160),
        Meta: QColor(220, 220, 200),
        Attribute: None,
    }

    #: Standard column descriptor
    Column = namedtuple(
        "Column", ["var", "role", "background", "format"])
    #: Basket column descriptor (i.e. sparse X/Y/metas/ compressed into
    #: a single column).
    Basket = namedtuple(
        "Basket", ["vars", "role", "background", "density", "format"])

    # The class uses the same names (X_density etc) as Table
    # pylint: disable=invalid-name
    def __init__(self, sourcedata, parent=None):
        super().__init__(parent)
        self.source = sourcedata
        self.domain = domain = sourcedata.domain

        self.X_density = sourcedata.X_density()
        self.Y_density = sourcedata.Y_density()
        self.M_density = sourcedata.metas_density()

        def format_sparse(vars, datagetter, instance):
            data = datagetter(instance)
            return ", ".join("{}={}".format(vars[i].name, vars[i].repr_val(v))
                             for i, v in zip(data.indices, data.data))

        def format_sparse_bool(vars, datagetter, instance):
            data = datagetter(instance)
            return ", ".join(vars[i].name for i in data.indices)

        def format_dense(var, instance):
            return str(instance[var])

        def make_basket_formater(vars, density, role):
            formater = (format_sparse if density == Storage.SPARSE
                        else format_sparse_bool)
            if role == TableModel.Attribute:
                getter = operator.attrgetter("sparse_x")
            elif role == TableModel.ClassVar:
                getter = operator.attrgetter("sparse_y")
            elif role == TableModel.Meta:
                getter = operator.attrgetter("sparse_metas")
            return partial(formater, vars, getter)

        def make_basket(vars, density, role):
            return TableModel.Basket(
                vars, TableModel.Attribute, self.ColorForRole[role], density,
                make_basket_formater(vars, density, role)
            )

        def make_column(var, role):
            return TableModel.Column(
                var, role, self.ColorForRole[role],
                partial(format_dense, var)
            )

        columns = []

        if self.Y_density != Storage.DENSE and domain.class_vars:
            coldesc = make_basket(domain.class_vars, self.Y_density,
                                  TableModel.ClassVar)
            columns.append(coldesc)
        else:
            columns += [make_column(var, TableModel.ClassVar)
                        for var in domain.class_vars]

        if self.M_density != Storage.DENSE and domain.metas:
            coldesc = make_basket(domain.metas, self.M_density,
                                  TableModel.Meta)
            columns.append(coldesc)
        else:
            columns += [make_column(var, TableModel.Meta)
                        for var in domain.metas]

        if self.X_density != Storage.DENSE and domain.attributes:
            coldesc = make_basket(domain.attributes, self.X_density,
                                  TableModel.Attribute)
            columns.append(coldesc)
        else:
            columns += [make_column(var, TableModel.Attribute)
                        for var in domain.attributes]

        #: list of all domain variables (class_vars + metas + attrs)
        self.vars = domain.class_vars + domain.metas + domain.attributes
        self.columns = columns

        #: A list of all unique attribute labels (in all variables)
        self._labels = sorted(
            reduce(operator.ior,
                   [set(var.attributes) for var in self.vars],
                   set()))

        @lru_cache(maxsize=1000)
        def row_instance(index):
            return self.source[int(index)]
        self._row_instance = row_instance

        # column basic statistics (VariableStatsRole), computed when
        # first needed.
        self.__stats = None
        self.__rowCount = sourcedata.approx_len()
        self.__columnCount = len(self.columns)

        if self.__rowCount > (2 ** 31 - 1):
            raise ValueError("len(sourcedata) > 2 ** 31 - 1")

    def sortColumnData(self, column):
        return self._columnSortKeyData(column, TableModel.ValueRole)

    @deprecated('Orange.widgets.utils.itemmodels.TableModel.sortColumnData')
    def columnSortKeyData(self, column, role):
        return self._columnSortKeyData(column, role)

    def _columnSortKeyData(self, column, role):
        """
        Return a sequence of source table objects which can be used as
        `keys` for sorting.

        :param int column: Sort column.
        :param Qt.ItemRole role: Sort item role.

        """
        coldesc = self.columns[column]
        if isinstance(coldesc, TableModel.Column) \
                and role == TableModel.ValueRole:
            col_data = numpy.asarray(self.source.get_column_view(coldesc.var)[0])

            if coldesc.var.is_continuous:
                # continuous from metas have dtype object; cast it to float
                col_data = col_data.astype(float)
            return col_data
        else:
            return numpy.asarray([self.index(i, column).data(role)
                                  for i in range(self.rowCount())])

    def data(self, index, role,
             # For optimizing out LOAD_GLOBAL byte code instructions in
             # the item role tests.
             _str=str,
             _Qt_DisplayRole=Qt.DisplayRole,
             _Qt_EditRole=Qt.EditRole,
             _Qt_BackgroundRole=Qt.BackgroundRole,
             _ValueRole=ValueRole,
             _ClassValueRole=ClassValueRole,
             _VariableRole=VariableRole,
             _DomainRole=DomainRole,
             _VariableStatsRole=VariableStatsRole,
             # Some cached local precomputed values.
             # All of the above roles we respond to
             _recognizedRoles=frozenset([Qt.DisplayRole,
                                         Qt.EditRole,
                                         Qt.BackgroundRole,
                                         ValueRole,
                                         ClassValueRole,
                                         VariableRole,
                                         DomainRole,
                                         VariableStatsRole])):
        """
        Reimplemented from `QAbstractItemModel.data`
        """
        if role not in _recognizedRoles:
            return None

        row, col = index.row(), index.column()
        if  not 0 <= row <= self.__rowCount:
            return None

        row = self.mapToSourceRows(row)

        try:
            instance = self._row_instance(row)
        except IndexError:
            self.layoutAboutToBeChanged.emit()
            self.beginRemoveRows(self.parent(), row, max(self.rowCount(), row))
            self.__rowCount = min(row, self.__rowCount)
            self.endRemoveRows()
            self.layoutChanged.emit()
            return None
        coldesc = self.columns[col]

        if role == _Qt_DisplayRole:
            return coldesc.format(instance)
        elif role == _Qt_EditRole and isinstance(coldesc, TableModel.Column):
            return instance[coldesc.var]
        elif role == _Qt_BackgroundRole:
            return coldesc.background
        elif role == _ValueRole and isinstance(coldesc, TableModel.Column):
            return instance[coldesc.var]
        elif role == _ClassValueRole:
            try:
                return instance.get_class()
            except TypeError:
                return None
        elif role == _VariableRole and isinstance(coldesc, TableModel.Column):
            return coldesc.var
        elif role == _DomainRole:
            return coldesc.role
        elif role == _VariableStatsRole:
            return self._stats_for_column(col)
        else:
            return None

    def setData(self, index, value, role):
        row = self.mapFromSourceRows(index.row())
        if role == Qt.EditRole:
            try:
                self.source[row, index.column()] = value
            except (TypeError, IndexError):
                return False
            else:
                self.dataChanged.emit(index, index)
                return True
        else:
            return False

    def parent(self, index=QModelIndex()):
        """Reimplemented from `QAbstractTableModel.parent`."""
        return QModelIndex()

    def rowCount(self, parent=QModelIndex()):
        """Reimplemented from `QAbstractTableModel.rowCount`."""
        return 0 if parent.isValid() else self.__rowCount

    def columnCount(self, parent=QModelIndex()):
        """Reimplemented from `QAbstractTableModel.columnCount`."""
        return 0 if parent.isValid() else self.__columnCount

    def headerData(self, section, orientation, role):
        """Reimplemented from `QAbstractTableModel.headerData`."""
        if orientation == Qt.Vertical:
            if role == Qt.DisplayRole:
                return int(self.mapToSourceRows(section) + 1)
            return None

        coldesc = self.columns[section]
        if role == Qt.DisplayRole:
            if isinstance(coldesc, TableModel.Basket):
                return "{...}"
            else:
                return coldesc.var.name
        elif role == Qt.ToolTipRole:
            return self._tooltip(coldesc)
        elif role == TableModel.VariableRole \
                and isinstance(coldesc, TableModel.Column):
            return coldesc.var
        elif role == TableModel.VariableStatsRole:
            return self._stats_for_column(section)
        elif role == TableModel.DomainRole:
            return coldesc.role
        else:
            return None

    def _tooltip(self, coldesc):
        """
        Return an header tool tip text for an `column` descriptor.
        """
        if isinstance(coldesc, TableModel.Basket):
            return None

        labels = self._labels
        variable = coldesc.var
        pairs = [(escape(key), escape(str(variable.attributes[key])))
                 for key in labels if key in variable.attributes]
        tip = "<b>%s</b>" % escape(variable.name)
        tip = "<br/>".join([tip] + ["%s = %s" % pair for pair in pairs])
        return tip

    def _stats_for_column(self, column):
        """
        Return BasicStats for `column` index.
        """
        coldesc = self.columns[column]
        if isinstance(coldesc, TableModel.Basket):
            return None

        if self.__stats is None:
            self.__stats = datacaching.getCached(
                self.source, basic_stats.DomainBasicStats,
                (self.source, True)
            )

        return self.__stats[coldesc.var]

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user